use crate::diff_render::create_diff_summary; use crate::exec_command::relativize_to_home; use crate::exec_command::strip_bash_lc_and_escape; use crate::markdown::append_markdown; use crate::slash_command::SlashCommand; use crate::text_formatting::format_and_truncate_tool_result; use base64::Engine; use codex_ansi_escape::ansi_escape_line; use codex_common::create_config_summary_entries; use codex_common::elapsed::format_duration; use codex_core::config::Config; use codex_core::plan_tool::PlanItemArg; use codex_core::plan_tool::StepStatus; use codex_core::plan_tool::UpdatePlanArgs; use codex_core::project_doc::discover_project_doc_paths; use codex_core::protocol::FileChange; use codex_core::protocol::McpInvocation; use codex_core::protocol::SandboxPolicy; use codex_core::protocol::SessionConfiguredEvent; use codex_core::protocol::TokenUsage; use codex_login::get_auth_file; use codex_login::try_read_auth_json; use codex_protocol::parse_command::ParsedCommand; use image::DynamicImage; use image::ImageReader; use mcp_types::EmbeddedResourceResource; use mcp_types::ResourceLink; use ratatui::prelude::*; use ratatui::style::Color; use ratatui::style::Modifier; use ratatui::style::Style; use ratatui::widgets::Paragraph; use ratatui::widgets::WidgetRef; use ratatui::widgets::Wrap; use shlex::try_join as shlex_try_join; use std::collections::HashMap; use std::io::Cursor; use std::path::PathBuf; use std::time::Duration; use std::time::Instant; use tracing::error; use uuid::Uuid; #[derive(Clone, Debug)] pub(crate) struct CommandOutput { pub(crate) exit_code: i32, pub(crate) stdout: String, pub(crate) stderr: String, } pub(crate) enum PatchEventType { ApprovalRequest, ApplyBegin { auto_approved: bool }, } /// Represents an event to display in the conversation history. Returns its /// `Vec>` representation to make it easier to display in a /// scrollable list. pub(crate) trait HistoryCell: std::fmt::Debug + Send + Sync { fn display_lines(&self) -> Vec>; fn transcript_lines(&self) -> Vec> { self.display_lines() } fn desired_height(&self, width: u16) -> u16 { Paragraph::new(Text::from(self.display_lines())) .wrap(Wrap { trim: false }) .line_count(width) .try_into() .unwrap_or(0) } } #[derive(Debug)] pub(crate) struct PlainHistoryCell { lines: Vec>, } impl HistoryCell for PlainHistoryCell { fn display_lines(&self) -> Vec> { self.lines.clone() } } #[derive(Debug)] pub(crate) struct TranscriptOnlyHistoryCell { lines: Vec>, } impl HistoryCell for TranscriptOnlyHistoryCell { fn display_lines(&self) -> Vec> { Vec::new() } fn transcript_lines(&self) -> Vec> { self.lines.clone() } } #[derive(Debug)] pub(crate) struct ExecCell { pub(crate) command: Vec, pub(crate) parsed: Vec, pub(crate) output: Option, start_time: Option, } impl HistoryCell for ExecCell { fn display_lines(&self) -> Vec> { exec_command_lines( &self.command, &self.parsed, self.output.as_ref(), self.start_time, ) } } impl WidgetRef for &ExecCell { fn render_ref(&self, area: Rect, buf: &mut Buffer) { Paragraph::new(Text::from(self.display_lines())) .wrap(Wrap { trim: false }) .render(area, buf); } } #[derive(Debug)] struct CompletedMcpToolCallWithImageOutput { _image: DynamicImage, } impl HistoryCell for CompletedMcpToolCallWithImageOutput { fn display_lines(&self) -> Vec> { vec![ Line::from("tool result (image output omitted)"), Line::from(""), ] } } const TOOL_CALL_MAX_LINES: usize = 5; fn title_case(s: &str) -> String { if s.is_empty() { return String::new(); } let mut chars = s.chars(); let first = match chars.next() { Some(c) => c, None => return String::new(), }; let rest: String = chars.as_str().to_ascii_lowercase(); first.to_uppercase().collect::() + &rest } fn pretty_provider_name(id: &str) -> String { if id.eq_ignore_ascii_case("openai") { "OpenAI".to_string() } else { title_case(id) } } pub(crate) fn new_session_info( config: &Config, event: SessionConfiguredEvent, is_first_event: bool, ) -> PlainHistoryCell { let SessionConfiguredEvent { model, session_id: _, history_log_id: _, history_entry_count: _, } = event; if is_first_event { let cwd_str = match relativize_to_home(&config.cwd) { Some(rel) if !rel.as_os_str().is_empty() => format!("~/{}", rel.display()), Some(_) => "~".to_string(), None => config.cwd.display().to_string(), }; let lines: Vec> = vec![ Line::from(vec![ Span::raw(">_ ").dim(), Span::styled( "You are using OpenAI Codex in", Style::default().add_modifier(Modifier::BOLD), ), Span::raw(format!(" {cwd_str}")).dim(), ]), Line::from("".dim()), Line::from(" To get started, describe a task or try one of these commands:".dim()), Line::from("".dim()), Line::from(format!(" /init - {}", SlashCommand::Init.description()).dim()), Line::from(format!(" /status - {}", SlashCommand::Status.description()).dim()), Line::from(format!(" /approvals - {}", SlashCommand::Approvals.description()).dim()), Line::from(format!(" /model - {}", SlashCommand::Model.description()).dim()), Line::from("".dim()), ]; PlainHistoryCell { lines } } else if config.model == model { PlainHistoryCell { lines: Vec::new() } } else { let lines = vec![ Line::from("model changed:".magenta().bold()), Line::from(format!("requested: {}", config.model)), Line::from(format!("used: {model}")), Line::from(""), ]; PlainHistoryCell { lines } } } pub(crate) fn new_user_prompt(message: String) -> PlainHistoryCell { let mut lines: Vec> = Vec::new(); lines.push(Line::from("user".cyan().bold())); lines.extend(message.lines().map(|l| Line::from(l.to_string()))); lines.push(Line::from("")); PlainHistoryCell { lines } } pub(crate) fn new_active_exec_command( command: Vec, parsed: Vec, ) -> ExecCell { ExecCell { command, parsed, output: None, start_time: Some(Instant::now()), } } pub(crate) fn new_completed_exec_command( command: Vec, parsed: Vec, output: CommandOutput, ) -> ExecCell { ExecCell { command, parsed, output: Some(output), start_time: None, } } fn exec_duration(start: Instant) -> String { format!("{}s", start.elapsed().as_secs()) } fn exec_command_lines( command: &[String], parsed: &[ParsedCommand], output: Option<&CommandOutput>, start_time: Option, ) -> Vec> { match parsed.is_empty() { true => new_exec_command_generic(command, output, start_time), false => new_parsed_command(command, parsed, output, start_time), } } fn new_parsed_command( command: &[String], parsed_commands: &[ParsedCommand], output: Option<&CommandOutput>, start_time: Option, ) -> Vec> { let mut lines: Vec = Vec::new(); match output { None => { let mut spans = vec!["⚙︎ Working".magenta().bold()]; if let Some(st) = start_time { let dur = exec_duration(st); spans.push(format!(" • {dur}").dim()); } lines.push(Line::from(spans)); } Some(o) if o.exit_code == 0 => { lines.push(Line::from(vec!["✓".green(), " Completed".into()])); } Some(o) => { lines.push(Line::from(vec![ "✗".red(), format!(" Failed (exit {})", o.exit_code).into(), ])); } }; // Optionally include the complete, unaltered command from the model. if std::env::var("SHOW_FULL_COMMANDS") .map(|v| !v.is_empty()) .unwrap_or(false) { let full_cmd = shlex_try_join(command.iter().map(|s| s.as_str())) .unwrap_or_else(|_| command.join(" ")); lines.push(Line::from(vec![ Span::styled(" └ ", Style::default().add_modifier(Modifier::DIM)), Span::styled( full_cmd, Style::default() .add_modifier(Modifier::DIM) .add_modifier(Modifier::ITALIC), ), ])); } for (i, parsed) in parsed_commands.iter().enumerate() { let text = match parsed { ParsedCommand::Read { name, .. } => format!("📖 {name}"), ParsedCommand::ListFiles { cmd, path } => match path { Some(p) => format!("📂 {p}"), None => format!("📂 {cmd}"), }, ParsedCommand::Search { query, path, cmd } => match (query, path) { (Some(q), Some(p)) => format!("🔎 {q} in {p}"), (Some(q), None) => format!("🔎 {q}"), (None, Some(p)) => format!("🔎 {p}"), (None, None) => format!("🔎 {cmd}"), }, ParsedCommand::Format { .. } => "✨ Formatting".to_string(), ParsedCommand::Test { cmd } => format!("🧪 {cmd}"), ParsedCommand::Lint { cmd, .. } => format!("🧹 {cmd}"), ParsedCommand::Unknown { cmd } => format!("⌨️ {cmd}"), ParsedCommand::Noop { cmd } => format!("🔄 {cmd}"), }; let first_prefix = if i == 0 { " └ " } else { " " }; for (j, line_text) in text.lines().enumerate() { let prefix = if j == 0 { first_prefix } else { " " }; lines.push(Line::from(vec![ Span::styled(prefix, Style::default().add_modifier(Modifier::DIM)), line_text.to_string().dim(), ])); } } lines.extend(output_lines(output, true, false)); lines.push(Line::from("")); lines } fn new_exec_command_generic( command: &[String], output: Option<&CommandOutput>, start_time: Option, ) -> Vec> { let mut lines: Vec> = Vec::new(); let command_escaped = strip_bash_lc_and_escape(command); let mut cmd_lines = command_escaped.lines(); if let Some(first) = cmd_lines.next() { let mut spans: Vec = vec!["⚡ Running".magenta()]; if let Some(st) = start_time { let dur = exec_duration(st); spans.push(format!(" • {dur}").dim()); } spans.push(" ".into()); spans.push(first.to_string().into()); lines.push(Line::from(spans)); } else { let mut spans: Vec = vec!["⚡ Running".magenta()]; if let Some(st) = start_time { let dur = exec_duration(st); spans.push(format!(" • {dur}").dim()); } lines.push(Line::from(spans)); } for cont in cmd_lines { lines.push(Line::from(cont.to_string())); } lines.extend(output_lines(output, false, true)); lines } pub(crate) fn new_active_mcp_tool_call(invocation: McpInvocation) -> PlainHistoryCell { let title_line = Line::from(vec!["tool".magenta(), " running...".dim()]); let lines: Vec = vec![ title_line, format_mcp_invocation(invocation.clone()), Line::from(""), ]; PlainHistoryCell { lines } } /// If the first content is an image, return a new cell with the image. /// TODO(rgwood-dd): Handle images properly even if they're not the first result. fn try_new_completed_mcp_tool_call_with_image_output( result: &Result, ) -> Option { match result { Ok(mcp_types::CallToolResult { content, .. }) => { if let Some(mcp_types::ContentBlock::ImageContent(image)) = content.first() { let raw_data = match base64::engine::general_purpose::STANDARD.decode(&image.data) { Ok(data) => data, Err(e) => { error!("Failed to decode image data: {e}"); return None; } }; let reader = match ImageReader::new(Cursor::new(raw_data)).with_guessed_format() { Ok(reader) => reader, Err(e) => { error!("Failed to guess image format: {e}"); return None; } }; let image = match reader.decode() { Ok(image) => image, Err(e) => { error!("Image decoding failed: {e}"); return None; } }; Some(CompletedMcpToolCallWithImageOutput { _image: image }) } else { None } } _ => None, } } pub(crate) fn new_completed_mcp_tool_call( num_cols: usize, invocation: McpInvocation, duration: Duration, success: bool, result: Result, ) -> Box { if let Some(cell) = try_new_completed_mcp_tool_call_with_image_output(&result) { return Box::new(cell); } let duration = format_duration(duration); let status_str = if success { "success" } else { "failed" }; let title_line = Line::from(vec![ "tool".magenta(), " ".into(), if success { status_str.green() } else { status_str.red() }, format!(", duration: {duration}").dim(), ]); let mut lines: Vec> = Vec::new(); lines.push(title_line); lines.push(format_mcp_invocation(invocation)); match result { Ok(mcp_types::CallToolResult { content, .. }) => { if !content.is_empty() { lines.push(Line::from("")); for tool_call_result in content { let line_text = match tool_call_result { mcp_types::ContentBlock::TextContent(text) => { format_and_truncate_tool_result( &text.text, TOOL_CALL_MAX_LINES, num_cols, ) } mcp_types::ContentBlock::ImageContent(_) => { // TODO show images even if they're not the first result, will require a refactor of `CompletedMcpToolCall` "".to_string() } mcp_types::ContentBlock::AudioContent(_) => "