mirror of
https://github.com/openai/codex.git
synced 2026-11-21 22:50:37 +00:00
Merge branch 'etraut/next-turn-state-core' into etraut/next-turn-state-app-server
# Conflicts: # codex-rs/app-server/README.md # codex-rs/app-server/src/request_processors.rs # codex-rs/app-server/src/request_processors/turn_processor.rs
This commit is contained in:
@@ -46,14 +46,13 @@ fn format_warning(additional_dirs: &[PathBuf]) -> String {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::add_dir_warning_message;
|
||||
use codex_app_server_protocol::FileSystemAccessMode;
|
||||
use codex_app_server_protocol::FileSystemPath;
|
||||
use codex_app_server_protocol::FileSystemSandboxEntry;
|
||||
use codex_app_server_protocol::FileSystemSpecialPath;
|
||||
use codex_app_server_protocol::PermissionProfile as AppServerPermissionProfile;
|
||||
use codex_app_server_protocol::PermissionProfileFileSystemPermissions;
|
||||
use codex_app_server_protocol::PermissionProfileNetworkPermissions;
|
||||
use codex_protocol::models::ManagedFileSystemPermissions;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_protocol::permissions::FileSystemAccessMode;
|
||||
use codex_protocol::permissions::FileSystemPath;
|
||||
use codex_protocol::permissions::FileSystemSandboxEntry;
|
||||
use codex_protocol::permissions::FileSystemSpecialPath;
|
||||
use codex_protocol::permissions::NetworkSandboxPolicy;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
@@ -80,10 +79,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn returns_none_for_external_sandbox() {
|
||||
let profile: PermissionProfile = AppServerPermissionProfile::External {
|
||||
network: PermissionProfileNetworkPermissions { enabled: true },
|
||||
}
|
||||
.into();
|
||||
let profile: PermissionProfile = PermissionProfile::External {
|
||||
network: NetworkSandboxPolicy::Enabled,
|
||||
};
|
||||
let dirs = vec![PathBuf::from("/tmp/example")];
|
||||
assert_eq!(
|
||||
add_dir_warning_message(&dirs, &profile, Path::new("/tmp/project")),
|
||||
@@ -105,9 +103,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn warns_when_profile_can_write_elsewhere_but_not_cwd() {
|
||||
let profile: PermissionProfile = AppServerPermissionProfile::Managed {
|
||||
network: PermissionProfileNetworkPermissions { enabled: false },
|
||||
file_system: PermissionProfileFileSystemPermissions::Restricted {
|
||||
let profile: PermissionProfile = PermissionProfile::Managed {
|
||||
network: NetworkSandboxPolicy::Restricted,
|
||||
file_system: ManagedFileSystemPermissions::Restricted {
|
||||
entries: vec![
|
||||
FileSystemSandboxEntry {
|
||||
path: FileSystemPath::Special {
|
||||
@@ -124,8 +122,7 @@ mod tests {
|
||||
],
|
||||
glob_scan_max_depth: None,
|
||||
},
|
||||
}
|
||||
.into();
|
||||
};
|
||||
let dirs = vec![PathBuf::from("/tmp/extra")];
|
||||
|
||||
assert_eq!(
|
||||
|
||||
+19
-5
@@ -16,6 +16,7 @@ use crate::app_event::WindowsSandboxEnableMode;
|
||||
use crate::app_event_sender::AppEventSender;
|
||||
use crate::app_server_session::AppServerSession;
|
||||
use crate::app_server_session::AppServerStartedThread;
|
||||
use crate::app_server_session::TurnPermissionsOverride;
|
||||
use crate::app_server_session::app_server_rate_limit_snapshots;
|
||||
use crate::bottom_pane::AppLinkViewParams;
|
||||
use crate::bottom_pane::ApprovalRequest;
|
||||
@@ -46,6 +47,7 @@ use crate::keymap::RuntimeKeymap;
|
||||
use crate::legacy_core::config::Config;
|
||||
use crate::legacy_core::config::ConfigBuilder;
|
||||
use crate::legacy_core::config::ConfigOverrides;
|
||||
use crate::legacy_core::config::PermissionProfileSnapshot;
|
||||
use crate::legacy_core::config::edit::ConfigEdit;
|
||||
use crate::legacy_core::config::edit::ConfigEditsBuilder;
|
||||
#[cfg(target_os = "windows")]
|
||||
@@ -139,6 +141,8 @@ use codex_protocol::ThreadId;
|
||||
use codex_protocol::config_types::Personality;
|
||||
#[cfg(target_os = "windows")]
|
||||
use codex_protocol::config_types::WindowsSandboxLevel;
|
||||
use codex_protocol::models::ActivePermissionProfile;
|
||||
use codex_protocol::models::BUILT_IN_PERMISSION_PROFILE_WORKSPACE;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_protocol::openai_models::ModelAvailabilityNux;
|
||||
use codex_protocol::openai_models::ModelPreset;
|
||||
@@ -149,6 +153,7 @@ use codex_protocol::permissions::FileSystemSandboxKind;
|
||||
use codex_rollout::StateDbHandle;
|
||||
use codex_terminal_detection::user_agent;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_approval_presets::builtin_permission_profile_for_active_permission_profile;
|
||||
use color_eyre::eyre::Result;
|
||||
use color_eyre::eyre::WrapErr;
|
||||
use crossterm::event::KeyCode;
|
||||
@@ -326,7 +331,7 @@ fn default_exec_approval_decisions(
|
||||
struct AutoReviewMode {
|
||||
approval_policy: AskForApproval,
|
||||
approvals_reviewer: ApprovalsReviewer,
|
||||
permission_profile: PermissionProfile,
|
||||
active_permission_profile: ActivePermissionProfile,
|
||||
}
|
||||
|
||||
/// Enabling the Auto-review experiment in the TUI should also switch the
|
||||
@@ -337,7 +342,17 @@ fn auto_review_mode() -> AutoReviewMode {
|
||||
AutoReviewMode {
|
||||
approval_policy: AskForApproval::OnRequest,
|
||||
approvals_reviewer: ApprovalsReviewer::AutoReview,
|
||||
permission_profile: PermissionProfile::workspace_write(),
|
||||
active_permission_profile: ActivePermissionProfile::new(
|
||||
BUILT_IN_PERMISSION_PROFILE_WORKSPACE,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl AutoReviewMode {
|
||||
fn permission_profile(&self) -> PermissionProfile {
|
||||
builtin_permission_profile_for_active_permission_profile(&self.active_permission_profile)
|
||||
.expect("auto-review mode should use a built-in permission profile")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -397,8 +412,7 @@ fn session_summary(
|
||||
let usage_line = (!token_usage.is_zero()).then(|| token_usage.to_string());
|
||||
let thread_id =
|
||||
resumable_thread(thread_id, thread_name, rollout_path).map(|thread| thread.thread_id);
|
||||
let resume_command =
|
||||
crate::legacy_core::util::resume_command(/*thread_name*/ None, thread_id);
|
||||
let resume_command = codex_utils_cli::resume_command(/*thread_name*/ None, thread_id);
|
||||
|
||||
if usage_line.is_none() && resume_command.is_none() {
|
||||
return None;
|
||||
@@ -958,7 +972,7 @@ See the Codex keymap documentation for supported actions and examples."
|
||||
// world-writable dirs on Windows.
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let startup_permission_profile = app.config.permissions.permission_profile();
|
||||
let startup_permission_profile = app.config.permissions.effective_permission_profile();
|
||||
let should_check = WindowsSandboxLevel::from_config(&app.config)
|
||||
!= WindowsSandboxLevel::Disabled
|
||||
&& managed_filesystem_sandbox_is_restricted(&startup_permission_profile)
|
||||
|
||||
@@ -105,24 +105,41 @@ impl App {
|
||||
true
|
||||
}
|
||||
|
||||
pub(super) fn try_set_permission_profile_on_config(
|
||||
pub(super) fn try_set_builtin_active_permission_profile_on_config(
|
||||
&mut self,
|
||||
config: &mut Config,
|
||||
permission_profile: PermissionProfile,
|
||||
active_permission_profile: ActivePermissionProfile,
|
||||
user_message_prefix: &str,
|
||||
log_message: &str,
|
||||
) -> bool {
|
||||
) -> Option<PermissionProfile> {
|
||||
let Some(permission_profile) =
|
||||
builtin_permission_profile_for_active_permission_profile(&active_permission_profile)
|
||||
else {
|
||||
tracing::warn!(
|
||||
id = %active_permission_profile.id,
|
||||
"{log_message}: unsupported active permission profile"
|
||||
);
|
||||
self.chat_widget.add_error_message(format!(
|
||||
"{user_message_prefix}: unsupported active permission profile `{}`",
|
||||
active_permission_profile.id
|
||||
));
|
||||
return None;
|
||||
};
|
||||
|
||||
if let Err(err) = config
|
||||
.permissions
|
||||
.set_permission_profile(permission_profile)
|
||||
.set_permission_profile_from_session_snapshot(PermissionProfileSnapshot::active(
|
||||
permission_profile.clone(),
|
||||
active_permission_profile,
|
||||
))
|
||||
{
|
||||
tracing::warn!(error = %err, "{log_message}");
|
||||
self.chat_widget
|
||||
.add_error_message(format!("{user_message_prefix}: {err}"));
|
||||
return false;
|
||||
return None;
|
||||
}
|
||||
|
||||
true
|
||||
Some(permission_profile)
|
||||
}
|
||||
|
||||
pub(super) async fn update_feature_flags(&mut self, updates: Vec<(Feature, bool)>) {
|
||||
@@ -149,6 +166,7 @@ impl App {
|
||||
let mut approval_policy_override = None;
|
||||
let mut approvals_reviewer_override = None;
|
||||
let mut permission_profile_override = None;
|
||||
let mut active_permission_profile_override = None;
|
||||
let mut feature_updates_to_apply = Vec::with_capacity(updates.len());
|
||||
// Auto-Review owns `approvals_reviewer`, but disabling the feature
|
||||
// from inside a profile should not silently clear a value configured at
|
||||
@@ -240,14 +258,16 @@ impl App {
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
if !self.try_set_permission_profile_on_config(
|
||||
&mut feature_config,
|
||||
auto_review_preset.permission_profile.clone(),
|
||||
"Failed to enable Auto-review",
|
||||
"failed to set auto-review permission profile on staged config",
|
||||
) {
|
||||
let Some(permission_profile) = self
|
||||
.try_set_builtin_active_permission_profile_on_config(
|
||||
&mut feature_config,
|
||||
auto_review_preset.active_permission_profile.clone(),
|
||||
"Failed to enable Auto-review",
|
||||
"failed to set auto-review permission profile on staged config",
|
||||
)
|
||||
else {
|
||||
continue;
|
||||
}
|
||||
};
|
||||
feature_edits.extend([
|
||||
ConfigEdit::SetPath {
|
||||
segments: scoped_segments("approval_policy"),
|
||||
@@ -259,7 +279,9 @@ impl App {
|
||||
},
|
||||
]);
|
||||
approval_policy_override = Some(auto_review_preset.approval_policy);
|
||||
permission_profile_override = Some(auto_review_preset.permission_profile.clone());
|
||||
permission_profile_override = Some(permission_profile);
|
||||
active_permission_profile_override =
|
||||
Some(auto_review_preset.active_permission_profile.clone());
|
||||
}
|
||||
next_config = feature_config;
|
||||
feature_updates_to_apply.push((feature, effective_enabled));
|
||||
@@ -299,10 +321,18 @@ impl App {
|
||||
self.config.permissions.approval_policy.value(),
|
||||
));
|
||||
}
|
||||
if permission_profile_override.is_some()
|
||||
let permission_profile_override_value = permission_profile_override
|
||||
.is_some()
|
||||
.then(|| self.config.permissions.permission_profile().clone());
|
||||
if let Some(permission_profile) = permission_profile_override_value.as_ref()
|
||||
&& let Err(err) = self
|
||||
.chat_widget
|
||||
.set_permission_profile(self.config.permissions.permission_profile())
|
||||
.set_permission_profile_from_session_snapshot(
|
||||
PermissionProfileSnapshot::from_session_snapshot(
|
||||
permission_profile.clone(),
|
||||
active_permission_profile_override.clone(),
|
||||
),
|
||||
)
|
||||
{
|
||||
tracing::error!(
|
||||
error = %err,
|
||||
@@ -311,9 +341,8 @@ impl App {
|
||||
self.chat_widget
|
||||
.add_error_message(format!("Failed to enable Auto-review: {err}"));
|
||||
}
|
||||
if permission_profile_override.is_some() {
|
||||
self.runtime_permission_profile_override =
|
||||
Some(self.config.permissions.permission_profile());
|
||||
if let Some(permission_profile) = permission_profile_override_value {
|
||||
self.runtime_permission_profile_override = Some(permission_profile);
|
||||
}
|
||||
|
||||
if approval_policy_override.is_some()
|
||||
@@ -331,7 +360,7 @@ impl App {
|
||||
/*cwd*/ None,
|
||||
approval_policy_override,
|
||||
approvals_reviewer_override,
|
||||
permission_profile_override,
|
||||
active_permission_profile_override,
|
||||
/*windows_sandbox_level*/ None,
|
||||
/*model*/ None,
|
||||
/*effort*/ None,
|
||||
@@ -358,7 +387,7 @@ impl App {
|
||||
/*cwd*/ None,
|
||||
/*approval_policy*/ None,
|
||||
/*approvals_reviewer*/ None,
|
||||
/*permission_profile*/ None,
|
||||
/*active_permission_profile*/ None,
|
||||
#[cfg(target_os = "windows")]
|
||||
Some(windows_sandbox_level),
|
||||
/*model*/ None,
|
||||
@@ -659,6 +688,7 @@ mod tests {
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: next_cwd.clone().abs(),
|
||||
runtime_workspace_roots: Vec::new(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: None,
|
||||
message_history: None,
|
||||
|
||||
@@ -1111,7 +1111,7 @@ impl App {
|
||||
/*cwd*/ None,
|
||||
/*approval_policy*/ None,
|
||||
/*approvals_reviewer*/ None,
|
||||
/*permission_profile*/ None,
|
||||
/*active_permission_profile*/ None,
|
||||
#[cfg(target_os = "windows")]
|
||||
Some(windows_sandbox_level),
|
||||
/*model*/ None,
|
||||
@@ -1136,7 +1136,7 @@ impl App {
|
||||
/*cwd*/ None,
|
||||
Some(AskForApproval::from(preset.approval)),
|
||||
Some(self.config.approvals_reviewer),
|
||||
Some(preset.permission_profile.clone()),
|
||||
Some(preset.active_permission_profile.clone()),
|
||||
#[cfg(target_os = "windows")]
|
||||
Some(windows_sandbox_level),
|
||||
/*model*/ None,
|
||||
@@ -1150,9 +1150,10 @@ impl App {
|
||||
self.app_event_tx.send(AppEvent::UpdateAskForApprovalPolicy(
|
||||
AskForApproval::from(preset.approval),
|
||||
));
|
||||
self.app_event_tx.send(AppEvent::UpdatePermissionProfile(
|
||||
preset.permission_profile.clone(),
|
||||
));
|
||||
self.app_event_tx
|
||||
.send(AppEvent::UpdateActivePermissionProfile(
|
||||
preset.active_permission_profile.clone(),
|
||||
));
|
||||
let _ = mode;
|
||||
self.chat_widget.add_plain_history_lines(vec![
|
||||
Line::from(vec!["• ".dim(), "Sandbox ready".into()]),
|
||||
@@ -1400,25 +1401,32 @@ impl App {
|
||||
self.sync_active_thread_permission_settings_to_cached_session()
|
||||
.await;
|
||||
}
|
||||
AppEvent::UpdatePermissionProfile(permission_profile) => {
|
||||
AppEvent::UpdateActivePermissionProfile(active_permission_profile) => {
|
||||
let mut config = self.config.clone();
|
||||
let Some(permission_profile) = self
|
||||
.try_set_builtin_active_permission_profile_on_config(
|
||||
&mut config,
|
||||
active_permission_profile.clone(),
|
||||
"Failed to set permission profile",
|
||||
"failed to set active permission profile on app config",
|
||||
)
|
||||
else {
|
||||
return Ok(AppRunControl::Continue);
|
||||
};
|
||||
#[cfg(target_os = "windows")]
|
||||
let permission_profile_is_managed_restricted =
|
||||
managed_filesystem_sandbox_is_restricted(&permission_profile);
|
||||
let permission_profile_for_chat = permission_profile.clone();
|
||||
|
||||
let mut config = self.config.clone();
|
||||
if !self.try_set_permission_profile_on_config(
|
||||
&mut config,
|
||||
permission_profile,
|
||||
"Failed to set permission profile",
|
||||
"failed to set permission profile on app config",
|
||||
) {
|
||||
return Ok(AppRunControl::Continue);
|
||||
}
|
||||
self.config = config;
|
||||
if let Err(err) = self
|
||||
.chat_widget
|
||||
.set_permission_profile(permission_profile_for_chat)
|
||||
.set_permission_profile_from_session_snapshot(
|
||||
PermissionProfileSnapshot::active(
|
||||
permission_profile_for_chat,
|
||||
active_permission_profile,
|
||||
),
|
||||
)
|
||||
{
|
||||
tracing::warn!(%err, "failed to set permission profile on chat config");
|
||||
self.chat_widget
|
||||
@@ -1426,7 +1434,7 @@ impl App {
|
||||
return Ok(AppRunControl::Continue);
|
||||
}
|
||||
self.runtime_permission_profile_override =
|
||||
Some(self.config.permissions.permission_profile());
|
||||
Some(self.config.permissions.permission_profile().clone());
|
||||
self.sync_active_thread_permission_settings_to_cached_session()
|
||||
.await;
|
||||
|
||||
@@ -1450,7 +1458,8 @@ impl App {
|
||||
std::env::vars().collect();
|
||||
let tx = self.app_event_tx.clone();
|
||||
let logs_base_dir = self.config.codex_home.clone();
|
||||
let permission_profile = self.config.permissions.permission_profile();
|
||||
let permission_profile =
|
||||
self.config.permissions.effective_permission_profile();
|
||||
Self::spawn_world_writable_scan(
|
||||
cwd,
|
||||
env_map,
|
||||
|
||||
@@ -5,6 +5,9 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
const SIDE_EDIT_PREVIOUS_UNAVAILABLE_MESSAGE: &str =
|
||||
"Editing previous prompts is unavailable in side conversations.";
|
||||
|
||||
impl App {
|
||||
pub(super) async fn launch_external_editor(&mut self, tui: &mut tui::Tui) {
|
||||
let editor_cmd = match external_editor::resolve_editor_command() {
|
||||
@@ -197,6 +200,8 @@ impl App {
|
||||
// handles it.
|
||||
if self.should_handle_backtrack_esc(key_event) {
|
||||
self.handle_backtrack_esc_key(tui);
|
||||
} else if self.should_reject_side_backtrack_esc(key_event) {
|
||||
self.reject_side_backtrack_esc();
|
||||
} else {
|
||||
self.chat_widget.handle_key_event(key_event);
|
||||
}
|
||||
@@ -252,11 +257,25 @@ impl App {
|
||||
}
|
||||
|
||||
pub(super) fn should_handle_backtrack_esc(&self, key_event: KeyEvent) -> bool {
|
||||
self.chat_widget.is_normal_backtrack_mode()
|
||||
!self.chat_widget.side_conversation_active()
|
||||
&& self.chat_widget.is_normal_backtrack_mode()
|
||||
&& self.chat_widget.composer_is_empty()
|
||||
&& !self.chat_widget.should_handle_vim_insert_escape(key_event)
|
||||
}
|
||||
|
||||
pub(super) fn should_reject_side_backtrack_esc(&self, key_event: KeyEvent) -> bool {
|
||||
self.chat_widget.side_conversation_active()
|
||||
&& self.chat_widget.is_normal_backtrack_mode()
|
||||
&& self.chat_widget.composer_is_empty()
|
||||
&& !self.chat_widget.should_handle_vim_insert_escape(key_event)
|
||||
}
|
||||
|
||||
pub(super) fn reject_side_backtrack_esc(&mut self) {
|
||||
self.reset_backtrack_state();
|
||||
self.chat_widget
|
||||
.add_error_message(SIDE_EDIT_PREVIOUS_UNAVAILABLE_MESSAGE.to_string());
|
||||
}
|
||||
|
||||
fn app_keymap_shortcuts_available(&self) -> bool {
|
||||
self.overlay.is_none() && self.chat_widget.no_modal_or_popup_active()
|
||||
}
|
||||
|
||||
@@ -54,24 +54,16 @@ fn send_world_writable_scan_failed(tx: &AppEventSender) {
|
||||
}
|
||||
|
||||
pub(super) fn side_return_shortcut_matches(key_event: KeyEvent) -> bool {
|
||||
match key_event {
|
||||
KeyEvent {
|
||||
code: KeyCode::Esc,
|
||||
kind: KeyEventKind::Press | KeyEventKind::Repeat,
|
||||
..
|
||||
} => true,
|
||||
matches!(
|
||||
key_event,
|
||||
KeyEvent {
|
||||
code: KeyCode::Char(c),
|
||||
modifiers,
|
||||
kind: KeyEventKind::Press,
|
||||
..
|
||||
} if modifiers.contains(KeyModifiers::CONTROL)
|
||||
&& (c.eq_ignore_ascii_case(&'c') || c.eq_ignore_ascii_case(&'d')) =>
|
||||
{
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
&& (c.eq_ignore_ascii_case(&'c') || c.eq_ignore_ascii_case(&'d'))
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -79,16 +71,7 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn side_return_shortcuts_match_esc_ctrl_c_and_ctrl_d() {
|
||||
assert!(side_return_shortcut_matches(KeyEvent::new(
|
||||
KeyCode::Esc,
|
||||
KeyModifiers::NONE,
|
||||
)));
|
||||
assert!(side_return_shortcut_matches(KeyEvent::new_with_kind(
|
||||
KeyCode::Esc,
|
||||
KeyModifiers::NONE,
|
||||
KeyEventKind::Repeat,
|
||||
)));
|
||||
fn side_return_shortcuts_match_ctrl_c_and_ctrl_d() {
|
||||
assert!(side_return_shortcut_matches(KeyEvent::new(
|
||||
KeyCode::Char('c'),
|
||||
KeyModifiers::CONTROL,
|
||||
@@ -105,6 +88,11 @@ mod tests {
|
||||
KeyCode::Char('D'),
|
||||
KeyModifiers::CONTROL,
|
||||
)));
|
||||
assert!(!side_return_shortcut_matches(KeyEvent::new_with_kind(
|
||||
KeyCode::Esc,
|
||||
KeyModifiers::NONE,
|
||||
KeyEventKind::Press,
|
||||
)));
|
||||
assert!(!side_return_shortcut_matches(KeyEvent::new_with_kind(
|
||||
KeyCode::Esc,
|
||||
KeyModifiers::NONE,
|
||||
|
||||
@@ -20,7 +20,7 @@ const SIDE_NO_STARTED_CONVERSATION_MESSAGE: &str = concat!(
|
||||
"Send a message first, then try /side again."
|
||||
);
|
||||
const SIDE_ALREADY_OPEN_MESSAGE: &str =
|
||||
"A side conversation is already open. Press Esc to return before starting another.";
|
||||
"A side conversation is already open. Press Ctrl+C to return before starting another.";
|
||||
const SIDE_BOUNDARY_PROMPT: &str = r#"Side conversation boundary.
|
||||
|
||||
Everything before this boundary is inherited history from the parent thread. It is reference context only. It is not your current task.
|
||||
@@ -247,7 +247,7 @@ impl App {
|
||||
if let Some(parent_status) = parent_status {
|
||||
label_parts.push(parent_status.label(parent_is_main).to_string());
|
||||
}
|
||||
label_parts.push("Esc to return".to_string());
|
||||
label_parts.push("Ctrl+C to return".to_string());
|
||||
self.chat_widget
|
||||
.set_side_conversation_context_label(Some(format!("Side {}", label_parts.join(" · "))));
|
||||
}
|
||||
|
||||
@@ -66,9 +66,9 @@ pub(super) fn emit_project_config_warnings(app_event_tx: &AppEventSender, config
|
||||
}
|
||||
|
||||
pub(super) fn emit_system_bwrap_warning(app_event_tx: &AppEventSender, config: &Config) {
|
||||
let Some(message) = crate::legacy_core::config::system_bwrap_warning(
|
||||
config.permissions.permission_profile.get(),
|
||||
) else {
|
||||
let Some(message) =
|
||||
codex_sandboxing::system_bwrap_warning(config.permissions.permission_profile())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
|
||||
+107
-18
@@ -28,6 +28,7 @@ use crate::app_command::AppCommand as Op;
|
||||
use crate::diff_model::FileChange;
|
||||
use crate::legacy_core::config::ConfigBuilder;
|
||||
use crate::legacy_core::config::ConfigOverrides;
|
||||
use crate::legacy_core::config::PermissionProfileSnapshot;
|
||||
use crate::legacy_core::config::TerminalResizeReflowMaxRows;
|
||||
use codex_app_server_protocol::AdditionalFileSystemPermissions;
|
||||
use codex_app_server_protocol::AdditionalNetworkPermissions;
|
||||
@@ -1640,7 +1641,18 @@ async fn update_feature_flags_enabling_guardian_selects_auto_review() -> Result<
|
||||
.config_ref()
|
||||
.permissions
|
||||
.permission_profile(),
|
||||
auto_review.permission_profile
|
||||
&auto_review.permission_profile()
|
||||
);
|
||||
assert_eq!(
|
||||
app.config.permissions.active_permission_profile(),
|
||||
Some(auto_review.active_permission_profile.clone())
|
||||
);
|
||||
assert_eq!(
|
||||
app.chat_widget
|
||||
.config_ref()
|
||||
.permissions
|
||||
.active_permission_profile(),
|
||||
Some(auto_review.active_permission_profile.clone())
|
||||
);
|
||||
assert_eq!(
|
||||
app.chat_widget.config_ref().approvals_reviewer,
|
||||
@@ -1649,7 +1661,7 @@ async fn update_feature_flags_enabling_guardian_selects_auto_review() -> Result<
|
||||
assert_eq!(app.runtime_approval_policy_override, None);
|
||||
assert_eq!(
|
||||
app.runtime_permission_profile_override,
|
||||
Some(auto_review.permission_profile.clone())
|
||||
Some(auto_review.permission_profile())
|
||||
);
|
||||
assert_eq!(
|
||||
op_rx.try_recv(),
|
||||
@@ -1657,7 +1669,7 @@ async fn update_feature_flags_enabling_guardian_selects_auto_review() -> Result<
|
||||
cwd: None,
|
||||
approval_policy: Some(auto_review.approval_policy),
|
||||
approvals_reviewer: Some(auto_review.approvals_reviewer),
|
||||
permission_profile: Some(auto_review.permission_profile.clone()),
|
||||
active_permission_profile: Some(auto_review.active_permission_profile.clone()),
|
||||
windows_sandbox_level: None,
|
||||
model: None,
|
||||
effort: None,
|
||||
@@ -1719,7 +1731,9 @@ async fn update_feature_flags_disabling_guardian_clears_review_policy_and_restor
|
||||
app.chat_widget
|
||||
.set_approval_policy(AskForApproval::OnRequest);
|
||||
app.chat_widget
|
||||
.set_permission_profile(PermissionProfile::workspace_write())?;
|
||||
.set_permission_profile_from_session_snapshot(PermissionProfileSnapshot::legacy(
|
||||
PermissionProfile::workspace_write(),
|
||||
))?;
|
||||
|
||||
app.update_feature_flags(vec![(Feature::GuardianApproval, false)])
|
||||
.await;
|
||||
@@ -1747,7 +1761,7 @@ async fn update_feature_flags_disabling_guardian_clears_review_policy_and_restor
|
||||
cwd: None,
|
||||
approval_policy: None,
|
||||
approvals_reviewer: Some(ApprovalsReviewer::User),
|
||||
permission_profile: None,
|
||||
active_permission_profile: None,
|
||||
windows_sandbox_level: None,
|
||||
model: None,
|
||||
effort: None,
|
||||
@@ -1817,7 +1831,7 @@ async fn update_feature_flags_enabling_guardian_overrides_explicit_manual_review
|
||||
.config_ref()
|
||||
.permissions
|
||||
.permission_profile(),
|
||||
auto_review.permission_profile
|
||||
&auto_review.permission_profile()
|
||||
);
|
||||
assert_eq!(
|
||||
op_rx.try_recv(),
|
||||
@@ -1825,7 +1839,7 @@ async fn update_feature_flags_enabling_guardian_overrides_explicit_manual_review
|
||||
cwd: None,
|
||||
approval_policy: Some(auto_review.approval_policy),
|
||||
approvals_reviewer: Some(auto_review.approvals_reviewer),
|
||||
permission_profile: Some(auto_review.permission_profile.clone()),
|
||||
active_permission_profile: Some(auto_review.active_permission_profile.clone()),
|
||||
windows_sandbox_level: None,
|
||||
model: None,
|
||||
effort: None,
|
||||
@@ -1882,7 +1896,7 @@ async fn update_feature_flags_disabling_guardian_clears_manual_review_policy_wit
|
||||
cwd: None,
|
||||
approval_policy: None,
|
||||
approvals_reviewer: Some(ApprovalsReviewer::User),
|
||||
permission_profile: None,
|
||||
active_permission_profile: None,
|
||||
windows_sandbox_level: None,
|
||||
model: None,
|
||||
effort: None,
|
||||
@@ -1941,7 +1955,7 @@ async fn update_feature_flags_enabling_guardian_in_profile_sets_profile_auto_rev
|
||||
cwd: None,
|
||||
approval_policy: Some(auto_review.approval_policy),
|
||||
approvals_reviewer: Some(auto_review.approvals_reviewer),
|
||||
permission_profile: Some(auto_review.permission_profile.clone()),
|
||||
active_permission_profile: Some(auto_review.active_permission_profile.clone()),
|
||||
windows_sandbox_level: None,
|
||||
model: None,
|
||||
effort: None,
|
||||
@@ -2028,7 +2042,7 @@ guardian_approval = true
|
||||
cwd: None,
|
||||
approval_policy: None,
|
||||
approvals_reviewer: Some(ApprovalsReviewer::User),
|
||||
permission_profile: None,
|
||||
active_permission_profile: None,
|
||||
windows_sandbox_level: None,
|
||||
model: None,
|
||||
effort: None,
|
||||
@@ -2796,10 +2810,13 @@ async fn inactive_thread_started_notification_initializes_replay_session() -> Re
|
||||
ThreadId::from_string("00000000-0000-0000-0000-000000000101").expect("valid thread");
|
||||
let agent_thread_id =
|
||||
ThreadId::from_string("00000000-0000-0000-0000-000000000202").expect("valid thread");
|
||||
let primary_cwd = test_path_buf("/tmp/main").abs();
|
||||
let shared_root = test_path_buf("/tmp/shared").abs();
|
||||
let primary_session = ThreadSessionState {
|
||||
approval_policy: AskForApproval::OnRequest,
|
||||
permission_profile: PermissionProfile::workspace_write(),
|
||||
..test_thread_session(main_thread_id, test_path_buf("/tmp/main"))
|
||||
runtime_workspace_roots: vec![primary_cwd.clone(), shared_root.clone()],
|
||||
..test_thread_session(main_thread_id, primary_cwd.to_path_buf())
|
||||
};
|
||||
|
||||
app.primary_thread_id = Some(main_thread_id);
|
||||
@@ -2871,6 +2888,10 @@ async fn inactive_thread_started_notification_initializes_replay_session() -> Re
|
||||
assert_eq!(session.model_provider_id, "agent-provider");
|
||||
assert_eq!(session.approval_policy, primary_session.approval_policy);
|
||||
assert_eq!(session.cwd.as_path(), test_path_buf("/tmp/agent").as_path());
|
||||
assert_eq!(
|
||||
session.runtime_workspace_roots,
|
||||
vec![test_path_buf("/tmp/agent").abs(), shared_root]
|
||||
);
|
||||
assert_eq!(session.rollout_path, Some(rollout_path));
|
||||
assert_eq!(
|
||||
app.agent_navigation.get(&agent_thread_id),
|
||||
@@ -2892,10 +2913,12 @@ async fn inactive_thread_started_notification_preserves_primary_model_when_path_
|
||||
ThreadId::from_string("00000000-0000-0000-0000-000000000301").expect("valid thread");
|
||||
let agent_thread_id =
|
||||
ThreadId::from_string("00000000-0000-0000-0000-000000000302").expect("valid thread");
|
||||
let primary_cwd = test_path_buf("/tmp/main").abs();
|
||||
let primary_session = ThreadSessionState {
|
||||
approval_policy: AskForApproval::OnRequest,
|
||||
permission_profile: PermissionProfile::workspace_write(),
|
||||
..test_thread_session(main_thread_id, test_path_buf("/tmp/main"))
|
||||
runtime_workspace_roots: vec![primary_cwd.clone()],
|
||||
..test_thread_session(main_thread_id, primary_cwd.to_path_buf())
|
||||
};
|
||||
|
||||
app.primary_thread_id = Some(main_thread_id);
|
||||
@@ -2962,10 +2985,12 @@ async fn thread_read_session_state_does_not_reuse_primary_permission_profile() {
|
||||
ThreadId::from_string("00000000-0000-0000-0000-000000000401").expect("valid thread");
|
||||
let read_thread_id =
|
||||
ThreadId::from_string("00000000-0000-0000-0000-000000000402").expect("valid thread");
|
||||
let primary_cwd = test_path_buf("/tmp/main").abs();
|
||||
let primary_session = ThreadSessionState {
|
||||
approval_policy: AskForApproval::OnRequest,
|
||||
permission_profile: PermissionProfile::workspace_write(),
|
||||
..test_thread_session(main_thread_id, test_path_buf("/tmp/main"))
|
||||
runtime_workspace_roots: vec![primary_cwd.clone()],
|
||||
..test_thread_session(main_thread_id, primary_cwd.to_path_buf())
|
||||
};
|
||||
app.primary_session_configured = Some(primary_session);
|
||||
|
||||
@@ -2997,11 +3022,16 @@ async fn thread_read_session_state_does_not_reuse_primary_permission_profile() {
|
||||
|
||||
assert_eq!(session.thread_id, read_thread_id);
|
||||
assert_eq!(session.cwd.as_path(), test_path_buf("/tmp/read").as_path());
|
||||
assert_eq!(
|
||||
session.runtime_workspace_roots,
|
||||
vec![test_path_buf("/tmp/read").abs()]
|
||||
);
|
||||
let expected_permission_profile = app
|
||||
.chat_widget
|
||||
.config_ref()
|
||||
.permissions
|
||||
.permission_profile();
|
||||
.permission_profile()
|
||||
.clone();
|
||||
assert_eq!(
|
||||
session.permission_profile, expected_permission_profile,
|
||||
"thread/read does not return fresh server permissions; the fallback profile must use the \
|
||||
@@ -3123,7 +3153,9 @@ async fn side_fork_config_inherits_parent_thread_runtime_settings() {
|
||||
app.chat_widget
|
||||
.set_approval_policy(AskForApproval::OnRequest);
|
||||
app.chat_widget
|
||||
.set_permission_profile(parent_permission_profile.clone())
|
||||
.set_permission_profile_from_session_snapshot(PermissionProfileSnapshot::legacy(
|
||||
parent_permission_profile.clone(),
|
||||
))
|
||||
.expect("test permission profile should be accepted");
|
||||
app.chat_widget
|
||||
.set_approvals_reviewer(ApprovalsReviewer::AutoReview);
|
||||
@@ -3144,7 +3176,7 @@ async fn side_fork_config_inherits_parent_thread_runtime_settings() {
|
||||
Some(ReasoningEffortConfig::High),
|
||||
Some(parent_service_tier),
|
||||
AskForApproval::OnRequest.to_core(),
|
||||
parent_permission_profile,
|
||||
&parent_permission_profile,
|
||||
ApprovalsReviewer::AutoReview,
|
||||
)
|
||||
);
|
||||
@@ -3168,7 +3200,9 @@ async fn side_start_block_message_tracks_open_side_conversation() {
|
||||
|
||||
assert_eq!(
|
||||
app.side_start_block_message(),
|
||||
Some("A side conversation is already open. Press Esc to return before starting another.")
|
||||
Some(
|
||||
"A side conversation is already open. Press Ctrl+C to return before starting another."
|
||||
)
|
||||
);
|
||||
|
||||
app.side_threads.remove(&side_thread_id);
|
||||
@@ -3685,6 +3719,7 @@ async fn render_clear_ui_header_after_long_transcript_for_snapshot() -> String {
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/tmp/project").abs(),
|
||||
runtime_workspace_roots: Vec::new(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::High),
|
||||
message_history: None,
|
||||
@@ -3933,6 +3968,7 @@ fn test_thread_session(thread_id: ThreadId, cwd: PathBuf) -> ThreadSessionState
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: cwd.abs(),
|
||||
runtime_workspace_roots: Vec::new(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: None,
|
||||
message_history: None,
|
||||
@@ -4508,6 +4544,7 @@ async fn backtrack_selection_with_duplicate_history_targets_unique_turn() {
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
runtime_workspace_roots: Vec::new(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: None,
|
||||
message_history: None,
|
||||
@@ -4571,6 +4608,7 @@ async fn backtrack_selection_with_duplicate_history_targets_unique_turn() {
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
runtime_workspace_roots: Vec::new(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: None,
|
||||
message_history: None,
|
||||
@@ -4663,6 +4701,7 @@ async fn backtrack_resubmit_preserves_data_image_urls_in_user_turn() {
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
runtime_workspace_roots: Vec::new(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: None,
|
||||
message_history: None,
|
||||
@@ -4704,7 +4743,7 @@ async fn backtrack_resubmit_preserves_data_image_urls_in_user_turn() {
|
||||
assert!(items.iter().any(|item| {
|
||||
matches!(
|
||||
item,
|
||||
UserInput::Image { url } if url == &data_image_url
|
||||
UserInput::Image { url, .. } if url == &data_image_url
|
||||
)
|
||||
}));
|
||||
}
|
||||
@@ -4898,6 +4937,7 @@ async fn refreshed_snapshot_session_persists_resumed_turns() {
|
||||
)];
|
||||
let resumed_session = ThreadSessionState {
|
||||
cwd: test_path_buf("/tmp/refreshed").abs(),
|
||||
runtime_workspace_roots: Vec::new(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
..initial_session.clone()
|
||||
};
|
||||
@@ -5062,6 +5102,7 @@ async fn new_session_requests_shutdown_for_previous_conversation() {
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
runtime_workspace_roots: Vec::new(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: None,
|
||||
message_history: None,
|
||||
@@ -5183,6 +5224,7 @@ async fn clear_only_ui_reset_preserves_chat_session_state() {
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/tmp/project").abs(),
|
||||
runtime_workspace_roots: Vec::new(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: None,
|
||||
message_history: None,
|
||||
@@ -5247,3 +5289,50 @@ async fn backtrack_esc_does_not_steal_empty_vim_insert_escape() {
|
||||
assert!(!app.chat_widget.should_handle_vim_insert_escape(esc));
|
||||
assert!(app.should_handle_backtrack_esc(esc));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn side_conversations_reject_backtrack_esc_without_stealing_vim_insert_escape() {
|
||||
let mut app = make_test_app().await;
|
||||
let esc = crossterm::event::KeyEvent::new(crossterm::event::KeyCode::Esc, KeyModifiers::NONE);
|
||||
|
||||
app.chat_widget
|
||||
.set_side_conversation_active(/*active*/ true);
|
||||
assert!(app.chat_widget.composer_is_empty());
|
||||
assert!(!app.should_handle_backtrack_esc(esc));
|
||||
assert!(app.should_reject_side_backtrack_esc(esc));
|
||||
|
||||
app.chat_widget.toggle_vim_mode_and_notify();
|
||||
app.chat_widget
|
||||
.handle_key_event(crossterm::event::KeyEvent::new(
|
||||
crossterm::event::KeyCode::Char('i'),
|
||||
KeyModifiers::NONE,
|
||||
));
|
||||
|
||||
assert!(app.chat_widget.should_handle_vim_insert_escape(esc));
|
||||
assert!(!app.should_handle_backtrack_esc(esc));
|
||||
assert!(!app.should_reject_side_backtrack_esc(esc));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn side_backtrack_rejection_reports_unavailable_message_snapshot() {
|
||||
let (mut app, mut app_event_rx, _op_rx) = make_test_app_with_channels().await;
|
||||
app.backtrack.primed = true;
|
||||
|
||||
app.reject_side_backtrack_esc();
|
||||
|
||||
assert!(!app.backtrack.primed);
|
||||
let cell = match app_event_rx.try_recv() {
|
||||
Ok(AppEvent::InsertHistoryCell(cell)) => cell,
|
||||
other => panic!("expected InsertHistoryCell event, got {other:?}"),
|
||||
};
|
||||
let rendered = cell
|
||||
.display_lines(/*width*/ 80)
|
||||
.into_iter()
|
||||
.map(|line| line.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
assert_app_snapshot!(
|
||||
"side_backtrack_rejection_reports_unavailable_message",
|
||||
rendered
|
||||
);
|
||||
}
|
||||
|
||||
@@ -352,6 +352,7 @@ mod tests {
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: cwd.abs(),
|
||||
runtime_workspace_roots: Vec::new(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: None,
|
||||
message_history: None,
|
||||
|
||||
@@ -510,7 +510,7 @@ impl App {
|
||||
cwd,
|
||||
approval_policy,
|
||||
approvals_reviewer,
|
||||
permission_profile,
|
||||
active_permission_profile,
|
||||
model,
|
||||
effort,
|
||||
summary,
|
||||
@@ -588,12 +588,11 @@ impl App {
|
||||
let config = self.chat_widget.config_ref();
|
||||
let approvals_reviewer =
|
||||
approvals_reviewer.unwrap_or(config.approvals_reviewer);
|
||||
let active_permission_profile =
|
||||
if config.permissions.permission_profile() == permission_profile.clone() {
|
||||
config.permissions.active_permission_profile()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let permissions_override = Self::turn_permissions_override_from_config(
|
||||
config,
|
||||
active_permission_profile.as_ref(),
|
||||
self.runtime_permission_profile_override.as_ref(),
|
||||
);
|
||||
app_server
|
||||
.turn_start(
|
||||
thread_id,
|
||||
@@ -601,8 +600,8 @@ impl App {
|
||||
cwd.clone(),
|
||||
*approval_policy,
|
||||
approvals_reviewer,
|
||||
permission_profile.clone(),
|
||||
active_permission_profile,
|
||||
permissions_override,
|
||||
config.permissions.user_visible_workspace_roots(),
|
||||
model.to_string(),
|
||||
*effort,
|
||||
*summary,
|
||||
@@ -697,6 +696,34 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
fn turn_permissions_override_from_config(
|
||||
config: &Config,
|
||||
active_permission_profile: Option<&ActivePermissionProfile>,
|
||||
runtime_permission_profile_override: Option<&PermissionProfile>,
|
||||
) -> TurnPermissionsOverride {
|
||||
if let Some(active_permission_profile) = active_permission_profile {
|
||||
return TurnPermissionsOverride::ActiveProfile(active_permission_profile.clone());
|
||||
}
|
||||
|
||||
let effective_permission_profile = config.permissions.effective_permission_profile();
|
||||
let runtime_permission_profile_override =
|
||||
runtime_permission_profile_override.map(|profile| {
|
||||
profile
|
||||
.clone()
|
||||
.materialize_project_roots_with_workspace_roots(
|
||||
&config.effective_workspace_roots(),
|
||||
)
|
||||
});
|
||||
if runtime_permission_profile_override
|
||||
.as_ref()
|
||||
.is_some_and(|profile| profile == &effective_permission_profile)
|
||||
{
|
||||
return TurnPermissionsOverride::LegacySandbox(effective_permission_profile);
|
||||
}
|
||||
|
||||
TurnPermissionsOverride::Preserve
|
||||
}
|
||||
|
||||
pub(super) fn handle_skills_list_result(
|
||||
&mut self,
|
||||
result: Result<SkillsListResponse>,
|
||||
@@ -892,7 +919,8 @@ impl App {
|
||||
session.thread_id = thread_id;
|
||||
session.thread_name = notification.thread.name.clone();
|
||||
session.model_provider_id = notification.thread.model_provider.clone();
|
||||
session.cwd = notification.thread.cwd.clone();
|
||||
session
|
||||
.set_cwd_retargeting_implicit_runtime_workspace_root(notification.thread.cwd.clone());
|
||||
let rollout_path = notification.thread.path.clone();
|
||||
if let Some(model) =
|
||||
read_session_model(self.state_db.as_deref(), thread_id, rollout_path.as_deref()).await
|
||||
@@ -1453,3 +1481,77 @@ impl App {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use codex_protocol::models::ActivePermissionProfile;
|
||||
use codex_protocol::models::BUILT_IN_PERMISSION_PROFILE_WORKSPACE;
|
||||
|
||||
async fn config_with_workspace_profile() -> Config {
|
||||
let temp_dir = tempfile::tempdir().expect("tempdir");
|
||||
ConfigBuilder::default()
|
||||
.codex_home(temp_dir.path().to_path_buf())
|
||||
.harness_overrides(ConfigOverrides {
|
||||
default_permissions: Some(BUILT_IN_PERMISSION_PROFILE_WORKSPACE.to_string()),
|
||||
..ConfigOverrides::default()
|
||||
})
|
||||
.build()
|
||||
.await
|
||||
.expect("config should build")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn turn_permissions_use_active_profile_when_available() {
|
||||
let config = config_with_workspace_profile().await;
|
||||
let active_permission_profile = config.permissions.active_permission_profile();
|
||||
|
||||
assert_eq!(
|
||||
App::turn_permissions_override_from_config(
|
||||
&config,
|
||||
active_permission_profile.as_ref(),
|
||||
/*runtime_permission_profile_override*/ None,
|
||||
),
|
||||
TurnPermissionsOverride::ActiveProfile(ActivePermissionProfile::new(
|
||||
BUILT_IN_PERMISSION_PROFILE_WORKSPACE
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn turn_permissions_preserve_server_snapshot_without_local_override() {
|
||||
let mut config = config_with_workspace_profile().await;
|
||||
config
|
||||
.permissions
|
||||
.set_permission_profile(PermissionProfile::read_only())
|
||||
.expect("read-only profile should be allowed");
|
||||
|
||||
assert_eq!(
|
||||
App::turn_permissions_override_from_config(
|
||||
&config, /*active_permission_profile*/ None,
|
||||
/*runtime_permission_profile_override*/ None,
|
||||
),
|
||||
TurnPermissionsOverride::Preserve
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn turn_permissions_send_legacy_sandbox_for_local_override() {
|
||||
let mut config = config_with_workspace_profile().await;
|
||||
let permission_profile = PermissionProfile::workspace_write();
|
||||
config
|
||||
.permissions
|
||||
.set_permission_profile(permission_profile.clone())
|
||||
.expect("workspace profile should be allowed");
|
||||
let effective_permission_profile = config.permissions.effective_permission_profile();
|
||||
|
||||
assert_eq!(
|
||||
App::turn_permissions_override_from_config(
|
||||
&config,
|
||||
/*active_permission_profile*/ None,
|
||||
Some(&permission_profile),
|
||||
),
|
||||
TurnPermissionsOverride::LegacySandbox(effective_permission_profile)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,7 +19,8 @@ impl App {
|
||||
.chat_widget
|
||||
.config_ref()
|
||||
.permissions
|
||||
.permission_profile();
|
||||
.permission_profile()
|
||||
.clone();
|
||||
let active_permission_profile = self
|
||||
.chat_widget
|
||||
.config_ref()
|
||||
@@ -71,6 +72,7 @@ impl App {
|
||||
permission_profile: permission_profile.clone(),
|
||||
active_permission_profile: active_permission_profile.clone(),
|
||||
cwd: thread.cwd.clone(),
|
||||
runtime_workspace_roots: self.config.workspace_roots.clone(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: self.chat_widget.current_reasoning_effort(),
|
||||
message_history: None,
|
||||
@@ -80,7 +82,7 @@ impl App {
|
||||
session.thread_id = thread_id;
|
||||
session.thread_name = thread.name.clone();
|
||||
session.model_provider_id = thread.model_provider.clone();
|
||||
session.cwd = thread.cwd.clone();
|
||||
session.set_cwd_retargeting_implicit_runtime_workspace_root(thread.cwd.clone());
|
||||
session.permission_profile = permission_profile;
|
||||
session.active_permission_profile = active_permission_profile;
|
||||
session.instruction_source_paths = Vec::new();
|
||||
@@ -101,6 +103,7 @@ impl App {
|
||||
.config_ref()
|
||||
.permissions
|
||||
.permission_profile()
|
||||
.clone()
|
||||
}
|
||||
|
||||
fn current_active_permission_profile(&self) -> Option<ActivePermissionProfile> {
|
||||
@@ -117,18 +120,19 @@ mod tests {
|
||||
use crate::app::side::SideThreadState;
|
||||
use crate::app::test_support::make_test_app;
|
||||
use crate::app::thread_events::ThreadEventChannel;
|
||||
use crate::legacy_core::config::PermissionProfileSnapshot;
|
||||
use crate::test_support::PathBufExt;
|
||||
use crate::test_support::test_path_buf;
|
||||
use codex_app_server_protocol::AskForApproval;
|
||||
use codex_app_server_protocol::FileSystemAccessMode;
|
||||
use codex_app_server_protocol::FileSystemPath;
|
||||
use codex_app_server_protocol::FileSystemSandboxEntry;
|
||||
use codex_app_server_protocol::FileSystemSpecialPath;
|
||||
use codex_app_server_protocol::PermissionProfile as AppServerPermissionProfile;
|
||||
use codex_app_server_protocol::PermissionProfileFileSystemPermissions;
|
||||
use codex_app_server_protocol::PermissionProfileNetworkPermissions;
|
||||
use codex_config::types::ApprovalsReviewer;
|
||||
use codex_protocol::models::BUILT_IN_PERMISSION_PROFILE_WORKSPACE;
|
||||
use codex_protocol::models::ManagedFileSystemPermissions;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_protocol::permissions::FileSystemAccessMode;
|
||||
use codex_protocol::permissions::FileSystemPath;
|
||||
use codex_protocol::permissions::FileSystemSandboxEntry;
|
||||
use codex_protocol::permissions::FileSystemSpecialPath;
|
||||
use codex_protocol::permissions::NetworkSandboxPolicy;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -146,6 +150,7 @@ mod tests {
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: cwd.abs(),
|
||||
runtime_workspace_roots: vec![cwd.abs()],
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: None,
|
||||
message_history: None,
|
||||
@@ -193,9 +198,14 @@ mod tests {
|
||||
codex_config::Constrained::allow_any(AskForApproval::OnRequest.to_core());
|
||||
app.config.approvals_reviewer = ApprovalsReviewer::AutoReview;
|
||||
let expected_permission_profile = PermissionProfile::workspace_write();
|
||||
let expected_active_permission_profile =
|
||||
ActivePermissionProfile::new(BUILT_IN_PERMISSION_PROFILE_WORKSPACE);
|
||||
app.chat_widget.handle_thread_session(main_session.clone());
|
||||
app.chat_widget
|
||||
.set_permission_profile(expected_permission_profile.clone())
|
||||
.set_permission_profile_from_session_snapshot(PermissionProfileSnapshot::active(
|
||||
expected_permission_profile.clone(),
|
||||
expected_active_permission_profile.clone(),
|
||||
))
|
||||
.expect("set widget permission profile");
|
||||
app.config
|
||||
.permissions
|
||||
@@ -209,6 +219,7 @@ mod tests {
|
||||
approval_policy: AskForApproval::OnRequest,
|
||||
approvals_reviewer: ApprovalsReviewer::AutoReview,
|
||||
permission_profile: expected_permission_profile,
|
||||
active_permission_profile: Some(expected_active_permission_profile),
|
||||
..main_session
|
||||
};
|
||||
assert_eq!(
|
||||
@@ -244,9 +255,9 @@ mod tests {
|
||||
let mut app = make_test_app().await;
|
||||
let thread_id =
|
||||
ThreadId::from_string("00000000-0000-0000-0000-000000000403").expect("valid thread");
|
||||
let profile: PermissionProfile = AppServerPermissionProfile::Managed {
|
||||
network: PermissionProfileNetworkPermissions { enabled: false },
|
||||
file_system: PermissionProfileFileSystemPermissions::Restricted {
|
||||
let profile: PermissionProfile = PermissionProfile::Managed {
|
||||
network: NetworkSandboxPolicy::Restricted,
|
||||
file_system: ManagedFileSystemPermissions::Restricted {
|
||||
entries: vec![
|
||||
FileSystemSandboxEntry {
|
||||
path: FileSystemPath::Special {
|
||||
@@ -263,8 +274,7 @@ mod tests {
|
||||
],
|
||||
glob_scan_max_depth: None,
|
||||
},
|
||||
}
|
||||
.into();
|
||||
};
|
||||
let session = ThreadSessionState {
|
||||
permission_profile: profile.clone(),
|
||||
..test_thread_session(thread_id, test_path_buf("/tmp/main"))
|
||||
@@ -350,11 +360,12 @@ mod tests {
|
||||
.chat_widget
|
||||
.config_ref()
|
||||
.permissions
|
||||
.permission_profile();
|
||||
.permission_profile()
|
||||
.clone();
|
||||
assert_eq!(session.permission_profile, expected_permission_profile);
|
||||
assert_ne!(
|
||||
session.permission_profile,
|
||||
app.config.permissions.permission_profile(),
|
||||
app.config.permissions.permission_profile().clone(),
|
||||
"thread/read fallback must use the active widget permissions rather than stale app \
|
||||
config defaults"
|
||||
);
|
||||
|
||||
@@ -16,7 +16,7 @@ use codex_protocol::config_types::CollaborationMode;
|
||||
use codex_protocol::config_types::Personality;
|
||||
use codex_protocol::config_types::ReasoningSummary as ReasoningSummaryConfig;
|
||||
use codex_protocol::config_types::WindowsSandboxLevel;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_protocol::models::ActivePermissionProfile;
|
||||
use codex_protocol::openai_models::ReasoningEffort as ReasoningEffortConfig;
|
||||
use codex_protocol::request_permissions::RequestPermissionsResponse;
|
||||
use serde::Serialize;
|
||||
@@ -41,7 +41,7 @@ pub(crate) enum AppCommand {
|
||||
cwd: PathBuf,
|
||||
approval_policy: AskForApproval,
|
||||
approvals_reviewer: Option<ApprovalsReviewer>,
|
||||
permission_profile: PermissionProfile,
|
||||
active_permission_profile: Option<ActivePermissionProfile>,
|
||||
model: String,
|
||||
effort: Option<ReasoningEffortConfig>,
|
||||
summary: Option<ReasoningSummaryConfig>,
|
||||
@@ -54,7 +54,7 @@ pub(crate) enum AppCommand {
|
||||
cwd: Option<PathBuf>,
|
||||
approval_policy: Option<AskForApproval>,
|
||||
approvals_reviewer: Option<ApprovalsReviewer>,
|
||||
permission_profile: Option<PermissionProfile>,
|
||||
active_permission_profile: Option<ActivePermissionProfile>,
|
||||
windows_sandbox_level: Option<WindowsSandboxLevel>,
|
||||
model: Option<String>,
|
||||
effort: Option<Option<ReasoningEffortConfig>>,
|
||||
@@ -142,7 +142,7 @@ impl AppCommand {
|
||||
items: Vec<UserInput>,
|
||||
cwd: PathBuf,
|
||||
approval_policy: AskForApproval,
|
||||
permission_profile: PermissionProfile,
|
||||
active_permission_profile: Option<ActivePermissionProfile>,
|
||||
model: String,
|
||||
effort: Option<ReasoningEffortConfig>,
|
||||
summary: Option<ReasoningSummaryConfig>,
|
||||
@@ -156,7 +156,7 @@ impl AppCommand {
|
||||
cwd,
|
||||
approval_policy,
|
||||
approvals_reviewer: None,
|
||||
permission_profile,
|
||||
active_permission_profile,
|
||||
model,
|
||||
effort,
|
||||
summary,
|
||||
@@ -172,7 +172,7 @@ impl AppCommand {
|
||||
cwd: Option<PathBuf>,
|
||||
approval_policy: Option<AskForApproval>,
|
||||
approvals_reviewer: Option<ApprovalsReviewer>,
|
||||
permission_profile: Option<PermissionProfile>,
|
||||
active_permission_profile: Option<ActivePermissionProfile>,
|
||||
windows_sandbox_level: Option<WindowsSandboxLevel>,
|
||||
model: Option<String>,
|
||||
effort: Option<Option<ReasoningEffortConfig>>,
|
||||
@@ -185,7 +185,7 @@ impl AppCommand {
|
||||
cwd,
|
||||
approval_policy,
|
||||
approvals_reviewer,
|
||||
permission_profile,
|
||||
active_permission_profile,
|
||||
windows_sandbox_level,
|
||||
model,
|
||||
effort,
|
||||
|
||||
@@ -43,7 +43,7 @@ use codex_features::Feature;
|
||||
use codex_plugin::PluginCapabilitySummary;
|
||||
use codex_protocol::config_types::CollaborationModeMask;
|
||||
use codex_protocol::config_types::Personality;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_protocol::models::ActivePermissionProfile;
|
||||
use codex_protocol::openai_models::ReasoningEffort;
|
||||
use codex_realtime_webrtc::RealtimeWebrtcEvent;
|
||||
use codex_realtime_webrtc::RealtimeWebrtcSessionHandle;
|
||||
@@ -742,8 +742,8 @@ pub(crate) enum AppEvent {
|
||||
/// Update the current approval policy in the running app and widget.
|
||||
UpdateAskForApprovalPolicy(AskForApproval),
|
||||
|
||||
/// Update the current permission profile in the running app and widget.
|
||||
UpdatePermissionProfile(PermissionProfile),
|
||||
/// Update the current built-in active permission profile in the running app and widget.
|
||||
UpdateActivePermissionProfile(ActivePermissionProfile),
|
||||
|
||||
/// Update the current approvals reviewer in the running app and widget.
|
||||
UpdateApprovalsReviewer(ApprovalsReviewer),
|
||||
|
||||
@@ -34,7 +34,6 @@ use codex_app_server_protocol::MemoryResetResponse;
|
||||
use codex_app_server_protocol::Model as ApiModel;
|
||||
use codex_app_server_protocol::ModelListParams;
|
||||
use codex_app_server_protocol::ModelListResponse;
|
||||
use codex_app_server_protocol::PermissionProfileModificationParams;
|
||||
use codex_app_server_protocol::PermissionProfileSelectionParams;
|
||||
use codex_app_server_protocol::RateLimitSnapshot;
|
||||
use codex_app_server_protocol::RequestId;
|
||||
@@ -108,7 +107,6 @@ use codex_otel::TelemetryAuthMode;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::approvals::GuardianAssessmentEvent;
|
||||
use codex_protocol::models::ActivePermissionProfile;
|
||||
use codex_protocol::models::ActivePermissionProfileModification;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use codex_protocol::openai_models::ModelAvailabilityNux;
|
||||
@@ -174,6 +172,16 @@ pub(crate) struct AppServerStartedThread {
|
||||
pub(crate) turns: Vec<Turn>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) enum TurnPermissionsOverride {
|
||||
/// Leave the app-server thread's sticky permission profile unchanged.
|
||||
Preserve,
|
||||
/// Select a named or built-in profile by id.
|
||||
ActiveProfile(ActivePermissionProfile),
|
||||
/// Apply a user-selected legacy/custom permission profile.
|
||||
LegacySandbox(PermissionProfile),
|
||||
}
|
||||
|
||||
impl AppServerSession {
|
||||
pub(crate) fn new(client: AppServerClient) -> Self {
|
||||
Self {
|
||||
@@ -550,8 +558,8 @@ impl AppServerSession {
|
||||
cwd: PathBuf,
|
||||
approval_policy: AskForApproval,
|
||||
approvals_reviewer: codex_protocol::config_types::ApprovalsReviewer,
|
||||
permission_profile: PermissionProfile,
|
||||
active_permission_profile: Option<ActivePermissionProfile>,
|
||||
permissions_override: TurnPermissionsOverride,
|
||||
workspace_roots: &[AbsolutePathBuf],
|
||||
model: String,
|
||||
effort: Option<codex_protocol::openai_models::ReasoningEffort>,
|
||||
summary: Option<codex_protocol::config_types::ReasoningSummary>,
|
||||
@@ -561,12 +569,8 @@ impl AppServerSession {
|
||||
output_schema: Option<serde_json::Value>,
|
||||
) -> Result<TurnStartResponse> {
|
||||
let request_id = self.next_request_id();
|
||||
let (sandbox_policy, permissions) = turn_permissions_overrides(
|
||||
&permission_profile,
|
||||
active_permission_profile,
|
||||
cwd.as_path(),
|
||||
self.thread_params_mode(),
|
||||
);
|
||||
let (sandbox_policy, permissions) =
|
||||
turn_permissions_overrides(permissions_override, cwd.as_path());
|
||||
self.client
|
||||
.request_typed(ClientRequest::TurnStart {
|
||||
request_id,
|
||||
@@ -576,6 +580,12 @@ impl AppServerSession {
|
||||
responsesapi_client_metadata: None,
|
||||
environments: None,
|
||||
cwd: Some(cwd),
|
||||
runtime_workspace_roots: Some(
|
||||
workspace_roots
|
||||
.iter()
|
||||
.map(AbsolutePathBuf::to_path_buf)
|
||||
.collect(),
|
||||
),
|
||||
approval_policy: Some(approval_policy),
|
||||
approvals_reviewer: Some(approvals_reviewer.into()),
|
||||
sandbox_policy,
|
||||
@@ -1175,47 +1185,36 @@ fn sandbox_mode_from_permission_profile(
|
||||
fn permissions_selection_from_active_profile(
|
||||
active: ActivePermissionProfile,
|
||||
) -> PermissionProfileSelectionParams {
|
||||
let modifications = active
|
||||
.modifications
|
||||
.into_iter()
|
||||
.map(|modification| match modification {
|
||||
ActivePermissionProfileModification::AdditionalWritableRoot { path } => {
|
||||
PermissionProfileModificationParams::AdditionalWritableRoot { path }
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
PermissionProfileSelectionParams::Profile {
|
||||
id: active.id,
|
||||
modifications: (!modifications.is_empty()).then_some(modifications),
|
||||
}
|
||||
PermissionProfileSelectionParams::new(active.id)
|
||||
}
|
||||
|
||||
fn turn_permissions_overrides(
|
||||
permission_profile: &PermissionProfile,
|
||||
active_permission_profile: Option<ActivePermissionProfile>,
|
||||
permissions_override: TurnPermissionsOverride,
|
||||
cwd: &std::path::Path,
|
||||
thread_params_mode: ThreadParamsMode,
|
||||
) -> (
|
||||
Option<codex_app_server_protocol::SandboxPolicy>,
|
||||
Option<PermissionProfileSelectionParams>,
|
||||
) {
|
||||
let permissions = if matches!(thread_params_mode, ThreadParamsMode::Embedded) {
|
||||
active_permission_profile.map(permissions_selection_from_active_profile)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let sandbox_policy = (matches!(thread_params_mode, ThreadParamsMode::Remote)
|
||||
|| permissions.is_none())
|
||||
.then(|| {
|
||||
let legacy_profile = legacy_compatible_permission_profile(permission_profile, cwd);
|
||||
let policy = legacy_profile
|
||||
.to_legacy_sandbox_policy(cwd)
|
||||
.unwrap_or_else(|err| {
|
||||
unreachable!("legacy-compatible permissions must project to legacy policy: {err}")
|
||||
});
|
||||
policy.into()
|
||||
});
|
||||
(sandbox_policy, permissions)
|
||||
match permissions_override {
|
||||
TurnPermissionsOverride::Preserve => (None, None),
|
||||
TurnPermissionsOverride::ActiveProfile(active_permission_profile) => (
|
||||
None,
|
||||
Some(permissions_selection_from_active_profile(
|
||||
active_permission_profile,
|
||||
)),
|
||||
),
|
||||
TurnPermissionsOverride::LegacySandbox(permission_profile) => {
|
||||
let legacy_profile = legacy_compatible_permission_profile(&permission_profile, cwd);
|
||||
let policy = legacy_profile
|
||||
.to_legacy_sandbox_policy(cwd)
|
||||
.unwrap_or_else(|err| {
|
||||
unreachable!(
|
||||
"legacy-compatible permissions must project to legacy policy: {err}"
|
||||
)
|
||||
});
|
||||
(Some(policy.into()), None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn permissions_selection_from_config(
|
||||
@@ -1243,7 +1242,7 @@ fn thread_start_params_from_config(
|
||||
.is_none()
|
||||
.then(|| {
|
||||
sandbox_mode_from_permission_profile(
|
||||
&config.permissions.permission_profile(),
|
||||
&config.permissions.effective_permission_profile(),
|
||||
config.cwd.as_path(),
|
||||
)
|
||||
})
|
||||
@@ -1253,6 +1252,13 @@ fn thread_start_params_from_config(
|
||||
model_provider: thread_params_mode.model_provider_from_config(config),
|
||||
service_tier: service_tier_override_from_config(config),
|
||||
cwd: thread_cwd_from_config(config, thread_params_mode, remote_cwd_override),
|
||||
runtime_workspace_roots: Some(
|
||||
config
|
||||
.workspace_roots
|
||||
.iter()
|
||||
.map(AbsolutePathBuf::to_path_buf)
|
||||
.collect(),
|
||||
),
|
||||
approval_policy: Some(config.permissions.approval_policy.value().into()),
|
||||
approvals_reviewer: approvals_reviewer_override_from_config(config),
|
||||
sandbox,
|
||||
@@ -1277,7 +1283,7 @@ fn thread_resume_params_from_config(
|
||||
.is_none()
|
||||
.then(|| {
|
||||
sandbox_mode_from_permission_profile(
|
||||
&config.permissions.permission_profile(),
|
||||
&config.permissions.effective_permission_profile(),
|
||||
config.cwd.as_path(),
|
||||
)
|
||||
})
|
||||
@@ -1288,6 +1294,13 @@ fn thread_resume_params_from_config(
|
||||
model_provider: thread_params_mode.model_provider_from_config(&config),
|
||||
service_tier: service_tier_override_from_config(&config),
|
||||
cwd: thread_cwd_from_config(&config, thread_params_mode, remote_cwd_override),
|
||||
runtime_workspace_roots: Some(
|
||||
config
|
||||
.workspace_roots
|
||||
.iter()
|
||||
.map(AbsolutePathBuf::to_path_buf)
|
||||
.collect(),
|
||||
),
|
||||
approval_policy: Some(config.permissions.approval_policy.value().into()),
|
||||
approvals_reviewer: approvals_reviewer_override_from_config(&config),
|
||||
sandbox,
|
||||
@@ -1309,7 +1322,7 @@ fn thread_fork_params_from_config(
|
||||
.is_none()
|
||||
.then(|| {
|
||||
sandbox_mode_from_permission_profile(
|
||||
&config.permissions.permission_profile(),
|
||||
&config.permissions.effective_permission_profile(),
|
||||
config.cwd.as_path(),
|
||||
)
|
||||
})
|
||||
@@ -1320,6 +1333,13 @@ fn thread_fork_params_from_config(
|
||||
model_provider: thread_params_mode.model_provider_from_config(&config),
|
||||
service_tier: service_tier_override_from_config(&config),
|
||||
cwd: thread_cwd_from_config(&config, thread_params_mode, remote_cwd_override),
|
||||
runtime_workspace_roots: Some(
|
||||
config
|
||||
.workspace_roots
|
||||
.iter()
|
||||
.map(AbsolutePathBuf::to_path_buf)
|
||||
.collect(),
|
||||
),
|
||||
approval_policy: Some(config.permissions.approval_policy.value().into()),
|
||||
approvals_reviewer: approvals_reviewer_override_from_config(&config),
|
||||
sandbox,
|
||||
@@ -1397,9 +1417,8 @@ async fn thread_session_state_from_thread_start_response(
|
||||
config: &Config,
|
||||
thread_params_mode: ThreadParamsMode,
|
||||
) -> Result<ThreadSessionState, String> {
|
||||
let permission_profile = permission_profile_from_thread_response(
|
||||
let permission_profile = display_permission_profile_from_thread_response(
|
||||
&response.sandbox,
|
||||
response.permission_profile.as_ref(),
|
||||
response.cwd.as_path(),
|
||||
config,
|
||||
thread_params_mode,
|
||||
@@ -1417,6 +1436,7 @@ async fn thread_session_state_from_thread_start_response(
|
||||
permission_profile,
|
||||
response.active_permission_profile.clone().map(Into::into),
|
||||
response.cwd.clone(),
|
||||
response.runtime_workspace_roots.clone(),
|
||||
response.instruction_sources.clone(),
|
||||
response.reasoning_effort,
|
||||
config,
|
||||
@@ -1429,13 +1449,21 @@ async fn thread_session_state_from_thread_resume_response(
|
||||
config: &Config,
|
||||
thread_params_mode: ThreadParamsMode,
|
||||
) -> Result<ThreadSessionState, String> {
|
||||
let permission_profile = permission_profile_from_thread_response(
|
||||
&response.sandbox,
|
||||
response.permission_profile.as_ref(),
|
||||
response.cwd.as_path(),
|
||||
config,
|
||||
thread_params_mode,
|
||||
);
|
||||
let permission_profile = if matches!(thread_params_mode, ThreadParamsMode::Embedded)
|
||||
&& response.active_permission_profile.is_none()
|
||||
{
|
||||
PermissionProfile::from_legacy_sandbox_policy_for_cwd(
|
||||
&response.sandbox.to_core(),
|
||||
response.cwd.as_path(),
|
||||
)
|
||||
} else {
|
||||
display_permission_profile_from_thread_response(
|
||||
&response.sandbox,
|
||||
response.cwd.as_path(),
|
||||
config,
|
||||
thread_params_mode,
|
||||
)
|
||||
};
|
||||
thread_session_state_from_thread_response(
|
||||
&response.thread.id,
|
||||
response.thread.forked_from_id.clone(),
|
||||
@@ -1449,6 +1477,7 @@ async fn thread_session_state_from_thread_resume_response(
|
||||
permission_profile,
|
||||
response.active_permission_profile.clone().map(Into::into),
|
||||
response.cwd.clone(),
|
||||
response.runtime_workspace_roots.clone(),
|
||||
response.instruction_sources.clone(),
|
||||
response.reasoning_effort,
|
||||
config,
|
||||
@@ -1461,9 +1490,8 @@ async fn thread_session_state_from_thread_fork_response(
|
||||
config: &Config,
|
||||
thread_params_mode: ThreadParamsMode,
|
||||
) -> Result<ThreadSessionState, String> {
|
||||
let permission_profile = permission_profile_from_thread_response(
|
||||
let permission_profile = display_permission_profile_from_thread_response(
|
||||
&response.sandbox,
|
||||
response.permission_profile.as_ref(),
|
||||
response.cwd.as_path(),
|
||||
config,
|
||||
thread_params_mode,
|
||||
@@ -1481,6 +1509,7 @@ async fn thread_session_state_from_thread_fork_response(
|
||||
permission_profile,
|
||||
response.active_permission_profile.clone().map(Into::into),
|
||||
response.cwd.clone(),
|
||||
response.runtime_workspace_roots.clone(),
|
||||
response.instruction_sources.clone(),
|
||||
response.reasoning_effort,
|
||||
config,
|
||||
@@ -1488,18 +1517,14 @@ async fn thread_session_state_from_thread_fork_response(
|
||||
.await
|
||||
}
|
||||
|
||||
fn permission_profile_from_thread_response(
|
||||
fn display_permission_profile_from_thread_response(
|
||||
sandbox: &codex_app_server_protocol::SandboxPolicy,
|
||||
permission_profile: Option<&codex_app_server_protocol::PermissionProfile>,
|
||||
cwd: &std::path::Path,
|
||||
config: &Config,
|
||||
thread_params_mode: ThreadParamsMode,
|
||||
) -> PermissionProfile {
|
||||
if let Some(permission_profile) = permission_profile {
|
||||
return permission_profile.clone().into();
|
||||
}
|
||||
match thread_params_mode {
|
||||
ThreadParamsMode::Embedded => config.permissions.permission_profile(),
|
||||
ThreadParamsMode::Embedded => config.permissions.effective_permission_profile(),
|
||||
ThreadParamsMode::Remote => {
|
||||
PermissionProfile::from_legacy_sandbox_policy_for_cwd(&sandbox.to_core(), cwd)
|
||||
}
|
||||
@@ -1523,6 +1548,7 @@ async fn thread_session_state_from_thread_response(
|
||||
permission_profile: PermissionProfile,
|
||||
active_permission_profile: Option<ActivePermissionProfile>,
|
||||
cwd: AbsolutePathBuf,
|
||||
runtime_workspace_roots: Vec<AbsolutePathBuf>,
|
||||
instruction_source_paths: Vec<AbsolutePathBuf>,
|
||||
reasoning_effort: Option<codex_protocol::openai_models::ReasoningEffort>,
|
||||
config: &Config,
|
||||
@@ -1550,6 +1576,7 @@ async fn thread_session_state_from_thread_response(
|
||||
permission_profile,
|
||||
active_permission_profile,
|
||||
cwd,
|
||||
runtime_workspace_roots,
|
||||
instruction_source_paths,
|
||||
reasoning_effort,
|
||||
message_history: Some(MessageHistoryMetadata {
|
||||
@@ -1577,13 +1604,6 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::legacy_core::config::ConfigBuilder;
|
||||
use crate::legacy_core::config::ConfigOverrides;
|
||||
use codex_app_server_protocol::FileSystemAccessMode;
|
||||
use codex_app_server_protocol::FileSystemPath;
|
||||
use codex_app_server_protocol::FileSystemSandboxEntry;
|
||||
use codex_app_server_protocol::FileSystemSpecialPath;
|
||||
use codex_app_server_protocol::PermissionProfile as AppServerPermissionProfile;
|
||||
use codex_app_server_protocol::PermissionProfileFileSystemPermissions;
|
||||
use codex_app_server_protocol::PermissionProfileNetworkPermissions;
|
||||
use codex_app_server_protocol::ThreadStatus;
|
||||
use codex_app_server_protocol::Turn;
|
||||
use codex_app_server_protocol::TurnStatus;
|
||||
@@ -1594,7 +1614,13 @@ mod tests {
|
||||
use codex_protocol::config_types::WebSearchMode;
|
||||
use codex_protocol::models::BUILT_IN_PERMISSION_PROFILE_READ_ONLY;
|
||||
use codex_protocol::models::BUILT_IN_PERMISSION_PROFILE_WORKSPACE;
|
||||
use codex_protocol::models::ManagedFileSystemPermissions;
|
||||
use codex_protocol::openai_models::ReasoningEffort;
|
||||
use codex_protocol::permissions::FileSystemAccessMode;
|
||||
use codex_protocol::permissions::FileSystemPath;
|
||||
use codex_protocol::permissions::FileSystemSandboxEntry;
|
||||
use codex_protocol::permissions::FileSystemSpecialPath;
|
||||
use codex_protocol::permissions::NetworkSandboxPolicy;
|
||||
use codex_utils_absolute_path::test_support::PathBufExt;
|
||||
use codex_utils_absolute_path::test_support::test_path_buf;
|
||||
use pretty_assertions::assert_eq;
|
||||
@@ -1629,6 +1655,16 @@ mod tests {
|
||||
);
|
||||
|
||||
assert_eq!(params.cwd, Some(config.cwd.to_string_lossy().to_string()));
|
||||
assert_eq!(
|
||||
params.runtime_workspace_roots,
|
||||
Some(
|
||||
config
|
||||
.workspace_roots
|
||||
.iter()
|
||||
.map(AbsolutePathBuf::to_path_buf)
|
||||
.collect()
|
||||
)
|
||||
);
|
||||
assert_eq!(params.sandbox, None);
|
||||
assert_eq!(
|
||||
params.permissions,
|
||||
@@ -1665,10 +1701,8 @@ mod tests {
|
||||
permissions_selection_from_active_profile(active_permission_profile.clone());
|
||||
|
||||
let (sandbox_policy, permissions) = turn_permissions_overrides(
|
||||
&PermissionProfile::workspace_write(),
|
||||
Some(active_permission_profile),
|
||||
TurnPermissionsOverride::ActiveProfile(active_permission_profile),
|
||||
cwd.as_path(),
|
||||
ThreadParamsMode::Embedded,
|
||||
);
|
||||
|
||||
assert_eq!(sandbox_policy, None);
|
||||
@@ -1676,14 +1710,43 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn embedded_turn_permissions_fall_back_to_sandbox_without_active_profile() {
|
||||
fn embedded_turn_permissions_select_profile_id_only() {
|
||||
let cwd = test_path_buf("/workspace/project").abs();
|
||||
let active_permission_profile =
|
||||
ActivePermissionProfile::new(BUILT_IN_PERMISSION_PROFILE_WORKSPACE);
|
||||
|
||||
let (sandbox_policy, permissions) = turn_permissions_overrides(
|
||||
TurnPermissionsOverride::ActiveProfile(active_permission_profile),
|
||||
cwd.as_path(),
|
||||
);
|
||||
|
||||
assert_eq!(sandbox_policy, None);
|
||||
assert_eq!(
|
||||
permissions,
|
||||
Some(PermissionProfileSelectionParams::new(
|
||||
BUILT_IN_PERMISSION_PROFILE_WORKSPACE
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turn_permissions_preserve_thread_permissions_without_override() {
|
||||
let cwd = test_path_buf("/workspace/project").abs();
|
||||
|
||||
let (sandbox_policy, permissions) =
|
||||
turn_permissions_overrides(TurnPermissionsOverride::Preserve, cwd.as_path());
|
||||
|
||||
assert_eq!(sandbox_policy, None);
|
||||
assert_eq!(permissions, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_turn_permissions_project_to_sandbox_when_explicitly_overridden() {
|
||||
let cwd = test_path_buf("/workspace/project").abs();
|
||||
|
||||
let (sandbox_policy, permissions) = turn_permissions_overrides(
|
||||
&PermissionProfile::read_only(),
|
||||
/*active_permission_profile*/ None,
|
||||
TurnPermissionsOverride::LegacySandbox(PermissionProfile::read_only()),
|
||||
cwd.as_path(),
|
||||
ThreadParamsMode::Embedded,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
@@ -1696,25 +1759,19 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_turn_permissions_use_sandbox_even_with_active_profile() {
|
||||
fn remote_turn_permissions_preserve_active_profile_selection() {
|
||||
let cwd = test_path_buf("/workspace/project").abs();
|
||||
let active_permission_profile = ActivePermissionProfile::new("strict");
|
||||
let expected_permissions =
|
||||
permissions_selection_from_active_profile(active_permission_profile.clone());
|
||||
|
||||
let (sandbox_policy, permissions) = turn_permissions_overrides(
|
||||
&PermissionProfile::read_only(),
|
||||
Some(ActivePermissionProfile::new(
|
||||
BUILT_IN_PERMISSION_PROFILE_READ_ONLY,
|
||||
)),
|
||||
TurnPermissionsOverride::ActiveProfile(active_permission_profile),
|
||||
cwd.as_path(),
|
||||
ThreadParamsMode::Remote,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
sandbox_policy,
|
||||
Some(codex_app_server_protocol::SandboxPolicy::ReadOnly {
|
||||
network_access: false
|
||||
})
|
||||
);
|
||||
assert_eq!(permissions, None);
|
||||
assert_eq!(sandbox_policy, None);
|
||||
assert_eq!(permissions, Some(expected_permissions));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -1723,9 +1780,16 @@ mod tests {
|
||||
let config = build_config(&temp_dir).await;
|
||||
let thread_id = ThreadId::new();
|
||||
let expected_sandbox = sandbox_mode_from_permission_profile(
|
||||
&config.permissions.permission_profile(),
|
||||
&config.permissions.effective_permission_profile(),
|
||||
config.cwd.as_path(),
|
||||
);
|
||||
let expected_runtime_workspace_roots = Some(
|
||||
config
|
||||
.workspace_roots
|
||||
.iter()
|
||||
.map(AbsolutePathBuf::to_path_buf)
|
||||
.collect::<Vec<_>>(),
|
||||
);
|
||||
|
||||
let start = thread_start_params_from_config(
|
||||
&config,
|
||||
@@ -1749,6 +1813,18 @@ mod tests {
|
||||
assert_eq!(start.cwd, None);
|
||||
assert_eq!(resume.cwd, None);
|
||||
assert_eq!(fork.cwd, None);
|
||||
assert_eq!(
|
||||
start.runtime_workspace_roots,
|
||||
expected_runtime_workspace_roots
|
||||
);
|
||||
assert_eq!(
|
||||
resume.runtime_workspace_roots,
|
||||
expected_runtime_workspace_roots
|
||||
);
|
||||
assert_eq!(
|
||||
fork.runtime_workspace_roots,
|
||||
expected_runtime_workspace_roots
|
||||
);
|
||||
assert_eq!(start.model_provider, None);
|
||||
assert_eq!(resume.model_provider, None);
|
||||
assert_eq!(fork.model_provider, None);
|
||||
@@ -1766,9 +1842,9 @@ mod tests {
|
||||
fn sandbox_mode_does_not_project_non_cwd_write_roots_for_remote_sessions() {
|
||||
let cwd = test_path_buf("/workspace/project").abs();
|
||||
let extra_root = test_path_buf("/workspace/cache").abs();
|
||||
let permission_profile: PermissionProfile = AppServerPermissionProfile::Managed {
|
||||
network: PermissionProfileNetworkPermissions { enabled: false },
|
||||
file_system: PermissionProfileFileSystemPermissions::Restricted {
|
||||
let permission_profile: PermissionProfile = PermissionProfile::Managed {
|
||||
network: NetworkSandboxPolicy::Restricted,
|
||||
file_system: ManagedFileSystemPermissions::Restricted {
|
||||
entries: vec![
|
||||
FileSystemSandboxEntry {
|
||||
path: FileSystemPath::Special {
|
||||
@@ -1783,8 +1859,7 @@ mod tests {
|
||||
],
|
||||
glob_scan_max_depth: None,
|
||||
},
|
||||
}
|
||||
.into();
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
sandbox_mode_from_permission_profile(&permission_profile, cwd.as_path()),
|
||||
@@ -1795,9 +1870,9 @@ mod tests {
|
||||
#[test]
|
||||
fn sandbox_mode_projects_cwd_write_for_remote_sessions() {
|
||||
let cwd = test_path_buf("/workspace/project").abs();
|
||||
let permission_profile: PermissionProfile = AppServerPermissionProfile::Managed {
|
||||
network: PermissionProfileNetworkPermissions { enabled: false },
|
||||
file_system: PermissionProfileFileSystemPermissions::Restricted {
|
||||
let permission_profile: PermissionProfile = PermissionProfile::Managed {
|
||||
network: NetworkSandboxPolicy::Restricted,
|
||||
file_system: ManagedFileSystemPermissions::Restricted {
|
||||
entries: vec![
|
||||
FileSystemSandboxEntry {
|
||||
path: FileSystemPath::Special {
|
||||
@@ -1814,8 +1889,7 @@ mod tests {
|
||||
],
|
||||
glob_scan_max_depth: None,
|
||||
},
|
||||
}
|
||||
.into();
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
sandbox_mode_from_permission_profile(&permission_profile, cwd.as_path()),
|
||||
@@ -1830,7 +1904,7 @@ mod tests {
|
||||
let thread_id = ThreadId::new();
|
||||
let remote_cwd = PathBuf::from("repo/on/server");
|
||||
let expected_sandbox = sandbox_mode_from_permission_profile(
|
||||
&config.permissions.permission_profile(),
|
||||
&config.permissions.effective_permission_profile(),
|
||||
config.cwd.as_path(),
|
||||
);
|
||||
|
||||
@@ -2019,6 +2093,10 @@ mod tests {
|
||||
model_provider: "openai".to_string(),
|
||||
service_tier: None,
|
||||
cwd: test_path_buf("/tmp/project").abs(),
|
||||
runtime_workspace_roots: vec![
|
||||
test_path_buf("/tmp/project").abs(),
|
||||
test_path_buf("/tmp/project/extra").abs(),
|
||||
],
|
||||
instruction_sources: vec![test_path_buf("/tmp/project/AGENTS.md").abs()],
|
||||
approval_policy: codex_app_server_protocol::AskForApproval::Never,
|
||||
approvals_reviewer: codex_app_server_protocol::ApprovalsReviewer::User,
|
||||
@@ -2026,7 +2104,6 @@ mod tests {
|
||||
.to_legacy_sandbox_policy(test_path_buf("/tmp/project").as_path())
|
||||
.expect("read-only profile must be legacy-compatible")
|
||||
.into(),
|
||||
permission_profile: Some(read_only_profile.clone().into()),
|
||||
active_permission_profile: None,
|
||||
reasoning_effort: None,
|
||||
};
|
||||
@@ -2039,6 +2116,10 @@ mod tests {
|
||||
.await
|
||||
.expect("resume response should map");
|
||||
assert_eq!(started.session.forked_from_id, Some(forked_from_id));
|
||||
assert_eq!(
|
||||
started.session.runtime_workspace_roots,
|
||||
response.runtime_workspace_roots
|
||||
);
|
||||
assert_eq!(
|
||||
started.session.instruction_source_paths,
|
||||
response.instruction_sources
|
||||
@@ -2046,64 +2127,75 @@ mod tests {
|
||||
assert_eq!(started.session.permission_profile, read_only_profile);
|
||||
assert_eq!(started.turns.len(), 1);
|
||||
assert_eq!(started.turns[0], response.thread.turns[0]);
|
||||
|
||||
let embedded_config = ConfigBuilder::default()
|
||||
.codex_home(temp_dir.path().join("embedded-codex-home"))
|
||||
.harness_overrides(ConfigOverrides {
|
||||
default_permissions: Some(BUILT_IN_PERMISSION_PROFILE_WORKSPACE.to_string()),
|
||||
..ConfigOverrides::default()
|
||||
})
|
||||
.build()
|
||||
.await
|
||||
.expect("config should build");
|
||||
let started = started_thread_from_resume_response(
|
||||
response.clone(),
|
||||
&embedded_config,
|
||||
ThreadParamsMode::Embedded,
|
||||
)
|
||||
.await
|
||||
.expect("embedded resume response should map");
|
||||
assert_eq!(started.session.permission_profile, read_only_profile);
|
||||
|
||||
let mut empty_roots_response = response;
|
||||
empty_roots_response.runtime_workspace_roots = Vec::new();
|
||||
let started = started_thread_from_resume_response(
|
||||
empty_roots_response,
|
||||
&config,
|
||||
ThreadParamsMode::Remote,
|
||||
)
|
||||
.await
|
||||
.expect("resume response should map");
|
||||
assert_eq!(started.session.runtime_workspace_roots, Vec::new());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_thread_response_prefers_permission_profile_over_legacy_sandbox() {
|
||||
async fn remote_thread_response_uses_legacy_sandbox_fallback() {
|
||||
let temp_dir = tempfile::tempdir().expect("tempdir");
|
||||
let config = build_config(&temp_dir).await;
|
||||
let cwd = test_path_buf("/tmp/project").abs();
|
||||
let fallback_sandbox = PermissionProfile::read_only()
|
||||
let sandbox = PermissionProfile::read_only()
|
||||
.to_legacy_sandbox_policy(cwd.as_path())
|
||||
.expect("read-only profile must be legacy-compatible")
|
||||
.into();
|
||||
let response_profile = AppServerPermissionProfile::Managed {
|
||||
file_system: PermissionProfileFileSystemPermissions::Restricted {
|
||||
entries: vec![
|
||||
FileSystemSandboxEntry {
|
||||
path: FileSystemPath::Special {
|
||||
value: FileSystemSpecialPath::Root,
|
||||
},
|
||||
access: FileSystemAccessMode::Read,
|
||||
},
|
||||
FileSystemSandboxEntry {
|
||||
path: FileSystemPath::Special {
|
||||
value: FileSystemSpecialPath::ProjectRoots {
|
||||
subpath: Some(".env".into()),
|
||||
},
|
||||
},
|
||||
access: FileSystemAccessMode::None,
|
||||
},
|
||||
],
|
||||
glob_scan_max_depth: None,
|
||||
},
|
||||
network: PermissionProfileNetworkPermissions { enabled: false },
|
||||
};
|
||||
let split_profile: PermissionProfile = response_profile.clone().into();
|
||||
|
||||
assert_eq!(
|
||||
permission_profile_from_thread_response(
|
||||
&fallback_sandbox,
|
||||
Some(&response_profile),
|
||||
display_permission_profile_from_thread_response(
|
||||
&sandbox,
|
||||
cwd.as_path(),
|
||||
&config,
|
||||
ThreadParamsMode::Remote,
|
||||
),
|
||||
split_profile
|
||||
PermissionProfile::read_only()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn embedded_thread_response_prefers_permission_profile_when_present() {
|
||||
async fn embedded_thread_response_uses_local_config_profile() {
|
||||
let temp_dir = tempfile::tempdir().expect("tempdir");
|
||||
let config = build_config(&temp_dir).await;
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(temp_dir.path().to_path_buf())
|
||||
.harness_overrides(ConfigOverrides {
|
||||
default_permissions: Some(BUILT_IN_PERMISSION_PROFILE_READ_ONLY.to_string()),
|
||||
..ConfigOverrides::default()
|
||||
})
|
||||
.build()
|
||||
.await
|
||||
.expect("config should build");
|
||||
let cwd = test_path_buf("/tmp/project").abs();
|
||||
let response_profile = PermissionProfile::read_only().into();
|
||||
|
||||
assert_eq!(
|
||||
permission_profile_from_thread_response(
|
||||
display_permission_profile_from_thread_response(
|
||||
&codex_app_server_protocol::SandboxPolicy::DangerFullAccess,
|
||||
Some(&response_profile),
|
||||
cwd.as_path(),
|
||||
&config,
|
||||
ThreadParamsMode::Embedded,
|
||||
@@ -2142,6 +2234,7 @@ mod tests {
|
||||
/*active_permission_profile*/ None,
|
||||
test_path_buf("/tmp/project").abs(),
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
/*reasoning_effort*/ None,
|
||||
&config,
|
||||
)
|
||||
@@ -2176,6 +2269,7 @@ mod tests {
|
||||
/*active_permission_profile*/ None,
|
||||
test_path_buf("/tmp/project").abs(),
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
/*reasoning_effort*/ None,
|
||||
&config,
|
||||
)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,45 @@
|
||||
//! Editable composer draft state kept separate from composer control flow.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::bottom_pane::MentionBinding;
|
||||
use crate::bottom_pane::paste_burst::PasteBurst;
|
||||
use crate::bottom_pane::textarea::TextArea;
|
||||
use crate::bottom_pane::textarea::TextAreaState;
|
||||
|
||||
pub(super) struct DraftState {
|
||||
pub(super) textarea: TextArea,
|
||||
pub(super) textarea_state: RefCell<TextAreaState>,
|
||||
pub(super) is_bash_mode: bool,
|
||||
pub(super) pending_pastes: Vec<(String, String)>,
|
||||
pub(super) input_enabled: bool,
|
||||
pub(super) input_disabled_placeholder: Option<String>,
|
||||
pub(super) paste_burst: PasteBurst,
|
||||
pub(super) disable_paste_burst: bool,
|
||||
pub(super) mention_bindings: HashMap<u64, ComposerMentionBinding>,
|
||||
pub(super) recent_submission_mention_bindings: Vec<MentionBinding>,
|
||||
}
|
||||
|
||||
impl DraftState {
|
||||
pub(super) fn new() -> Self {
|
||||
Self {
|
||||
textarea: TextArea::new(),
|
||||
textarea_state: RefCell::new(TextAreaState::default()),
|
||||
is_bash_mode: false,
|
||||
pending_pastes: Vec::new(),
|
||||
input_enabled: true,
|
||||
input_disabled_placeholder: None,
|
||||
paste_burst: PasteBurst::default(),
|
||||
disable_paste_burst: false,
|
||||
mention_bindings: HashMap::new(),
|
||||
recent_submission_mention_bindings: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct ComposerMentionBinding {
|
||||
pub(super) mention: String,
|
||||
pub(super) path: String,
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
//! Footer and status-row presentation state for the chat composer.
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
use ratatui::text::Line;
|
||||
|
||||
use crate::bottom_pane::footer::CollaborationModeIndicator;
|
||||
use crate::bottom_pane::footer::FooterMode;
|
||||
use crate::bottom_pane::footer::GoalStatusIndicator;
|
||||
use crate::key_hint::KeyBinding;
|
||||
#[cfg(test)]
|
||||
use std::time::Duration;
|
||||
|
||||
pub(super) struct FooterState {
|
||||
pub(super) quit_shortcut_expires_at: Option<Instant>,
|
||||
pub(super) quit_shortcut_key: KeyBinding,
|
||||
pub(super) esc_backtrack_hint: bool,
|
||||
pub(super) use_shift_enter_hint: bool,
|
||||
pub(super) mode: FooterMode,
|
||||
pub(super) hint_override: Option<Vec<(String, String)>>,
|
||||
pub(super) plan_mode_nudge_visible: bool,
|
||||
pub(super) flash: Option<FooterFlash>,
|
||||
pub(super) context_window_percent: Option<i64>,
|
||||
pub(super) context_window_used_tokens: Option<i64>,
|
||||
pub(super) collaboration_mode_indicator: Option<CollaborationModeIndicator>,
|
||||
pub(super) goal_status_indicator: Option<GoalStatusIndicator>,
|
||||
pub(super) ide_context_active: bool,
|
||||
pub(super) status_line_value: Option<Line<'static>>,
|
||||
pub(super) status_line_hyperlink_url: Option<String>,
|
||||
pub(super) status_line_enabled: bool,
|
||||
pub(super) side_conversation_context_label: Option<String>,
|
||||
pub(super) active_agent_label: Option<String>,
|
||||
pub(super) external_editor_key: Option<KeyBinding>,
|
||||
pub(super) show_transcript_key: Option<KeyBinding>,
|
||||
pub(super) insert_newline_key: Option<KeyBinding>,
|
||||
pub(super) queue_key: Option<KeyBinding>,
|
||||
pub(super) toggle_shortcuts_key: Option<KeyBinding>,
|
||||
pub(super) history_search_key: Option<KeyBinding>,
|
||||
pub(super) reasoning_down_key: Option<KeyBinding>,
|
||||
pub(super) reasoning_up_key: Option<KeyBinding>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct FooterFlash {
|
||||
pub(super) line: Line<'static>,
|
||||
pub(super) expires_at: Instant,
|
||||
}
|
||||
|
||||
impl FooterState {
|
||||
pub(super) fn flash_visible(&self) -> bool {
|
||||
self.flash
|
||||
.as_ref()
|
||||
.is_some_and(|flash| Instant::now() < flash.expires_at)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn show_flash(&mut self, line: Line<'static>, duration: Duration) {
|
||||
let expires_at = Instant::now()
|
||||
.checked_add(duration)
|
||||
.unwrap_or_else(Instant::now);
|
||||
self.flash = Some(FooterFlash { line, expires_at });
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn status_line_text(&self) -> Option<String> {
|
||||
self.status_line_value.as_ref().map(|line| {
|
||||
line.spans
|
||||
.iter()
|
||||
.map(|span| span.content.as_ref())
|
||||
.collect::<String>()
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -102,10 +102,10 @@ impl ChatComposer {
|
||||
/// from replacing an empty composer with the latest prompt before the user has searched for
|
||||
/// anything.
|
||||
pub(super) fn begin_history_search(&mut self) -> (InputResult, bool) {
|
||||
if let Some(pasted) = self.paste_burst.flush_before_modified_input() {
|
||||
if let Some(pasted) = self.draft.paste_burst.flush_before_modified_input() {
|
||||
self.handle_paste(pasted);
|
||||
}
|
||||
self.paste_burst.clear_window_after_non_char();
|
||||
self.draft.paste_burst.clear_window_after_non_char();
|
||||
|
||||
if self.popups.current_file_query.is_some() {
|
||||
self.app_event_tx
|
||||
@@ -185,7 +185,7 @@ impl ChatComposer {
|
||||
{
|
||||
self.history_search = None;
|
||||
self.history.reset_search();
|
||||
self.footer_mode = reset_mode_after_activity(self.footer_mode);
|
||||
self.footer.mode = reset_mode_after_activity(self.footer.mode);
|
||||
self.move_cursor_to_end();
|
||||
}
|
||||
(InputResult::None, true)
|
||||
@@ -296,7 +296,7 @@ impl ChatComposer {
|
||||
return false;
|
||||
};
|
||||
self.history.reset_navigation();
|
||||
self.footer_mode = reset_mode_after_activity(self.footer_mode);
|
||||
self.footer.mode = reset_mode_after_activity(self.footer.mode);
|
||||
self.restore_draft(search.original_draft);
|
||||
true
|
||||
}
|
||||
@@ -385,7 +385,7 @@ impl ChatComposer {
|
||||
if !matches!(search.status, HistorySearchStatus::Match) || search.query.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
Self::case_insensitive_match_ranges(self.textarea.text(), &search.query)
|
||||
Self::case_insensitive_match_ranges(self.draft.textarea.text(), &search.query)
|
||||
}
|
||||
|
||||
fn case_insensitive_match_ranges(text: &str, query: &str) -> Vec<Range<usize>> {
|
||||
@@ -520,7 +520,7 @@ mod tests {
|
||||
let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL));
|
||||
|
||||
assert!(composer.history_search_active());
|
||||
assert!(composer.textarea.is_empty());
|
||||
assert!(composer.draft.textarea.is_empty());
|
||||
assert_eq!(composer.footer_mode(), FooterMode::HistorySearch);
|
||||
}
|
||||
|
||||
@@ -558,18 +558,21 @@ mod tests {
|
||||
|
||||
let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL));
|
||||
assert!(composer.history_search_active());
|
||||
assert_eq!(composer.textarea.text(), "draft");
|
||||
assert_eq!(composer.draft.textarea.text(), "draft");
|
||||
|
||||
for ch in ['g', 'i', 't'] {
|
||||
let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::NONE));
|
||||
}
|
||||
assert_eq!(composer.textarea.text(), "git status");
|
||||
assert_eq!(composer.draft.textarea.text(), "git status");
|
||||
assert_eq!(composer.footer_mode(), FooterMode::HistorySearch);
|
||||
|
||||
let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
|
||||
assert!(!composer.history_search_active());
|
||||
assert_eq!(composer.textarea.text(), "git status");
|
||||
assert_eq!(composer.textarea.cursor(), composer.textarea.text().len());
|
||||
assert_eq!(composer.draft.textarea.text(), "git status");
|
||||
assert_eq!(
|
||||
composer.draft.textarea.cursor(),
|
||||
composer.draft.textarea.text().len()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -593,8 +596,8 @@ mod tests {
|
||||
let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::NONE));
|
||||
}
|
||||
|
||||
assert_eq!(composer.textarea.text(), "git status");
|
||||
assert_eq!(composer.textarea.cursor(), "git status".len() - 1);
|
||||
assert_eq!(composer.draft.textarea.text(), "git status");
|
||||
assert_eq!(composer.draft.textarea.cursor(), "git status".len() - 1);
|
||||
assert_eq!(composer.footer_mode(), FooterMode::HistorySearch);
|
||||
}
|
||||
|
||||
@@ -618,13 +621,19 @@ mod tests {
|
||||
for ch in ['b', 'u', 'g'] {
|
||||
let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::NONE));
|
||||
}
|
||||
assert_eq!(composer.textarea.text(), "Find and fix a bug in @filename");
|
||||
assert_eq!(
|
||||
composer.draft.textarea.text(),
|
||||
"Find and fix a bug in @filename"
|
||||
);
|
||||
|
||||
for _ in 0..3 {
|
||||
let _ =
|
||||
composer.handle_key_event(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL));
|
||||
}
|
||||
assert_eq!(composer.textarea.text(), "Find and fix a bug in @filename");
|
||||
assert_eq!(
|
||||
composer.draft.textarea.text(),
|
||||
"Find and fix a bug in @filename"
|
||||
);
|
||||
assert!(
|
||||
composer
|
||||
.history_search
|
||||
@@ -635,7 +644,10 @@ mod tests {
|
||||
for _ in 0..3 {
|
||||
let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE));
|
||||
}
|
||||
assert_eq!(composer.textarea.text(), "Find and fix a bug in @filename");
|
||||
assert_eq!(
|
||||
composer.draft.textarea.text(),
|
||||
"Find and fix a bug in @filename"
|
||||
);
|
||||
assert!(
|
||||
composer
|
||||
.history_search
|
||||
@@ -776,17 +788,17 @@ mod tests {
|
||||
.history
|
||||
.record_local_submission(HistoryEntry::new("remembered command".to_string()));
|
||||
composer.set_text_content("draft".to_string(), Vec::new(), Vec::new());
|
||||
composer.textarea.set_cursor(/*pos*/ 2);
|
||||
composer.draft.textarea.set_cursor(/*pos*/ 2);
|
||||
|
||||
let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL));
|
||||
assert_eq!(composer.textarea.text(), "draft");
|
||||
assert_eq!(composer.draft.textarea.text(), "draft");
|
||||
let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::NONE));
|
||||
assert_eq!(composer.textarea.text(), "remembered command");
|
||||
assert_eq!(composer.draft.textarea.text(), "remembered command");
|
||||
|
||||
let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
|
||||
assert!(!composer.history_search_active());
|
||||
assert_eq!(composer.textarea.text(), "draft");
|
||||
assert_eq!(composer.textarea.cursor(), 2);
|
||||
assert_eq!(composer.draft.textarea.text(), "draft");
|
||||
assert_eq!(composer.draft.textarea.cursor(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -805,13 +817,13 @@ mod tests {
|
||||
.history
|
||||
.record_local_submission(HistoryEntry::new("remembered command".to_string()));
|
||||
composer.set_text_content("draft".to_string(), Vec::new(), Vec::new());
|
||||
composer.textarea.set_cursor(/*pos*/ 2);
|
||||
composer.draft.textarea.set_cursor(/*pos*/ 2);
|
||||
|
||||
let _ =
|
||||
composer.handle_key_event(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL));
|
||||
let _ =
|
||||
composer.handle_key_event(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::NONE));
|
||||
assert_eq!(composer.textarea.text(), "remembered command");
|
||||
assert_eq!(composer.draft.textarea.text(), "remembered command");
|
||||
composer
|
||||
}
|
||||
|
||||
@@ -824,8 +836,8 @@ mod tests {
|
||||
let _ = composer.handle_key_event(cancel_key);
|
||||
|
||||
assert!(!composer.history_search_active());
|
||||
assert_eq!(composer.textarea.text(), "draft");
|
||||
assert_eq!(composer.textarea.cursor(), 2);
|
||||
assert_eq!(composer.draft.textarea.text(), "draft");
|
||||
assert_eq!(composer.draft.textarea.cursor(), 2);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -843,18 +855,18 @@ mod tests {
|
||||
|
||||
let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Char('h'), KeyModifiers::NONE));
|
||||
assert!(composer.is_in_paste_burst());
|
||||
assert_eq!(composer.textarea.text(), "");
|
||||
assert_eq!(composer.draft.textarea.text(), "");
|
||||
|
||||
let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL));
|
||||
|
||||
assert!(composer.history_search_active());
|
||||
assert!(!composer.is_in_paste_burst());
|
||||
assert_eq!(composer.textarea.text(), "h");
|
||||
assert_eq!(composer.draft.textarea.text(), "h");
|
||||
|
||||
let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
|
||||
|
||||
assert!(!composer.history_search_active());
|
||||
assert_eq!(composer.textarea.text(), "h");
|
||||
assert_eq!(composer.draft.textarea.text(), "h");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -881,18 +893,18 @@ mod tests {
|
||||
now += Duration::from_millis(1);
|
||||
}
|
||||
assert!(composer.is_in_paste_burst());
|
||||
assert_eq!(composer.textarea.text(), "");
|
||||
assert_eq!(composer.draft.textarea.text(), "");
|
||||
|
||||
let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL));
|
||||
|
||||
assert!(composer.history_search_active());
|
||||
assert!(!composer.is_in_paste_burst());
|
||||
assert_eq!(composer.textarea.text(), "paste");
|
||||
assert_eq!(composer.draft.textarea.text(), "paste");
|
||||
|
||||
let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
|
||||
|
||||
assert!(!composer.history_search_active());
|
||||
assert_eq!(composer.textarea.text(), "paste");
|
||||
assert_eq!(composer.draft.textarea.text(), "paste");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -918,14 +930,14 @@ mod tests {
|
||||
for ch in ['m', 'a', 't', 'c', 'h'] {
|
||||
let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::NONE));
|
||||
}
|
||||
assert_eq!(composer.textarea.text(), "oldest matching entry");
|
||||
assert_eq!(composer.draft.textarea.text(), "oldest matching entry");
|
||||
|
||||
let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
|
||||
assert!(!composer.history_search_active());
|
||||
assert!(composer.textarea.is_empty());
|
||||
assert!(composer.draft.textarea.is_empty());
|
||||
|
||||
let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Up, KeyModifiers::NONE));
|
||||
assert_eq!(composer.textarea.text(), "newest entry");
|
||||
assert_eq!(composer.draft.textarea.text(), "newest entry");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -950,7 +962,7 @@ mod tests {
|
||||
}
|
||||
|
||||
assert!(composer.history_search_active());
|
||||
assert_eq!(composer.textarea.text(), "draft");
|
||||
assert_eq!(composer.draft.textarea.text(), "draft");
|
||||
assert_eq!(composer.footer_mode(), FooterMode::HistorySearch);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -808,18 +808,20 @@ impl BottomPane {
|
||||
self.composer.current_text()
|
||||
}
|
||||
|
||||
pub(crate) fn composer_draft_snapshot(&self) -> chat_composer::ComposerDraftSnapshot {
|
||||
self.composer.draft_snapshot()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn composer_text_elements(&self) -> Vec<TextElement> {
|
||||
self.composer.text_elements()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn composer_local_images(&self) -> Vec<LocalImageAttachment> {
|
||||
self.composer.local_images()
|
||||
}
|
||||
|
||||
pub(crate) fn composer_mention_bindings(&self) -> Vec<MentionBinding> {
|
||||
self.composer.mention_bindings()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn composer_local_image_paths(&self) -> Vec<PathBuf> {
|
||||
self.composer.local_image_paths()
|
||||
@@ -865,6 +867,7 @@ impl BottomPane {
|
||||
self.request_redraw();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn remote_image_urls(&self) -> Vec<String> {
|
||||
self.composer.remote_image_urls()
|
||||
}
|
||||
|
||||
@@ -61,6 +61,7 @@ use crate::legacy_core::DEFAULT_AGENTS_MD_FILENAME;
|
||||
use crate::legacy_core::config::Config;
|
||||
use crate::legacy_core::config::Constrained;
|
||||
use crate::legacy_core::config::ConstraintResult;
|
||||
use crate::legacy_core::config::PermissionProfileSnapshot;
|
||||
#[cfg(target_os = "windows")]
|
||||
use crate::legacy_core::windows_sandbox::WindowsSandboxLevelExt;
|
||||
use crate::mention_codec::LinkedMention;
|
||||
@@ -165,6 +166,7 @@ use codex_terminal_detection::TerminalInfo;
|
||||
use codex_terminal_detection::TerminalName;
|
||||
use codex_terminal_detection::terminal_info;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_cli::resume_command;
|
||||
use crossterm::event::KeyCode;
|
||||
use crossterm::event::KeyEvent;
|
||||
use crossterm::event::KeyEventKind;
|
||||
@@ -441,6 +443,7 @@ use crate::workspace_command::WorkspaceCommandRunner;
|
||||
use chrono::Local;
|
||||
use codex_app_server_protocol::AskForApproval;
|
||||
use codex_file_search::FileMatch;
|
||||
use codex_protocol::models::ActivePermissionProfile;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_protocol::openai_models::InputModality;
|
||||
use codex_protocol::openai_models::ModelPreset;
|
||||
@@ -1433,8 +1436,8 @@ impl ChatWidget {
|
||||
}
|
||||
|
||||
fn rename_confirmation_cell(name: &str, thread_id: Option<ThreadId>) -> PlainHistoryCell {
|
||||
let resume_cmd = crate::legacy_core::util::resume_command(Some(name), thread_id)
|
||||
.unwrap_or_else(|| format!("codex resume {name}"));
|
||||
let resume_cmd =
|
||||
resume_command(Some(name), thread_id).unwrap_or_else(|| format!("codex resume {name}"));
|
||||
let name = name.to_string();
|
||||
let line = vec![
|
||||
"• ".into(),
|
||||
|
||||
@@ -152,12 +152,13 @@ impl ChatWidget {
|
||||
return None;
|
||||
}
|
||||
|
||||
let composer = self.bottom_pane.composer_draft_snapshot();
|
||||
let existing_message = UserMessage {
|
||||
text: self.bottom_pane.composer_text(),
|
||||
text_elements: self.bottom_pane.composer_text_elements(),
|
||||
local_images: self.bottom_pane.composer_local_images(),
|
||||
remote_image_urls: self.bottom_pane.remote_image_urls(),
|
||||
mention_bindings: self.bottom_pane.composer_mention_bindings(),
|
||||
text: composer.text,
|
||||
text_elements: composer.text_elements,
|
||||
local_images: composer.local_images,
|
||||
remote_image_urls: composer.remote_image_urls,
|
||||
mention_bindings: composer.mention_bindings,
|
||||
};
|
||||
|
||||
let rejected_messages = self
|
||||
@@ -236,13 +237,14 @@ impl ChatWidget {
|
||||
}
|
||||
|
||||
pub(crate) fn capture_thread_input_state(&self) -> Option<ThreadInputState> {
|
||||
let draft = self.bottom_pane.composer_draft_snapshot();
|
||||
let composer = ThreadComposerState {
|
||||
text: self.bottom_pane.composer_text(),
|
||||
text_elements: self.bottom_pane.composer_text_elements(),
|
||||
local_images: self.bottom_pane.composer_local_images(),
|
||||
remote_image_urls: self.bottom_pane.remote_image_urls(),
|
||||
mention_bindings: self.bottom_pane.composer_mention_bindings(),
|
||||
pending_pastes: self.bottom_pane.composer_pending_pastes(),
|
||||
text: draft.text,
|
||||
text_elements: draft.text_elements,
|
||||
local_images: draft.local_images,
|
||||
remote_image_urls: draft.remote_image_urls,
|
||||
mention_bindings: draft.mention_bindings,
|
||||
pending_pastes: draft.pending_pastes,
|
||||
};
|
||||
Some(ThreadInputState {
|
||||
composer: composer.has_content().then_some(composer),
|
||||
|
||||
@@ -164,12 +164,14 @@ impl ChatWidget {
|
||||
for image_url in &remote_image_urls {
|
||||
items.push(UserInput::Image {
|
||||
url: image_url.clone(),
|
||||
detail: None,
|
||||
});
|
||||
}
|
||||
|
||||
for image in &local_images {
|
||||
items.push(UserInput::LocalImage {
|
||||
path: image.path.clone(),
|
||||
detail: None,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -334,12 +336,12 @@ impl ChatWidget {
|
||||
None if self.config.notices.fast_default_opt_out == Some(true) => Some(None),
|
||||
None => None,
|
||||
};
|
||||
let permission_profile = self.config.permissions.permission_profile();
|
||||
let active_permission_profile = self.config.permissions.active_permission_profile();
|
||||
let op = AppCommand::user_turn(
|
||||
items,
|
||||
self.config.cwd.to_path_buf(),
|
||||
AskForApproval::from(self.config.permissions.approval_policy.value()),
|
||||
permission_profile,
|
||||
active_permission_profile,
|
||||
effective_mode.model().to_string(),
|
||||
effective_mode.reasoning_effort(),
|
||||
/*summary*/ None,
|
||||
|
||||
@@ -11,6 +11,9 @@ use codex_app_server_protocol::McpServerStatusUpdatedNotification;
|
||||
|
||||
use super::ChatWidget;
|
||||
|
||||
const MCP_STARTUP_SINGLE_HEADER_PREFIX: &str = "Booting MCP server:";
|
||||
const MCP_STARTUP_MULTI_HEADER_PREFIX: &str = "Starting MCP servers";
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) enum McpStartupStatus {
|
||||
Starting,
|
||||
@@ -153,11 +156,11 @@ impl ChatWidget {
|
||||
}
|
||||
let header = if total > 1 {
|
||||
format!(
|
||||
"Starting MCP servers ({completed}/{total}): {}",
|
||||
"{MCP_STARTUP_MULTI_HEADER_PREFIX} ({completed}/{total}): {}",
|
||||
to_show.join(", ")
|
||||
)
|
||||
} else {
|
||||
format!("Booting MCP server: {first}")
|
||||
format!("{MCP_STARTUP_SINGLE_HEADER_PREFIX} {first}")
|
||||
};
|
||||
self.set_status_header(header);
|
||||
}
|
||||
@@ -187,12 +190,16 @@ impl ChatWidget {
|
||||
self.on_warning(format!("MCP startup incomplete ({})", parts.join("; ")));
|
||||
}
|
||||
|
||||
let mcp_startup_owned_status = self.status_header_is_mcp_startup_owned();
|
||||
self.mcp_startup_status = None;
|
||||
self.mcp_startup_ignore_updates_until_next_start = true;
|
||||
self.mcp_startup_allow_terminal_only_next_round = false;
|
||||
self.mcp_startup_pending_next_round.clear();
|
||||
self.mcp_startup_pending_next_round_saw_starting = false;
|
||||
self.update_task_running_state();
|
||||
if self.bottom_pane.is_task_running() && mcp_startup_owned_status {
|
||||
self.restore_reasoning_status_header();
|
||||
}
|
||||
self.maybe_send_next_queued_input();
|
||||
self.request_redraw();
|
||||
}
|
||||
@@ -234,6 +241,18 @@ impl ChatWidget {
|
||||
self.finish_mcp_startup(failed, cancelled);
|
||||
}
|
||||
|
||||
pub(super) fn status_header_is_mcp_startup_owned(&self) -> bool {
|
||||
self.status_state
|
||||
.current_status
|
||||
.header
|
||||
.starts_with(MCP_STARTUP_SINGLE_HEADER_PREFIX)
|
||||
|| self
|
||||
.status_state
|
||||
.current_status
|
||||
.header
|
||||
.starts_with(MCP_STARTUP_MULTI_HEADER_PREFIX)
|
||||
}
|
||||
|
||||
pub(super) fn on_mcp_server_status_updated(
|
||||
&mut self,
|
||||
notification: McpServerStatusUpdatedNotification,
|
||||
|
||||
@@ -17,7 +17,7 @@ impl ChatWidget {
|
||||
let include_read_only = cfg!(target_os = "windows");
|
||||
let current_approval =
|
||||
AskForApproval::from(self.config.permissions.approval_policy.value());
|
||||
let current_permission_profile = self.config.permissions.permission_profile();
|
||||
let current_permission_profile = self.config.permissions.permission_profile().clone();
|
||||
let guardian_approval_enabled = self.config.features.enabled(Feature::GuardianApproval);
|
||||
let current_review_policy = self.config.approvals_reviewer;
|
||||
let mut items: Vec<SelectionItem> = Vec::new();
|
||||
@@ -124,7 +124,7 @@ impl ChatWidget {
|
||||
} else {
|
||||
Self::approval_preset_actions(
|
||||
preset_approval,
|
||||
preset.permission_profile.clone(),
|
||||
preset.active_permission_profile.clone(),
|
||||
base_name.clone(),
|
||||
ApprovalsReviewer::User,
|
||||
)
|
||||
@@ -134,7 +134,7 @@ impl ChatWidget {
|
||||
{
|
||||
Self::approval_preset_actions(
|
||||
preset_approval,
|
||||
preset.permission_profile.clone(),
|
||||
preset.active_permission_profile.clone(),
|
||||
base_name.clone(),
|
||||
ApprovalsReviewer::User,
|
||||
)
|
||||
@@ -142,7 +142,7 @@ impl ChatWidget {
|
||||
} else {
|
||||
Self::approval_preset_actions(
|
||||
preset_approval,
|
||||
preset.permission_profile.clone(),
|
||||
preset.active_permission_profile.clone(),
|
||||
base_name.clone(),
|
||||
ApprovalsReviewer::User,
|
||||
)
|
||||
@@ -180,7 +180,7 @@ impl ChatWidget {
|
||||
),
|
||||
actions: Self::approval_preset_actions(
|
||||
preset_approval,
|
||||
preset.permission_profile.clone(),
|
||||
preset.active_permission_profile.clone(),
|
||||
"Auto-review".to_string(),
|
||||
ApprovalsReviewer::AutoReview,
|
||||
),
|
||||
@@ -308,17 +308,16 @@ impl ChatWidget {
|
||||
|
||||
pub(super) fn approval_preset_actions(
|
||||
approval: AskForApproval,
|
||||
permission_profile: PermissionProfile,
|
||||
active_permission_profile: ActivePermissionProfile,
|
||||
label: String,
|
||||
approvals_reviewer: ApprovalsReviewer,
|
||||
) -> Vec<SelectionAction> {
|
||||
vec![Box::new(move |tx| {
|
||||
let permission_profile_clone = permission_profile.clone();
|
||||
tx.send(AppEvent::CodexOp(AppCommand::override_turn_context(
|
||||
/*cwd*/ None,
|
||||
Some(approval),
|
||||
Some(approvals_reviewer),
|
||||
Some(permission_profile_clone.clone()),
|
||||
Some(active_permission_profile.clone()),
|
||||
/*windows_sandbox_level*/ None,
|
||||
/*model*/ None,
|
||||
/*effort*/ None,
|
||||
@@ -328,7 +327,9 @@ impl ChatWidget {
|
||||
/*personality*/ None,
|
||||
)));
|
||||
tx.send(AppEvent::UpdateAskForApprovalPolicy(approval));
|
||||
tx.send(AppEvent::UpdatePermissionProfile(permission_profile_clone));
|
||||
tx.send(AppEvent::UpdateActivePermissionProfile(
|
||||
active_permission_profile.clone(),
|
||||
));
|
||||
tx.send(AppEvent::UpdateApprovalsReviewer(approvals_reviewer));
|
||||
tx.send(AppEvent::InsertHistoryCell(Box::new(
|
||||
history_cell::new_info_event(
|
||||
@@ -385,7 +386,6 @@ impl ChatWidget {
|
||||
) {
|
||||
let selected_name = preset.label.to_string();
|
||||
let approval = AskForApproval::from(preset.approval);
|
||||
let permission_profile = preset.permission_profile;
|
||||
let mut header_children: Vec<Box<dyn Renderable>> = Vec::new();
|
||||
let title_line = Line::from("Enable full access?").bold();
|
||||
let info_line = Line::from(vec![
|
||||
@@ -402,7 +402,7 @@ impl ChatWidget {
|
||||
|
||||
let mut accept_actions = Self::approval_preset_actions(
|
||||
approval,
|
||||
permission_profile.clone(),
|
||||
preset.active_permission_profile.clone(),
|
||||
selected_name.clone(),
|
||||
ApprovalsReviewer::User,
|
||||
);
|
||||
@@ -412,7 +412,7 @@ impl ChatWidget {
|
||||
|
||||
let mut accept_and_remember_actions = Self::approval_preset_actions(
|
||||
approval,
|
||||
permission_profile,
|
||||
preset.active_permission_profile,
|
||||
selected_name,
|
||||
ApprovalsReviewer::User,
|
||||
);
|
||||
|
||||
@@ -285,7 +285,7 @@ impl ChatWidget {
|
||||
/*cwd*/ None,
|
||||
/*approval_policy*/ None,
|
||||
/*approvals_reviewer*/ None,
|
||||
/*permission_profile*/ None,
|
||||
/*active_permission_profile*/ None,
|
||||
/*windows_sandbox_level*/ None,
|
||||
Some(switch_model_for_events.clone()),
|
||||
Some(Some(default_effort)),
|
||||
|
||||
@@ -107,7 +107,7 @@ impl ChatWidget {
|
||||
/*cwd*/ None,
|
||||
/*approval_policy*/ None,
|
||||
/*approvals_reviewer*/ None,
|
||||
/*permission_profile*/ None,
|
||||
/*active_permission_profile*/ None,
|
||||
/*windows_sandbox_level*/ None,
|
||||
/*model*/ None,
|
||||
/*effort*/ None,
|
||||
|
||||
@@ -33,6 +33,11 @@ impl ChatWidget {
|
||||
self.current_rollout_path = session.rollout_path.clone();
|
||||
self.current_cwd = Some(session.cwd.to_path_buf());
|
||||
self.config.cwd = session.cwd.clone();
|
||||
let runtime_workspace_roots = session.runtime_workspace_roots.clone();
|
||||
self.config.workspace_roots = runtime_workspace_roots.clone();
|
||||
self.config
|
||||
.permissions
|
||||
.set_workspace_roots(runtime_workspace_roots);
|
||||
self.effective_service_tier = session.service_tier.clone();
|
||||
if let Err(err) = self
|
||||
.config
|
||||
@@ -44,19 +49,26 @@ impl ChatWidget {
|
||||
self.config.permissions.approval_policy =
|
||||
Constrained::allow_only(session.approval_policy.to_core());
|
||||
}
|
||||
let permission_snapshot = PermissionProfileSnapshot::from_session_snapshot(
|
||||
session.permission_profile.clone(),
|
||||
session.active_permission_profile.clone(),
|
||||
);
|
||||
let permission_sync = self
|
||||
.config
|
||||
.permissions
|
||||
.set_permission_profile_with_active_profile(
|
||||
session.permission_profile.clone(),
|
||||
session.active_permission_profile.clone(),
|
||||
);
|
||||
.set_permission_profile_from_session_snapshot(permission_snapshot.clone());
|
||||
if let Err(err) = permission_sync {
|
||||
tracing::warn!(%err, "failed to sync permissions from SessionConfigured");
|
||||
self.config.permissions.permission_profile =
|
||||
Constrained::allow_only(session.permission_profile.clone());
|
||||
self.config.permissions.active_permission_profile =
|
||||
session.active_permission_profile.clone();
|
||||
if let Err(replace_err) = self
|
||||
.config
|
||||
.permissions
|
||||
.replace_permission_profile_from_session_snapshot(permission_snapshot)
|
||||
{
|
||||
tracing::error!(
|
||||
%replace_err,
|
||||
"failed to replace permissions from SessionConfigured after constraint fallback"
|
||||
);
|
||||
}
|
||||
}
|
||||
self.config.approvals_reviewer = session.approvals_reviewer;
|
||||
self.status_line_project_root_name_cache = None;
|
||||
|
||||
@@ -17,13 +17,14 @@ impl ChatWidget {
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the permission profile in the widget's config copy.
|
||||
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
|
||||
pub(crate) fn set_permission_profile(
|
||||
pub(crate) fn set_permission_profile_from_session_snapshot(
|
||||
&mut self,
|
||||
profile: PermissionProfile,
|
||||
snapshot: PermissionProfileSnapshot,
|
||||
) -> ConstraintResult<()> {
|
||||
self.config.permissions.set_permission_profile(profile)?;
|
||||
self.config
|
||||
.permissions
|
||||
.set_permission_profile_from_session_snapshot(snapshot)?;
|
||||
self.refresh_status_surfaces();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ use super::*;
|
||||
|
||||
impl ChatWidget {
|
||||
pub(super) fn open_theme_picker(&mut self) {
|
||||
let codex_home = crate::legacy_core::config::find_codex_home().ok();
|
||||
let codex_home = codex_utils_home_dir::find_codex_home().ok();
|
||||
let terminal_width = self
|
||||
.last_rendered_width
|
||||
.get()
|
||||
@@ -53,7 +53,7 @@ impl ChatWidget {
|
||||
/*cwd*/ None,
|
||||
/*approval_policy*/ None,
|
||||
/*approvals_reviewer*/ None,
|
||||
/*permission_profile*/ None,
|
||||
/*active_permission_profile*/ None,
|
||||
/*windows_sandbox_level*/ None,
|
||||
/*model*/ None,
|
||||
/*effort*/ None,
|
||||
|
||||
@@ -25,6 +25,10 @@ impl ChatWidget {
|
||||
self.bottom_pane.set_side_conversation_active(active);
|
||||
}
|
||||
|
||||
pub(crate) fn side_conversation_active(&self) -> bool {
|
||||
self.active_side_conversation
|
||||
}
|
||||
|
||||
pub(crate) fn set_side_conversation_context_label(&mut self, label: Option<String>) {
|
||||
self.bottom_pane.set_side_conversation_context_label(label);
|
||||
}
|
||||
|
||||
@@ -32,7 +32,8 @@ struct PreparedSlashCommandArgs {
|
||||
const SIDE_STARTING_CONTEXT_LABEL: &str = "Side starting...";
|
||||
const SIDE_REVIEW_UNAVAILABLE_MESSAGE: &str =
|
||||
"'/side' is unavailable while code review is running.";
|
||||
const SIDE_SLASH_COMMAND_UNAVAILABLE_HINT: &str = "Press Esc to return to the main thread first.";
|
||||
const SIDE_SLASH_COMMAND_UNAVAILABLE_HINT: &str =
|
||||
"Press Ctrl+C to return to the main thread first.";
|
||||
const GOAL_USAGE: &str = "Usage: /goal <objective>";
|
||||
const GOAL_USAGE_HINT: &str = "Example: /goal improve benchmark coverage";
|
||||
const RAW_USAGE: &str = "Usage: /raw [on|off]";
|
||||
|
||||
+1
-1
@@ -6,4 +6,4 @@ expression: terminal.backend()
|
||||
" "
|
||||
"› Check recently modified functions for compatibility "
|
||||
" "
|
||||
" gpt-5.5 Side from main thread · Esc to return "
|
||||
" gpt-5.5 Side from main thread · Ctrl+C to return "
|
||||
|
||||
+1
-1
@@ -6,4 +6,4 @@ expression: terminal.backend()
|
||||
" "
|
||||
"› Check recently modified functions for compatibility "
|
||||
" "
|
||||
" gpt-5.5 default · … Side from main thread · main needs input · Esc to return "
|
||||
" gpt-5.5 default… Side from main thread · main needs input · Ctrl+C to return "
|
||||
|
||||
@@ -901,8 +901,10 @@ fn permissions_display(config: &Config) -> String {
|
||||
return active_permission_profile.id.clone();
|
||||
}
|
||||
|
||||
let permission_profile = config.permissions.permission_profile();
|
||||
let summary = summarize_permission_profile(&permission_profile, config.cwd.as_path());
|
||||
let permission_profile = config.permissions.effective_permission_profile();
|
||||
let workspace_roots = config.effective_workspace_roots();
|
||||
let summary =
|
||||
summarize_permission_profile(&permission_profile, &config.cwd, workspace_roots.as_slice());
|
||||
if let Some(details) = summary.strip_prefix("read-only")
|
||||
&& !details.contains("(network access enabled)")
|
||||
{
|
||||
|
||||
@@ -149,6 +149,8 @@ pub(super) use codex_protocol::config_types::CollaborationMode;
|
||||
pub(super) use codex_protocol::config_types::ModeKind;
|
||||
pub(super) use codex_protocol::config_types::Personality;
|
||||
pub(super) use codex_protocol::config_types::ServiceTier;
|
||||
pub(super) use codex_protocol::models::ActivePermissionProfile;
|
||||
pub(super) use codex_protocol::models::BUILT_IN_PERMISSION_PROFILE_WORKSPACE;
|
||||
pub(super) use codex_protocol::models::FileSystemPermissions;
|
||||
pub(super) use codex_protocol::models::MessagePhase;
|
||||
pub(super) use codex_protocol::models::NetworkPermissions;
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
use super::*;
|
||||
use codex_app_server_protocol::FileSystemAccessMode;
|
||||
use codex_app_server_protocol::FileSystemPath;
|
||||
use codex_app_server_protocol::FileSystemSandboxEntry;
|
||||
use codex_app_server_protocol::FileSystemSpecialPath;
|
||||
use codex_app_server_protocol::PermissionProfile as AppServerPermissionProfile;
|
||||
use codex_app_server_protocol::PermissionProfileFileSystemPermissions;
|
||||
use codex_app_server_protocol::PermissionProfileNetworkPermissions;
|
||||
use codex_protocol::models::ManagedFileSystemPermissions;
|
||||
use codex_protocol::permissions::FileSystemAccessMode;
|
||||
use codex_protocol::permissions::FileSystemPath;
|
||||
use codex_protocol::permissions::FileSystemSandboxEntry;
|
||||
use codex_protocol::permissions::FileSystemSpecialPath;
|
||||
use codex_protocol::permissions::NetworkSandboxPolicy;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
@@ -28,6 +27,7 @@ async fn submission_preserves_text_elements_and_local_images() {
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
runtime_workspace_roots: Vec::new(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
message_history: None,
|
||||
@@ -57,7 +57,8 @@ async fn submission_preserves_text_elements_and_local_images() {
|
||||
assert_eq!(
|
||||
items[0],
|
||||
UserInput::LocalImage {
|
||||
path: local_images[0].clone()
|
||||
path: local_images[0].clone(),
|
||||
detail: None,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
@@ -92,14 +93,14 @@ async fn submission_preserves_text_elements_and_local_images() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn submission_includes_configured_permission_profile() {
|
||||
async fn submission_includes_configured_active_permission_profile() {
|
||||
let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||
|
||||
let thread_id = ThreadId::new();
|
||||
let rollout_file = NamedTempFile::new().unwrap();
|
||||
let expected_permission_profile: PermissionProfile = AppServerPermissionProfile::Managed {
|
||||
network: PermissionProfileNetworkPermissions { enabled: false },
|
||||
file_system: PermissionProfileFileSystemPermissions::Restricted {
|
||||
let expected_permission_profile: PermissionProfile = PermissionProfile::Managed {
|
||||
network: NetworkSandboxPolicy::Restricted,
|
||||
file_system: ManagedFileSystemPermissions::Restricted {
|
||||
entries: vec![
|
||||
FileSystemSandboxEntry {
|
||||
path: FileSystemPath::Special {
|
||||
@@ -116,8 +117,8 @@ async fn submission_includes_configured_permission_profile() {
|
||||
],
|
||||
glob_scan_max_depth: None,
|
||||
},
|
||||
}
|
||||
.into();
|
||||
};
|
||||
let expected_active_permission_profile = ActivePermissionProfile::new("custom");
|
||||
let configured = crate::session_state::ThreadSessionState {
|
||||
thread_id,
|
||||
forked_from_id: None,
|
||||
@@ -128,9 +129,10 @@ async fn submission_includes_configured_permission_profile() {
|
||||
service_tier: None,
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
permission_profile: expected_permission_profile.clone(),
|
||||
active_permission_profile: None,
|
||||
permission_profile: expected_permission_profile,
|
||||
active_permission_profile: Some(expected_active_permission_profile.clone()),
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
runtime_workspace_roots: Vec::new(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
message_history: None,
|
||||
@@ -147,26 +149,29 @@ async fn submission_includes_configured_permission_profile() {
|
||||
);
|
||||
chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
|
||||
|
||||
let permission_profile = match next_submit_op(&mut op_rx) {
|
||||
let active_permission_profile = match next_submit_op(&mut op_rx) {
|
||||
Op::UserTurn {
|
||||
permission_profile, ..
|
||||
} => permission_profile,
|
||||
active_permission_profile,
|
||||
..
|
||||
} => active_permission_profile,
|
||||
other => panic!("expected Op::UserTurn, got {other:?}"),
|
||||
};
|
||||
assert_eq!(permission_profile, expected_permission_profile);
|
||||
assert_eq!(
|
||||
active_permission_profile,
|
||||
Some(expected_active_permission_profile)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn submission_keeps_profile_when_legacy_projection_is_external() {
|
||||
async fn submission_omits_active_permission_profile_for_legacy_snapshot() {
|
||||
let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||
|
||||
let thread_id = ThreadId::new();
|
||||
let rollout_file = NamedTempFile::new().unwrap();
|
||||
let expected_permission_profile: PermissionProfile = AppServerPermissionProfile::Managed {
|
||||
network: PermissionProfileNetworkPermissions { enabled: false },
|
||||
file_system: PermissionProfileFileSystemPermissions::Unrestricted,
|
||||
}
|
||||
.into();
|
||||
let expected_permission_profile: PermissionProfile = PermissionProfile::Managed {
|
||||
network: NetworkSandboxPolicy::Restricted,
|
||||
file_system: ManagedFileSystemPermissions::Unrestricted,
|
||||
};
|
||||
let configured = crate::session_state::ThreadSessionState {
|
||||
thread_id,
|
||||
forked_from_id: None,
|
||||
@@ -177,9 +182,10 @@ async fn submission_keeps_profile_when_legacy_projection_is_external() {
|
||||
service_tier: None,
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
permission_profile: expected_permission_profile.clone(),
|
||||
permission_profile: expected_permission_profile,
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
runtime_workspace_roots: Vec::new(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
message_history: None,
|
||||
@@ -193,13 +199,14 @@ async fn submission_keeps_profile_when_legacy_projection_is_external() {
|
||||
.set_composer_text("submit".to_string(), Vec::new(), Vec::new());
|
||||
chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
|
||||
|
||||
let permission_profile = match next_submit_op(&mut op_rx) {
|
||||
let active_permission_profile = match next_submit_op(&mut op_rx) {
|
||||
Op::UserTurn {
|
||||
permission_profile, ..
|
||||
} => permission_profile,
|
||||
active_permission_profile,
|
||||
..
|
||||
} => active_permission_profile,
|
||||
other => panic!("expected Op::UserTurn, got {other:?}"),
|
||||
};
|
||||
assert_eq!(permission_profile, expected_permission_profile);
|
||||
assert_eq!(active_permission_profile, None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -221,6 +228,7 @@ async fn submission_with_remote_and_local_images_keeps_local_placeholder_numberi
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
runtime_workspace_roots: Vec::new(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
message_history: None,
|
||||
@@ -255,12 +263,14 @@ async fn submission_with_remote_and_local_images_keeps_local_placeholder_numberi
|
||||
items[0],
|
||||
UserInput::Image {
|
||||
url: remote_url.clone(),
|
||||
detail: None,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
items[1],
|
||||
UserInput::LocalImage {
|
||||
path: local_images[0].clone(),
|
||||
detail: None,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
@@ -314,6 +324,7 @@ async fn enter_with_only_remote_images_submits_user_turn() {
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
runtime_workspace_roots: Vec::new(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
message_history: None,
|
||||
@@ -337,6 +348,7 @@ async fn enter_with_only_remote_images_submits_user_turn() {
|
||||
items,
|
||||
vec![UserInput::Image {
|
||||
url: remote_url.clone(),
|
||||
detail: None,
|
||||
}]
|
||||
);
|
||||
assert_eq!(summary, None);
|
||||
@@ -377,6 +389,7 @@ async fn shift_enter_with_only_remote_images_does_not_submit_user_turn() {
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
runtime_workspace_roots: Vec::new(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
message_history: None,
|
||||
@@ -415,6 +428,7 @@ async fn enter_with_only_remote_images_does_not_submit_when_modal_is_active() {
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
runtime_workspace_roots: Vec::new(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
message_history: None,
|
||||
@@ -453,6 +467,7 @@ async fn enter_with_only_remote_images_does_not_submit_when_input_disabled() {
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
runtime_workspace_roots: Vec::new(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
message_history: None,
|
||||
@@ -494,6 +509,7 @@ async fn submission_prefers_selected_duplicate_skill_path() {
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
runtime_workspace_roots: Vec::new(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
message_history: None,
|
||||
@@ -1148,9 +1164,11 @@ fn user_message_display_from_inputs_matches_flattened_user_message_shape() {
|
||||
},
|
||||
UserInput::Image {
|
||||
url: "https://example.com/remote.png".to_string(),
|
||||
detail: None,
|
||||
},
|
||||
UserInput::LocalImage {
|
||||
path: local_image.clone(),
|
||||
detail: None,
|
||||
},
|
||||
UserInput::Skill {
|
||||
name: "demo".to_string(),
|
||||
@@ -1223,6 +1241,7 @@ async fn committed_user_message_with_hidden_prompt_context_renders_local_images(
|
||||
},
|
||||
UserInput::LocalImage {
|
||||
path: local_image.clone(),
|
||||
detail: None,
|
||||
},
|
||||
],
|
||||
);
|
||||
|
||||
@@ -957,6 +957,7 @@ async fn bang_shell_enter_while_task_running_submits_run_user_shell_command() {
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
runtime_workspace_roots: Vec::new(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
message_history: None,
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
use super::*;
|
||||
use codex_app_server_protocol::FileSystemAccessMode;
|
||||
use codex_app_server_protocol::FileSystemPath;
|
||||
use codex_app_server_protocol::FileSystemSandboxEntry;
|
||||
use codex_app_server_protocol::FileSystemSpecialPath;
|
||||
use codex_app_server_protocol::NetworkAccess;
|
||||
use codex_app_server_protocol::PermissionProfile as AppServerPermissionProfile;
|
||||
use codex_app_server_protocol::PermissionProfileFileSystemPermissions;
|
||||
use codex_app_server_protocol::PermissionProfileNetworkPermissions;
|
||||
use codex_app_server_protocol::SandboxPolicy;
|
||||
use codex_protocol::models::ManagedFileSystemPermissions;
|
||||
use codex_protocol::permissions::FileSystemAccessMode;
|
||||
use codex_protocol::permissions::FileSystemPath;
|
||||
use codex_protocol::permissions::FileSystemSandboxEntry;
|
||||
use codex_protocol::permissions::FileSystemSpecialPath;
|
||||
use codex_protocol::permissions::NetworkSandboxPolicy;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
@@ -29,6 +28,7 @@ async fn resumed_initial_messages_render_history() {
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
runtime_workspace_roots: Vec::new(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
message_history: None,
|
||||
@@ -99,6 +99,7 @@ async fn replayed_user_message_preserves_text_elements_and_local_images() {
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
runtime_workspace_roots: Vec::new(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
message_history: None,
|
||||
@@ -117,6 +118,7 @@ async fn replayed_user_message_preserves_text_elements_and_local_images() {
|
||||
},
|
||||
AppServerUserInput::LocalImage {
|
||||
path: local_images[0].clone(),
|
||||
detail: None,
|
||||
},
|
||||
],
|
||||
ReplayKind::ResumeInitialMessages,
|
||||
@@ -167,6 +169,7 @@ async fn replayed_user_message_preserves_remote_image_urls() {
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
runtime_workspace_roots: Vec::new(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
message_history: None,
|
||||
@@ -185,6 +188,7 @@ async fn replayed_user_message_preserves_remote_image_urls() {
|
||||
},
|
||||
AppServerUserInput::Image {
|
||||
url: remote_image_urls[0].clone(),
|
||||
detail: None,
|
||||
},
|
||||
],
|
||||
ReplayKind::ResumeInitialMessages,
|
||||
@@ -227,9 +231,9 @@ async fn session_configured_syncs_widget_config_permissions_and_cwd() {
|
||||
chat.config.cwd = test_path_buf("/home/user/main").abs();
|
||||
|
||||
let expected_cwd = test_path_buf("/home/user/sub-agent").abs();
|
||||
let expected_app_server_permission_profile = AppServerPermissionProfile::Managed {
|
||||
network: PermissionProfileNetworkPermissions { enabled: false },
|
||||
file_system: PermissionProfileFileSystemPermissions::Restricted {
|
||||
let expected_app_server_permission_profile = PermissionProfile::Managed {
|
||||
network: NetworkSandboxPolicy::Restricted,
|
||||
file_system: ManagedFileSystemPermissions::Restricted {
|
||||
entries: vec![
|
||||
FileSystemSandboxEntry {
|
||||
path: FileSystemPath::Special {
|
||||
@@ -247,8 +251,7 @@ async fn session_configured_syncs_widget_config_permissions_and_cwd() {
|
||||
glob_scan_max_depth: None,
|
||||
},
|
||||
};
|
||||
let expected_permission_profile: PermissionProfile =
|
||||
expected_app_server_permission_profile.clone().into();
|
||||
let expected_permission_profile = expected_app_server_permission_profile.clone();
|
||||
let expected_core_sandbox = expected_permission_profile
|
||||
.to_legacy_sandbox_policy(expected_cwd.as_path())
|
||||
.expect("permission profile should project to legacy sandbox policy");
|
||||
@@ -266,6 +269,7 @@ async fn session_configured_syncs_widget_config_permissions_and_cwd() {
|
||||
permission_profile: expected_permission_profile,
|
||||
active_permission_profile: None,
|
||||
cwd: expected_cwd.clone(),
|
||||
runtime_workspace_roots: vec![expected_cwd.clone()],
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
message_history: None,
|
||||
@@ -282,18 +286,78 @@ async fn session_configured_syncs_widget_config_permissions_and_cwd() {
|
||||
let actual_sandbox = SandboxPolicy::from(chat.config_ref().legacy_sandbox_policy());
|
||||
assert_eq!(&actual_sandbox, &expected_sandbox);
|
||||
assert_eq!(
|
||||
AppServerPermissionProfile::from(chat.config_ref().permissions.permission_profile()),
|
||||
chat.config_ref().permissions.effective_permission_profile(),
|
||||
expected_app_server_permission_profile
|
||||
);
|
||||
assert_eq!(&chat.config_ref().cwd, &expected_cwd);
|
||||
|
||||
let updated_profile = PermissionProfile::workspace_write();
|
||||
chat.set_permission_profile(updated_profile.clone())
|
||||
.expect("set permission profile");
|
||||
chat.set_permission_profile_from_session_snapshot(PermissionProfileSnapshot::legacy(
|
||||
updated_profile.clone(),
|
||||
))
|
||||
.expect("set permission profile");
|
||||
assert_eq!(
|
||||
chat.config_ref().permissions.permission_profile(),
|
||||
updated_profile,
|
||||
"local permission changes should replace SessionConfigured profile-derived runtime permissions"
|
||||
&updated_profile,
|
||||
"local permission changes should replace SessionConfigured canonical permissions"
|
||||
);
|
||||
assert_eq!(
|
||||
chat.config_ref().permissions.effective_permission_profile(),
|
||||
updated_profile
|
||||
.materialize_project_roots_with_workspace_roots(std::slice::from_ref(&expected_cwd,)),
|
||||
"effective permissions should still use the current thread runtime workspace roots"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn session_configured_preserves_profile_workspace_roots() {
|
||||
let (mut chat, _rx, _ops) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||
|
||||
let previous_cwd = test_path_buf("/home/user/main").abs();
|
||||
let profile_root = test_path_buf("/home/user/shared").abs();
|
||||
chat.config.cwd = previous_cwd.clone();
|
||||
chat.config.workspace_roots = vec![previous_cwd, profile_root.clone()];
|
||||
chat.config.workspace_roots_explicit = false;
|
||||
chat.config
|
||||
.permissions
|
||||
.set_workspace_roots(chat.config.workspace_roots.clone());
|
||||
|
||||
let session_cwd = test_path_buf("/home/user/sub-agent").abs();
|
||||
let session_runtime_workspace_roots = vec![session_cwd.clone()];
|
||||
let session_effective_workspace_roots = vec![session_cwd.clone(), profile_root];
|
||||
let session_permission_profile = PermissionProfile::workspace_write()
|
||||
.materialize_project_roots_with_workspace_roots(&session_effective_workspace_roots);
|
||||
let configured = crate::session_state::ThreadSessionState {
|
||||
thread_id: ThreadId::new(),
|
||||
forked_from_id: None,
|
||||
fork_parent_title: None,
|
||||
thread_name: None,
|
||||
model: "test-model".to_string(),
|
||||
model_provider_id: "test-provider".to_string(),
|
||||
service_tier: None,
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
permission_profile: session_permission_profile.clone(),
|
||||
active_permission_profile: None,
|
||||
cwd: session_cwd.clone(),
|
||||
runtime_workspace_roots: session_runtime_workspace_roots.clone(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
message_history: None,
|
||||
network_proxy: None,
|
||||
rollout_path: None,
|
||||
};
|
||||
|
||||
chat.handle_thread_session(configured);
|
||||
|
||||
assert_eq!(&chat.config_ref().cwd, &session_cwd);
|
||||
assert_eq!(
|
||||
chat.config_ref().permissions.user_visible_workspace_roots(),
|
||||
session_runtime_workspace_roots.as_slice()
|
||||
);
|
||||
assert_eq!(
|
||||
chat.config_ref().permissions.effective_permission_profile(),
|
||||
session_permission_profile
|
||||
);
|
||||
}
|
||||
|
||||
@@ -301,11 +365,10 @@ async fn session_configured_syncs_widget_config_permissions_and_cwd() {
|
||||
async fn session_configured_external_sandbox_keeps_external_runtime_policy() {
|
||||
let (mut chat, _rx, _ops) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||
|
||||
let expected_app_server_permission_profile = AppServerPermissionProfile::External {
|
||||
network: PermissionProfileNetworkPermissions { enabled: false },
|
||||
let expected_app_server_permission_profile = PermissionProfile::External {
|
||||
network: NetworkSandboxPolicy::Restricted,
|
||||
};
|
||||
let expected_permission_profile: PermissionProfile =
|
||||
expected_app_server_permission_profile.clone().into();
|
||||
let expected_permission_profile = expected_app_server_permission_profile.clone();
|
||||
let expected_sandbox = SandboxPolicy::ExternalSandbox {
|
||||
network_access: NetworkAccess::Restricted,
|
||||
};
|
||||
@@ -322,6 +385,7 @@ async fn session_configured_external_sandbox_keeps_external_runtime_policy() {
|
||||
permission_profile: expected_permission_profile,
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/external").abs(),
|
||||
runtime_workspace_roots: Vec::new(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
message_history: None,
|
||||
@@ -334,7 +398,7 @@ async fn session_configured_external_sandbox_keeps_external_runtime_policy() {
|
||||
let actual_sandbox = SandboxPolicy::from(chat.config_ref().legacy_sandbox_policy());
|
||||
assert_eq!(&actual_sandbox, &expected_sandbox);
|
||||
assert_eq!(
|
||||
AppServerPermissionProfile::from(chat.config_ref().permissions.permission_profile()),
|
||||
chat.config_ref().permissions.effective_permission_profile(),
|
||||
expected_app_server_permission_profile
|
||||
);
|
||||
}
|
||||
@@ -360,6 +424,7 @@ async fn replayed_user_message_with_only_remote_images_renders_history_cell() {
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
runtime_workspace_roots: Vec::new(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
message_history: None,
|
||||
@@ -373,6 +438,7 @@ async fn replayed_user_message_with_only_remote_images_renders_history_cell() {
|
||||
"user-1",
|
||||
vec![AppServerUserInput::Image {
|
||||
url: remote_image_urls[0].clone(),
|
||||
detail: None,
|
||||
}],
|
||||
ReplayKind::ResumeInitialMessages,
|
||||
);
|
||||
@@ -414,6 +480,7 @@ async fn replayed_user_message_with_only_local_images_renders_history_cell() {
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
runtime_workspace_roots: Vec::new(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
message_history: None,
|
||||
@@ -427,6 +494,7 @@ async fn replayed_user_message_with_only_local_images_renders_history_cell() {
|
||||
"user-1",
|
||||
vec![AppServerUserInput::LocalImage {
|
||||
path: local_images[0].clone(),
|
||||
detail: None,
|
||||
}],
|
||||
ReplayKind::ResumeInitialMessages,
|
||||
);
|
||||
@@ -684,6 +752,7 @@ async fn replayed_reasoning_item_hides_raw_reasoning_when_disabled() {
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_project_path().abs(),
|
||||
runtime_workspace_roots: Vec::new(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: None,
|
||||
message_history: None,
|
||||
@@ -729,6 +798,7 @@ async fn replayed_reasoning_item_shows_raw_reasoning_when_enabled() {
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_project_path().abs(),
|
||||
runtime_workspace_roots: Vec::new(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: None,
|
||||
message_history: None,
|
||||
|
||||
@@ -57,6 +57,46 @@ async fn mcp_startup_complete_does_not_clear_running_task() {
|
||||
|
||||
assert!(chat.bottom_pane.is_task_running());
|
||||
assert!(chat.bottom_pane.status_indicator_visible());
|
||||
assert_eq!(chat.status_state.current_status.header, "Working");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn turn_start_preserves_active_mcp_startup_header() {
|
||||
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||
chat.set_mcp_startup_expected_servers(["schaltwerk".to_string()]);
|
||||
|
||||
notify_mcp_status(&mut chat, "schaltwerk", McpServerStartupState::Starting);
|
||||
handle_turn_started(&mut chat, "turn-1");
|
||||
|
||||
assert!(chat.bottom_pane.is_task_running());
|
||||
assert_eq!(
|
||||
chat.status_state.current_status.header,
|
||||
"Booting MCP server: schaltwerk"
|
||||
);
|
||||
|
||||
notify_mcp_status(&mut chat, "schaltwerk", McpServerStartupState::Ready);
|
||||
|
||||
assert_eq!(chat.status_state.current_status.header, "Working");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn turn_start_replaces_idle_completed_mcp_startup_header() {
|
||||
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||
chat.set_mcp_startup_expected_servers(["schaltwerk".to_string()]);
|
||||
|
||||
notify_mcp_status(&mut chat, "schaltwerk", McpServerStartupState::Starting);
|
||||
notify_mcp_status(&mut chat, "schaltwerk", McpServerStartupState::Ready);
|
||||
|
||||
assert!(!chat.bottom_pane.is_task_running());
|
||||
assert_eq!(
|
||||
chat.status_state.current_status.header,
|
||||
"Booting MCP server: schaltwerk"
|
||||
);
|
||||
|
||||
handle_turn_started(&mut chat, "turn-1");
|
||||
|
||||
assert!(chat.bottom_pane.is_task_running());
|
||||
assert_eq!(chat.status_state.current_status.header, "Working");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -125,6 +165,82 @@ async fn app_server_mcp_startup_failure_renders_warning_history() {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mcp_startup_failure_restores_running_status_header() {
|
||||
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||
chat.show_welcome_banner = false;
|
||||
chat.set_mcp_startup_expected_servers(["alpha".to_string(), "beta".to_string()]);
|
||||
handle_turn_started(&mut chat, "turn-1");
|
||||
|
||||
notify_mcp_status(&mut chat, "alpha", McpServerStartupState::Starting);
|
||||
notify_mcp_status(&mut chat, "beta", McpServerStartupState::Starting);
|
||||
assert!(
|
||||
chat.status_state
|
||||
.current_status
|
||||
.header
|
||||
.starts_with("Starting MCP servers")
|
||||
);
|
||||
|
||||
notify_mcp_status_error(
|
||||
&mut chat,
|
||||
"alpha",
|
||||
"MCP client for `alpha` failed to start: handshake failed",
|
||||
);
|
||||
notify_mcp_status(&mut chat, "beta", McpServerStartupState::Ready);
|
||||
let _ = drain_insert_history(&mut rx);
|
||||
|
||||
assert!(chat.bottom_pane.is_task_running());
|
||||
assert!(chat.bottom_pane.status_indicator_visible());
|
||||
assert_eq!(chat.status_state.current_status.header, "Working");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mcp_startup_complete_preserves_review_status() {
|
||||
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||
chat.show_welcome_banner = false;
|
||||
chat.set_mcp_startup_expected_servers(["alpha".to_string()]);
|
||||
handle_turn_started(&mut chat, "turn-1");
|
||||
|
||||
notify_mcp_status(&mut chat, "alpha", McpServerStartupState::Starting);
|
||||
assert!(
|
||||
chat.status_state
|
||||
.current_status
|
||||
.header
|
||||
.starts_with("Booting MCP server")
|
||||
);
|
||||
|
||||
chat.on_guardian_assessment(GuardianAssessmentEvent {
|
||||
id: "guardian-1".to_string(),
|
||||
target_item_id: Some("guardian-target-1".to_string()),
|
||||
turn_id: "turn-1".to_string(),
|
||||
started_at_ms: 0,
|
||||
completed_at_ms: None,
|
||||
status: GuardianAssessmentStatus::InProgress,
|
||||
risk_level: None,
|
||||
user_authorization: None,
|
||||
rationale: None,
|
||||
decision_source: None,
|
||||
action: GuardianAssessmentAction::Command {
|
||||
source: GuardianCommandSource::Shell,
|
||||
command: "rm -rf '/tmp/guardian target'".to_string(),
|
||||
cwd: test_path_buf("/tmp").abs(),
|
||||
},
|
||||
});
|
||||
|
||||
notify_mcp_status(&mut chat, "alpha", McpServerStartupState::Ready);
|
||||
|
||||
assert!(chat.bottom_pane.is_task_running());
|
||||
assert!(chat.bottom_pane.status_indicator_visible());
|
||||
assert_eq!(
|
||||
chat.status_state.current_status.header,
|
||||
"Reviewing approval request"
|
||||
);
|
||||
assert_eq!(
|
||||
chat.status_state.current_status.details,
|
||||
Some("rm -rf '/tmp/guardian target'".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn app_server_mcp_startup_lag_settles_startup_and_ignores_late_updates() {
|
||||
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||
|
||||
@@ -1,17 +1,16 @@
|
||||
use super::*;
|
||||
use codex_app_server_protocol::FileSystemAccessMode;
|
||||
use codex_app_server_protocol::FileSystemPath;
|
||||
use codex_app_server_protocol::FileSystemSandboxEntry;
|
||||
use codex_app_server_protocol::FileSystemSpecialPath;
|
||||
use codex_app_server_protocol::PermissionProfile as AppServerPermissionProfile;
|
||||
use codex_app_server_protocol::PermissionProfileFileSystemPermissions;
|
||||
use codex_app_server_protocol::PermissionProfileNetworkPermissions;
|
||||
use codex_protocol::models::ManagedFileSystemPermissions;
|
||||
use codex_protocol::permissions::FileSystemAccessMode;
|
||||
use codex_protocol::permissions::FileSystemPath;
|
||||
use codex_protocol::permissions::FileSystemSandboxEntry;
|
||||
use codex_protocol::permissions::FileSystemSpecialPath;
|
||||
use codex_protocol::permissions::NetworkSandboxPolicy;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn app_server_workspace_write_profile(extra_root: AbsolutePathBuf) -> PermissionProfile {
|
||||
AppServerPermissionProfile::Managed {
|
||||
network: PermissionProfileNetworkPermissions { enabled: false },
|
||||
file_system: PermissionProfileFileSystemPermissions::Restricted {
|
||||
PermissionProfile::Managed {
|
||||
network: NetworkSandboxPolicy::Restricted,
|
||||
file_system: ManagedFileSystemPermissions::Restricted {
|
||||
entries: vec![
|
||||
FileSystemSandboxEntry {
|
||||
path: FileSystemPath::Special {
|
||||
@@ -45,7 +44,6 @@ fn app_server_workspace_write_profile(extra_root: AbsolutePathBuf) -> Permission
|
||||
glob_scan_max_depth: None,
|
||||
},
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -127,9 +125,9 @@ async fn preset_matching_does_not_treat_non_cwd_writable_profile_as_read_only()
|
||||
.into_iter()
|
||||
.find(|p| p.id == "read-only")
|
||||
.expect("read-only preset exists");
|
||||
let current_profile: PermissionProfile = AppServerPermissionProfile::Managed {
|
||||
network: PermissionProfileNetworkPermissions { enabled: false },
|
||||
file_system: PermissionProfileFileSystemPermissions::Restricted {
|
||||
let current_profile: PermissionProfile = PermissionProfile::Managed {
|
||||
network: NetworkSandboxPolicy::Restricted,
|
||||
file_system: ManagedFileSystemPermissions::Restricted {
|
||||
entries: vec![
|
||||
FileSystemSandboxEntry {
|
||||
path: FileSystemPath::Special {
|
||||
@@ -146,8 +144,7 @@ async fn preset_matching_does_not_treat_non_cwd_writable_profile_as_read_only()
|
||||
],
|
||||
glob_scan_max_depth: None,
|
||||
},
|
||||
}
|
||||
.into();
|
||||
};
|
||||
let cwd = test_path_buf("/tmp/project").abs();
|
||||
|
||||
assert!(
|
||||
@@ -584,6 +581,7 @@ async fn permissions_selection_marks_auto_review_current_after_session_configure
|
||||
permission_profile: PermissionProfile::workspace_write(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_project_path().abs(),
|
||||
runtime_workspace_roots: Vec::new(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: None,
|
||||
message_history: None,
|
||||
@@ -631,6 +629,7 @@ async fn permissions_selection_marks_auto_review_current_with_custom_workspace_w
|
||||
permission_profile,
|
||||
active_permission_profile: None,
|
||||
cwd,
|
||||
runtime_workspace_roots: Vec::new(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: None,
|
||||
message_history: None,
|
||||
@@ -740,7 +739,9 @@ async fn permissions_selection_sends_approvals_reviewer_in_override_turn_context
|
||||
cwd: None,
|
||||
approval_policy: Some(AskForApproval::OnRequest),
|
||||
approvals_reviewer: Some(ApprovalsReviewer::AutoReview),
|
||||
permission_profile: Some(PermissionProfile::workspace_write()),
|
||||
active_permission_profile: Some(ActivePermissionProfile::new(
|
||||
BUILT_IN_PERMISSION_PROFILE_WORKSPACE,
|
||||
)),
|
||||
windows_sandbox_level: None,
|
||||
model: None,
|
||||
effort: None,
|
||||
@@ -750,6 +751,20 @@ async fn permissions_selection_sends_approvals_reviewer_in_override_turn_context
|
||||
personality: None,
|
||||
}
|
||||
);
|
||||
|
||||
let active_permission_profile_update = std::iter::from_fn(|| rx.try_recv().ok())
|
||||
.find_map(|event| match event {
|
||||
AppEvent::UpdateActivePermissionProfile(active_permission_profile) => {
|
||||
Some(active_permission_profile)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.expect("expected UpdateActivePermissionProfile event");
|
||||
|
||||
assert_eq!(
|
||||
active_permission_profile_update,
|
||||
ActivePermissionProfile::new(BUILT_IN_PERMISSION_PROFILE_WORKSPACE)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -1217,6 +1217,7 @@ async fn submit_user_message_emits_structured_plugin_mentions_from_bindings() {
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
runtime_workspace_roots: Vec::new(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
message_history: None,
|
||||
@@ -1403,6 +1404,7 @@ async fn plan_slash_command_with_args_submits_prompt_in_plan_mode() {
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
runtime_workspace_roots: Vec::new(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
message_history: None,
|
||||
|
||||
@@ -597,6 +597,7 @@ async fn item_completed_pops_pending_steer_with_local_image_and_text_elements()
|
||||
vec![
|
||||
UserInput::Image {
|
||||
url: "data:image/png;base64,placeholder".to_string(),
|
||||
detail: None,
|
||||
},
|
||||
UserInput::Text {
|
||||
text,
|
||||
|
||||
@@ -106,7 +106,7 @@ async fn slash_commands_without_side_flag_are_rejected_for_side_threads() {
|
||||
let rendered = lines_to_single_string(&cell.display_lines(/*width*/ 80));
|
||||
assert!(
|
||||
rendered.contains(
|
||||
"'/review' is unavailable in side conversations. Press Esc to return to the main thread first."
|
||||
"'/review' is unavailable in side conversations. Press Ctrl+C to return to the main thread first."
|
||||
),
|
||||
"expected side conversation slash command error, got {rendered:?}"
|
||||
);
|
||||
@@ -132,7 +132,7 @@ async fn slash_side_is_rejected_for_side_threads() {
|
||||
let rendered = lines_to_single_string(&cell.display_lines(/*width*/ 80));
|
||||
assert!(
|
||||
rendered.contains(
|
||||
"'/side' is unavailable in side conversations. Press Esc to return to the main thread first."
|
||||
"'/side' is unavailable in side conversations. Press Ctrl+C to return to the main thread first."
|
||||
),
|
||||
"expected side conversation slash command error, got {rendered:?}"
|
||||
);
|
||||
@@ -276,7 +276,7 @@ async fn side_context_label_preserves_status_line_snapshot() {
|
||||
chat.refresh_status_line();
|
||||
chat.set_side_conversation_active(/*active*/ true);
|
||||
chat.set_side_conversation_context_label(Some(
|
||||
"Side from main thread · Esc to return".to_string(),
|
||||
"Side from main thread · Ctrl+C to return".to_string(),
|
||||
));
|
||||
|
||||
let width = 80;
|
||||
@@ -297,7 +297,7 @@ async fn side_context_label_shows_parent_status_snapshot() {
|
||||
chat.show_welcome_banner = false;
|
||||
chat.set_side_conversation_active(/*active*/ true);
|
||||
chat.set_side_conversation_context_label(Some(
|
||||
"Side from main thread · main needs input · Esc to return".to_string(),
|
||||
"Side from main thread · main needs input · Ctrl+C to return".to_string(),
|
||||
));
|
||||
|
||||
let width = 80;
|
||||
|
||||
@@ -2230,6 +2230,7 @@ async fn session_configured_clears_goal_status_footer() {
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
runtime_workspace_roots: Vec::new(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
message_history: None,
|
||||
|
||||
@@ -66,7 +66,9 @@ impl ChatWidget {
|
||||
self.bottom_pane
|
||||
.set_interrupt_hint_visible(/*visible*/ true);
|
||||
self.status_state.terminal_title_status_kind = TerminalTitleStatusKind::Working;
|
||||
self.set_status_header(String::from("Working"));
|
||||
if self.mcp_startup_status.is_none() || !self.status_header_is_mcp_startup_owned() {
|
||||
self.set_status_header(String::from("Working"));
|
||||
}
|
||||
self.full_reasoning_buffer.clear();
|
||||
self.reasoning_buffer.clear();
|
||||
self.set_ambient_pet_notification(
|
||||
|
||||
@@ -593,8 +593,8 @@ impl ChatWidget {
|
||||
)
|
||||
}),
|
||||
),
|
||||
UserInput::Image { url } => remote_image_urls.push(url.clone()),
|
||||
UserInput::LocalImage { path } => local_images.push(path.clone()),
|
||||
UserInput::Image { url, .. } => remote_image_urls.push(url.clone()),
|
||||
UserInput::LocalImage { path, .. } => local_images.push(path.clone()),
|
||||
UserInput::Skill { .. } | UserInput::Mention { .. } => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,14 +15,7 @@ impl ChatWidget {
|
||||
}
|
||||
let cwd = self.config.cwd.clone();
|
||||
let env_map: std::collections::HashMap<String, String> = std::env::vars().collect();
|
||||
let Ok(policy) = self
|
||||
.config
|
||||
.permissions
|
||||
.permission_profile()
|
||||
.to_legacy_sandbox_policy(self.config.cwd.as_path())
|
||||
else {
|
||||
return Some((Vec::new(), 0, true));
|
||||
};
|
||||
let policy = self.config.legacy_sandbox_policy();
|
||||
match codex_windows_sandbox::apply_world_writable_scan_and_denies(
|
||||
self.config.codex_home.as_path(),
|
||||
cwd.as_path(),
|
||||
@@ -49,10 +42,10 @@ impl ChatWidget {
|
||||
extra_count: usize,
|
||||
failed_scan: bool,
|
||||
) {
|
||||
let (approval, permission_profile) = match &preset {
|
||||
let (approval, active_permission_profile) = match &preset {
|
||||
Some(p) => (
|
||||
Some(AskForApproval::from(p.approval)),
|
||||
Some(p.permission_profile.clone()),
|
||||
Some(p.active_permission_profile.clone()),
|
||||
),
|
||||
None => (None, None),
|
||||
};
|
||||
@@ -72,7 +65,9 @@ impl ChatWidget {
|
||||
let mode_label = preset
|
||||
.as_ref()
|
||||
.map(|p| describe_profile(&p.permission_profile))
|
||||
.unwrap_or_else(|| describe_profile(&self.config.permissions.permission_profile()));
|
||||
.unwrap_or_else(|| {
|
||||
describe_profile(&self.config.permissions.effective_permission_profile())
|
||||
});
|
||||
let info_line = if failed_scan {
|
||||
Line::from(vec![
|
||||
"We couldn't complete the world-writable scan, so protections cannot be verified. "
|
||||
@@ -115,10 +110,12 @@ impl ChatWidget {
|
||||
tx.send(AppEvent::SkipNextWorldWritableScan);
|
||||
}));
|
||||
}
|
||||
if let (Some(approval), Some(permission_profile)) = (approval, permission_profile.clone()) {
|
||||
if let (Some(approval), Some(active_permission_profile)) =
|
||||
(approval, active_permission_profile.clone())
|
||||
{
|
||||
accept_actions.extend(Self::approval_preset_actions(
|
||||
approval,
|
||||
permission_profile,
|
||||
active_permission_profile,
|
||||
mode_label.to_string(),
|
||||
ApprovalsReviewer::User,
|
||||
));
|
||||
@@ -129,10 +126,12 @@ impl ChatWidget {
|
||||
tx.send(AppEvent::UpdateWorldWritableWarningAcknowledged(true));
|
||||
tx.send(AppEvent::PersistWorldWritableWarningAcknowledged);
|
||||
}));
|
||||
if let (Some(approval), Some(permission_profile)) = (approval, permission_profile) {
|
||||
if let (Some(approval), Some(active_permission_profile)) =
|
||||
(approval, active_permission_profile)
|
||||
{
|
||||
accept_and_remember_actions.extend(Self::approval_preset_actions(
|
||||
approval,
|
||||
permission_profile,
|
||||
active_permission_profile,
|
||||
mode_label.to_string(),
|
||||
ApprovalsReviewer::User,
|
||||
));
|
||||
|
||||
@@ -5,7 +5,7 @@ use codex_utils_cli::ApprovalModeCliArg;
|
||||
use codex_utils_cli::CliConfigOverrides;
|
||||
use codex_utils_cli::SharedCliOptions;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[derive(Parser, Clone, Debug)]
|
||||
#[command(version)]
|
||||
pub struct Cli {
|
||||
/// Optional user prompt to start the session.
|
||||
@@ -89,7 +89,7 @@ impl std::ops::DerefMut for Cli {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct TuiSharedCliOptions(SharedCliOptions);
|
||||
|
||||
impl TuiSharedCliOptions {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,360 @@
|
||||
//! Approval, denial, and review-status transcript cells.
|
||||
|
||||
use super::*;
|
||||
|
||||
fn truncate_exec_snippet(full_cmd: &str) -> String {
|
||||
let mut snippet = match full_cmd.split_once('\n') {
|
||||
Some((first, _)) => format!("{first} ..."),
|
||||
None => full_cmd.to_string(),
|
||||
};
|
||||
snippet = truncate_text(&snippet, /*max_graphemes*/ 80);
|
||||
snippet
|
||||
}
|
||||
|
||||
fn exec_snippet(command: &[String]) -> String {
|
||||
let full_cmd = strip_bash_lc_and_escape(command);
|
||||
truncate_exec_snippet(&full_cmd)
|
||||
}
|
||||
|
||||
fn non_empty_exec_snippet(command: &[String]) -> Option<String> {
|
||||
let snippet = exec_snippet(command);
|
||||
(!snippet.is_empty()).then_some(snippet)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) enum ReviewDecision {
|
||||
Approved,
|
||||
ApprovedExecpolicyAmendment {
|
||||
proposed_execpolicy_amendment: ExecPolicyAmendment,
|
||||
},
|
||||
ApprovedForSession,
|
||||
NetworkPolicyAmendment {
|
||||
network_policy_amendment: NetworkPolicyAmendment,
|
||||
},
|
||||
Denied,
|
||||
TimedOut,
|
||||
Abort,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) enum ApprovalDecisionSubject {
|
||||
Command(Vec<String>),
|
||||
NetworkAccess { target: String },
|
||||
}
|
||||
|
||||
pub fn new_approval_decision_cell(
|
||||
subject: ApprovalDecisionSubject,
|
||||
decision: ReviewDecision,
|
||||
actor: ApprovalDecisionActor,
|
||||
) -> Box<dyn HistoryCell> {
|
||||
use ReviewDecision::*;
|
||||
use codex_protocol::approvals::NetworkPolicyRuleAction;
|
||||
|
||||
let (symbol, summary): (Span<'static>, Vec<Span<'static>>) = match decision {
|
||||
Approved => match subject {
|
||||
ApprovalDecisionSubject::Command(command) => {
|
||||
let summary = if let Some(snippet) = non_empty_exec_snippet(&command) {
|
||||
vec![
|
||||
actor.subject().into(),
|
||||
"approved".bold(),
|
||||
" codex to run ".into(),
|
||||
Span::from(snippet).dim(),
|
||||
" this time".bold(),
|
||||
]
|
||||
} else {
|
||||
vec![
|
||||
actor.subject().into(),
|
||||
"approved".bold(),
|
||||
" this request".into(),
|
||||
" this time".bold(),
|
||||
]
|
||||
};
|
||||
("✔ ".green(), summary)
|
||||
}
|
||||
ApprovalDecisionSubject::NetworkAccess { target } => (
|
||||
"✔ ".green(),
|
||||
vec![
|
||||
actor.subject().into(),
|
||||
"approved".bold(),
|
||||
" codex network access to ".into(),
|
||||
Span::from(target).dim(),
|
||||
" this time".bold(),
|
||||
],
|
||||
),
|
||||
},
|
||||
ApprovedExecpolicyAmendment {
|
||||
proposed_execpolicy_amendment,
|
||||
} => {
|
||||
let snippet = Span::from(exec_snippet(&proposed_execpolicy_amendment.command)).dim();
|
||||
(
|
||||
"✔ ".green(),
|
||||
vec![
|
||||
actor.subject().into(),
|
||||
"approved".bold(),
|
||||
" codex to always run commands that start with ".into(),
|
||||
snippet,
|
||||
],
|
||||
)
|
||||
}
|
||||
ApprovedForSession => match subject {
|
||||
ApprovalDecisionSubject::Command(command) => {
|
||||
let summary = if let Some(snippet) = non_empty_exec_snippet(&command) {
|
||||
vec![
|
||||
actor.subject().into(),
|
||||
"approved".bold(),
|
||||
" codex to run ".into(),
|
||||
Span::from(snippet).dim(),
|
||||
" every time this session".bold(),
|
||||
]
|
||||
} else {
|
||||
vec![
|
||||
actor.subject().into(),
|
||||
"approved".bold(),
|
||||
" this request".into(),
|
||||
" every time this session".bold(),
|
||||
]
|
||||
};
|
||||
("✔ ".green(), summary)
|
||||
}
|
||||
ApprovalDecisionSubject::NetworkAccess { target } => (
|
||||
"✔ ".green(),
|
||||
vec![
|
||||
actor.subject().into(),
|
||||
"approved".bold(),
|
||||
" codex network access to ".into(),
|
||||
Span::from(target).dim(),
|
||||
" every time this session".bold(),
|
||||
],
|
||||
),
|
||||
},
|
||||
NetworkPolicyAmendment {
|
||||
network_policy_amendment,
|
||||
} => {
|
||||
let target = match subject {
|
||||
ApprovalDecisionSubject::NetworkAccess { target } => target,
|
||||
ApprovalDecisionSubject::Command(_) => network_policy_amendment.host,
|
||||
};
|
||||
match network_policy_amendment.action {
|
||||
NetworkPolicyRuleAction::Allow => (
|
||||
"✔ ".green(),
|
||||
vec![
|
||||
actor.subject().into(),
|
||||
"persisted".bold(),
|
||||
" Codex network access to ".into(),
|
||||
Span::from(target).dim(),
|
||||
],
|
||||
),
|
||||
NetworkPolicyRuleAction::Deny => (
|
||||
"✗ ".red(),
|
||||
vec![
|
||||
actor.subject().into(),
|
||||
"denied".bold(),
|
||||
" codex network access to ".into(),
|
||||
Span::from(target).dim(),
|
||||
" and saved that rule".into(),
|
||||
],
|
||||
),
|
||||
}
|
||||
}
|
||||
Denied => match subject {
|
||||
ApprovalDecisionSubject::Command(command) => {
|
||||
let summary = if let Some(snippet) = non_empty_exec_snippet(&command) {
|
||||
let snippet = Span::from(snippet).dim();
|
||||
match actor {
|
||||
ApprovalDecisionActor::User => vec![
|
||||
actor.subject().into(),
|
||||
"did not approve".bold(),
|
||||
" codex to run ".into(),
|
||||
snippet,
|
||||
],
|
||||
ApprovalDecisionActor::Guardian => vec![
|
||||
"Request ".into(),
|
||||
"denied".bold(),
|
||||
" for codex to run ".into(),
|
||||
snippet,
|
||||
],
|
||||
}
|
||||
} else {
|
||||
match actor {
|
||||
ApprovalDecisionActor::User => vec![
|
||||
actor.subject().into(),
|
||||
"did not approve".bold(),
|
||||
" this request".into(),
|
||||
],
|
||||
ApprovalDecisionActor::Guardian => {
|
||||
vec!["Request ".into(), "denied".bold()]
|
||||
}
|
||||
}
|
||||
};
|
||||
("✗ ".red(), summary)
|
||||
}
|
||||
ApprovalDecisionSubject::NetworkAccess { target } => (
|
||||
"✗ ".red(),
|
||||
vec![
|
||||
actor.subject().into(),
|
||||
"did not approve".bold(),
|
||||
" codex network access to ".into(),
|
||||
Span::from(target).dim(),
|
||||
],
|
||||
),
|
||||
},
|
||||
TimedOut => match subject {
|
||||
ApprovalDecisionSubject::Command(command) => {
|
||||
let summary = if let Some(snippet) = non_empty_exec_snippet(&command) {
|
||||
vec![
|
||||
"Review ".into(),
|
||||
"timed out".bold(),
|
||||
" before codex could run ".into(),
|
||||
Span::from(snippet).dim(),
|
||||
]
|
||||
} else {
|
||||
vec![
|
||||
"Review ".into(),
|
||||
"timed out".bold(),
|
||||
" before this request could be approved".into(),
|
||||
]
|
||||
};
|
||||
("✗ ".red(), summary)
|
||||
}
|
||||
ApprovalDecisionSubject::NetworkAccess { target } => (
|
||||
"✗ ".red(),
|
||||
vec![
|
||||
"Review ".into(),
|
||||
"timed out".bold(),
|
||||
" before codex could access ".into(),
|
||||
Span::from(target).dim(),
|
||||
],
|
||||
),
|
||||
},
|
||||
Abort => match subject {
|
||||
ApprovalDecisionSubject::Command(command) => {
|
||||
let summary = if let Some(snippet) = non_empty_exec_snippet(&command) {
|
||||
vec![
|
||||
actor.subject().into(),
|
||||
"canceled".bold(),
|
||||
" the request to run ".into(),
|
||||
Span::from(snippet).dim(),
|
||||
]
|
||||
} else {
|
||||
vec![
|
||||
actor.subject().into(),
|
||||
"canceled".bold(),
|
||||
" this request".into(),
|
||||
]
|
||||
};
|
||||
("✗ ".red(), summary)
|
||||
}
|
||||
ApprovalDecisionSubject::NetworkAccess { target } => (
|
||||
"✗ ".red(),
|
||||
vec![
|
||||
actor.subject().into(),
|
||||
"canceled".bold(),
|
||||
" the request for codex network access to ".into(),
|
||||
Span::from(target).dim(),
|
||||
],
|
||||
),
|
||||
},
|
||||
};
|
||||
|
||||
Box::new(PrefixedWrappedHistoryCell::new(
|
||||
Line::from(summary),
|
||||
symbol,
|
||||
" ",
|
||||
))
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ApprovalDecisionActor {
|
||||
User,
|
||||
Guardian,
|
||||
}
|
||||
|
||||
impl ApprovalDecisionActor {
|
||||
fn subject(self) -> &'static str {
|
||||
match self {
|
||||
Self::User => "You ",
|
||||
Self::Guardian => "Auto-reviewer ",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn new_guardian_denied_patch_request(files: Vec<String>) -> Box<dyn HistoryCell> {
|
||||
let mut summary = vec![
|
||||
"Request ".into(),
|
||||
"denied".bold(),
|
||||
" for codex to apply ".into(),
|
||||
];
|
||||
if files.len() == 1 {
|
||||
summary.push("a patch touching ".into());
|
||||
summary.push(Span::from(files[0].clone()).dim());
|
||||
} else {
|
||||
summary.push("a patch touching ".into());
|
||||
summary.push(Span::from(files.len().to_string()).dim());
|
||||
summary.push(" files".into());
|
||||
}
|
||||
|
||||
Box::new(PrefixedWrappedHistoryCell::new(
|
||||
Line::from(summary),
|
||||
"✗ ".red(),
|
||||
" ",
|
||||
))
|
||||
}
|
||||
|
||||
pub fn new_guardian_denied_action_request(summary: String) -> Box<dyn HistoryCell> {
|
||||
let line = Line::from(vec![
|
||||
"Request ".into(),
|
||||
"denied".bold(),
|
||||
" for ".into(),
|
||||
Span::from(summary).dim(),
|
||||
]);
|
||||
Box::new(PrefixedWrappedHistoryCell::new(line, "✗ ".red(), " "))
|
||||
}
|
||||
|
||||
pub fn new_guardian_approved_action_request(summary: String) -> Box<dyn HistoryCell> {
|
||||
let line = Line::from(vec![
|
||||
"Request ".into(),
|
||||
"approved".bold(),
|
||||
" for ".into(),
|
||||
Span::from(summary).dim(),
|
||||
]);
|
||||
Box::new(PrefixedWrappedHistoryCell::new(line, "✔ ".green(), " "))
|
||||
}
|
||||
|
||||
pub fn new_guardian_timed_out_patch_request(files: Vec<String>) -> Box<dyn HistoryCell> {
|
||||
let mut summary = vec![
|
||||
"Review ".into(),
|
||||
"timed out".bold(),
|
||||
" before codex could apply ".into(),
|
||||
];
|
||||
if files.len() == 1 {
|
||||
summary.push("a patch touching ".into());
|
||||
summary.push(Span::from(files[0].clone()).dim());
|
||||
} else {
|
||||
summary.push("a patch touching ".into());
|
||||
summary.push(Span::from(files.len().to_string()).dim());
|
||||
summary.push(" files".into());
|
||||
}
|
||||
|
||||
Box::new(PrefixedWrappedHistoryCell::new(
|
||||
Line::from(summary),
|
||||
"✗ ".red(),
|
||||
" ",
|
||||
))
|
||||
}
|
||||
|
||||
pub fn new_guardian_timed_out_action_request(summary: String) -> Box<dyn HistoryCell> {
|
||||
let line = Line::from(vec![
|
||||
"Review ".into(),
|
||||
"timed out".bold(),
|
||||
" before ".into(),
|
||||
Span::from(summary).dim(),
|
||||
]);
|
||||
Box::new(PrefixedWrappedHistoryCell::new(line, "✗ ".red(), " "))
|
||||
}
|
||||
|
||||
/// Cyan history cell line showing the current review status.
|
||||
pub(crate) fn new_review_status_line(message: String) -> PlainHistoryCell {
|
||||
PlainHistoryCell {
|
||||
lines: vec![Line::from(message.cyan())],
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
//! Shared history-cell building blocks reused across transcript concerns.
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct PlainHistoryCell {
|
||||
pub(super) lines: Vec<Line<'static>>,
|
||||
}
|
||||
|
||||
impl PlainHistoryCell {
|
||||
pub(crate) fn new(lines: Vec<Line<'static>>) -> Self {
|
||||
Self { lines }
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryCell for PlainHistoryCell {
|
||||
fn display_lines(&self, _width: u16) -> Vec<Line<'static>> {
|
||||
self.lines.clone()
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
plain_lines(self.lines.clone())
|
||||
}
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct PrefixedWrappedHistoryCell {
|
||||
text: Text<'static>,
|
||||
initial_prefix: Line<'static>,
|
||||
subsequent_prefix: Line<'static>,
|
||||
}
|
||||
|
||||
impl PrefixedWrappedHistoryCell {
|
||||
pub(crate) fn new(
|
||||
text: impl Into<Text<'static>>,
|
||||
initial_prefix: impl Into<Line<'static>>,
|
||||
subsequent_prefix: impl Into<Line<'static>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
text: text.into(),
|
||||
initial_prefix: initial_prefix.into(),
|
||||
subsequent_prefix: subsequent_prefix.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryCell for PrefixedWrappedHistoryCell {
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
if width == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let opts = RtOptions::new(width.max(1) as usize)
|
||||
.initial_indent(self.initial_prefix.clone())
|
||||
.subsequent_indent(self.subsequent_prefix.clone());
|
||||
adaptive_wrap_lines(&self.text, opts)
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
plain_lines(self.text.clone().lines)
|
||||
}
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct CompositeHistoryCell {
|
||||
pub(super) parts: Vec<Box<dyn HistoryCell>>,
|
||||
}
|
||||
|
||||
impl CompositeHistoryCell {
|
||||
pub(crate) fn new(parts: Vec<Box<dyn HistoryCell>>) -> Self {
|
||||
Self { parts }
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryCell for CompositeHistoryCell {
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
let mut out: Vec<Line<'static>> = Vec::new();
|
||||
let mut first = true;
|
||||
for part in &self.parts {
|
||||
let mut lines = part.display_lines(width);
|
||||
if !lines.is_empty() {
|
||||
if !first {
|
||||
out.push(Line::from(""));
|
||||
}
|
||||
out.append(&mut lines);
|
||||
first = false;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
let mut out: Vec<Line<'static>> = Vec::new();
|
||||
let mut first = true;
|
||||
for part in &self.parts {
|
||||
let mut lines = part.raw_lines();
|
||||
if !lines.is_empty() {
|
||||
if !first {
|
||||
out.push(Line::from(""));
|
||||
}
|
||||
out.append(&mut lines);
|
||||
first = false;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
//! Background terminal interaction and process-summary history cells.
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct UnifiedExecInteractionCell {
|
||||
command_display: Option<String>,
|
||||
stdin: String,
|
||||
}
|
||||
|
||||
impl UnifiedExecInteractionCell {
|
||||
pub(crate) fn new(command_display: Option<String>, stdin: String) -> Self {
|
||||
Self {
|
||||
command_display,
|
||||
stdin,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryCell for UnifiedExecInteractionCell {
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
if width == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let wrap_width = width as usize;
|
||||
let waited_only = self.stdin.is_empty();
|
||||
|
||||
let mut header_spans = if waited_only {
|
||||
vec!["• Waited for background terminal".bold()]
|
||||
} else {
|
||||
vec!["↳ ".dim(), "Interacted with background terminal".bold()]
|
||||
};
|
||||
if let Some(command) = &self.command_display
|
||||
&& !command.is_empty()
|
||||
{
|
||||
header_spans.push(" · ".dim());
|
||||
header_spans.push(command.clone().dim());
|
||||
}
|
||||
let header = Line::from(header_spans);
|
||||
|
||||
let mut out: Vec<Line<'static>> = Vec::new();
|
||||
let header_wrapped = adaptive_wrap_line(&header, RtOptions::new(wrap_width));
|
||||
push_owned_lines(&header_wrapped, &mut out);
|
||||
|
||||
if waited_only {
|
||||
return out;
|
||||
}
|
||||
|
||||
let input_lines: Vec<Line<'static>> = self
|
||||
.stdin
|
||||
.lines()
|
||||
.map(|line| Line::from(line.to_string()))
|
||||
.collect();
|
||||
|
||||
let input_wrapped = adaptive_wrap_lines(
|
||||
input_lines,
|
||||
RtOptions::new(wrap_width)
|
||||
.initial_indent(Line::from(" └ ".dim()))
|
||||
.subsequent_indent(Line::from(" ".dim())),
|
||||
);
|
||||
out.extend(input_wrapped);
|
||||
out
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
let mut out = Vec::new();
|
||||
if self.stdin.is_empty() {
|
||||
if let Some(command) = self
|
||||
.command_display
|
||||
.as_ref()
|
||||
.filter(|command| !command.is_empty())
|
||||
{
|
||||
out.push(Line::from(format!(
|
||||
"Waited for background terminal: {command}"
|
||||
)));
|
||||
} else {
|
||||
out.push(Line::from("Waited for background terminal"));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
if let Some(command) = self
|
||||
.command_display
|
||||
.as_ref()
|
||||
.filter(|command| !command.is_empty())
|
||||
{
|
||||
out.push(Line::from(format!(
|
||||
"Interacted with background terminal: {command}"
|
||||
)));
|
||||
} else {
|
||||
out.push(Line::from("Interacted with background terminal"));
|
||||
}
|
||||
out.extend(raw_lines_from_source(&self.stdin));
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn new_unified_exec_interaction(
|
||||
command_display: Option<String>,
|
||||
stdin: String,
|
||||
) -> UnifiedExecInteractionCell {
|
||||
UnifiedExecInteractionCell::new(command_display, stdin)
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct UnifiedExecProcessesCell {
|
||||
processes: Vec<UnifiedExecProcessDetails>,
|
||||
}
|
||||
|
||||
impl UnifiedExecProcessesCell {
|
||||
fn new(processes: Vec<UnifiedExecProcessDetails>) -> Self {
|
||||
Self { processes }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct UnifiedExecProcessDetails {
|
||||
pub(crate) command_display: String,
|
||||
pub(crate) recent_chunks: Vec<String>,
|
||||
}
|
||||
|
||||
impl HistoryCell for UnifiedExecProcessesCell {
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
if width == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let wrap_width = width as usize;
|
||||
let max_processes = 16usize;
|
||||
let mut out: Vec<Line<'static>> = Vec::new();
|
||||
out.push(vec!["Background terminals".bold()].into());
|
||||
out.push("".into());
|
||||
|
||||
if self.processes.is_empty() {
|
||||
out.push(" • No background terminals running.".italic().into());
|
||||
return out;
|
||||
}
|
||||
|
||||
let prefix = " • ";
|
||||
let prefix_width = UnicodeWidthStr::width(prefix);
|
||||
let truncation_suffix = " [...]";
|
||||
let truncation_suffix_width = UnicodeWidthStr::width(truncation_suffix);
|
||||
let mut shown = 0usize;
|
||||
for process in &self.processes {
|
||||
if shown >= max_processes {
|
||||
break;
|
||||
}
|
||||
let command = &process.command_display;
|
||||
let (snippet, snippet_truncated) = {
|
||||
let (first_line, has_more_lines) = match command.split_once('\n') {
|
||||
Some((first, _)) => (first, true),
|
||||
None => (command.as_str(), false),
|
||||
};
|
||||
let max_graphemes = 80;
|
||||
let mut graphemes = first_line.grapheme_indices(true);
|
||||
if let Some((byte_index, _)) = graphemes.nth(max_graphemes) {
|
||||
(first_line[..byte_index].to_string(), true)
|
||||
} else {
|
||||
(first_line.to_string(), has_more_lines)
|
||||
}
|
||||
};
|
||||
if wrap_width <= prefix_width {
|
||||
out.push(Line::from(prefix.dim()));
|
||||
shown += 1;
|
||||
continue;
|
||||
}
|
||||
let budget = wrap_width.saturating_sub(prefix_width);
|
||||
let mut needs_suffix = snippet_truncated;
|
||||
if !needs_suffix {
|
||||
let (_, remainder, _) = take_prefix_by_width(&snippet, budget);
|
||||
if !remainder.is_empty() {
|
||||
needs_suffix = true;
|
||||
}
|
||||
}
|
||||
if needs_suffix && budget > truncation_suffix_width {
|
||||
let available = budget.saturating_sub(truncation_suffix_width);
|
||||
let (truncated, _, _) = take_prefix_by_width(&snippet, available);
|
||||
out.push(vec![prefix.dim(), truncated.cyan(), truncation_suffix.dim()].into());
|
||||
} else {
|
||||
let (truncated, _, _) = take_prefix_by_width(&snippet, budget);
|
||||
out.push(vec![prefix.dim(), truncated.cyan()].into());
|
||||
}
|
||||
|
||||
let chunk_prefix_first = " ↳ ";
|
||||
let chunk_prefix_next = " ";
|
||||
for (idx, chunk) in process.recent_chunks.iter().enumerate() {
|
||||
let chunk_prefix = if idx == 0 {
|
||||
chunk_prefix_first
|
||||
} else {
|
||||
chunk_prefix_next
|
||||
};
|
||||
let chunk_prefix_width = UnicodeWidthStr::width(chunk_prefix);
|
||||
if wrap_width <= chunk_prefix_width {
|
||||
out.push(Line::from(chunk_prefix.dim()));
|
||||
continue;
|
||||
}
|
||||
let budget = wrap_width.saturating_sub(chunk_prefix_width);
|
||||
let (truncated, remainder, _) = take_prefix_by_width(chunk, budget);
|
||||
if !remainder.is_empty() && budget > truncation_suffix_width {
|
||||
let available = budget.saturating_sub(truncation_suffix_width);
|
||||
let (shorter, _, _) = take_prefix_by_width(chunk, available);
|
||||
out.push(
|
||||
vec![chunk_prefix.dim(), shorter.dim(), truncation_suffix.dim()].into(),
|
||||
);
|
||||
} else {
|
||||
out.push(vec![chunk_prefix.dim(), truncated.dim()].into());
|
||||
}
|
||||
}
|
||||
shown += 1;
|
||||
}
|
||||
|
||||
let remaining = self.processes.len().saturating_sub(shown);
|
||||
if remaining > 0 {
|
||||
let more_text = format!("... and {remaining} more running");
|
||||
if wrap_width <= prefix_width {
|
||||
out.push(Line::from(prefix.dim()));
|
||||
} else {
|
||||
let budget = wrap_width.saturating_sub(prefix_width);
|
||||
let (truncated, _, _) = take_prefix_by_width(&more_text, budget);
|
||||
out.push(vec![prefix.dim(), truncated.dim()].into());
|
||||
}
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
plain_lines(self.display_lines(u16::MAX))
|
||||
}
|
||||
|
||||
fn desired_height(&self, width: u16) -> u16 {
|
||||
self.display_lines(width).len() as u16
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn new_unified_exec_processes_output(
|
||||
processes: Vec<UnifiedExecProcessDetails>,
|
||||
) -> CompositeHistoryCell {
|
||||
let command = PlainHistoryCell::new(vec!["/ps".magenta().into()]);
|
||||
let summary = UnifiedExecProcessesCell::new(processes);
|
||||
CompositeHistoryCell::new(vec![Box::new(command), Box::new(summary)])
|
||||
}
|
||||
@@ -0,0 +1,780 @@
|
||||
//! MCP tool-call, inventory, and output history cells.
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct CompletedMcpToolCallWithImageOutput {
|
||||
_image: DynamicImage,
|
||||
}
|
||||
impl HistoryCell for CompletedMcpToolCallWithImageOutput {
|
||||
fn display_lines(&self, _width: u16) -> Vec<Line<'static>> {
|
||||
vec!["tool result (image output)".into()]
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
vec![Line::from("tool result (image output)")]
|
||||
}
|
||||
}
|
||||
fn mcp_auth_status_label(status: McpAuthStatus) -> &'static str {
|
||||
match status {
|
||||
McpAuthStatus::Unsupported => "Unsupported",
|
||||
McpAuthStatus::NotLoggedIn => "Not logged in",
|
||||
McpAuthStatus::BearerToken => "Bearer token",
|
||||
McpAuthStatus::OAuth => "OAuth",
|
||||
}
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct McpToolCallCell {
|
||||
call_id: String,
|
||||
invocation: McpInvocation,
|
||||
start_time: Instant,
|
||||
duration: Option<Duration>,
|
||||
result: Option<Result<codex_protocol::mcp::CallToolResult, String>>,
|
||||
animations_enabled: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct McpInvocation {
|
||||
pub(crate) server: String,
|
||||
pub(crate) tool: String,
|
||||
pub(crate) arguments: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
impl McpToolCallCell {
|
||||
pub(crate) fn new(
|
||||
call_id: String,
|
||||
invocation: McpInvocation,
|
||||
animations_enabled: bool,
|
||||
) -> Self {
|
||||
Self {
|
||||
call_id,
|
||||
invocation,
|
||||
start_time: Instant::now(),
|
||||
duration: None,
|
||||
result: None,
|
||||
animations_enabled,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn call_id(&self) -> &str {
|
||||
&self.call_id
|
||||
}
|
||||
|
||||
pub(crate) fn complete(
|
||||
&mut self,
|
||||
duration: Duration,
|
||||
result: Result<codex_protocol::mcp::CallToolResult, String>,
|
||||
) -> Option<Box<dyn HistoryCell>> {
|
||||
let image_cell = try_new_completed_mcp_tool_call_with_image_output(&result)
|
||||
.map(|cell| Box::new(cell) as Box<dyn HistoryCell>);
|
||||
self.duration = Some(duration);
|
||||
self.result = Some(result);
|
||||
image_cell
|
||||
}
|
||||
|
||||
fn success(&self) -> Option<bool> {
|
||||
match self.result.as_ref() {
|
||||
Some(Ok(result)) => Some(!result.is_error.unwrap_or(false)),
|
||||
Some(Err(_)) => Some(false),
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn mark_failed(&mut self) {
|
||||
let elapsed = self.start_time.elapsed();
|
||||
self.duration = Some(elapsed);
|
||||
self.result = Some(Err("interrupted".to_string()));
|
||||
}
|
||||
|
||||
fn render_content_block(block: &serde_json::Value, width: usize) -> String {
|
||||
let content = match serde_json::from_value::<rmcp::model::Content>(block.clone()) {
|
||||
Ok(content) => content,
|
||||
Err(_) => {
|
||||
return format_and_truncate_tool_result(
|
||||
&block.to_string(),
|
||||
TOOL_CALL_MAX_LINES,
|
||||
width,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
match content.raw {
|
||||
rmcp::model::RawContent::Text(text) => {
|
||||
format_and_truncate_tool_result(&text.text, TOOL_CALL_MAX_LINES, width)
|
||||
}
|
||||
rmcp::model::RawContent::Image(_) => "<image content>".to_string(),
|
||||
rmcp::model::RawContent::Audio(_) => "<audio content>".to_string(),
|
||||
rmcp::model::RawContent::Resource(resource) => {
|
||||
let uri = match resource.resource {
|
||||
rmcp::model::ResourceContents::TextResourceContents { uri, .. } => uri,
|
||||
rmcp::model::ResourceContents::BlobResourceContents { uri, .. } => uri,
|
||||
};
|
||||
format!("embedded resource: {uri}")
|
||||
}
|
||||
rmcp::model::RawContent::ResourceLink(link) => format!("link: {}", link.uri),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryCell for McpToolCallCell {
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
let mut lines: Vec<Line<'static>> = Vec::new();
|
||||
let status = self.success();
|
||||
let bullet = match status {
|
||||
Some(true) => "•".green().bold(),
|
||||
Some(false) => "•".red().bold(),
|
||||
None => activity_indicator(
|
||||
Some(self.start_time),
|
||||
MotionMode::from_animations_enabled(self.animations_enabled),
|
||||
ReducedMotionIndicator::StaticBullet,
|
||||
)
|
||||
.unwrap_or_else(|| "•".dim()),
|
||||
};
|
||||
let header_text = if status.is_some() {
|
||||
"Called"
|
||||
} else {
|
||||
"Calling"
|
||||
};
|
||||
|
||||
let invocation_line = line_to_static(&format_mcp_invocation(self.invocation.clone()));
|
||||
let mut compact_spans = vec![bullet.clone(), " ".into(), header_text.bold(), " ".into()];
|
||||
let mut compact_header = Line::from(compact_spans.clone());
|
||||
let reserved = compact_header.width();
|
||||
|
||||
let inline_invocation =
|
||||
invocation_line.width() <= (width as usize).saturating_sub(reserved);
|
||||
|
||||
if inline_invocation {
|
||||
compact_header.extend(invocation_line.spans.clone());
|
||||
lines.push(compact_header);
|
||||
} else {
|
||||
compact_spans.pop(); // drop trailing space for standalone header
|
||||
lines.push(Line::from(compact_spans));
|
||||
|
||||
let opts = RtOptions::new((width as usize).saturating_sub(4))
|
||||
.initial_indent("".into())
|
||||
.subsequent_indent(" ".into());
|
||||
let wrapped = adaptive_wrap_line(&invocation_line, opts);
|
||||
let body_lines: Vec<Line<'static>> = wrapped.iter().map(line_to_static).collect();
|
||||
lines.extend(prefix_lines(body_lines, " └ ".dim(), " ".into()));
|
||||
}
|
||||
|
||||
let mut detail_lines: Vec<Line<'static>> = Vec::new();
|
||||
// Reserve four columns for the tree prefix (" └ "/" ") and ensure the wrapper still has at least one cell to work with.
|
||||
let detail_wrap_width = (width as usize).saturating_sub(4).max(1);
|
||||
|
||||
if let Some(result) = &self.result {
|
||||
match result {
|
||||
Ok(codex_protocol::mcp::CallToolResult { content, .. }) => {
|
||||
if !content.is_empty() {
|
||||
for block in content {
|
||||
let text = Self::render_content_block(block, detail_wrap_width);
|
||||
for segment in text.split('\n') {
|
||||
let line = Line::from(segment.to_string().dim());
|
||||
let wrapped = adaptive_wrap_line(
|
||||
&line,
|
||||
RtOptions::new(detail_wrap_width)
|
||||
.initial_indent("".into())
|
||||
.subsequent_indent(" ".into()),
|
||||
);
|
||||
detail_lines.extend(wrapped.iter().map(line_to_static));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
let err_text = format_and_truncate_tool_result(
|
||||
&format!("Error: {err}"),
|
||||
TOOL_CALL_MAX_LINES,
|
||||
width as usize,
|
||||
);
|
||||
let err_line = Line::from(err_text.dim());
|
||||
let wrapped = adaptive_wrap_line(
|
||||
&err_line,
|
||||
RtOptions::new(detail_wrap_width)
|
||||
.initial_indent("".into())
|
||||
.subsequent_indent(" ".into()),
|
||||
);
|
||||
detail_lines.extend(wrapped.iter().map(line_to_static));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !detail_lines.is_empty() {
|
||||
let initial_prefix: Span<'static> = if inline_invocation {
|
||||
" └ ".dim()
|
||||
} else {
|
||||
" ".into()
|
||||
};
|
||||
lines.extend(prefix_lines(detail_lines, initial_prefix, " ".into()));
|
||||
}
|
||||
|
||||
lines
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
let header_text = if self.success().is_some() {
|
||||
"Called"
|
||||
} else {
|
||||
"Calling"
|
||||
};
|
||||
let mut lines = vec![Line::from(format!(
|
||||
"{header_text} {}",
|
||||
format_mcp_invocation(self.invocation.clone())
|
||||
))];
|
||||
|
||||
if let Some(result) = &self.result {
|
||||
match result {
|
||||
Ok(codex_protocol::mcp::CallToolResult { content, .. }) => {
|
||||
for block in content {
|
||||
let text = Self::render_content_block(block, RAW_TOOL_OUTPUT_WIDTH);
|
||||
lines.extend(raw_lines_from_source(&text));
|
||||
}
|
||||
}
|
||||
Err(err) => lines.push(Line::from(format!("Error: {err}"))),
|
||||
}
|
||||
}
|
||||
|
||||
lines
|
||||
}
|
||||
|
||||
fn transcript_animation_tick(&self) -> Option<u64> {
|
||||
if !self.animations_enabled || self.result.is_some() {
|
||||
return None;
|
||||
}
|
||||
Some((self.start_time.elapsed().as_millis() / 50) as u64)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn new_active_mcp_tool_call(
|
||||
call_id: String,
|
||||
invocation: McpInvocation,
|
||||
animations_enabled: bool,
|
||||
) -> McpToolCallCell {
|
||||
McpToolCallCell::new(call_id, invocation, animations_enabled)
|
||||
}
|
||||
/// Returns an additional history cell if an MCP tool result includes a decodable image.
|
||||
///
|
||||
/// This intentionally returns at most one cell: the first image in `CallToolResult.content` that
|
||||
/// successfully base64-decodes and parses as an image. This is used as a lightweight “image output
|
||||
/// exists” affordance separate from the main MCP tool call cell.
|
||||
///
|
||||
/// Manual testing tip:
|
||||
/// - Run the rmcp stdio test server (`codex-rs/rmcp-client/src/bin/test_stdio_server.rs`) and
|
||||
/// register it as an MCP server via `codex mcp add`.
|
||||
/// - Use its `image_scenario` tool with cases like `text_then_image`,
|
||||
/// `invalid_base64_then_image`, or `invalid_image_bytes_then_image` to ensure this path triggers
|
||||
/// even when the first block is not a valid image.
|
||||
fn try_new_completed_mcp_tool_call_with_image_output(
|
||||
result: &Result<codex_protocol::mcp::CallToolResult, String>,
|
||||
) -> Option<CompletedMcpToolCallWithImageOutput> {
|
||||
let image = result
|
||||
.as_ref()
|
||||
.ok()?
|
||||
.content
|
||||
.iter()
|
||||
.find_map(decode_mcp_image)?;
|
||||
|
||||
Some(CompletedMcpToolCallWithImageOutput { _image: image })
|
||||
}
|
||||
|
||||
/// Decodes an MCP `ImageContent` block into an in-memory image.
|
||||
///
|
||||
/// Returns `None` when the block is not an image, when base64 decoding fails, when the format
|
||||
/// cannot be inferred, or when the image decoder rejects the bytes.
|
||||
fn decode_mcp_image(block: &serde_json::Value) -> Option<DynamicImage> {
|
||||
let content = serde_json::from_value::<rmcp::model::Content>(block.clone()).ok()?;
|
||||
let rmcp::model::RawContent::Image(image) = content.raw else {
|
||||
return None;
|
||||
};
|
||||
let base64_data = if let Some(data_url) = image.data.strip_prefix("data:") {
|
||||
data_url.split_once(',')?.1
|
||||
} else {
|
||||
image.data.as_str()
|
||||
};
|
||||
let raw_data = base64::engine::general_purpose::STANDARD
|
||||
.decode(base64_data)
|
||||
.map_err(|e| {
|
||||
error!("Failed to decode image data: {e}");
|
||||
e
|
||||
})
|
||||
.ok()?;
|
||||
let reader = ImageReader::new(Cursor::new(raw_data))
|
||||
.with_guessed_format()
|
||||
.map_err(|e| {
|
||||
error!("Failed to guess image format: {e}");
|
||||
e
|
||||
})
|
||||
.ok()?;
|
||||
|
||||
reader
|
||||
.decode()
|
||||
.map_err(|e| {
|
||||
error!("Image decoding failed: {e}");
|
||||
e
|
||||
})
|
||||
.ok()
|
||||
}
|
||||
/// Render a summary of configured MCP servers from the current `Config`.
|
||||
pub(crate) fn empty_mcp_output() -> PlainHistoryCell {
|
||||
let lines: Vec<Line<'static>> = vec![
|
||||
"/mcp".magenta().into(),
|
||||
"".into(),
|
||||
vec!["🔌 ".into(), "MCP Tools".bold()].into(),
|
||||
"".into(),
|
||||
" • No MCP servers configured.".italic().into(),
|
||||
Line::from(vec![
|
||||
" See the ".into(),
|
||||
"\u{1b}]8;;https://developers.openai.com/codex/mcp\u{7}MCP docs\u{1b}]8;;\u{7}"
|
||||
.underlined(),
|
||||
" to configure them.".into(),
|
||||
])
|
||||
.style(Style::default().add_modifier(Modifier::DIM)),
|
||||
];
|
||||
|
||||
PlainHistoryCell { lines }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
/// Render MCP tools grouped by connection using the fully-qualified tool names.
|
||||
pub(crate) fn new_mcp_tools_output(
|
||||
config: &Config,
|
||||
tools: HashMap<String, codex_protocol::mcp::Tool>,
|
||||
resources: HashMap<String, Vec<Resource>>,
|
||||
resource_templates: HashMap<String, Vec<ResourceTemplate>>,
|
||||
auth_statuses: &HashMap<String, McpAuthStatus>,
|
||||
) -> PlainHistoryCell {
|
||||
let mut lines: Vec<Line<'static>> = vec![
|
||||
"/mcp".magenta().into(),
|
||||
"".into(),
|
||||
vec!["🔌 ".into(), "MCP Tools".bold()].into(),
|
||||
"".into(),
|
||||
];
|
||||
|
||||
if tools.is_empty() {
|
||||
lines.push(" • No MCP tools available.".italic().into());
|
||||
lines.push("".into());
|
||||
}
|
||||
|
||||
let effective_servers = config.mcp_servers.get().clone();
|
||||
let mut servers: Vec<_> = effective_servers.iter().collect();
|
||||
servers.sort_by(|(a, _), (b, _)| a.cmp(b));
|
||||
|
||||
for (server, cfg) in servers {
|
||||
let prefix = qualified_mcp_tool_name_prefix(server);
|
||||
let mut names: Vec<String> = tools
|
||||
.keys()
|
||||
.filter(|k| k.starts_with(&prefix))
|
||||
.map(|k| k[prefix.len()..].to_string())
|
||||
.collect();
|
||||
names.sort();
|
||||
|
||||
let auth_status = auth_statuses
|
||||
.get(server.as_str())
|
||||
.copied()
|
||||
.unwrap_or(McpAuthStatus::Unsupported);
|
||||
let mut header: Vec<Span<'static>> = vec![" • ".into(), server.clone().into()];
|
||||
if !cfg.enabled {
|
||||
header.push(" ".into());
|
||||
header.push("(disabled)".red());
|
||||
lines.push(header.into());
|
||||
if let Some(reason) = cfg.disabled_reason.as_ref().map(ToString::to_string) {
|
||||
lines.push(vec![" • Reason: ".into(), reason.dim()].into());
|
||||
}
|
||||
lines.push(Line::from(""));
|
||||
continue;
|
||||
}
|
||||
lines.push(header.into());
|
||||
lines.push(vec![" • Status: ".into(), "enabled".green()].into());
|
||||
lines.push(
|
||||
vec![
|
||||
" • Auth: ".into(),
|
||||
mcp_auth_status_label(auth_status).into(),
|
||||
]
|
||||
.into(),
|
||||
);
|
||||
|
||||
match &cfg.transport {
|
||||
McpServerTransportConfig::Stdio {
|
||||
command,
|
||||
args,
|
||||
env,
|
||||
env_vars,
|
||||
cwd,
|
||||
} => {
|
||||
let args_suffix = if args.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(" {}", args.join(" "))
|
||||
};
|
||||
let cmd_display = format!("{command}{args_suffix}");
|
||||
lines.push(vec![" • Command: ".into(), cmd_display.into()].into());
|
||||
|
||||
if let Some(cwd) = cwd.as_ref() {
|
||||
lines.push(vec![" • Cwd: ".into(), cwd.display().to_string().into()].into());
|
||||
}
|
||||
|
||||
let env_display = format_env_display(env.as_ref(), env_vars);
|
||||
if env_display != "-" {
|
||||
lines.push(vec![" • Env: ".into(), env_display.into()].into());
|
||||
}
|
||||
}
|
||||
McpServerTransportConfig::StreamableHttp {
|
||||
url,
|
||||
http_headers,
|
||||
env_http_headers,
|
||||
..
|
||||
} => {
|
||||
lines.push(vec![" • URL: ".into(), url.clone().into()].into());
|
||||
if let Some(headers) = http_headers.as_ref()
|
||||
&& !headers.is_empty()
|
||||
{
|
||||
let mut pairs: Vec<_> = headers.iter().collect();
|
||||
pairs.sort_by(|(a, _), (b, _)| a.cmp(b));
|
||||
let display = pairs
|
||||
.into_iter()
|
||||
.map(|(name, _)| format!("{name}=*****"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
lines.push(vec![" • HTTP headers: ".into(), display.into()].into());
|
||||
}
|
||||
if let Some(headers) = env_http_headers.as_ref()
|
||||
&& !headers.is_empty()
|
||||
{
|
||||
let mut pairs: Vec<_> = headers.iter().collect();
|
||||
pairs.sort_by(|(a, _), (b, _)| a.cmp(b));
|
||||
let display = pairs
|
||||
.into_iter()
|
||||
.map(|(name, var)| format!("{name}={var}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
lines.push(vec![" • Env HTTP headers: ".into(), display.into()].into());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if names.is_empty() {
|
||||
lines.push(" • Tools: (none)".into());
|
||||
} else {
|
||||
lines.push(vec![" • Tools: ".into(), names.join(", ").into()].into());
|
||||
}
|
||||
|
||||
let server_resources: Vec<Resource> =
|
||||
resources.get(server.as_str()).cloned().unwrap_or_default();
|
||||
if server_resources.is_empty() {
|
||||
lines.push(" • Resources: (none)".into());
|
||||
} else {
|
||||
let mut spans: Vec<Span<'static>> = vec![" • Resources: ".into()];
|
||||
|
||||
for (idx, resource) in server_resources.iter().enumerate() {
|
||||
if idx > 0 {
|
||||
spans.push(", ".into());
|
||||
}
|
||||
|
||||
let label = resource.title.as_ref().unwrap_or(&resource.name);
|
||||
spans.push(label.clone().into());
|
||||
spans.push(" ".into());
|
||||
spans.push(format!("({})", resource.uri).dim());
|
||||
}
|
||||
|
||||
lines.push(spans.into());
|
||||
}
|
||||
|
||||
let server_templates: Vec<ResourceTemplate> = resource_templates
|
||||
.get(server.as_str())
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
if server_templates.is_empty() {
|
||||
lines.push(" • Resource templates: (none)".into());
|
||||
} else {
|
||||
let mut spans: Vec<Span<'static>> = vec![" • Resource templates: ".into()];
|
||||
|
||||
for (idx, template) in server_templates.iter().enumerate() {
|
||||
if idx > 0 {
|
||||
spans.push(", ".into());
|
||||
}
|
||||
|
||||
let label = template.title.as_ref().unwrap_or(&template.name);
|
||||
spans.push(label.clone().into());
|
||||
spans.push(" ".into());
|
||||
spans.push(format!("({})", template.uri_template).dim());
|
||||
}
|
||||
|
||||
lines.push(spans.into());
|
||||
}
|
||||
|
||||
lines.push(Line::from(""));
|
||||
}
|
||||
|
||||
PlainHistoryCell { lines }
|
||||
}
|
||||
|
||||
/// Build the `/mcp` history cell from app-server `McpServerStatus` responses.
|
||||
///
|
||||
/// The server list comes directly from the app-server status response, sorted
|
||||
/// alphabetically. Local config is only used to enrich returned servers with
|
||||
/// transport details such as command, URL, cwd, and environment display.
|
||||
///
|
||||
/// This mirrors the layout of [`new_mcp_tools_output`] but sources data from
|
||||
/// the paginated RPC response rather than the in-process `McpManager`. The
|
||||
/// `detail` flag controls whether resources and resource templates are rendered.
|
||||
pub(crate) fn new_mcp_tools_output_from_statuses(
|
||||
config: &Config,
|
||||
statuses: &[McpServerStatus],
|
||||
detail: McpServerStatusDetail,
|
||||
) -> PlainHistoryCell {
|
||||
let mut lines: Vec<Line<'static>> = vec![
|
||||
"/mcp".magenta().into(),
|
||||
"".into(),
|
||||
vec!["🔌 ".into(), "MCP Tools".bold()].into(),
|
||||
"".into(),
|
||||
];
|
||||
|
||||
let mut statuses_by_name = HashMap::new();
|
||||
for status in statuses {
|
||||
statuses_by_name.insert(status.name.as_str(), status);
|
||||
}
|
||||
|
||||
let mut server_names: Vec<String> = statuses.iter().map(|status| status.name.clone()).collect();
|
||||
server_names.sort();
|
||||
|
||||
let has_any_tools = statuses.iter().any(|status| !status.tools.is_empty());
|
||||
if !has_any_tools {
|
||||
lines.push(" • No MCP tools available.".italic().into());
|
||||
lines.push("".into());
|
||||
}
|
||||
|
||||
for server in server_names {
|
||||
let cfg = config.mcp_servers.get().get(server.as_str());
|
||||
let status = statuses_by_name.get(server.as_str()).copied();
|
||||
let header: Vec<Span<'static>> = vec![" • ".into(), server.clone().into()];
|
||||
|
||||
lines.push(header.into());
|
||||
if matches!(detail, McpServerStatusDetail::Full) {
|
||||
let enabled = cfg.map(|cfg| cfg.enabled).unwrap_or(true);
|
||||
let status_text = if enabled {
|
||||
"enabled".green()
|
||||
} else {
|
||||
"disabled".red()
|
||||
};
|
||||
lines.push(vec![" • Status: ".into(), status_text].into());
|
||||
if let Some(reason) = cfg.and_then(|cfg| cfg.disabled_reason.as_ref()) {
|
||||
lines.push(vec![" • Reason: ".into(), reason.to_string().dim()].into());
|
||||
}
|
||||
}
|
||||
let auth_status = status
|
||||
.map(|status| match status.auth_status {
|
||||
codex_app_server_protocol::McpAuthStatus::Unsupported => McpAuthStatus::Unsupported,
|
||||
codex_app_server_protocol::McpAuthStatus::NotLoggedIn => McpAuthStatus::NotLoggedIn,
|
||||
codex_app_server_protocol::McpAuthStatus::BearerToken => McpAuthStatus::BearerToken,
|
||||
codex_app_server_protocol::McpAuthStatus::OAuth => McpAuthStatus::OAuth,
|
||||
})
|
||||
.unwrap_or(McpAuthStatus::Unsupported);
|
||||
lines.push(
|
||||
vec![
|
||||
" • Auth: ".into(),
|
||||
mcp_auth_status_label(auth_status).into(),
|
||||
]
|
||||
.into(),
|
||||
);
|
||||
|
||||
if let Some(cfg) = cfg {
|
||||
match &cfg.transport {
|
||||
McpServerTransportConfig::Stdio {
|
||||
command,
|
||||
args,
|
||||
env,
|
||||
env_vars,
|
||||
cwd,
|
||||
} => {
|
||||
let args_suffix = if args.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(" {}", args.join(" "))
|
||||
};
|
||||
let cmd_display = format!("{command}{args_suffix}");
|
||||
lines.push(vec![" • Command: ".into(), cmd_display.into()].into());
|
||||
|
||||
if let Some(cwd) = cwd.as_ref() {
|
||||
lines.push(
|
||||
vec![" • Cwd: ".into(), cwd.display().to_string().into()].into(),
|
||||
);
|
||||
}
|
||||
|
||||
let env_display = format_env_display(env.as_ref(), env_vars.as_slice());
|
||||
if env_display != "-" {
|
||||
lines.push(vec![" • Env: ".into(), env_display.into()].into());
|
||||
}
|
||||
}
|
||||
McpServerTransportConfig::StreamableHttp {
|
||||
url,
|
||||
http_headers,
|
||||
env_http_headers,
|
||||
..
|
||||
} => {
|
||||
lines.push(vec![" • URL: ".into(), url.clone().into()].into());
|
||||
if let Some(headers) = http_headers.as_ref()
|
||||
&& !headers.is_empty()
|
||||
{
|
||||
let mut pairs: Vec<_> = headers.iter().collect();
|
||||
pairs.sort_by(|(a, _), (b, _)| a.cmp(b));
|
||||
let display = pairs
|
||||
.into_iter()
|
||||
.map(|(name, _)| format!("{name}=*****"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
lines.push(vec![" • HTTP headers: ".into(), display.into()].into());
|
||||
}
|
||||
if let Some(headers) = env_http_headers.as_ref()
|
||||
&& !headers.is_empty()
|
||||
{
|
||||
let mut pairs: Vec<_> = headers.iter().collect();
|
||||
pairs.sort_by(|(a, _), (b, _)| a.cmp(b));
|
||||
let display = pairs
|
||||
.into_iter()
|
||||
.map(|(name, var)| format!("{name}={var}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
lines.push(vec![" • Env HTTP headers: ".into(), display.into()].into());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut names = status
|
||||
.map(|status| status.tools.keys().cloned().collect::<Vec<_>>())
|
||||
.unwrap_or_default();
|
||||
names.sort();
|
||||
if names.is_empty() {
|
||||
lines.push(" • Tools: (none)".into());
|
||||
} else {
|
||||
lines.push(vec![" • Tools: ".into(), names.join(", ").into()].into());
|
||||
}
|
||||
|
||||
if matches!(detail, McpServerStatusDetail::Full) {
|
||||
let server_resources = status
|
||||
.map(|status| status.resources.clone())
|
||||
.unwrap_or_default();
|
||||
if server_resources.is_empty() {
|
||||
lines.push(" • Resources: (none)".into());
|
||||
} else {
|
||||
let mut spans: Vec<Span<'static>> = vec![" • Resources: ".into()];
|
||||
|
||||
for (idx, resource) in server_resources.iter().enumerate() {
|
||||
if idx > 0 {
|
||||
spans.push(", ".into());
|
||||
}
|
||||
|
||||
let label = resource.title.as_ref().unwrap_or(&resource.name);
|
||||
spans.push(label.clone().into());
|
||||
spans.push(" ".into());
|
||||
spans.push(format!("({})", resource.uri).dim());
|
||||
}
|
||||
|
||||
lines.push(spans.into());
|
||||
}
|
||||
|
||||
let server_templates = status
|
||||
.map(|status| status.resource_templates.clone())
|
||||
.unwrap_or_default();
|
||||
if server_templates.is_empty() {
|
||||
lines.push(" • Resource templates: (none)".into());
|
||||
} else {
|
||||
let mut spans: Vec<Span<'static>> = vec![" • Resource templates: ".into()];
|
||||
|
||||
for (idx, template) in server_templates.iter().enumerate() {
|
||||
if idx > 0 {
|
||||
spans.push(", ".into());
|
||||
}
|
||||
|
||||
let label = template.title.as_ref().unwrap_or(&template.name);
|
||||
spans.push(label.clone().into());
|
||||
spans.push(" ".into());
|
||||
spans.push(format!("({})", template.uri_template).dim());
|
||||
}
|
||||
|
||||
lines.push(spans.into());
|
||||
}
|
||||
}
|
||||
|
||||
lines.push(Line::from(""));
|
||||
}
|
||||
|
||||
PlainHistoryCell { lines }
|
||||
}
|
||||
/// A transient history cell that shows an animated spinner while the MCP
|
||||
/// inventory RPC is in flight.
|
||||
///
|
||||
/// Inserted as the `active_cell` by `ChatWidget::add_mcp_output()` and removed
|
||||
/// once the fetch completes. The app removes committed copies from transcript
|
||||
/// history, while `ChatWidget::clear_mcp_inventory_loading()` only clears the
|
||||
/// in-flight `active_cell`.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct McpInventoryLoadingCell {
|
||||
start_time: Instant,
|
||||
animations_enabled: bool,
|
||||
}
|
||||
|
||||
impl McpInventoryLoadingCell {
|
||||
pub(crate) fn new(animations_enabled: bool) -> Self {
|
||||
Self {
|
||||
start_time: Instant::now(),
|
||||
animations_enabled,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryCell for McpInventoryLoadingCell {
|
||||
fn display_lines(&self, _width: u16) -> Vec<Line<'static>> {
|
||||
vec![
|
||||
vec![
|
||||
activity_indicator(
|
||||
Some(self.start_time),
|
||||
MotionMode::from_animations_enabled(self.animations_enabled),
|
||||
ReducedMotionIndicator::StaticBullet,
|
||||
)
|
||||
.unwrap_or_else(|| "•".dim()),
|
||||
" ".into(),
|
||||
"Loading MCP inventory".bold(),
|
||||
"…".dim(),
|
||||
]
|
||||
.into(),
|
||||
]
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
vec![Line::from("Loading MCP inventory...")]
|
||||
}
|
||||
|
||||
fn transcript_animation_tick(&self) -> Option<u64> {
|
||||
if !self.animations_enabled {
|
||||
return None;
|
||||
}
|
||||
Some((self.start_time.elapsed().as_millis() / 50) as u64)
|
||||
}
|
||||
}
|
||||
|
||||
/// Convenience constructor for [`McpInventoryLoadingCell`].
|
||||
pub(crate) fn new_mcp_inventory_loading(animations_enabled: bool) -> McpInventoryLoadingCell {
|
||||
McpInventoryLoadingCell::new(animations_enabled)
|
||||
}
|
||||
fn format_mcp_invocation<'a>(invocation: McpInvocation) -> Line<'a> {
|
||||
let args_str = invocation
|
||||
.arguments
|
||||
.as_ref()
|
||||
.map(|v: &serde_json::Value| {
|
||||
// Use compact form to keep things short but readable.
|
||||
serde_json::to_string(v).unwrap_or_else(|_| v.to_string())
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
let invocation_spans = vec![
|
||||
invocation.server.clone().cyan(),
|
||||
".".into(),
|
||||
invocation.tool.cyan(),
|
||||
"(".into(),
|
||||
args_str.dim(),
|
||||
")".into(),
|
||||
];
|
||||
invocation_spans.into()
|
||||
}
|
||||
@@ -0,0 +1,455 @@
|
||||
//! User, assistant, reasoning, and streaming message history cells.
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct UserHistoryCell {
|
||||
pub message: String,
|
||||
pub text_elements: Vec<TextElement>,
|
||||
#[allow(dead_code)]
|
||||
pub local_image_paths: Vec<PathBuf>,
|
||||
pub remote_image_urls: Vec<String>,
|
||||
}
|
||||
|
||||
/// Build logical lines for a user message with styled text elements.
|
||||
///
|
||||
/// This preserves explicit newlines while interleaving element spans and skips
|
||||
/// malformed byte ranges instead of panicking during history rendering.
|
||||
fn build_user_message_lines_with_elements(
|
||||
message: &str,
|
||||
elements: &[TextElement],
|
||||
style: Style,
|
||||
element_style: Style,
|
||||
) -> Vec<Line<'static>> {
|
||||
let mut elements = elements.to_vec();
|
||||
elements.sort_by_key(|e| e.byte_range.start);
|
||||
let mut offset = 0usize;
|
||||
let mut raw_lines: Vec<Line<'static>> = Vec::new();
|
||||
for line_text in message.split('\n') {
|
||||
let line_start = offset;
|
||||
let line_end = line_start + line_text.len();
|
||||
let mut spans: Vec<Span<'static>> = Vec::new();
|
||||
// Track how much of the line we've emitted to interleave plain and styled spans.
|
||||
let mut cursor = line_start;
|
||||
for elem in &elements {
|
||||
let start = elem.byte_range.start.max(line_start);
|
||||
let end = elem.byte_range.end.min(line_end);
|
||||
if start >= end {
|
||||
continue;
|
||||
}
|
||||
let rel_start = start - line_start;
|
||||
let rel_end = end - line_start;
|
||||
// Guard against malformed UTF-8 byte ranges from upstream data; skip
|
||||
// invalid elements rather than panicking while rendering history.
|
||||
if !line_text.is_char_boundary(rel_start) || !line_text.is_char_boundary(rel_end) {
|
||||
continue;
|
||||
}
|
||||
let rel_cursor = cursor - line_start;
|
||||
if cursor < start
|
||||
&& line_text.is_char_boundary(rel_cursor)
|
||||
&& let Some(segment) = line_text.get(rel_cursor..rel_start)
|
||||
{
|
||||
spans.push(Span::from(segment.to_string()));
|
||||
}
|
||||
if let Some(segment) = line_text.get(rel_start..rel_end) {
|
||||
spans.push(Span::styled(segment.to_string(), element_style));
|
||||
cursor = end;
|
||||
}
|
||||
}
|
||||
let rel_cursor = cursor - line_start;
|
||||
if cursor < line_end
|
||||
&& line_text.is_char_boundary(rel_cursor)
|
||||
&& let Some(segment) = line_text.get(rel_cursor..)
|
||||
{
|
||||
spans.push(Span::from(segment.to_string()));
|
||||
}
|
||||
let line = if spans.is_empty() {
|
||||
Line::from(line_text.to_string()).style(style)
|
||||
} else {
|
||||
Line::from(spans).style(style)
|
||||
};
|
||||
raw_lines.push(line);
|
||||
// Split on '\n' so any '\r' stays in the line; advancing by 1 accounts
|
||||
// for the separator byte.
|
||||
offset = line_end + 1;
|
||||
}
|
||||
|
||||
raw_lines
|
||||
}
|
||||
|
||||
fn remote_image_display_line(style: Style, index: usize) -> Line<'static> {
|
||||
Line::from(local_image_label_text(index)).style(style)
|
||||
}
|
||||
|
||||
fn trim_trailing_blank_lines(mut lines: Vec<Line<'static>>) -> Vec<Line<'static>> {
|
||||
while lines
|
||||
.last()
|
||||
.is_some_and(|line| line.spans.iter().all(|span| span.content.trim().is_empty()))
|
||||
{
|
||||
lines.pop();
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
impl HistoryCell for UserHistoryCell {
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
let wrap_width = width
|
||||
.saturating_sub(
|
||||
LIVE_PREFIX_COLS + 1, /* keep a one-column right margin for wrapping */
|
||||
)
|
||||
.max(1);
|
||||
|
||||
let style = user_message_style();
|
||||
let element_style = style.fg(Color::Cyan);
|
||||
|
||||
let wrapped_remote_images = if self.remote_image_urls.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(adaptive_wrap_lines(
|
||||
self.remote_image_urls
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(idx, _url)| {
|
||||
remote_image_display_line(element_style, idx.saturating_add(1))
|
||||
}),
|
||||
RtOptions::new(usize::from(wrap_width))
|
||||
.wrap_algorithm(textwrap::WrapAlgorithm::FirstFit),
|
||||
))
|
||||
};
|
||||
|
||||
let wrapped_message = if self.message.is_empty() && self.text_elements.is_empty() {
|
||||
None
|
||||
} else if self.text_elements.is_empty() {
|
||||
let message_without_trailing_newlines = self.message.trim_end_matches(['\r', '\n']);
|
||||
let wrapped = adaptive_wrap_lines(
|
||||
message_without_trailing_newlines
|
||||
.split('\n')
|
||||
.map(|line| Line::from(line).style(style)),
|
||||
// Wrap algorithm matches textarea.rs.
|
||||
RtOptions::new(usize::from(wrap_width))
|
||||
.wrap_algorithm(textwrap::WrapAlgorithm::FirstFit),
|
||||
);
|
||||
let wrapped = trim_trailing_blank_lines(wrapped);
|
||||
(!wrapped.is_empty()).then_some(wrapped)
|
||||
} else {
|
||||
let raw_lines = build_user_message_lines_with_elements(
|
||||
&self.message,
|
||||
&self.text_elements,
|
||||
style,
|
||||
element_style,
|
||||
);
|
||||
let wrapped = adaptive_wrap_lines(
|
||||
raw_lines,
|
||||
RtOptions::new(usize::from(wrap_width))
|
||||
.wrap_algorithm(textwrap::WrapAlgorithm::FirstFit),
|
||||
);
|
||||
let wrapped = trim_trailing_blank_lines(wrapped);
|
||||
(!wrapped.is_empty()).then_some(wrapped)
|
||||
};
|
||||
|
||||
if wrapped_remote_images.is_none() && wrapped_message.is_none() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let mut lines: Vec<Line<'static>> = vec![Line::from("").style(style)];
|
||||
|
||||
if let Some(wrapped_remote_images) = wrapped_remote_images {
|
||||
lines.extend(prefix_lines(
|
||||
wrapped_remote_images,
|
||||
" ".into(),
|
||||
" ".into(),
|
||||
));
|
||||
if wrapped_message.is_some() {
|
||||
lines.push(Line::from("").style(style));
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(wrapped_message) = wrapped_message {
|
||||
lines.extend(prefix_lines(
|
||||
wrapped_message,
|
||||
"› ".bold().dim(),
|
||||
" ".into(),
|
||||
));
|
||||
}
|
||||
|
||||
lines.push(Line::from("").style(style));
|
||||
lines
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
let mut lines = raw_lines_from_source(self.message.trim_end_matches(['\r', '\n']));
|
||||
if !self.remote_image_urls.is_empty() {
|
||||
if !lines.is_empty() {
|
||||
lines.push(Line::from(""));
|
||||
}
|
||||
lines.extend(
|
||||
self.remote_image_urls
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(idx, _url)| Line::from(local_image_label_text(idx.saturating_add(1)))),
|
||||
);
|
||||
}
|
||||
lines
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ReasoningSummaryCell {
|
||||
_header: String,
|
||||
content: String,
|
||||
/// Session cwd used to render local file links inside the reasoning body.
|
||||
cwd: PathBuf,
|
||||
transcript_only: bool,
|
||||
}
|
||||
|
||||
impl ReasoningSummaryCell {
|
||||
/// Create a reasoning summary cell that will render local file links relative to the session
|
||||
/// cwd active when the summary was recorded.
|
||||
pub(crate) fn new(header: String, content: String, cwd: &Path, transcript_only: bool) -> Self {
|
||||
Self {
|
||||
_header: header,
|
||||
content,
|
||||
cwd: cwd.to_path_buf(),
|
||||
transcript_only,
|
||||
}
|
||||
}
|
||||
|
||||
fn lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
let mut lines: Vec<Line<'static>> = Vec::new();
|
||||
append_markdown(
|
||||
&self.content,
|
||||
crate::width::usable_content_width_u16(width, /*reserved_cols*/ 2),
|
||||
Some(self.cwd.as_path()),
|
||||
&mut lines,
|
||||
);
|
||||
let summary_style = Style::default().dim().italic();
|
||||
let summary_lines = lines
|
||||
.into_iter()
|
||||
.map(|mut line| {
|
||||
line.spans = line
|
||||
.spans
|
||||
.into_iter()
|
||||
.map(|span| span.patch_style(summary_style))
|
||||
.collect();
|
||||
line
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
adaptive_wrap_lines(
|
||||
&summary_lines,
|
||||
RtOptions::new(width as usize)
|
||||
.initial_indent("• ".dim().into())
|
||||
.subsequent_indent(" ".into()),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryCell for ReasoningSummaryCell {
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
if self.transcript_only {
|
||||
Vec::new()
|
||||
} else {
|
||||
self.lines(width)
|
||||
}
|
||||
}
|
||||
|
||||
fn transcript_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
self.lines(width)
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
if self.transcript_only {
|
||||
Vec::new()
|
||||
} else {
|
||||
raw_lines_from_source(self.content.trim())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct AgentMessageCell {
|
||||
lines: Vec<Line<'static>>,
|
||||
is_first_line: bool,
|
||||
}
|
||||
|
||||
impl AgentMessageCell {
|
||||
pub(crate) fn new(lines: Vec<Line<'static>>, is_first_line: bool) -> Self {
|
||||
Self {
|
||||
lines,
|
||||
is_first_line,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryCell for AgentMessageCell {
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
adaptive_wrap_lines(
|
||||
&self.lines,
|
||||
RtOptions::new(width as usize)
|
||||
.initial_indent(if self.is_first_line {
|
||||
"• ".dim().into()
|
||||
} else {
|
||||
" ".into()
|
||||
})
|
||||
.subsequent_indent(" ".into()),
|
||||
)
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
plain_lines(self.lines.clone())
|
||||
}
|
||||
|
||||
fn is_stream_continuation(&self) -> bool {
|
||||
!self.is_first_line
|
||||
}
|
||||
}
|
||||
|
||||
/// A consolidated agent message cell that stores raw markdown source and re-renders from it.
|
||||
///
|
||||
/// After a stream finalizes, the `ConsolidateAgentMessage` handler in `App`
|
||||
/// replaces the contiguous run of `AgentMessageCell`s with a single
|
||||
/// `AgentMarkdownCell`. On terminal resize, `display_lines(width)` re-renders
|
||||
/// from source via `append_markdown_agent`, producing correctly-sized tables
|
||||
/// with box-drawing borders.
|
||||
///
|
||||
/// The cell snapshots `cwd` at construction so local file-link display remains aligned with the
|
||||
/// session that produced the message. Reusing the current process cwd during reflow would make old
|
||||
/// transcript content change meaning after a later `/cd` or resumed session.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct AgentMarkdownCell {
|
||||
markdown_source: String,
|
||||
cwd: PathBuf,
|
||||
}
|
||||
|
||||
impl AgentMarkdownCell {
|
||||
/// Create a finalized source-backed assistant message cell.
|
||||
///
|
||||
/// `markdown_source` must be the raw source accumulated by the stream controller, not already
|
||||
/// wrapped terminal lines. Passing rendered lines here would make future resize reflow preserve
|
||||
/// stale wrapping instead of repairing it.
|
||||
pub(crate) fn new(markdown_source: String, cwd: &Path) -> Self {
|
||||
Self {
|
||||
markdown_source,
|
||||
cwd: cwd.to_path_buf(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryCell for AgentMarkdownCell {
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
let Some(wrap_width) =
|
||||
crate::width::usable_content_width_u16(width, /*reserved_cols*/ 2)
|
||||
else {
|
||||
return prefix_lines(vec![Line::default()], "• ".dim(), " ".into());
|
||||
};
|
||||
|
||||
let mut lines: Vec<Line<'static>> = Vec::new();
|
||||
// Re-render markdown from source at the current width. Reserve 2 columns for the "• " /
|
||||
// " " prefix prepended below.
|
||||
crate::markdown::append_markdown_agent_with_cwd(
|
||||
&self.markdown_source,
|
||||
Some(wrap_width),
|
||||
Some(self.cwd.as_path()),
|
||||
&mut lines,
|
||||
);
|
||||
prefix_lines(lines, "• ".dim(), " ".into())
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
raw_lines_from_source(&self.markdown_source)
|
||||
}
|
||||
}
|
||||
|
||||
/// Transient active-cell representation of the mutable tail of an agent stream.
|
||||
///
|
||||
/// During streaming, lines that have not yet been committed to scrollback because they belong to
|
||||
/// an in-progress table are displayed via this cell in the `active_cell` slot. It is replaced on
|
||||
/// every delta and cleared when the stream finalizes.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct StreamingAgentTailCell {
|
||||
lines: Vec<Line<'static>>,
|
||||
is_first_line: bool,
|
||||
}
|
||||
|
||||
impl StreamingAgentTailCell {
|
||||
pub(crate) fn new(lines: Vec<Line<'static>>, is_first_line: bool) -> Self {
|
||||
Self {
|
||||
lines,
|
||||
is_first_line,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryCell for StreamingAgentTailCell {
|
||||
fn display_lines(&self, _width: u16) -> Vec<Line<'static>> {
|
||||
// Tail lines are already rendered at the controller's current stream width.
|
||||
// Re-wrapping them here can split table borders and produce malformed in-flight rows.
|
||||
prefix_lines(
|
||||
self.lines.clone(),
|
||||
if self.is_first_line {
|
||||
"• ".dim()
|
||||
} else {
|
||||
" ".into()
|
||||
},
|
||||
" ".into(),
|
||||
)
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
plain_lines(self.display_lines(u16::MAX))
|
||||
}
|
||||
|
||||
fn is_stream_continuation(&self) -> bool {
|
||||
!self.is_first_line
|
||||
}
|
||||
}
|
||||
pub(crate) fn new_user_prompt(
|
||||
message: String,
|
||||
text_elements: Vec<TextElement>,
|
||||
local_image_paths: Vec<PathBuf>,
|
||||
remote_image_urls: Vec<String>,
|
||||
) -> UserHistoryCell {
|
||||
UserHistoryCell {
|
||||
message,
|
||||
text_elements,
|
||||
local_image_paths,
|
||||
remote_image_urls,
|
||||
}
|
||||
}
|
||||
/// Create the reasoning history cell emitted at the end of a reasoning block.
|
||||
///
|
||||
/// The helper snapshots `cwd` into the returned cell so local file links render the same way they
|
||||
/// did while the turn was live, even if rendering happens after other app state has advanced.
|
||||
pub(crate) fn new_reasoning_summary_block(
|
||||
full_reasoning_buffer: String,
|
||||
cwd: &Path,
|
||||
) -> Box<dyn HistoryCell> {
|
||||
let cwd = cwd.to_path_buf();
|
||||
let full_reasoning_buffer = full_reasoning_buffer.trim();
|
||||
if let Some(open) = full_reasoning_buffer.find("**") {
|
||||
let after_open = &full_reasoning_buffer[(open + 2)..];
|
||||
if let Some(close) = after_open.find("**") {
|
||||
let after_close_idx = open + 2 + close + 2;
|
||||
// if we don't have anything beyond `after_close_idx`
|
||||
// then we don't have a summary to inject into history
|
||||
if after_close_idx < full_reasoning_buffer.len() {
|
||||
let header_buffer = full_reasoning_buffer[..after_close_idx].to_string();
|
||||
let summary_buffer = full_reasoning_buffer[after_close_idx..].to_string();
|
||||
// Preserve the session cwd so local file links render the same way in the
|
||||
// collapsed reasoning block as they did while streaming live content.
|
||||
return Box::new(ReasoningSummaryCell::new(
|
||||
header_buffer,
|
||||
summary_buffer,
|
||||
&cwd,
|
||||
/*transcript_only*/ false,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
Box::new(ReasoningSummaryCell::new(
|
||||
"".to_string(),
|
||||
full_reasoning_buffer.to_string(),
|
||||
&cwd,
|
||||
/*transcript_only*/ true,
|
||||
))
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
//! Transcript/history cells for the Codex TUI.
|
||||
//!
|
||||
//! A `HistoryCell` is the unit of display in the conversation UI, representing both committed
|
||||
//! transcript entries and, transiently, an in-flight active cell that can mutate in place while
|
||||
//! streaming.
|
||||
//!
|
||||
//! The transcript overlay (`Ctrl+T`) appends a cached live tail derived from the active cell, and
|
||||
//! that cached tail is refreshed based on an active-cell cache key. Cells that change based on
|
||||
//! elapsed time expose `transcript_animation_tick()`, and code that mutates the active cell in place
|
||||
//! bumps the active-cell revision tracked by `ChatWidget`, so the cache key changes whenever the
|
||||
//! rendered transcript output can change.
|
||||
|
||||
use crate::diff_model::FileChange;
|
||||
use crate::diff_render::create_diff_summary;
|
||||
use crate::diff_render::display_path_for;
|
||||
use crate::exec_cell::CommandOutput;
|
||||
use crate::exec_cell::OutputLinesParams;
|
||||
use crate::exec_cell::TOOL_CALL_MAX_LINES;
|
||||
use crate::exec_cell::output_lines;
|
||||
use crate::exec_command::relativize_to_home;
|
||||
use crate::exec_command::strip_bash_lc_and_escape;
|
||||
use crate::legacy_core::config::Config;
|
||||
use crate::live_wrap::take_prefix_by_width;
|
||||
use crate::markdown::append_markdown;
|
||||
use crate::markdown::append_markdown_agent_with_cwd;
|
||||
use crate::motion::MotionMode;
|
||||
use crate::motion::ReducedMotionIndicator;
|
||||
use crate::motion::activity_indicator;
|
||||
use crate::render::line_utils::line_to_static;
|
||||
use crate::render::line_utils::prefix_lines;
|
||||
use crate::render::line_utils::push_owned_lines;
|
||||
use crate::render::renderable::Renderable;
|
||||
use crate::session_state::ThreadSessionState;
|
||||
use crate::style::proposed_plan_style;
|
||||
use crate::style::user_message_style;
|
||||
#[cfg(test)]
|
||||
use crate::test_support::PathBufExt;
|
||||
#[cfg(test)]
|
||||
use crate::test_support::test_path_buf;
|
||||
use crate::text_formatting::format_and_truncate_tool_result;
|
||||
use crate::text_formatting::truncate_text;
|
||||
use crate::tooltips;
|
||||
use crate::ui_consts::LIVE_PREFIX_COLS;
|
||||
use crate::update_action::UpdateAction;
|
||||
use crate::version::CODEX_CLI_VERSION;
|
||||
use crate::wrapping::RtOptions;
|
||||
use crate::wrapping::adaptive_wrap_line;
|
||||
use crate::wrapping::adaptive_wrap_lines;
|
||||
use base64::Engine;
|
||||
use codex_app_server_protocol::AskForApproval;
|
||||
use codex_app_server_protocol::McpAuthStatus;
|
||||
use codex_app_server_protocol::McpServerStatus;
|
||||
use codex_app_server_protocol::McpServerStatusDetail;
|
||||
use codex_app_server_protocol::ToolRequestUserInputAnswer;
|
||||
use codex_app_server_protocol::ToolRequestUserInputQuestion;
|
||||
use codex_app_server_protocol::WebSearchAction;
|
||||
use codex_config::types::McpServerTransportConfig;
|
||||
#[cfg(test)]
|
||||
use codex_mcp::qualified_mcp_tool_name_prefix;
|
||||
use codex_otel::RuntimeMetricsSummary;
|
||||
use codex_protocol::account::PlanType;
|
||||
use codex_protocol::approvals::ExecPolicyAmendment;
|
||||
use codex_protocol::approvals::NetworkPolicyAmendment;
|
||||
#[cfg(test)]
|
||||
use codex_protocol::mcp::Resource;
|
||||
#[cfg(test)]
|
||||
use codex_protocol::mcp::ResourceTemplate;
|
||||
use codex_protocol::models::ManagedFileSystemPermissions;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_protocol::models::local_image_label_text;
|
||||
use codex_protocol::openai_models::ReasoningEffort as ReasoningEffortConfig;
|
||||
use codex_protocol::permissions::NetworkSandboxPolicy;
|
||||
use codex_protocol::plan_tool::PlanItemArg;
|
||||
use codex_protocol::plan_tool::StepStatus;
|
||||
use codex_protocol::plan_tool::UpdatePlanArgs;
|
||||
use codex_protocol::user_input::TextElement;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_cli::format_env_display;
|
||||
use image::DynamicImage;
|
||||
use image::ImageReader;
|
||||
use ratatui::prelude::*;
|
||||
use ratatui::style::Color;
|
||||
use ratatui::style::Modifier;
|
||||
use ratatui::style::Style;
|
||||
use ratatui::style::Styled;
|
||||
use ratatui::style::Stylize;
|
||||
use ratatui::widgets::Clear;
|
||||
use ratatui::widgets::Paragraph;
|
||||
use ratatui::widgets::Wrap;
|
||||
use std::any::Any;
|
||||
use std::collections::HashMap;
|
||||
use std::io::Cursor;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
use tracing::error;
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
use unicode_width::UnicodeWidthStr;
|
||||
use url::Url;
|
||||
|
||||
const RAW_DIFF_SUMMARY_WIDTH: usize = 10_000;
|
||||
const RAW_TOOL_OUTPUT_WIDTH: usize = 10_000;
|
||||
|
||||
mod approvals;
|
||||
mod base;
|
||||
mod exec;
|
||||
mod hook_cell;
|
||||
mod mcp;
|
||||
mod messages;
|
||||
mod notices;
|
||||
mod patches;
|
||||
mod plans;
|
||||
mod request_user_input;
|
||||
mod search;
|
||||
mod separators;
|
||||
mod session;
|
||||
|
||||
pub(crate) use approvals::*;
|
||||
pub(crate) use base::*;
|
||||
pub(crate) use exec::*;
|
||||
pub(crate) use hook_cell::HookCell;
|
||||
pub(crate) use hook_cell::new_active_hook_cell;
|
||||
pub(crate) use hook_cell::new_completed_hook_cell;
|
||||
pub(crate) use mcp::*;
|
||||
pub(crate) use messages::*;
|
||||
pub(crate) use notices::*;
|
||||
pub(crate) use patches::*;
|
||||
pub(crate) use plans::*;
|
||||
pub(crate) use request_user_input::*;
|
||||
pub(crate) use search::*;
|
||||
pub(crate) use separators::*;
|
||||
pub(crate) use session::*;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(crate) enum HistoryRenderMode {
|
||||
Rich,
|
||||
Raw,
|
||||
}
|
||||
|
||||
pub(crate) fn raw_lines_from_source(source: &str) -> Vec<Line<'static>> {
|
||||
if source.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let mut parts = source.split('\n').collect::<Vec<_>>();
|
||||
if source.ends_with('\n') {
|
||||
parts.pop();
|
||||
}
|
||||
|
||||
parts
|
||||
.into_iter()
|
||||
.map(|line| Line::from(line.to_string()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn plain_lines(lines: impl IntoIterator<Item = Line<'static>>) -> Vec<Line<'static>> {
|
||||
lines
|
||||
.into_iter()
|
||||
.map(|line| {
|
||||
let text = line
|
||||
.spans
|
||||
.into_iter()
|
||||
.map(|span| span.content.into_owned())
|
||||
.collect::<String>();
|
||||
Line::from(text)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A single renderable unit of conversation history.
|
||||
///
|
||||
/// Each cell produces logical `Line`s and reports how many viewport
|
||||
/// rows those lines occupy at a given terminal width. The default
|
||||
/// height implementations use `Paragraph::wrap` to account for lines
|
||||
/// that overflow the viewport width (e.g. long URLs that are kept
|
||||
/// intact by adaptive wrapping). Concrete types only need to override
|
||||
/// heights when they apply additional layout logic beyond what
|
||||
/// `Paragraph::line_count` captures.
|
||||
pub(crate) trait HistoryCell: std::fmt::Debug + Send + Sync + Any {
|
||||
/// Returns the logical lines for the main chat viewport.
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>>;
|
||||
|
||||
/// Returns copy-friendly plain logical lines for raw scrollback mode.
|
||||
fn raw_lines(&self) -> Vec<Line<'static>>;
|
||||
|
||||
fn display_lines_for_mode(&self, width: u16, mode: HistoryRenderMode) -> Vec<Line<'static>> {
|
||||
match mode {
|
||||
HistoryRenderMode::Rich => self.display_lines(width),
|
||||
HistoryRenderMode::Raw => self.raw_lines(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the number of viewport rows needed to render this cell.
|
||||
///
|
||||
/// The default delegates to `Paragraph::line_count` with
|
||||
/// `Wrap { trim: false }`, which measures the actual row count after
|
||||
/// ratatui's viewport-level character wrapping. This is critical
|
||||
/// for lines containing URL-like tokens that are wider than the
|
||||
/// terminal — the logical line count would undercount.
|
||||
fn desired_height(&self, width: u16) -> u16 {
|
||||
self.desired_height_for_mode(width, HistoryRenderMode::Rich)
|
||||
}
|
||||
|
||||
fn desired_height_for_mode(&self, width: u16, mode: HistoryRenderMode) -> u16 {
|
||||
Paragraph::new(Text::from(self.display_lines_for_mode(width, mode)))
|
||||
.wrap(Wrap { trim: false })
|
||||
.line_count(width)
|
||||
.try_into()
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Returns lines for the transcript overlay (`Ctrl+T`).
|
||||
///
|
||||
/// Defaults to `display_lines`. Override when the transcript
|
||||
/// representation differs (e.g. `ExecCell` shows all calls with
|
||||
/// `$`-prefixed commands and exit status).
|
||||
fn transcript_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
self.display_lines(width)
|
||||
}
|
||||
|
||||
/// Returns the number of viewport rows for the transcript overlay.
|
||||
///
|
||||
/// Uses the same `Paragraph::line_count` measurement as
|
||||
/// `desired_height`. Contains a workaround for a ratatui bug where
|
||||
/// a single whitespace-only line reports 2 rows instead of 1.
|
||||
fn desired_transcript_height(&self, width: u16) -> u16 {
|
||||
let lines = self.transcript_lines(width);
|
||||
// Workaround: ratatui's line_count returns 2 for a single
|
||||
// whitespace-only line. Clamp to 1 in that case.
|
||||
if let [line] = &lines[..]
|
||||
&& line
|
||||
.spans
|
||||
.iter()
|
||||
.all(|s| s.content.chars().all(char::is_whitespace))
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
Paragraph::new(Text::from(lines))
|
||||
.wrap(Wrap { trim: false })
|
||||
.line_count(width)
|
||||
.try_into()
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
fn is_stream_continuation(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Returns a coarse "animation tick" when transcript output is time-dependent.
|
||||
///
|
||||
/// The transcript overlay caches the rendered output of the in-flight active cell, so cells
|
||||
/// that include time-based UI (spinner, shimmer, etc.) should return a tick that changes over
|
||||
/// time to signal that the cached tail should be recomputed. Returning `None` means the
|
||||
/// transcript lines are stable, while returning `Some(tick)` during an in-flight animation
|
||||
/// allows the overlay to keep up with the main viewport.
|
||||
///
|
||||
/// If a cell uses time-based visuals but always returns `None`, `Ctrl+T` can appear "frozen" on
|
||||
/// the first rendered frame even though the main viewport is animating.
|
||||
fn transcript_animation_tick(&self) -> Option<u64> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl Renderable for Box<dyn HistoryCell> {
|
||||
fn render(&self, area: Rect, buf: &mut Buffer) {
|
||||
let lines = self.display_lines(area.width);
|
||||
let paragraph = Paragraph::new(Text::from(lines)).wrap(Wrap { trim: false });
|
||||
let y = if area.height == 0 {
|
||||
0
|
||||
} else {
|
||||
let overflow = paragraph
|
||||
.line_count(area.width)
|
||||
.saturating_sub(usize::from(area.height));
|
||||
u16::try_from(overflow).unwrap_or(u16::MAX)
|
||||
};
|
||||
// Active-cell content can reflow dramatically during resize/stream updates. Clear the
|
||||
// entire draw area first so stale glyphs from previous frames never linger.
|
||||
Clear.render(area, buf);
|
||||
paragraph.scroll((y, 0)).render(area, buf);
|
||||
}
|
||||
fn desired_height(&self, width: u16) -> u16 {
|
||||
HistoryCell::desired_height(self.as_ref(), width)
|
||||
}
|
||||
}
|
||||
|
||||
impl dyn HistoryCell {
|
||||
pub(crate) fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn as_any_mut(&mut self) -> &mut dyn Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
//! Informational, warning, update, and policy notice history cells.
|
||||
|
||||
use super::*;
|
||||
|
||||
#[cfg_attr(debug_assertions, allow(dead_code))]
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct UpdateAvailableHistoryCell {
|
||||
latest_version: String,
|
||||
update_action: Option<UpdateAction>,
|
||||
}
|
||||
|
||||
#[cfg_attr(debug_assertions, allow(dead_code))]
|
||||
impl UpdateAvailableHistoryCell {
|
||||
pub(crate) fn new(latest_version: String, update_action: Option<UpdateAction>) -> Self {
|
||||
Self {
|
||||
latest_version,
|
||||
update_action,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryCell for UpdateAvailableHistoryCell {
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
use ratatui_macros::line;
|
||||
use ratatui_macros::text;
|
||||
let update_instruction = if let Some(update_action) = self.update_action {
|
||||
line!["Run ", update_action.command_str().cyan(), " to update."]
|
||||
} else {
|
||||
line![
|
||||
"See ",
|
||||
"https://github.com/openai/codex".cyan().underlined(),
|
||||
" for installation options."
|
||||
]
|
||||
};
|
||||
|
||||
let content = text![
|
||||
line![
|
||||
padded_emoji("✨").bold().cyan(),
|
||||
"Update available!".bold().cyan(),
|
||||
" ",
|
||||
format!("{CODEX_CLI_VERSION} -> {}", self.latest_version).bold(),
|
||||
],
|
||||
update_instruction,
|
||||
"",
|
||||
"See full release notes:",
|
||||
"https://github.com/openai/codex/releases/latest"
|
||||
.cyan()
|
||||
.underlined(),
|
||||
];
|
||||
|
||||
let inner_width = content
|
||||
.width()
|
||||
.min(usize::from(width.saturating_sub(4)))
|
||||
.max(1);
|
||||
with_border_with_inner_width(content.lines, inner_width)
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
let update_instruction = if let Some(update_action) = self.update_action {
|
||||
format!("Run {} to update.", update_action.command_str())
|
||||
} else {
|
||||
"See https://github.com/openai/codex for installation options.".to_string()
|
||||
};
|
||||
vec![
|
||||
Line::from("Update available!"),
|
||||
Line::from(format!("{CODEX_CLI_VERSION} -> {}", self.latest_version)),
|
||||
Line::from(update_instruction),
|
||||
Line::from(""),
|
||||
Line::from("See full release notes:"),
|
||||
Line::from("https://github.com/openai/codex/releases/latest"),
|
||||
]
|
||||
}
|
||||
}
|
||||
#[allow(clippy::disallowed_methods)]
|
||||
pub(crate) fn new_warning_event(message: String) -> PrefixedWrappedHistoryCell {
|
||||
PrefixedWrappedHistoryCell::new(message.yellow(), "⚠ ".yellow(), " ")
|
||||
}
|
||||
|
||||
const TRUSTED_ACCESS_FOR_CYBER_URL: &str = "https://chatgpt.com/cyber";
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct CyberPolicyNoticeCell;
|
||||
|
||||
pub(crate) fn new_cyber_policy_error_event() -> CyberPolicyNoticeCell {
|
||||
CyberPolicyNoticeCell
|
||||
}
|
||||
|
||||
impl HistoryCell for CyberPolicyNoticeCell {
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
let mut lines: Vec<Line<'static>> = Vec::new();
|
||||
lines.push(
|
||||
vec![
|
||||
"ⓘ ".cyan(),
|
||||
"This chat was flagged for possible cybersecurity risk".bold(),
|
||||
]
|
||||
.into(),
|
||||
);
|
||||
|
||||
let wrap_width = width.saturating_sub(2).max(1) as usize;
|
||||
let body = Line::from(vec![
|
||||
" If this seems wrong, try rephrasing your request. To get authorized for security work, join the "
|
||||
.dim(),
|
||||
"Trusted Access for Cyber".cyan().underlined(),
|
||||
" program.".dim(),
|
||||
]);
|
||||
let wrapped = adaptive_wrap_line(
|
||||
&body,
|
||||
RtOptions::new(wrap_width).subsequent_indent(" ".into()),
|
||||
);
|
||||
push_owned_lines(&wrapped, &mut lines);
|
||||
lines.push(
|
||||
vec![
|
||||
" ".into(),
|
||||
TRUSTED_ACCESS_FOR_CYBER_URL.cyan().underlined(),
|
||||
]
|
||||
.into(),
|
||||
);
|
||||
|
||||
lines
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
vec![
|
||||
Line::from("This chat was flagged for possible cybersecurity risk"),
|
||||
Line::from(
|
||||
"If this seems wrong, try rephrasing your request. To get authorized for security work, join the Trusted Access for Cyber program.",
|
||||
),
|
||||
Line::from(TRUSTED_ACCESS_FOR_CYBER_URL),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct DeprecationNoticeCell {
|
||||
summary: String,
|
||||
details: Option<String>,
|
||||
}
|
||||
|
||||
pub(crate) fn new_deprecation_notice(
|
||||
summary: String,
|
||||
details: Option<String>,
|
||||
) -> DeprecationNoticeCell {
|
||||
DeprecationNoticeCell { summary, details }
|
||||
}
|
||||
|
||||
impl HistoryCell for DeprecationNoticeCell {
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
let mut lines: Vec<Line<'static>> = Vec::new();
|
||||
lines.push(vec!["⚠ ".red().bold(), self.summary.clone().red()].into());
|
||||
|
||||
let wrap_width = width.saturating_sub(4).max(1) as usize;
|
||||
|
||||
if let Some(details) = &self.details {
|
||||
let detail_line = Line::from(details.clone().dim());
|
||||
let wrapped = adaptive_wrap_line(&detail_line, RtOptions::new(wrap_width));
|
||||
push_owned_lines(&wrapped, &mut lines);
|
||||
}
|
||||
|
||||
lines
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
let mut lines = vec![Line::from(self.summary.clone())];
|
||||
if let Some(details) = &self.details {
|
||||
lines.extend(raw_lines_from_source(details));
|
||||
}
|
||||
lines
|
||||
}
|
||||
}
|
||||
pub(crate) fn new_info_event(message: String, hint: Option<String>) -> PlainHistoryCell {
|
||||
let mut line = vec!["• ".dim(), message.into()];
|
||||
if let Some(hint) = hint {
|
||||
line.push(" ".into());
|
||||
line.push(hint.dark_gray());
|
||||
}
|
||||
let lines: Vec<Line<'static>> = vec![line.into()];
|
||||
PlainHistoryCell { lines }
|
||||
}
|
||||
|
||||
pub(crate) fn new_error_event(message: String) -> PlainHistoryCell {
|
||||
// Use a hair space (U+200A) to create a subtle, near-invisible separation
|
||||
// before the text. VS16 is intentionally omitted to keep spacing tighter
|
||||
// in terminals like Ghostty.
|
||||
let lines: Vec<Line<'static>> = vec![vec![format!("■ {message}").red()].into()];
|
||||
PlainHistoryCell { lines }
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
//! Patch summaries and image-tool transcript helpers.
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct PatchHistoryCell {
|
||||
changes: HashMap<PathBuf, FileChange>,
|
||||
cwd: PathBuf,
|
||||
}
|
||||
|
||||
impl HistoryCell for PatchHistoryCell {
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
create_diff_summary(&self.changes, &self.cwd, width as usize)
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
plain_lines(create_diff_summary(
|
||||
&self.changes,
|
||||
&self.cwd,
|
||||
RAW_DIFF_SUMMARY_WIDTH,
|
||||
))
|
||||
}
|
||||
}
|
||||
/// Create a new `PendingPatch` cell that lists the file‑level summary of
|
||||
/// a proposed patch. The summary lines should already be formatted (e.g.
|
||||
/// "A path/to/file.rs").
|
||||
pub(crate) fn new_patch_event(
|
||||
changes: HashMap<PathBuf, FileChange>,
|
||||
cwd: &Path,
|
||||
) -> PatchHistoryCell {
|
||||
PatchHistoryCell {
|
||||
changes,
|
||||
cwd: cwd.to_path_buf(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn new_patch_apply_failure(stderr: String) -> PlainHistoryCell {
|
||||
let mut lines: Vec<Line<'static>> = Vec::new();
|
||||
|
||||
// Failure title
|
||||
lines.push(Line::from("✘ Failed to apply patch".magenta().bold()));
|
||||
|
||||
if !stderr.trim().is_empty() {
|
||||
let output = output_lines(
|
||||
Some(&CommandOutput {
|
||||
exit_code: 1,
|
||||
formatted_output: String::new(),
|
||||
aggregated_output: stderr,
|
||||
}),
|
||||
OutputLinesParams {
|
||||
line_limit: TOOL_CALL_MAX_LINES,
|
||||
only_err: true,
|
||||
include_angle_pipe: true,
|
||||
include_prefix: true,
|
||||
},
|
||||
);
|
||||
lines.extend(output.lines);
|
||||
}
|
||||
|
||||
PlainHistoryCell { lines }
|
||||
}
|
||||
|
||||
pub(crate) fn new_view_image_tool_call(path: AbsolutePathBuf, cwd: &Path) -> PlainHistoryCell {
|
||||
let display_path = display_path_for(path.as_path(), cwd);
|
||||
|
||||
let lines: Vec<Line<'static>> = vec![
|
||||
vec!["• ".dim(), "Viewed Image".bold()].into(),
|
||||
vec![" └ ".dim(), display_path.dim()].into(),
|
||||
];
|
||||
|
||||
PlainHistoryCell { lines }
|
||||
}
|
||||
|
||||
pub(crate) fn new_image_generation_call(
|
||||
call_id: String,
|
||||
revised_prompt: Option<String>,
|
||||
saved_path: Option<AbsolutePathBuf>,
|
||||
) -> PlainHistoryCell {
|
||||
let detail = revised_prompt.unwrap_or_else(|| call_id.clone());
|
||||
|
||||
let mut lines: Vec<Line<'static>> = vec![
|
||||
vec!["• ".dim(), "Generated Image:".bold()].into(),
|
||||
vec![" └ ".dim(), detail.dim()].into(),
|
||||
];
|
||||
if let Some(saved_path) = saved_path {
|
||||
let saved_path = Url::from_file_path(saved_path.as_path())
|
||||
.map(|url| url.to_string())
|
||||
.unwrap_or_else(|_| saved_path.display().to_string());
|
||||
lines.push(vec![" └ ".dim(), "Saved to: ".dim(), saved_path.into()].into());
|
||||
}
|
||||
|
||||
PlainHistoryCell { lines }
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
//! Proposed-plan and plan-update history cells.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Transient active-cell representation of the mutable tail of a proposed-plan stream.
|
||||
///
|
||||
/// The controller prepares the full styled plan lines because plan tails need the same header,
|
||||
/// padding, and background treatment as committed `ProposedPlanStreamCell`s while remaining
|
||||
/// preview-only during streaming.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct StreamingPlanTailCell {
|
||||
lines: Vec<Line<'static>>,
|
||||
is_stream_continuation: bool,
|
||||
}
|
||||
|
||||
impl StreamingPlanTailCell {
|
||||
pub(crate) fn new(lines: Vec<Line<'static>>, is_stream_continuation: bool) -> Self {
|
||||
Self {
|
||||
lines,
|
||||
is_stream_continuation,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryCell for StreamingPlanTailCell {
|
||||
fn display_lines(&self, _width: u16) -> Vec<Line<'static>> {
|
||||
self.lines.clone()
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
plain_lines(self.lines.clone())
|
||||
}
|
||||
|
||||
fn is_stream_continuation(&self) -> bool {
|
||||
self.is_stream_continuation
|
||||
}
|
||||
}
|
||||
/// Render a user‑friendly plan update styled like a checkbox todo list.
|
||||
pub(crate) fn new_plan_update(update: UpdatePlanArgs) -> PlanUpdateCell {
|
||||
let UpdatePlanArgs { explanation, plan } = update;
|
||||
PlanUpdateCell { explanation, plan }
|
||||
}
|
||||
|
||||
/// Create a proposed-plan cell that snapshots the session cwd for later markdown rendering.
|
||||
///
|
||||
/// The plan body is stored as raw markdown so terminal resize reflow can render it again at the
|
||||
/// current width. Callers should use `new_proposed_plan_stream` only for transient live streaming
|
||||
/// cells, then consolidate to this source-backed cell when the plan is complete.
|
||||
pub(crate) fn new_proposed_plan(plan_markdown: String, cwd: &Path) -> ProposedPlanCell {
|
||||
ProposedPlanCell {
|
||||
plan_markdown,
|
||||
cwd: cwd.to_path_buf(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a transient proposed-plan stream cell from already rendered lines.
|
||||
///
|
||||
/// Stream cells are display fragments, not source-backed history. They should be replaced by
|
||||
/// `ProposedPlanCell` during consolidation before relying on resize reflow for finalized history.
|
||||
pub(crate) fn new_proposed_plan_stream(
|
||||
lines: Vec<Line<'static>>,
|
||||
is_stream_continuation: bool,
|
||||
) -> ProposedPlanStreamCell {
|
||||
ProposedPlanStreamCell {
|
||||
lines,
|
||||
is_stream_continuation,
|
||||
}
|
||||
}
|
||||
|
||||
/// Finalized proposed-plan history that can render itself again for a new width.
|
||||
///
|
||||
/// This is the source-backed counterpart to `ProposedPlanStreamCell`. It owns raw markdown and the
|
||||
/// session cwd needed for stable local-link rendering during later transcript reflow.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ProposedPlanCell {
|
||||
plan_markdown: String,
|
||||
/// Session cwd used to keep local file-link display aligned with live streamed plan rendering.
|
||||
cwd: PathBuf,
|
||||
}
|
||||
|
||||
/// Transient proposed-plan history emitted while a plan is still streaming.
|
||||
///
|
||||
/// The lines are already rendered for the stream's current width. A finalized transcript should not
|
||||
/// keep these cells after consolidation, because they cannot re-render their source on a later
|
||||
/// terminal resize.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ProposedPlanStreamCell {
|
||||
lines: Vec<Line<'static>>,
|
||||
is_stream_continuation: bool,
|
||||
}
|
||||
|
||||
impl HistoryCell for ProposedPlanCell {
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
let mut lines: Vec<Line<'static>> = Vec::new();
|
||||
lines.push(vec!["• ".dim(), "Proposed Plan".bold()].into());
|
||||
lines.push(Line::from(" "));
|
||||
|
||||
let mut plan_lines: Vec<Line<'static>> = vec![Line::from(" ")];
|
||||
let plan_style = proposed_plan_style();
|
||||
let wrap_width = width.saturating_sub(4).max(1) as usize;
|
||||
let mut body: Vec<Line<'static>> = Vec::new();
|
||||
append_markdown_agent_with_cwd(
|
||||
&self.plan_markdown,
|
||||
Some(wrap_width),
|
||||
Some(self.cwd.as_path()),
|
||||
&mut body,
|
||||
);
|
||||
if body.is_empty() {
|
||||
body.push(Line::from("(empty)".dim().italic()));
|
||||
}
|
||||
plan_lines.extend(prefix_lines(body, " ".into(), " ".into()));
|
||||
plan_lines.push(Line::from(" "));
|
||||
|
||||
lines.extend(plan_lines.into_iter().map(|line| line.style(plan_style)));
|
||||
lines
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
raw_lines_from_source(&self.plan_markdown)
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryCell for ProposedPlanStreamCell {
|
||||
fn display_lines(&self, _width: u16) -> Vec<Line<'static>> {
|
||||
self.lines.clone()
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
plain_lines(self.lines.clone())
|
||||
}
|
||||
|
||||
fn is_stream_continuation(&self) -> bool {
|
||||
self.is_stream_continuation
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct PlanUpdateCell {
|
||||
explanation: Option<String>,
|
||||
plan: Vec<PlanItemArg>,
|
||||
}
|
||||
|
||||
impl HistoryCell for PlanUpdateCell {
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
let render_note = |text: &str| -> Vec<Line<'static>> {
|
||||
let wrap_width = width.saturating_sub(4).max(1) as usize;
|
||||
let note = Line::from(text.to_string().dim().italic());
|
||||
let wrapped = adaptive_wrap_line(¬e, RtOptions::new(wrap_width));
|
||||
let mut out = Vec::new();
|
||||
push_owned_lines(&wrapped, &mut out);
|
||||
out
|
||||
};
|
||||
|
||||
let render_step = |status: &StepStatus, text: &str| -> Vec<Line<'static>> {
|
||||
let (box_str, step_style) = match status {
|
||||
StepStatus::Completed => ("✔ ", Style::default().crossed_out().dim()),
|
||||
StepStatus::InProgress => ("□ ", Style::default().cyan().bold()),
|
||||
StepStatus::Pending => ("□ ", Style::default().dim()),
|
||||
};
|
||||
|
||||
let opts = RtOptions::new(width.saturating_sub(4).max(1) as usize)
|
||||
.initial_indent(box_str.into())
|
||||
.subsequent_indent(" ".into());
|
||||
let step = Line::from(text.to_string().set_style(step_style));
|
||||
let wrapped = adaptive_wrap_line(&step, opts);
|
||||
let mut out = Vec::new();
|
||||
push_owned_lines(&wrapped, &mut out);
|
||||
out
|
||||
};
|
||||
|
||||
let mut lines: Vec<Line<'static>> = vec![];
|
||||
lines.push(vec!["• ".dim(), "Updated Plan".bold()].into());
|
||||
|
||||
let mut indented_lines = vec![];
|
||||
let note = self
|
||||
.explanation
|
||||
.as_ref()
|
||||
.map(|s| s.trim())
|
||||
.filter(|t| !t.is_empty());
|
||||
if let Some(expl) = note {
|
||||
indented_lines.extend(render_note(expl));
|
||||
};
|
||||
|
||||
if self.plan.is_empty() {
|
||||
indented_lines.push(Line::from("(no steps provided)".dim().italic()));
|
||||
} else {
|
||||
for PlanItemArg { step, status } in self.plan.iter() {
|
||||
indented_lines.extend(render_step(status, step));
|
||||
}
|
||||
}
|
||||
lines.extend(prefix_lines(indented_lines, " └ ".dim(), " ".into()));
|
||||
|
||||
lines
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
let mut lines = vec![Line::from("Updated Plan")];
|
||||
if let Some(explanation) = self
|
||||
.explanation
|
||||
.as_ref()
|
||||
.map(|s| s.trim())
|
||||
.filter(|s| !s.is_empty())
|
||||
{
|
||||
lines.extend(raw_lines_from_source(explanation));
|
||||
}
|
||||
if self.plan.is_empty() {
|
||||
lines.push(Line::from("(no steps provided)"));
|
||||
} else {
|
||||
for PlanItemArg { step, status } in &self.plan {
|
||||
lines.push(Line::from(format!("{status:?}: {step}")));
|
||||
}
|
||||
}
|
||||
lines
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
//! Completed request-user-input transcript rendering.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Renders a completed (or interrupted) request_user_input exchange in history.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct RequestUserInputResultCell {
|
||||
pub(crate) questions: Vec<ToolRequestUserInputQuestion>,
|
||||
pub(crate) answers: HashMap<String, ToolRequestUserInputAnswer>,
|
||||
pub(crate) interrupted: bool,
|
||||
}
|
||||
|
||||
impl HistoryCell for RequestUserInputResultCell {
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
let width = width.max(1) as usize;
|
||||
let total = self.questions.len();
|
||||
let answered = self
|
||||
.questions
|
||||
.iter()
|
||||
.filter(|question| {
|
||||
self.answers
|
||||
.get(&question.id)
|
||||
.is_some_and(|answer| !answer.answers.is_empty())
|
||||
})
|
||||
.count();
|
||||
let unanswered = total.saturating_sub(answered);
|
||||
|
||||
let mut header = vec!["•".dim(), " ".into(), "Questions".bold()];
|
||||
header.push(format!(" {answered}/{total} answered").dim());
|
||||
if self.interrupted {
|
||||
header.push(" (interrupted)".cyan());
|
||||
}
|
||||
|
||||
let mut lines: Vec<Line<'static>> = vec![header.into()];
|
||||
|
||||
for question in &self.questions {
|
||||
let answer = self.answers.get(&question.id);
|
||||
let answer_missing = match answer {
|
||||
Some(answer) => answer.answers.is_empty(),
|
||||
None => true,
|
||||
};
|
||||
let mut question_lines = wrap_with_prefix(
|
||||
&question.question,
|
||||
width,
|
||||
" • ".into(),
|
||||
" ".into(),
|
||||
Style::default(),
|
||||
);
|
||||
if answer_missing && let Some(last) = question_lines.last_mut() {
|
||||
last.spans.push(" (unanswered)".dim());
|
||||
}
|
||||
lines.extend(question_lines);
|
||||
|
||||
let Some(answer) = answer.filter(|answer| !answer.answers.is_empty()) else {
|
||||
continue;
|
||||
};
|
||||
if question.is_secret {
|
||||
lines.extend(wrap_with_prefix(
|
||||
"••••••",
|
||||
width,
|
||||
" answer: ".dim(),
|
||||
" ".dim(),
|
||||
Style::default().fg(Color::Cyan),
|
||||
));
|
||||
continue;
|
||||
}
|
||||
|
||||
let (options, note) = split_request_user_input_answer(answer);
|
||||
|
||||
for option in options {
|
||||
lines.extend(wrap_with_prefix(
|
||||
&option,
|
||||
width,
|
||||
" answer: ".dim(),
|
||||
" ".dim(),
|
||||
Style::default().fg(Color::Cyan),
|
||||
));
|
||||
}
|
||||
if let Some(note) = note {
|
||||
let (label, continuation, style) = if question.options.is_some() {
|
||||
(
|
||||
" note: ".dim(),
|
||||
" ".dim(),
|
||||
Style::default().fg(Color::Cyan),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
" answer: ".dim(),
|
||||
" ".dim(),
|
||||
Style::default().fg(Color::Cyan),
|
||||
)
|
||||
};
|
||||
lines.extend(wrap_with_prefix(¬e, width, label, continuation, style));
|
||||
}
|
||||
}
|
||||
|
||||
if self.interrupted && unanswered > 0 {
|
||||
let summary = format!("interrupted with {unanswered} unanswered");
|
||||
lines.extend(wrap_with_prefix(
|
||||
&summary,
|
||||
width,
|
||||
" ↳ ".cyan().dim(),
|
||||
" ".dim(),
|
||||
Style::default().fg(Color::Cyan).add_modifier(Modifier::DIM),
|
||||
));
|
||||
}
|
||||
|
||||
lines
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
let total = self.questions.len();
|
||||
let answered = self
|
||||
.questions
|
||||
.iter()
|
||||
.filter(|question| {
|
||||
self.answers
|
||||
.get(&question.id)
|
||||
.is_some_and(|answer| !answer.answers.is_empty())
|
||||
})
|
||||
.count();
|
||||
let mut lines = vec![Line::from(format!("Questions {answered}/{total} answered"))];
|
||||
if self.interrupted {
|
||||
lines.push(Line::from("(interrupted)"));
|
||||
}
|
||||
for question in &self.questions {
|
||||
lines.push(Line::from(question.question.clone()));
|
||||
if let Some(answer) = self
|
||||
.answers
|
||||
.get(&question.id)
|
||||
.filter(|answer| !answer.answers.is_empty())
|
||||
{
|
||||
if question.is_secret {
|
||||
lines.push(Line::from("answer: ******"));
|
||||
} else {
|
||||
let (options, note) = split_request_user_input_answer(answer);
|
||||
lines.extend(
|
||||
options
|
||||
.into_iter()
|
||||
.map(|option| Line::from(format!("answer: {option}"))),
|
||||
);
|
||||
if let Some(note) = note {
|
||||
lines.push(Line::from(format!("note: {note}")));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
lines.push(Line::from("(unanswered)"));
|
||||
}
|
||||
}
|
||||
lines
|
||||
}
|
||||
}
|
||||
|
||||
/// Wrap a plain string with textwrap and prefix each line, while applying a style to the content.
|
||||
fn wrap_with_prefix(
|
||||
text: &str,
|
||||
width: usize,
|
||||
initial_prefix: Span<'static>,
|
||||
subsequent_prefix: Span<'static>,
|
||||
style: Style,
|
||||
) -> Vec<Line<'static>> {
|
||||
let line = Line::from(vec![Span::from(text.to_string()).set_style(style)]);
|
||||
let opts = RtOptions::new(width.max(1))
|
||||
.initial_indent(Line::from(vec![initial_prefix]))
|
||||
.subsequent_indent(Line::from(vec![subsequent_prefix]));
|
||||
let wrapped = adaptive_wrap_line(&line, opts);
|
||||
let mut out = Vec::new();
|
||||
push_owned_lines(&wrapped, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// Split a request_user_input answer into option labels and an optional freeform note.
|
||||
/// Notes are encoded as "user_note: <text>" entries in the answers list.
|
||||
fn split_request_user_input_answer(
|
||||
answer: &ToolRequestUserInputAnswer,
|
||||
) -> (Vec<String>, Option<String>) {
|
||||
let mut options = Vec::new();
|
||||
let mut note = None;
|
||||
for entry in &answer.answers {
|
||||
if let Some(note_text) = entry.strip_prefix("user_note: ") {
|
||||
note = Some(note_text.to_string());
|
||||
} else {
|
||||
options.push(entry.clone());
|
||||
}
|
||||
}
|
||||
(options, note)
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
//! Web-search activity history cells.
|
||||
|
||||
use super::*;
|
||||
|
||||
fn web_search_header(completed: bool) -> &'static str {
|
||||
if completed {
|
||||
"Searched"
|
||||
} else {
|
||||
"Searching the web"
|
||||
}
|
||||
}
|
||||
|
||||
fn web_search_action_detail(action: &WebSearchAction) -> String {
|
||||
match action {
|
||||
WebSearchAction::Search { query, queries } => {
|
||||
query.clone().filter(|q| !q.is_empty()).unwrap_or_else(|| {
|
||||
let items = queries.as_ref();
|
||||
let first = items
|
||||
.and_then(|queries| queries.first())
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
if items.is_some_and(|queries| queries.len() > 1) && !first.is_empty() {
|
||||
format!("{first} ...")
|
||||
} else {
|
||||
first
|
||||
}
|
||||
})
|
||||
}
|
||||
WebSearchAction::OpenPage { url } => url.clone().unwrap_or_default(),
|
||||
WebSearchAction::FindInPage { url, pattern } => match (pattern, url) {
|
||||
(Some(pattern), Some(url)) => format!("'{pattern}' in {url}"),
|
||||
(Some(pattern), None) => format!("'{pattern}'"),
|
||||
(None, Some(url)) => url.clone(),
|
||||
(None, None) => String::new(),
|
||||
},
|
||||
WebSearchAction::Other => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn web_search_detail(action: Option<&WebSearchAction>, query: &str) -> String {
|
||||
let detail = action.map(web_search_action_detail).unwrap_or_default();
|
||||
if detail.is_empty() {
|
||||
query.to_string()
|
||||
} else {
|
||||
detail
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct WebSearchCell {
|
||||
call_id: String,
|
||||
query: String,
|
||||
action: Option<WebSearchAction>,
|
||||
start_time: Instant,
|
||||
completed: bool,
|
||||
animations_enabled: bool,
|
||||
}
|
||||
|
||||
impl WebSearchCell {
|
||||
pub(crate) fn new(
|
||||
call_id: String,
|
||||
query: String,
|
||||
action: Option<WebSearchAction>,
|
||||
animations_enabled: bool,
|
||||
) -> Self {
|
||||
Self {
|
||||
call_id,
|
||||
query,
|
||||
action,
|
||||
start_time: Instant::now(),
|
||||
completed: false,
|
||||
animations_enabled,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn call_id(&self) -> &str {
|
||||
&self.call_id
|
||||
}
|
||||
|
||||
pub(crate) fn update(&mut self, action: WebSearchAction, query: String) {
|
||||
self.action = Some(action);
|
||||
self.query = query;
|
||||
}
|
||||
|
||||
pub(crate) fn complete(&mut self) {
|
||||
self.completed = true;
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryCell for WebSearchCell {
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
let bullet = if self.completed {
|
||||
"•".dim()
|
||||
} else {
|
||||
activity_indicator(
|
||||
Some(self.start_time),
|
||||
MotionMode::from_animations_enabled(self.animations_enabled),
|
||||
ReducedMotionIndicator::StaticBullet,
|
||||
)
|
||||
.unwrap_or_else(|| "•".dim())
|
||||
};
|
||||
let header = web_search_header(self.completed);
|
||||
let detail = web_search_detail(self.action.as_ref(), &self.query);
|
||||
let text: Text<'static> = if detail.is_empty() {
|
||||
Line::from(vec![header.bold()]).into()
|
||||
} else {
|
||||
Line::from(vec![header.bold(), " ".into(), detail.into()]).into()
|
||||
};
|
||||
PrefixedWrappedHistoryCell::new(text, vec![bullet, " ".into()], " ").display_lines(width)
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
let header = web_search_header(self.completed);
|
||||
let detail = web_search_detail(self.action.as_ref(), &self.query);
|
||||
if detail.is_empty() {
|
||||
vec![Line::from(header)]
|
||||
} else {
|
||||
vec![Line::from(format!("{header} {detail}"))]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn new_active_web_search_call(
|
||||
call_id: String,
|
||||
query: String,
|
||||
animations_enabled: bool,
|
||||
) -> WebSearchCell {
|
||||
WebSearchCell::new(call_id, query, /*action*/ None, animations_enabled)
|
||||
}
|
||||
|
||||
pub(crate) fn new_web_search_call(
|
||||
call_id: String,
|
||||
query: String,
|
||||
action: WebSearchAction,
|
||||
) -> WebSearchCell {
|
||||
let mut cell = WebSearchCell::new(
|
||||
call_id,
|
||||
query,
|
||||
Some(action),
|
||||
/*animations_enabled*/ false,
|
||||
);
|
||||
cell.complete();
|
||||
cell
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
//! Turn separators and runtime-metrics labels for transcript history.
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Debug)]
|
||||
/// A visual divider between turns, optionally showing how long the assistant "worked for".
|
||||
///
|
||||
/// This separator is only emitted for turns that performed concrete work (e.g., running commands,
|
||||
/// applying patches, making MCP tool calls), so purely conversational turns do not show an empty
|
||||
/// divider.
|
||||
pub struct FinalMessageSeparator {
|
||||
elapsed_seconds: Option<u64>,
|
||||
runtime_metrics: Option<RuntimeMetricsSummary>,
|
||||
}
|
||||
impl FinalMessageSeparator {
|
||||
/// Creates a separator; completed turns should pass protocol turn duration when available.
|
||||
pub(crate) fn new(
|
||||
elapsed_seconds: Option<u64>,
|
||||
runtime_metrics: Option<RuntimeMetricsSummary>,
|
||||
) -> Self {
|
||||
Self {
|
||||
elapsed_seconds,
|
||||
runtime_metrics,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl HistoryCell for FinalMessageSeparator {
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
let mut label_parts = Vec::new();
|
||||
if let Some(elapsed_seconds) = self
|
||||
.elapsed_seconds
|
||||
.filter(|seconds| *seconds > 60)
|
||||
.map(crate::status_indicator_widget::fmt_elapsed_compact)
|
||||
{
|
||||
label_parts.push(format!("Worked for {elapsed_seconds}"));
|
||||
}
|
||||
if let Some(metrics_label) = self.runtime_metrics.and_then(runtime_metrics_label) {
|
||||
label_parts.push(metrics_label);
|
||||
}
|
||||
|
||||
if label_parts.is_empty() {
|
||||
return vec![Line::from_iter(["─".repeat(width as usize).dim()])];
|
||||
}
|
||||
|
||||
let label = format!("─ {} ─", label_parts.join(" • "));
|
||||
let (label, _suffix, label_width) = take_prefix_by_width(&label, width as usize);
|
||||
vec![
|
||||
Line::from_iter([
|
||||
label,
|
||||
"─".repeat((width as usize).saturating_sub(label_width)),
|
||||
])
|
||||
.dim(),
|
||||
]
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
let mut label_parts = Vec::new();
|
||||
if let Some(elapsed_seconds) = self
|
||||
.elapsed_seconds
|
||||
.filter(|seconds| *seconds > 60)
|
||||
.map(crate::status_indicator_widget::fmt_elapsed_compact)
|
||||
{
|
||||
label_parts.push(format!("Worked for {elapsed_seconds}"));
|
||||
}
|
||||
if let Some(metrics_label) = self.runtime_metrics.and_then(runtime_metrics_label) {
|
||||
label_parts.push(metrics_label);
|
||||
}
|
||||
if label_parts.is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
vec![Line::from(label_parts.join(" • "))]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn runtime_metrics_label(summary: RuntimeMetricsSummary) -> Option<String> {
|
||||
let mut parts = Vec::new();
|
||||
if summary.tool_calls.count > 0 {
|
||||
let duration = format_duration_ms(summary.tool_calls.duration_ms);
|
||||
let calls = pluralize(summary.tool_calls.count, "call", "calls");
|
||||
parts.push(format!(
|
||||
"Local tools: {} {calls} ({duration})",
|
||||
summary.tool_calls.count
|
||||
));
|
||||
}
|
||||
if summary.api_calls.count > 0 {
|
||||
let duration = format_duration_ms(summary.api_calls.duration_ms);
|
||||
let calls = pluralize(summary.api_calls.count, "call", "calls");
|
||||
parts.push(format!(
|
||||
"Inference: {} {calls} ({duration})",
|
||||
summary.api_calls.count
|
||||
));
|
||||
}
|
||||
if summary.websocket_calls.count > 0 {
|
||||
let duration = format_duration_ms(summary.websocket_calls.duration_ms);
|
||||
parts.push(format!(
|
||||
"WebSocket: {} events send ({duration})",
|
||||
summary.websocket_calls.count
|
||||
));
|
||||
}
|
||||
if summary.streaming_events.count > 0 {
|
||||
let duration = format_duration_ms(summary.streaming_events.duration_ms);
|
||||
let stream_label = pluralize(summary.streaming_events.count, "Stream", "Streams");
|
||||
let events = pluralize(summary.streaming_events.count, "event", "events");
|
||||
parts.push(format!(
|
||||
"{stream_label}: {} {events} ({duration})",
|
||||
summary.streaming_events.count
|
||||
));
|
||||
}
|
||||
if summary.websocket_events.count > 0 {
|
||||
let duration = format_duration_ms(summary.websocket_events.duration_ms);
|
||||
parts.push(format!(
|
||||
"{} events received ({duration})",
|
||||
summary.websocket_events.count
|
||||
));
|
||||
}
|
||||
if summary.responses_api_overhead_ms > 0 {
|
||||
let duration = format_duration_ms(summary.responses_api_overhead_ms);
|
||||
parts.push(format!("Responses API overhead: {duration}"));
|
||||
}
|
||||
if summary.responses_api_inference_time_ms > 0 {
|
||||
let duration = format_duration_ms(summary.responses_api_inference_time_ms);
|
||||
parts.push(format!("Responses API inference: {duration}"));
|
||||
}
|
||||
if summary.responses_api_engine_iapi_ttft_ms > 0
|
||||
|| summary.responses_api_engine_service_ttft_ms > 0
|
||||
{
|
||||
let mut ttft_parts = Vec::new();
|
||||
if summary.responses_api_engine_iapi_ttft_ms > 0 {
|
||||
let duration = format_duration_ms(summary.responses_api_engine_iapi_ttft_ms);
|
||||
ttft_parts.push(format!("{duration} (iapi)"));
|
||||
}
|
||||
if summary.responses_api_engine_service_ttft_ms > 0 {
|
||||
let duration = format_duration_ms(summary.responses_api_engine_service_ttft_ms);
|
||||
ttft_parts.push(format!("{duration} (service)"));
|
||||
}
|
||||
parts.push(format!("TTFT: {}", ttft_parts.join(" ")));
|
||||
}
|
||||
if summary.responses_api_engine_iapi_tbt_ms > 0
|
||||
|| summary.responses_api_engine_service_tbt_ms > 0
|
||||
{
|
||||
let mut tbt_parts = Vec::new();
|
||||
if summary.responses_api_engine_iapi_tbt_ms > 0 {
|
||||
let duration = format_duration_ms(summary.responses_api_engine_iapi_tbt_ms);
|
||||
tbt_parts.push(format!("{duration} (iapi)"));
|
||||
}
|
||||
if summary.responses_api_engine_service_tbt_ms > 0 {
|
||||
let duration = format_duration_ms(summary.responses_api_engine_service_tbt_ms);
|
||||
tbt_parts.push(format!("{duration} (service)"));
|
||||
}
|
||||
parts.push(format!("TBT: {}", tbt_parts.join(" ")));
|
||||
}
|
||||
if parts.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(parts.join(" • "))
|
||||
}
|
||||
}
|
||||
|
||||
fn format_duration_ms(duration_ms: u64) -> String {
|
||||
if duration_ms >= 1_000 {
|
||||
let seconds = duration_ms as f64 / 1_000.0;
|
||||
format!("{seconds:.1}s")
|
||||
} else {
|
||||
format!("{duration_ms}ms")
|
||||
}
|
||||
}
|
||||
|
||||
fn pluralize(count: u64, singular: &'static str, plural: &'static str) -> &'static str {
|
||||
if count == 1 { singular } else { plural }
|
||||
}
|
||||
@@ -0,0 +1,428 @@
|
||||
//! Session headers, onboarding guidance, and transcript cards.
|
||||
|
||||
use super::*;
|
||||
|
||||
pub(crate) const SESSION_HEADER_MAX_INNER_WIDTH: usize = 56; // Just an eyeballed value
|
||||
|
||||
pub(crate) fn card_inner_width(width: u16, max_inner_width: usize) -> Option<usize> {
|
||||
if width < 4 {
|
||||
return None;
|
||||
}
|
||||
let inner_width = std::cmp::min(width.saturating_sub(4) as usize, max_inner_width);
|
||||
Some(inner_width)
|
||||
}
|
||||
|
||||
/// Render `lines` inside a border sized to the widest span in the content.
|
||||
pub(crate) fn with_border(lines: Vec<Line<'static>>) -> Vec<Line<'static>> {
|
||||
with_border_internal(lines, /*forced_inner_width*/ None)
|
||||
}
|
||||
|
||||
/// Render `lines` inside a border whose inner width is at least `inner_width`.
|
||||
///
|
||||
/// This is useful when callers have already clamped their content to a
|
||||
/// specific width and want the border math centralized here instead of
|
||||
/// duplicating padding logic in the TUI widgets themselves.
|
||||
pub(crate) fn with_border_with_inner_width(
|
||||
lines: Vec<Line<'static>>,
|
||||
inner_width: usize,
|
||||
) -> Vec<Line<'static>> {
|
||||
with_border_internal(lines, Some(inner_width))
|
||||
}
|
||||
|
||||
fn with_border_internal(
|
||||
lines: Vec<Line<'static>>,
|
||||
forced_inner_width: Option<usize>,
|
||||
) -> Vec<Line<'static>> {
|
||||
let max_line_width = lines
|
||||
.iter()
|
||||
.map(|line| {
|
||||
line.iter()
|
||||
.map(|span| UnicodeWidthStr::width(span.content.as_ref()))
|
||||
.sum::<usize>()
|
||||
})
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
let content_width = forced_inner_width
|
||||
.unwrap_or(max_line_width)
|
||||
.max(max_line_width);
|
||||
|
||||
let mut out = Vec::with_capacity(lines.len() + 2);
|
||||
let border_inner_width = content_width + 2;
|
||||
out.push(vec![format!("╭{}╮", "─".repeat(border_inner_width)).dim()].into());
|
||||
|
||||
for line in lines.into_iter() {
|
||||
let used_width: usize = line
|
||||
.iter()
|
||||
.map(|span| UnicodeWidthStr::width(span.content.as_ref()))
|
||||
.sum();
|
||||
let span_count = line.spans.len();
|
||||
let mut spans: Vec<Span<'static>> = Vec::with_capacity(span_count + 4);
|
||||
spans.push(Span::from("│ ").dim());
|
||||
spans.extend(line.into_iter());
|
||||
if used_width < content_width {
|
||||
spans.push(Span::from(" ".repeat(content_width - used_width)).dim());
|
||||
}
|
||||
spans.push(Span::from(" │").dim());
|
||||
out.push(Line::from(spans));
|
||||
}
|
||||
|
||||
out.push(vec![format!("╰{}╯", "─".repeat(border_inner_width)).dim()].into());
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
/// Return the emoji followed by a hair space (U+200A).
|
||||
/// Using only the hair space avoids excessive padding after the emoji while
|
||||
/// still providing a small visual gap across terminals.
|
||||
pub(crate) fn padded_emoji(emoji: &str) -> String {
|
||||
format!("{emoji}\u{200A}")
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct TooltipHistoryCell {
|
||||
tip: String,
|
||||
cwd: PathBuf,
|
||||
}
|
||||
|
||||
impl TooltipHistoryCell {
|
||||
fn new(tip: String, cwd: &Path) -> Self {
|
||||
Self {
|
||||
tip,
|
||||
cwd: cwd.to_path_buf(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryCell for TooltipHistoryCell {
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
let indent = " ";
|
||||
let indent_width = UnicodeWidthStr::width(indent);
|
||||
let wrap_width = usize::from(width.max(1))
|
||||
.saturating_sub(indent_width)
|
||||
.max(1);
|
||||
let mut lines: Vec<Line<'static>> = Vec::new();
|
||||
append_markdown(
|
||||
&format!("**Tip:** {}", self.tip),
|
||||
Some(wrap_width),
|
||||
Some(self.cwd.as_path()),
|
||||
&mut lines,
|
||||
);
|
||||
|
||||
prefix_lines(lines, indent.into(), indent.into())
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
vec![Line::from(format!("Tip: {}", self.tip))]
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct SessionInfoCell(CompositeHistoryCell);
|
||||
|
||||
impl HistoryCell for SessionInfoCell {
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
self.0.display_lines(width)
|
||||
}
|
||||
|
||||
fn desired_height(&self, width: u16) -> u16 {
|
||||
self.0.desired_height(width)
|
||||
}
|
||||
|
||||
fn transcript_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
self.0.transcript_lines(width)
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
self.0.raw_lines()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn new_session_info(
|
||||
config: &Config,
|
||||
requested_model: &str,
|
||||
session: &ThreadSessionState,
|
||||
is_first_event: bool,
|
||||
tooltip_override: Option<String>,
|
||||
auth_plan: Option<PlanType>,
|
||||
show_fast_status: bool,
|
||||
) -> SessionInfoCell {
|
||||
// Header box rendered as history (so it appears at the very top)
|
||||
let header = SessionHeaderHistoryCell::new(
|
||||
session.model.clone(),
|
||||
session.reasoning_effort,
|
||||
show_fast_status,
|
||||
config.cwd.to_path_buf(),
|
||||
CODEX_CLI_VERSION,
|
||||
)
|
||||
.with_yolo_mode(has_yolo_permissions(
|
||||
session.approval_policy,
|
||||
&session.permission_profile,
|
||||
));
|
||||
let mut parts: Vec<Box<dyn HistoryCell>> = vec![Box::new(header)];
|
||||
|
||||
if is_first_event {
|
||||
// Help lines below the header (new copy and list)
|
||||
let help_lines: Vec<Line<'static>> = vec![
|
||||
" To get started, describe a task or try one of these commands:"
|
||||
.dim()
|
||||
.into(),
|
||||
Line::from(""),
|
||||
Line::from(vec![
|
||||
" ".into(),
|
||||
"/init".into(),
|
||||
" - create an AGENTS.md file with instructions for Codex".dim(),
|
||||
]),
|
||||
Line::from(vec![
|
||||
" ".into(),
|
||||
"/status".into(),
|
||||
" - show current session configuration".dim(),
|
||||
]),
|
||||
Line::from(vec![
|
||||
" ".into(),
|
||||
"/permissions".into(),
|
||||
" - choose what Codex is allowed to do".dim(),
|
||||
]),
|
||||
Line::from(vec![
|
||||
" ".into(),
|
||||
"/model".into(),
|
||||
" - choose what model and reasoning effort to use".dim(),
|
||||
]),
|
||||
Line::from(vec![
|
||||
" ".into(),
|
||||
"/review".into(),
|
||||
" - review any changes and find issues".dim(),
|
||||
]),
|
||||
];
|
||||
|
||||
parts.push(Box::new(PlainHistoryCell { lines: help_lines }));
|
||||
} else {
|
||||
if config.show_tooltips
|
||||
&& let Some(tooltips) = tooltip_override
|
||||
.or_else(|| tooltips::get_tooltip(auth_plan, show_fast_status))
|
||||
.map(|tip| TooltipHistoryCell::new(tip, &config.cwd))
|
||||
{
|
||||
parts.push(Box::new(tooltips));
|
||||
}
|
||||
if requested_model != session.model.as_str() {
|
||||
let lines = vec![
|
||||
"model changed:".magenta().bold().into(),
|
||||
format!("requested: {requested_model}").into(),
|
||||
format!("used: {}", session.model).into(),
|
||||
];
|
||||
parts.push(Box::new(PlainHistoryCell { lines }));
|
||||
}
|
||||
}
|
||||
|
||||
SessionInfoCell(CompositeHistoryCell { parts })
|
||||
}
|
||||
|
||||
pub(crate) fn is_yolo_mode(config: &Config) -> bool {
|
||||
has_yolo_permissions(
|
||||
AskForApproval::from(config.permissions.approval_policy.value()),
|
||||
&config.permissions.effective_permission_profile(),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn has_yolo_permissions(
|
||||
approval_policy: AskForApproval,
|
||||
permission_profile: &PermissionProfile,
|
||||
) -> bool {
|
||||
approval_policy == AskForApproval::Never
|
||||
&& matches!(
|
||||
permission_profile,
|
||||
PermissionProfile::Disabled
|
||||
| PermissionProfile::Managed {
|
||||
file_system: ManagedFileSystemPermissions::Unrestricted,
|
||||
network: NetworkSandboxPolicy::Enabled,
|
||||
}
|
||||
)
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct SessionHeaderHistoryCell {
|
||||
version: &'static str,
|
||||
model: String,
|
||||
model_style: Style,
|
||||
reasoning_effort: Option<ReasoningEffortConfig>,
|
||||
show_fast_status: bool,
|
||||
directory: PathBuf,
|
||||
yolo_mode: bool,
|
||||
}
|
||||
|
||||
impl SessionHeaderHistoryCell {
|
||||
pub(crate) fn new(
|
||||
model: String,
|
||||
reasoning_effort: Option<ReasoningEffortConfig>,
|
||||
show_fast_status: bool,
|
||||
directory: PathBuf,
|
||||
version: &'static str,
|
||||
) -> Self {
|
||||
Self::new_with_style(
|
||||
model,
|
||||
Style::default(),
|
||||
reasoning_effort,
|
||||
show_fast_status,
|
||||
directory,
|
||||
version,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn new_with_style(
|
||||
model: String,
|
||||
model_style: Style,
|
||||
reasoning_effort: Option<ReasoningEffortConfig>,
|
||||
show_fast_status: bool,
|
||||
directory: PathBuf,
|
||||
version: &'static str,
|
||||
) -> Self {
|
||||
Self {
|
||||
version,
|
||||
model,
|
||||
model_style,
|
||||
reasoning_effort,
|
||||
show_fast_status,
|
||||
directory,
|
||||
yolo_mode: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn with_yolo_mode(mut self, yolo_mode: bool) -> Self {
|
||||
self.yolo_mode = yolo_mode;
|
||||
self
|
||||
}
|
||||
|
||||
fn format_directory(&self, max_width: Option<usize>) -> String {
|
||||
Self::format_directory_inner(&self.directory, max_width)
|
||||
}
|
||||
|
||||
pub(crate) fn format_directory_inner(directory: &Path, max_width: Option<usize>) -> String {
|
||||
let formatted = if let Some(rel) = relativize_to_home(directory) {
|
||||
if rel.as_os_str().is_empty() {
|
||||
"~".to_string()
|
||||
} else {
|
||||
format!("~{}{}", std::path::MAIN_SEPARATOR, rel.display())
|
||||
}
|
||||
} else {
|
||||
directory.display().to_string()
|
||||
};
|
||||
|
||||
if let Some(max_width) = max_width {
|
||||
if max_width == 0 {
|
||||
return String::new();
|
||||
}
|
||||
if UnicodeWidthStr::width(formatted.as_str()) > max_width {
|
||||
return crate::text_formatting::center_truncate_path(&formatted, max_width);
|
||||
}
|
||||
}
|
||||
|
||||
formatted
|
||||
}
|
||||
|
||||
fn reasoning_label(&self) -> Option<&'static str> {
|
||||
self.reasoning_effort.map(|effort| match effort {
|
||||
ReasoningEffortConfig::Minimal => "minimal",
|
||||
ReasoningEffortConfig::Low => "low",
|
||||
ReasoningEffortConfig::Medium => "medium",
|
||||
ReasoningEffortConfig::High => "high",
|
||||
ReasoningEffortConfig::XHigh => "xhigh",
|
||||
ReasoningEffortConfig::None => "none",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryCell for SessionHeaderHistoryCell {
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
let Some(inner_width) = card_inner_width(width, SESSION_HEADER_MAX_INNER_WIDTH) else {
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let make_row = |spans: Vec<Span<'static>>| Line::from(spans);
|
||||
|
||||
// Title line rendered inside the box: ">_ OpenAI Codex (vX)"
|
||||
let title_spans: Vec<Span<'static>> = vec![
|
||||
Span::from(">_ ").dim(),
|
||||
Span::from("OpenAI Codex").bold(),
|
||||
Span::from(" ").dim(),
|
||||
Span::from(format!("(v{})", self.version)).dim(),
|
||||
];
|
||||
|
||||
const CHANGE_MODEL_HINT_COMMAND: &str = "/model";
|
||||
const CHANGE_MODEL_HINT_EXPLANATION: &str = " to change";
|
||||
const DIR_LABEL: &str = "directory:";
|
||||
const PERMISSIONS_LABEL: &str = "permissions:";
|
||||
let label_width = if self.yolo_mode {
|
||||
DIR_LABEL.len().max(PERMISSIONS_LABEL.len())
|
||||
} else {
|
||||
DIR_LABEL.len()
|
||||
};
|
||||
|
||||
let model_label = format!(
|
||||
"{model_label:<label_width$}",
|
||||
model_label = "model:",
|
||||
label_width = label_width
|
||||
);
|
||||
let reasoning_label = self.reasoning_label();
|
||||
let model_spans: Vec<Span<'static>> = {
|
||||
let mut spans = vec![
|
||||
Span::from(format!("{model_label} ")).dim(),
|
||||
Span::styled(self.model.clone(), self.model_style),
|
||||
];
|
||||
if let Some(reasoning) = reasoning_label {
|
||||
spans.push(Span::from(" "));
|
||||
spans.push(Span::from(reasoning));
|
||||
}
|
||||
if self.show_fast_status {
|
||||
spans.push(" ".into());
|
||||
spans.push(Span::styled("fast", self.model_style.magenta()));
|
||||
}
|
||||
spans.push(" ".dim());
|
||||
spans.push(CHANGE_MODEL_HINT_COMMAND.cyan());
|
||||
spans.push(CHANGE_MODEL_HINT_EXPLANATION.dim());
|
||||
spans
|
||||
};
|
||||
|
||||
let dir_label = format!("{DIR_LABEL:<label_width$}");
|
||||
let dir_prefix = format!("{dir_label} ");
|
||||
let dir_prefix_width = UnicodeWidthStr::width(dir_prefix.as_str());
|
||||
let dir_max_width = inner_width.saturating_sub(dir_prefix_width);
|
||||
let dir = self.format_directory(Some(dir_max_width));
|
||||
let dir_spans = vec![Span::from(dir_prefix).dim(), Span::from(dir)];
|
||||
|
||||
let mut lines = vec![
|
||||
make_row(title_spans),
|
||||
make_row(Vec::new()),
|
||||
make_row(model_spans),
|
||||
make_row(dir_spans),
|
||||
];
|
||||
|
||||
if self.yolo_mode {
|
||||
let permissions_label = format!("{PERMISSIONS_LABEL:<label_width$}");
|
||||
lines.push(make_row(vec![
|
||||
Span::from(format!("{permissions_label} ")).dim(),
|
||||
"YOLO mode".magenta().bold(),
|
||||
]));
|
||||
}
|
||||
|
||||
with_border(lines)
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
let mut lines = vec![
|
||||
Line::from(format!("OpenAI Codex (v{})", self.version)),
|
||||
Line::from(format!(
|
||||
"model: {}{}",
|
||||
self.model,
|
||||
self.reasoning_label()
|
||||
.map(|reasoning| format!(" {reasoning}"))
|
||||
.unwrap_or_default()
|
||||
)),
|
||||
Line::from(format!(
|
||||
"directory: {}",
|
||||
self.format_directory(/*max_width*/ None)
|
||||
)),
|
||||
];
|
||||
if self.yolo_mode {
|
||||
lines.push(Line::from("permissions: YOLO mode"));
|
||||
}
|
||||
lines
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user