Base: codex-main originale (prima del fork aKode)
This commit is contained in:
52
codex-rs/tui/src/history_cell/activity_details.rs
Normal file
52
codex-rs/tui/src/history_cell/activity_details.rs
Normal file
@@ -0,0 +1,52 @@
|
||||
//! Retain hidden reasoning between activity calls without breaking their compact group.
|
||||
//!
|
||||
//! Positions count preceding calls. Prepending history shifts those positions while sharing the
|
||||
//! original immutable detail cells, so expanded output keeps its chronological source content.
|
||||
//! Raw projection follows each cell's contract, retaining terminal input while hiding reasoning.
|
||||
|
||||
use super::HistoryCell;
|
||||
use super::HistoryRenderMode;
|
||||
use crate::terminal_hyperlinks::HyperlinkLine;
|
||||
use crate::terminal_hyperlinks::plain_hyperlink_lines;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub(crate) struct ActivityDetails {
|
||||
entries: Vec<(usize, Arc<dyn HistoryCell>)>,
|
||||
}
|
||||
|
||||
impl ActivityDetails {
|
||||
pub(crate) fn push(&mut self, after_calls: usize, cell: Arc<dyn HistoryCell>) {
|
||||
self.entries.push((after_calls, cell));
|
||||
}
|
||||
|
||||
pub(crate) fn prepend(&mut self, mut older: Self, older_calls: usize) {
|
||||
for (position, _) in &mut self.entries {
|
||||
*position += older_calls;
|
||||
}
|
||||
older.entries.append(&mut self.entries);
|
||||
*self = older;
|
||||
}
|
||||
|
||||
pub(crate) fn lines_after(
|
||||
&self,
|
||||
after_calls: usize,
|
||||
width: u16,
|
||||
mode: HistoryRenderMode,
|
||||
) -> Vec<HyperlinkLine> {
|
||||
self.entries
|
||||
.iter()
|
||||
.filter(|(position, _)| *position == after_calls)
|
||||
.flat_map(|(_, cell)| {
|
||||
let mut lines = match mode {
|
||||
HistoryRenderMode::Rich => cell.transcript_hyperlink_lines(width),
|
||||
HistoryRenderMode::Raw => plain_hyperlink_lines(cell.raw_lines()),
|
||||
};
|
||||
if mode == HistoryRenderMode::Rich && !lines.is_empty() {
|
||||
lines.insert(/*index*/ 0, HyperlinkLine::from(""));
|
||||
}
|
||||
lines
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
32
codex-rs/tui/src/history_cell/activity_group.rs
Normal file
32
codex-rs/tui/src/history_cell/activity_group.rs
Normal file
@@ -0,0 +1,32 @@
|
||||
//! Ordered calls and transcript details for adjacent activity groups.
|
||||
//!
|
||||
//! Call positions stay fixed as in-flight calls complete. Prepending older calls shifts the
|
||||
//! shared detail positions without recreating live clocks or discarding raw terminal input.
|
||||
|
||||
use super::ActivityDetails;
|
||||
use super::HistoryCell;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ActivityGroup<T> {
|
||||
pub(crate) calls: Vec<T>,
|
||||
pub(crate) details: ActivityDetails,
|
||||
}
|
||||
|
||||
impl<T> ActivityGroup<T> {
|
||||
pub(crate) fn new(calls: Vec<T>) -> Self {
|
||||
Self {
|
||||
calls,
|
||||
details: ActivityDetails::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn push_detail(&mut self, cell: Arc<dyn HistoryCell>) {
|
||||
self.details.push(self.calls.len(), cell);
|
||||
}
|
||||
|
||||
pub(crate) fn prepend(&mut self, older: Self) {
|
||||
self.details.prepend(older.details, older.calls.len());
|
||||
self.calls.splice(0..0, older.calls);
|
||||
}
|
||||
}
|
||||
20
codex-rs/tui/src/history_cell/activity_preview.rs
Normal file
20
codex-rs/tui/src/history_cell/activity_preview.rs
Normal file
@@ -0,0 +1,20 @@
|
||||
//! Shared bounds for owned-transcript action previews; expansion uses retained source content.
|
||||
|
||||
use crate::line_truncation::truncate_line_with_ellipsis_if_overflow;
|
||||
use crate::terminal_hyperlinks::HyperlinkLine;
|
||||
use ratatui::text::Line;
|
||||
|
||||
pub(crate) const DETAIL_PREVIEW_LINES: usize = 3;
|
||||
|
||||
/// Details an activity can reveal without materializing its expanded transcript.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum ActivityDisclosure {
|
||||
Generic,
|
||||
/// Retained output lines not fully visible in the preview, excluding storage omissions.
|
||||
OutputLines(usize),
|
||||
}
|
||||
|
||||
/// Clip a preview row without teaching selection to copy text that is currently hidden.
|
||||
pub(crate) fn clipped_line(line: Line<'static>, width: u16) -> HyperlinkLine {
|
||||
truncate_line_with_ellipsis_if_overflow(line, usize::from(width)).into()
|
||||
}
|
||||
351
codex-rs/tui/src/history_cell/approvals.rs
Normal file
351
codex-rs/tui/src/history_cell/approvals.rs
Normal file
@@ -0,0 +1,351 @@
|
||||
//! Approval, denial, and review-status transcript cells.
|
||||
|
||||
use super::*;
|
||||
use crate::style::accent_color;
|
||||
|
||||
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_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(), " "))
|
||||
}
|
||||
|
||||
/// Accented history cell line showing the current review status.
|
||||
pub(crate) fn new_review_status_line(message: String) -> PlainHistoryCell {
|
||||
PlainHistoryCell {
|
||||
lines: vec![Line::from(message.fg(accent_color()))],
|
||||
}
|
||||
}
|
||||
82
codex-rs/tui/src/history_cell/async_questions.rs
Normal file
82
codex-rs/tui/src/history_cell/async_questions.rs
Normal file
@@ -0,0 +1,82 @@
|
||||
//! Render each tagged title and the following suggestions from the tool's visible Markdown.
|
||||
|
||||
use crate::style::accent_color_on;
|
||||
use crate::terminal_hyperlinks::HyperlinkLine;
|
||||
use crate::terminal_hyperlinks::prefix_hyperlink_lines;
|
||||
use codex_protocol::items::AsyncUserInputQuestion;
|
||||
use ratatui::style::Style;
|
||||
use ratatui::text::Span;
|
||||
use std::ops::Range;
|
||||
|
||||
/// Core joins each title and its Markdown bullets, then separates questions by a blank line.
|
||||
/// Stop decorating if the metadata and visible Markdown diverge.
|
||||
pub(super) fn title_ranges(
|
||||
source: &str,
|
||||
questions: &[AsyncUserInputQuestion],
|
||||
) -> Vec<Range<usize>> {
|
||||
let mut titles = Vec::new();
|
||||
let mut rest = source;
|
||||
for question in questions {
|
||||
rest = rest.trim_start_matches('\n');
|
||||
let title = question.title.replace("\r\n", "\n");
|
||||
let title = title.trim_matches('\n');
|
||||
let Some(after_title) = rest.strip_prefix(title) else {
|
||||
break;
|
||||
};
|
||||
let start = source.len() - rest.len();
|
||||
titles.push(start..start + title.len());
|
||||
rest = after_title;
|
||||
for option in question.options.iter().flatten() {
|
||||
let option = option.replace("\r\n", "\n");
|
||||
let Some(after_option) = rest
|
||||
.trim_start_matches('\n')
|
||||
.strip_prefix("- ")
|
||||
.and_then(|s| s.strip_prefix(&option))
|
||||
else {
|
||||
return titles;
|
||||
};
|
||||
rest = after_option;
|
||||
}
|
||||
}
|
||||
titles
|
||||
}
|
||||
|
||||
pub(super) fn render(
|
||||
source: &str,
|
||||
titles: &[Range<usize>],
|
||||
markdown: impl Fn(&str) -> Vec<HyperlinkLine>,
|
||||
) -> Vec<HyperlinkLine> {
|
||||
let accent = Style::new().fg(accent_color_on(/*background*/ None));
|
||||
let mut lines = Vec::new();
|
||||
for (index, title) in titles.iter().enumerate() {
|
||||
if !lines.is_empty() {
|
||||
lines.push(HyperlinkLine::default());
|
||||
}
|
||||
let heading = markdown(&source[title.clone()])
|
||||
.into_iter()
|
||||
.map(|row| {
|
||||
let style = accent.patch(row.line.style);
|
||||
row.style(style).resolve_span_styles()
|
||||
})
|
||||
.collect();
|
||||
lines.extend(prefix_hyperlink_lines(
|
||||
heading,
|
||||
Span::styled("? ", accent),
|
||||
" ".into(),
|
||||
));
|
||||
|
||||
let end = titles
|
||||
.get(index + 1)
|
||||
.map_or(source.len(), |next| next.start);
|
||||
let body = source[title.end..end].trim_matches('\n');
|
||||
if !body.is_empty() {
|
||||
lines.push(HyperlinkLine::default());
|
||||
lines.extend(prefix_hyperlink_lines(
|
||||
markdown(body),
|
||||
" ".into(),
|
||||
" ".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
lines
|
||||
}
|
||||
119
codex-rs/tui/src/history_cell/async_replies.rs
Normal file
119
codex-rs/tui/src/history_cell/async_replies.rs
Normal file
@@ -0,0 +1,119 @@
|
||||
//! Render structured replies on the user-message surface. Only the repeated question is shortened.
|
||||
|
||||
use super::messages::sanitize_user_text;
|
||||
use crate::async_question_reply::AsyncQuestionReply;
|
||||
use crate::line_truncation::truncate_line_to_width;
|
||||
use crate::markdown_render::hide_web_link_destination;
|
||||
use crate::markdown_render::render_markdown_lines_with_width_cwd_and_hidden_link_destinations;
|
||||
use crate::style::accent_color_on;
|
||||
use crate::style::history_prompt_style;
|
||||
use crate::terminal_hyperlinks::HyperlinkLine;
|
||||
use crate::terminal_hyperlinks::LogicalLineSource;
|
||||
use crate::terminal_hyperlinks::prefix_hyperlink_lines;
|
||||
use crate::terminal_hyperlinks::remap_source_wrapped_line;
|
||||
use crate::terminal_hyperlinks::retain_initial_prefix;
|
||||
use crate::wrapping::RtOptions;
|
||||
use crate::wrapping::adaptive_wrap_line_to_width;
|
||||
use ratatui::style::Stylize;
|
||||
use std::path::Path;
|
||||
|
||||
pub(super) fn render(
|
||||
replies: &[AsyncQuestionReply],
|
||||
cwd: &Path,
|
||||
width: usize,
|
||||
) -> Vec<HyperlinkLine> {
|
||||
let surface = history_prompt_style();
|
||||
let accent = accent_color_on(surface.bg);
|
||||
let markdown = |text: &str, width| {
|
||||
render_markdown_lines_with_width_cwd_and_hidden_link_destinations(
|
||||
text,
|
||||
width,
|
||||
Some(cwd),
|
||||
&hide_web_link_destination,
|
||||
)
|
||||
};
|
||||
let mut lines = Vec::new();
|
||||
for reply in replies {
|
||||
if !lines.is_empty() {
|
||||
lines.push(HyperlinkLine::default().style(surface));
|
||||
}
|
||||
let mut question = markdown(&sanitize_user_text(reply.question.as_str().into()), None);
|
||||
if question.is_empty() {
|
||||
question.push(HyperlinkLine::default());
|
||||
}
|
||||
let mut wrapped = question
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.flat_map(|(index, row)| wrap(row, width, if index == 0 { "Re: " } else { "" }));
|
||||
let mut caption: Vec<_> = wrapped.by_ref().take(2).collect();
|
||||
if wrapped.next().is_some()
|
||||
&& let Some(last) = caption.last_mut()
|
||||
{
|
||||
last.line =
|
||||
truncate_line_to_width(std::mem::take(&mut last.line), width.saturating_sub(1));
|
||||
last.clip_hyperlinks_to_width(last.width());
|
||||
last.line.push_span("…");
|
||||
// Copy the visible excerpt as prose alongside the Markdown answer.
|
||||
caption.iter_mut().for_each(mark_as_prose);
|
||||
} else {
|
||||
retain_initial_prefix(&mut caption, "Re: ");
|
||||
}
|
||||
let caption = prefix_hyperlink_lines(caption, "↪ ".fg(accent).not_dim(), " ".into());
|
||||
lines.extend(caption.into_iter().map(|row| {
|
||||
let style = surface.fg(accent).dim().patch(row.line.style);
|
||||
row.style(style).resolve_span_styles()
|
||||
}));
|
||||
let text = sanitize_user_text(reply.answer.as_str().into());
|
||||
if text.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let mut answer = markdown(&text, Some(width));
|
||||
if !answer
|
||||
.iter()
|
||||
.flat_map(|row| &row.line.spans)
|
||||
.any(|span| !span.content.trim().is_empty())
|
||||
{
|
||||
answer = text
|
||||
.lines()
|
||||
.map(str::to_owned)
|
||||
.map(HyperlinkLine::from)
|
||||
.collect();
|
||||
answer.iter_mut().for_each(mark_as_prose);
|
||||
}
|
||||
lines.push(HyperlinkLine::default().style(surface));
|
||||
let answer = answer
|
||||
.into_iter()
|
||||
.flat_map(|row| wrap(row, width, ""))
|
||||
.map(|row| {
|
||||
let mut style = surface.patch(row.line.style);
|
||||
style.bg = surface.bg;
|
||||
row.style(style).resolve_span_styles()
|
||||
})
|
||||
.collect();
|
||||
lines.extend(prefix_hyperlink_lines(answer, " ".into(), " ".into()));
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
fn mark_as_prose(row: &mut HyperlinkLine) {
|
||||
row.source = Some(LogicalLineSource {
|
||||
copy_as_prose: true,
|
||||
..LogicalLineSource::from_line(&row.line)
|
||||
});
|
||||
}
|
||||
|
||||
// Markdown leaves some code and URLs overwide. Keep all of the row and its links in the gutter.
|
||||
fn wrap(row: HyperlinkLine, width: usize, initial: &'static str) -> Vec<HyperlinkLine> {
|
||||
if initial.is_empty() && row.width() <= width {
|
||||
return vec![row];
|
||||
}
|
||||
let indent = row
|
||||
.source
|
||||
.as_ref()
|
||||
.map(|s| s.continuation_indent.clone())
|
||||
.unwrap_or_default();
|
||||
let options = RtOptions::new(width)
|
||||
.initial_indent(initial.into())
|
||||
.subsequent_indent(indent);
|
||||
remap_source_wrapped_line(&row, adaptive_wrap_line_to_width(&row.line, options))
|
||||
}
|
||||
233
codex-rs/tui/src/history_cell/base.rs
Normal file
233
codex-rs/tui/src/history_cell/base.rs
Normal file
@@ -0,0 +1,233 @@
|
||||
//! Shared history-cell building blocks reused across transcript concerns.
|
||||
//! Wrapped prefixes remain display-only while annotated rows retain their logical source.
|
||||
|
||||
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 WebHyperlinkHistoryCell {
|
||||
lines: Vec<HyperlinkLine>,
|
||||
}
|
||||
|
||||
impl WebHyperlinkHistoryCell {
|
||||
pub(crate) fn new(lines: Vec<Line<'static>>) -> Self {
|
||||
Self {
|
||||
lines: crate::terminal_hyperlinks::annotate_web_urls(lines),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn new_hyperlink_lines(lines: Vec<HyperlinkLine>) -> Self {
|
||||
Self { lines }
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryCell for WebHyperlinkHistoryCell {
|
||||
fn display_lines(&self, _width: u16) -> Vec<Line<'static>> {
|
||||
self.lines.iter().map(|line| line.line.clone()).collect()
|
||||
}
|
||||
|
||||
fn display_hyperlink_lines(&self, _width: u16) -> Vec<HyperlinkLine> {
|
||||
self.lines.clone()
|
||||
}
|
||||
|
||||
fn transcript_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
self.display_hyperlink_lines(width)
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
plain_lines(self.lines.iter().map(|line| line.line.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>> {
|
||||
visible_lines(self.display_hyperlink_lines(width))
|
||||
}
|
||||
|
||||
fn display_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
if width == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let opts = RtOptions::new(usize::from(width))
|
||||
.initial_indent(self.initial_prefix.clone())
|
||||
.subsequent_indent(self.subsequent_prefix.clone());
|
||||
crate::terminal_hyperlinks::adaptive_wrap_hyperlink_lines(
|
||||
&plain_hyperlink_lines(self.text.lines.clone()),
|
||||
opts,
|
||||
)
|
||||
}
|
||||
|
||||
fn transcript_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
self.display_hyperlink_lines(width)
|
||||
}
|
||||
|
||||
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 warning_entries(&self) -> Vec<WarningEntry> {
|
||||
self.parts
|
||||
.iter()
|
||||
.flat_map(|part| part.warning_entries())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn live_raw_lines(&self) -> Vec<Line<'static>> {
|
||||
let mut lines = Vec::new();
|
||||
for part in &self.parts {
|
||||
let part = part.live_raw_lines();
|
||||
if !part.is_empty() {
|
||||
if !lines.is_empty() {
|
||||
lines.push(Line::default());
|
||||
}
|
||||
lines.extend(part);
|
||||
}
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
fn warning_keys(&self) -> Vec<WarningKey<'_>> {
|
||||
self.parts
|
||||
.iter()
|
||||
.flat_map(|part| part.warning_keys())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn compact_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
let mut out = Vec::new();
|
||||
for part in &self.parts {
|
||||
let lines = part.compact_hyperlink_lines(width);
|
||||
if !lines.is_empty() {
|
||||
if !out.is_empty() {
|
||||
out.push(HyperlinkLine::from(""));
|
||||
}
|
||||
out.extend(lines);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
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 display_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
let mut out = Vec::new();
|
||||
let mut first = true;
|
||||
for part in &self.parts {
|
||||
let mut lines = part.display_hyperlink_lines(width);
|
||||
if !lines.is_empty() {
|
||||
if !first {
|
||||
out.push(HyperlinkLine::from(""));
|
||||
}
|
||||
out.append(&mut lines);
|
||||
first = false;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn transcript_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
let mut out = Vec::new();
|
||||
let mut first = true;
|
||||
for part in &self.parts {
|
||||
let mut lines = part.transcript_hyperlink_lines(width);
|
||||
if !lines.is_empty() {
|
||||
if !first {
|
||||
out.push(HyperlinkLine::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
|
||||
}
|
||||
|
||||
fn has_stable_transcript_height(&self) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "base_tests.rs"]
|
||||
mod tests;
|
||||
95
codex-rs/tui/src/history_cell/base_tests.rs
Normal file
95
codex-rs/tui/src/history_cell/base_tests.rs
Normal file
@@ -0,0 +1,95 @@
|
||||
//! Prefixed rows preserve authored whitespace and exclude display gutters from source text.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[test]
|
||||
fn prefixed_wrapping_retains_one_source_line_across_widths_and_gutters() {
|
||||
let source = " let result = compute(alpha, beta, gamma); print(result);";
|
||||
let styled = Line::from(vec![
|
||||
" let result = ".into(),
|
||||
"compute".red().bold(),
|
||||
"(alpha, beta, gamma); print(result);".into(),
|
||||
])
|
||||
.cyan()
|
||||
.italic();
|
||||
let cell = PrefixedWrappedHistoryCell::new(styled, "✔ ".green(), " ");
|
||||
for width in [16, 24, 48] {
|
||||
let lines = cell.transcript_hyperlink_lines(width);
|
||||
let first = lines
|
||||
.first()
|
||||
.expect("wrapped source")
|
||||
.source
|
||||
.as_ref()
|
||||
.expect("source range");
|
||||
assert_eq!(first.text.as_ref(), source);
|
||||
assert_eq!(
|
||||
first.styled_range(0..source.len()),
|
||||
Line::from(vec![
|
||||
" let result = ".cyan().italic(),
|
||||
"compute".red().bold().italic(),
|
||||
"(alpha, beta, gamma); print(result);".cyan().italic(),
|
||||
])
|
||||
);
|
||||
assert_eq!(first.range.start, 0);
|
||||
let restyled = lines[0].clone().style(Style::new().on_blue());
|
||||
assert_eq!(
|
||||
restyled
|
||||
.source
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.styled_range(0..source.len()),
|
||||
Line::from(vec![
|
||||
" let result = ".cyan().italic().on_blue(),
|
||||
"compute".red().bold().italic().on_blue(),
|
||||
"(alpha, beta, gamma); print(result);"
|
||||
.cyan()
|
||||
.italic()
|
||||
.on_blue(),
|
||||
])
|
||||
);
|
||||
for line in &lines {
|
||||
let origin = line.source.as_ref().expect("source range");
|
||||
let visible = line.line.to_string();
|
||||
assert!(Arc::ptr_eq(&origin.text, &first.text));
|
||||
assert_eq!(
|
||||
&visible[origin.prefix_bytes..origin.prefix_bytes + origin.range.len()],
|
||||
&source[origin.range.clone()],
|
||||
);
|
||||
assert!(line.line.width() <= usize::from(width));
|
||||
}
|
||||
assert_eq!(
|
||||
lines
|
||||
.last()
|
||||
.expect("last row")
|
||||
.source
|
||||
.as_ref()
|
||||
.expect("source")
|
||||
.range
|
||||
.end,
|
||||
source.len()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prefixed_wrapping_keeps_hard_lines_distinct_even_when_their_text_repeats() {
|
||||
let cell = PrefixedWrappedHistoryCell::new(
|
||||
Text::from(vec![
|
||||
Line::from("repeated text"),
|
||||
Line::from("repeated text"),
|
||||
]),
|
||||
"✔ ",
|
||||
" ",
|
||||
);
|
||||
let lines = cell.transcript_hyperlink_lines(/*width*/ 40);
|
||||
let first = lines[0].source.as_ref().expect("first source");
|
||||
let second = lines[1].source.as_ref().expect("second source");
|
||||
assert_eq!(
|
||||
(first.text.as_ref(), second.text.as_ref()),
|
||||
("repeated text", "repeated text")
|
||||
);
|
||||
assert!(!Arc::ptr_eq(&first.text, &second.text));
|
||||
assert!(cell.display_hyperlink_lines(/*width*/ 0).is_empty());
|
||||
}
|
||||
284
codex-rs/tui/src/history_cell/computer_activity.rs
Normal file
284
codex-rs/tui/src/history_cell/computer_activity.rs
Normal file
@@ -0,0 +1,284 @@
|
||||
//! Compact adjacent computer calls without discarding their chronological transcript details.
|
||||
//!
|
||||
//! CUA calls and intervening transcript-only reasoning share this cell. Visible history items
|
||||
//! and turn boundaries end the group.
|
||||
//! Preview selection favors failures and images, but never changes the order of retained rows.
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ComputerActivityCell {
|
||||
pub(crate) group: ActivityGroup<McpToolCallCell>,
|
||||
}
|
||||
|
||||
impl Default for ComputerActivityCell {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
group: ActivityGroup::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ComputerActivityCell {
|
||||
fn detailed_hyperlink_lines(&self, width: u16, mode: HistoryRenderMode) -> Vec<HyperlinkLine> {
|
||||
let mut lines = Vec::new();
|
||||
for (index, call) in self.group.calls.iter().enumerate() {
|
||||
lines.extend(call.transcript_hyperlink_lines(width));
|
||||
lines.extend(self.group.details.lines_after(index + 1, width, mode));
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
pub(crate) fn call_ids(&self) -> impl Iterator<Item = &str> {
|
||||
self.group.calls.iter().map(McpToolCallCell::call_id)
|
||||
}
|
||||
|
||||
/// Prepend validated historical calls without recreating pending live calls or their clocks.
|
||||
pub(crate) fn prepend(&mut self, older: Self) {
|
||||
self.group.prepend(older.group);
|
||||
}
|
||||
|
||||
pub(crate) fn start(&mut self, call: McpToolCallCell) {
|
||||
if !self
|
||||
.group
|
||||
.calls
|
||||
.iter()
|
||||
.any(|existing| existing.call_id == call.call_id)
|
||||
{
|
||||
self.group.calls.push(call);
|
||||
}
|
||||
}
|
||||
|
||||
/// Completion-only replay follows the same path as a live start followed by completion.
|
||||
pub(crate) fn complete(
|
||||
&mut self,
|
||||
call: McpToolCallCell,
|
||||
duration: Duration,
|
||||
result: Result<codex_protocol::mcp::CallToolResult, String>,
|
||||
) {
|
||||
let id = call.call_id.clone();
|
||||
self.start(call);
|
||||
if let Some(call) = self.group.calls.iter_mut().find(|call| call.call_id == id) {
|
||||
call.complete(duration, result);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_active(&self) -> bool {
|
||||
self.group.calls.iter().any(|call| call.result.is_none())
|
||||
}
|
||||
|
||||
pub(crate) fn mark_failed(&mut self) {
|
||||
for call in &mut self.group.calls {
|
||||
if call.result.is_none() {
|
||||
call.mark_failed();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn has_image(call: &McpToolCallCell) -> bool {
|
||||
matches!(&call.result, Some(Ok(result)) if result.has_image)
|
||||
}
|
||||
|
||||
/// Keep previews on one physical row, including grapheme clusters and narrow terminals.
|
||||
fn preview(text: &str, width: usize) -> String {
|
||||
let normalized = text.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
let (prefix, rest, _) = take_prefix_by_width(&normalized, width);
|
||||
if rest.is_empty() {
|
||||
prefix
|
||||
} else if width == 0 {
|
||||
String::new()
|
||||
} else {
|
||||
let (prefix, _, _) = take_prefix_by_width(&normalized, width.saturating_sub(1));
|
||||
format!("{prefix}…")
|
||||
}
|
||||
}
|
||||
|
||||
fn error_preview(call: &McpToolCallCell) -> Option<&str> {
|
||||
let text = match call.result.as_ref()? {
|
||||
Err(error) => error.as_str(),
|
||||
Ok(result) => result
|
||||
.content
|
||||
.iter()
|
||||
.filter_map(result::McpContentBlock::text)
|
||||
.find(|text| text.starts_with("Script error:"))
|
||||
.or_else(|| {
|
||||
result
|
||||
.content
|
||||
.iter()
|
||||
.find_map(|block| block.text().filter(|text| !text.trim().is_empty()))
|
||||
})?,
|
||||
};
|
||||
// CUA errors can append entire API manuals. The first nonempty line is the diagnostic;
|
||||
// preserve subsequent lines only in the full transcript, without inventing a paraphrase.
|
||||
text.strip_prefix("Script error:")
|
||||
.unwrap_or(text)
|
||||
.lines()
|
||||
.map(str::trim)
|
||||
.find(|line| !line.is_empty())
|
||||
}
|
||||
|
||||
impl HistoryCell for ComputerActivityCell {
|
||||
fn append_reasoning(&mut self, cell: Box<dyn HistoryCell>) -> Result<(), Box<dyn HistoryCell>> {
|
||||
if self.group.calls.is_empty() {
|
||||
Err(cell)
|
||||
} else {
|
||||
self.group.push_detail(std::sync::Arc::from(cell));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn compact_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
let mut lines = self.display_lines(width);
|
||||
if width > 0 && !self.is_active() && self.group.calls.len() > 3 {
|
||||
// The owned transcript supplies the shared disclosure control. Legacy history keeps
|
||||
// its built-in summary, which is the final row whenever completed calls are hidden.
|
||||
lines.pop();
|
||||
if let Some(line) = lines.last_mut()
|
||||
&& let Some(prefix) = line.spans.first_mut()
|
||||
{
|
||||
*prefix = " └ ".dim();
|
||||
}
|
||||
}
|
||||
plain_hyperlink_lines(lines)
|
||||
}
|
||||
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
if width == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let active = self
|
||||
.group
|
||||
.calls
|
||||
.iter()
|
||||
.rposition(|call| call.result.is_none());
|
||||
let failures = self
|
||||
.group
|
||||
.calls
|
||||
.iter()
|
||||
.filter(|call| call.success() == Some(false))
|
||||
.count();
|
||||
let count = self.group.calls.len();
|
||||
let bullet = active
|
||||
.and_then(|index| {
|
||||
let call = &self.group.calls[index];
|
||||
activity_indicator(
|
||||
Some(call.start_time),
|
||||
MotionMode::from_animations_enabled(call.animations_enabled),
|
||||
ReducedMotionIndicator::StaticBullet,
|
||||
)
|
||||
})
|
||||
.unwrap_or_else(|| "•".dim());
|
||||
let label = if active.is_some() {
|
||||
"Using computer"
|
||||
} else {
|
||||
"Used computer"
|
||||
};
|
||||
let unit = if count == 1 { "action" } else { "actions" };
|
||||
let mut header = vec![
|
||||
bullet,
|
||||
" ".into(),
|
||||
label.bold(),
|
||||
format!(" · {count} {unit}").dim(),
|
||||
];
|
||||
if failures > 0 {
|
||||
header.push(format!(" · {failures} failed").red());
|
||||
}
|
||||
let mut lines = adaptive_wrap_line(
|
||||
&Line::from(header),
|
||||
RtOptions::new(usize::from(width).max(1)).subsequent_indent(" ".into()),
|
||||
)
|
||||
.iter()
|
||||
.map(line_to_static)
|
||||
.collect::<Vec<_>>();
|
||||
let mut selected = if let Some(index) = active {
|
||||
vec![index]
|
||||
} else {
|
||||
let mut indices = (0..count).collect::<Vec<_>>();
|
||||
indices.sort_by_key(|&index| {
|
||||
let call = &self.group.calls[index];
|
||||
std::cmp::Reverse((call.success() == Some(false), has_image(call), index))
|
||||
});
|
||||
indices.truncate(if count > 3 { 2 } else { 3 });
|
||||
indices
|
||||
};
|
||||
selected.sort_unstable();
|
||||
let hidden = count - selected.len();
|
||||
let visible = selected.len();
|
||||
for (row_index, index) in selected.into_iter().enumerate() {
|
||||
let call = &self.group.calls[index];
|
||||
let title = call
|
||||
.invocation
|
||||
.arguments
|
||||
.as_ref()
|
||||
.and_then(|args| args.get("title"))
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.filter(|title| !title.trim().is_empty())
|
||||
.unwrap_or("Computer action");
|
||||
let failed = call.success() == Some(false);
|
||||
let summary = if failed {
|
||||
match error_preview(call) {
|
||||
Some(error) if width < 60 => format!("Failed: {error}"),
|
||||
Some(error) => {
|
||||
let title = preview(title, usize::from(width) / 3);
|
||||
format!("Failed: {title} — {error}")
|
||||
}
|
||||
None => format!("Failed: {title}"),
|
||||
}
|
||||
} else if has_image(call) {
|
||||
format!("Captured screenshot · {title}")
|
||||
} else {
|
||||
title.to_string()
|
||||
};
|
||||
let summary = preview(&summary, usize::from(width).saturating_sub(4));
|
||||
let row = if failed { summary.red() } else { summary.dim() };
|
||||
let prefix = if row_index + 1 == visible && (hidden == 0 || active.is_some()) {
|
||||
" └ "
|
||||
} else {
|
||||
" ├ "
|
||||
};
|
||||
lines.push(vec![prefix.dim(), row].into());
|
||||
}
|
||||
if hidden > 0 && active.is_none() {
|
||||
let summary = preview(
|
||||
&format!(
|
||||
"{hidden} more · {}",
|
||||
crate::key_hint::ctrl(crossterm::event::KeyCode::Char('t')).display_label()
|
||||
),
|
||||
usize::from(width).saturating_sub(4),
|
||||
);
|
||||
lines.push(vec![" └ ".dim(), summary.dim()].into());
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
fn transcript_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
visible_lines(self.transcript_hyperlink_lines(width))
|
||||
}
|
||||
|
||||
fn transcript_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
self.detailed_hyperlink_lines(width, HistoryRenderMode::Rich)
|
||||
}
|
||||
|
||||
fn activity_ids(&self) -> Vec<String> {
|
||||
self.call_ids().map(|id| format!("mcp:{id}")).collect()
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
plain_lines(visible_lines(
|
||||
self.detailed_hyperlink_lines(u16::MAX, HistoryRenderMode::Raw),
|
||||
))
|
||||
}
|
||||
|
||||
fn transcript_animation_tick(&self) -> Option<u64> {
|
||||
self.group
|
||||
.calls
|
||||
.iter()
|
||||
.filter_map(HistoryCell::transcript_animation_tick)
|
||||
.max()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "computer_activity_tests.rs"]
|
||||
mod tests;
|
||||
194
codex-rs/tui/src/history_cell/computer_activity_tests.rs
Normal file
194
codex-rs/tui/src/history_cell/computer_activity_tests.rs
Normal file
@@ -0,0 +1,194 @@
|
||||
use super::*;
|
||||
use codex_protocol::mcp::CallToolResult;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
fn call(id: &str, title: &str) -> McpToolCallCell {
|
||||
McpToolCallCell::new(
|
||||
id.to_string(),
|
||||
McpInvocation {
|
||||
server: "cua_repl".to_string(),
|
||||
tool: "js".to_string(),
|
||||
arguments: Some(json!({"title": title, "code": "await cua.getState()"})),
|
||||
},
|
||||
/*animations_enabled*/ false,
|
||||
)
|
||||
}
|
||||
|
||||
fn result(text: &str) -> Result<CallToolResult, String> {
|
||||
Ok(CallToolResult {
|
||||
content: vec![json!({"type": "text", "text": text})],
|
||||
structured_content: None,
|
||||
is_error: Some(false),
|
||||
meta: None,
|
||||
})
|
||||
}
|
||||
|
||||
fn render(cell: &ComputerActivityCell, width: u16) -> String {
|
||||
cell.display_lines(width)
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepending_completed_history_preserves_the_pending_call_clock() {
|
||||
let mut older = ComputerActivityCell::default();
|
||||
older.complete(
|
||||
call("older", "Read the page"),
|
||||
Duration::ZERO,
|
||||
result("read"),
|
||||
);
|
||||
let mut live = ComputerActivityCell::default();
|
||||
live.start(call("pending", "Inspect selection"));
|
||||
let start_time = live.group.calls[0].start_time;
|
||||
|
||||
live.prepend(older);
|
||||
assert_eq!(
|
||||
(
|
||||
live.call_ids().collect::<Vec<_>>(),
|
||||
live.group.calls[1].start_time,
|
||||
live.is_active()
|
||||
),
|
||||
(vec!["older", "pending"], start_time, true),
|
||||
);
|
||||
live.complete(
|
||||
call("pending", "Inspect selection"),
|
||||
Duration::ZERO,
|
||||
result("inspected"),
|
||||
);
|
||||
assert_eq!(
|
||||
(live.call_ids().collect::<Vec<_>>(), live.is_active()),
|
||||
(vec!["older", "pending"], false),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn computer_activity_active_and_interrupted() {
|
||||
let mut cell = ComputerActivityCell::default();
|
||||
cell.complete(call("1", "Opened Chrome"), Duration::ZERO, result("ready"));
|
||||
cell.start(call("2", "Load the terminal"));
|
||||
cell.start(call("2", "Duplicate start"));
|
||||
insta::assert_snapshot!("computer_activity_active", render(&cell, /*width*/ 80));
|
||||
cell.mark_failed();
|
||||
insta::assert_snapshot!("computer_activity_interrupted", render(&cell, /*width*/ 80));
|
||||
assert_eq!(
|
||||
cell.group
|
||||
.calls
|
||||
.iter()
|
||||
.map(McpToolCallCell::success)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![Some(true), Some(false)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn computer_activity_prioritizes_errors_and_images_without_reordering() {
|
||||
let mut cell = ComputerActivityCell::default();
|
||||
cell.complete(
|
||||
call("1", "Open browser"),
|
||||
Duration::ZERO,
|
||||
Err("No browser is available\n\n## Computer Use\nFull tool documentation".to_string()),
|
||||
);
|
||||
cell.complete(
|
||||
call("2", "Connect to Chrome"),
|
||||
Duration::ZERO,
|
||||
result("connected"),
|
||||
);
|
||||
cell.complete(
|
||||
call("3", "Reproduce the clear-command bug"),
|
||||
Duration::ZERO,
|
||||
result("reproduced"),
|
||||
);
|
||||
let mut image = result("screenshot metadata").unwrap();
|
||||
image.content.push(json!({"type": "image", "mimeType": "image/png", "data": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg=="}));
|
||||
cell.complete(
|
||||
call("4", "Capture the reproduced bug"),
|
||||
Duration::ZERO,
|
||||
Ok(image),
|
||||
);
|
||||
cell.complete(
|
||||
call("5", "Check the final page"),
|
||||
Duration::ZERO,
|
||||
result("checked"),
|
||||
);
|
||||
insta::assert_snapshot!("computer_activity_mixed", render(&cell, /*width*/ 90));
|
||||
insta::assert_snapshot!("computer_activity_narrow", render(&cell, /*width*/ 24));
|
||||
insta::assert_snapshot!(
|
||||
"computer_activity_compact",
|
||||
cell.compact_hyperlink_lines(/*width*/ 24)
|
||||
.iter()
|
||||
.map(|line| line.line.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
);
|
||||
let transcript = cell
|
||||
.transcript_lines(/*width*/ 100)
|
||||
.iter()
|
||||
.map(|line| line.to_string().trim_end().to_owned())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
insta::assert_snapshot!("computer_activity_expanded", transcript);
|
||||
assert!(transcript.contains("Full tool documentation"));
|
||||
assert_eq!(
|
||||
cell.raw_lines(),
|
||||
plain_lines(cell.transcript_lines(u16::MAX))
|
||||
);
|
||||
assert!(
|
||||
cell.display_lines(/*width*/ 24)
|
||||
.iter()
|
||||
.all(|line| line.width() <= 24)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn computer_activity_completed_and_transport_errors_keep_full_details() {
|
||||
let mut cell = ComputerActivityCell::default();
|
||||
cell.complete(
|
||||
call("1", "Inspect page"),
|
||||
Duration::ZERO,
|
||||
result("A successful result with details"),
|
||||
);
|
||||
cell.complete(call("2", "Reload page"), Duration::ZERO, result("Loaded"));
|
||||
insta::assert_snapshot!("computer_activity_success", render(&cell, /*width*/ 80));
|
||||
let mut failure =
|
||||
result("Browser state changed\nRe-query the browser before continuing").unwrap();
|
||||
failure.is_error = Some(true);
|
||||
cell.complete(
|
||||
call("3", "Inspect refreshed page"),
|
||||
Duration::ZERO,
|
||||
Ok(failure),
|
||||
);
|
||||
insta::assert_snapshot!(
|
||||
"computer_activity_failed_result",
|
||||
render(&cell, /*width*/ 90)
|
||||
);
|
||||
cell.mark_failed();
|
||||
assert_eq!(
|
||||
cell.group
|
||||
.calls
|
||||
.iter()
|
||||
.map(McpToolCallCell::success)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![Some(true), Some(true), Some(false)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn computer_activity_preview_handles_unicode_and_long_diagnostics() {
|
||||
assert_eq!(preview(" 你好\nworld ", /*width*/ 6), "你好 …");
|
||||
let mut cell = ComputerActivityCell::default();
|
||||
cell.complete(
|
||||
call("1", "检查浏览器"),
|
||||
Duration::ZERO,
|
||||
Err("diagnostic ".repeat(200)),
|
||||
);
|
||||
insta::assert_snapshot!("computer_activity_unicode", render(&cell, /*width*/ 24));
|
||||
assert!(
|
||||
cell.display_lines(/*width*/ 24)
|
||||
.iter()
|
||||
.all(|line| line.width() <= 24)
|
||||
);
|
||||
assert!(cell.transcript_lines(/*width*/ 100).len() > 20);
|
||||
}
|
||||
75
codex-rs/tui/src/history_cell/delegated_message.rs
Normal file
75
codex-rs/tui/src/history_cell/delegated_message.rs
Normal file
@@ -0,0 +1,75 @@
|
||||
//! Render incoming thread messages with literal attribution and a Markdown body.
|
||||
|
||||
use super::messages::normalize_whitespace_only_hyperlink_lines;
|
||||
use super::*;
|
||||
use crate::markdown_render::ListSpacing;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct DelegatedMessageCell {
|
||||
attribution: String,
|
||||
markdown: String,
|
||||
}
|
||||
|
||||
impl DelegatedMessageCell {
|
||||
pub(crate) fn new(source_thread_id: &str, markdown: String) -> Self {
|
||||
Self {
|
||||
attribution: format!("Sent by Codex from task {source_thread_id}"),
|
||||
markdown,
|
||||
}
|
||||
}
|
||||
|
||||
fn render_lines(&self, width: u16, list_spacing: ListSpacing) -> Vec<HyperlinkLine> {
|
||||
if width == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let body_width = width.saturating_sub(2).max(1);
|
||||
let indent = " ";
|
||||
let mut lines = crate::terminal_hyperlinks::adaptive_wrap_hyperlink_lines(
|
||||
&[HyperlinkLine::from(self.attribution.clone())],
|
||||
RtOptions::new(usize::from(width))
|
||||
.initial_indent("• ".dim().into())
|
||||
.subsequent_indent(indent.into()),
|
||||
);
|
||||
lines.extend(normalize_whitespace_only_hyperlink_lines(
|
||||
prefix_hyperlink_lines(
|
||||
crate::markdown::render_markdown_for_viewport_with_list_spacing(
|
||||
&self.markdown,
|
||||
body_width,
|
||||
list_spacing,
|
||||
),
|
||||
indent.into(),
|
||||
indent.into(),
|
||||
),
|
||||
));
|
||||
lines
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryCell for DelegatedMessageCell {
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
visible_lines(self.display_hyperlink_lines(width))
|
||||
}
|
||||
|
||||
fn display_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
self.render_lines(width, ListSpacing::AfterMultiline)
|
||||
}
|
||||
|
||||
fn retained_hyperlink_lines(&self, width: u16, _detailed: bool) -> Vec<HyperlinkLine> {
|
||||
self.render_lines(width, ListSpacing::Uniform)
|
||||
}
|
||||
|
||||
fn transcript_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
self.display_hyperlink_lines(width)
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
std::iter::once(Line::from(self.attribution.clone()))
|
||||
.chain(
|
||||
self.markdown
|
||||
.lines()
|
||||
.map(|line| Line::from(line.to_owned())),
|
||||
)
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
268
codex-rs/tui/src/history_cell/dynamic.rs
Normal file
268
codex-rs/tui/src/history_cell/dynamic.rs
Normal file
@@ -0,0 +1,268 @@
|
||||
//! Dynamic tool activity with retained arguments and output across live and loaded transcripts.
|
||||
|
||||
use super::HistoryCell;
|
||||
use super::activity_preview::DETAIL_PREVIEW_LINES;
|
||||
use super::activity_preview::clipped_line;
|
||||
use super::raw_lines_from_source;
|
||||
use crate::style::accent_color;
|
||||
use crate::terminal_hyperlinks::HyperlinkLine;
|
||||
use crate::terminal_hyperlinks::adaptive_wrap_hyperlink_lines;
|
||||
use crate::terminal_hyperlinks::plain_hyperlink_lines;
|
||||
use crate::terminal_hyperlinks::visible_lines;
|
||||
use crate::wrapping::RtOptions;
|
||||
use codex_app_server_protocol::DynamicToolCallOutputContentItem;
|
||||
use codex_app_server_protocol::DynamicToolCallStatus;
|
||||
use codex_app_server_protocol::ThreadItemPayload;
|
||||
use ratatui::style::Stylize;
|
||||
use ratatui::text::Line;
|
||||
use serde_json::Value;
|
||||
use std::sync::Arc;
|
||||
use std::sync::RwLock;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct DynamicToolCallCell {
|
||||
call_id: String,
|
||||
data: Arc<RwLock<DynamicToolCallData>>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct DynamicToolCallData {
|
||||
name: String,
|
||||
arguments: Value,
|
||||
status: DynamicToolCallStatus,
|
||||
interrupted: bool,
|
||||
output: Option<Vec<String>>,
|
||||
duration_ms: Option<i64>,
|
||||
}
|
||||
|
||||
impl DynamicToolCallCell {
|
||||
pub(crate) fn from_item(item: ThreadItemPayload) -> Option<Self> {
|
||||
let (call_id, data) = DynamicToolCallData::from_item(item)?;
|
||||
Some(Self {
|
||||
call_id,
|
||||
data: Arc::new(RwLock::new(data)),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn call_id(&self) -> &str {
|
||||
&self.call_id
|
||||
}
|
||||
|
||||
pub(crate) fn is_active(&self) -> bool {
|
||||
self.data
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.is_active()
|
||||
}
|
||||
|
||||
/// Updates the original retained row when concurrent calls complete in a different order.
|
||||
pub(crate) fn update_from_item(&self, item: ThreadItemPayload) -> bool {
|
||||
let Some((call_id, data)) = DynamicToolCallData::from_item(item) else {
|
||||
return false;
|
||||
};
|
||||
if call_id != self.call_id {
|
||||
return false;
|
||||
}
|
||||
*self
|
||||
.data
|
||||
.write()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner) = data;
|
||||
true
|
||||
}
|
||||
|
||||
pub(crate) fn mark_interrupted(&self) {
|
||||
let mut data = self
|
||||
.data
|
||||
.write()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if !data.is_active() {
|
||||
return;
|
||||
}
|
||||
data.status = DynamicToolCallStatus::Failed;
|
||||
data.interrupted = true;
|
||||
data.output
|
||||
.get_or_insert_with(Vec::new)
|
||||
.push("Interrupted before this tool returned a result.".to_owned());
|
||||
}
|
||||
}
|
||||
|
||||
impl DynamicToolCallData {
|
||||
fn from_item(item: ThreadItemPayload) -> Option<(String, Self)> {
|
||||
let ThreadItemPayload::DynamicToolCall {
|
||||
id,
|
||||
namespace,
|
||||
tool,
|
||||
arguments,
|
||||
status,
|
||||
content_items,
|
||||
success,
|
||||
duration_ms,
|
||||
} = item
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
Some((
|
||||
id,
|
||||
Self {
|
||||
name: namespace
|
||||
.map_or_else(|| tool.clone(), |namespace| format!("{namespace}.{tool}")),
|
||||
arguments,
|
||||
status: if success == Some(false) {
|
||||
DynamicToolCallStatus::Failed
|
||||
} else {
|
||||
status
|
||||
},
|
||||
interrupted: false,
|
||||
output: content_items.map(|items| {
|
||||
items
|
||||
.into_iter()
|
||||
.map(|item| match item {
|
||||
DynamicToolCallOutputContentItem::InputText { text } => text,
|
||||
DynamicToolCallOutputContentItem::InputImage { .. } => {
|
||||
"<image content>".to_owned()
|
||||
}
|
||||
DynamicToolCallOutputContentItem::InputAudio { .. } => {
|
||||
"<audio content>".to_owned()
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}),
|
||||
duration_ms,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
fn is_active(&self) -> bool {
|
||||
matches!(self.status, DynamicToolCallStatus::InProgress)
|
||||
}
|
||||
|
||||
fn header(&self) -> Line<'static> {
|
||||
let (marker, verb) = if self.interrupted {
|
||||
("•".red().bold(), "Interrupted")
|
||||
} else {
|
||||
match self.status {
|
||||
DynamicToolCallStatus::InProgress => ("•".dim(), "Calling"),
|
||||
DynamicToolCallStatus::Completed => ("•".green(), "Called"),
|
||||
DynamicToolCallStatus::Failed => ("•".red().bold(), "Failed"),
|
||||
}
|
||||
};
|
||||
let mut line = Line::from(vec![
|
||||
marker,
|
||||
" ".into(),
|
||||
verb.bold(),
|
||||
" ".into(),
|
||||
self.name.clone().fg(accent_color()),
|
||||
]);
|
||||
if let Some(duration_ms) = self.duration_ms.filter(|duration| *duration >= 0) {
|
||||
line.push_span(format!(" · {duration_ms}ms").dim());
|
||||
}
|
||||
line
|
||||
}
|
||||
|
||||
fn output_lines(&self) -> Vec<Line<'static>> {
|
||||
match &self.output {
|
||||
Some(output) if output.is_empty() => vec![Line::from("(no output)".dim())],
|
||||
Some(output) => output
|
||||
.iter()
|
||||
.flat_map(|text| raw_lines_from_source(text))
|
||||
.collect(),
|
||||
None if self.is_active() => Vec::new(),
|
||||
None => vec![Line::from("(output unavailable)".dim())],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryCell for DynamicToolCallCell {
|
||||
fn has_stable_transcript_height(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn activity_ids(&self) -> Vec<String> {
|
||||
vec![format!("dynamic:{}", self.call_id)]
|
||||
}
|
||||
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
visible_lines(self.compact_hyperlink_lines(width))
|
||||
}
|
||||
|
||||
fn compact_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
let data = self
|
||||
.data
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let mut lines = vec![clipped_line(data.header(), width)];
|
||||
let (skip, output) = match &data.output {
|
||||
Some(output) if !output.is_empty() => {
|
||||
let output = output.iter().flat_map(|text| text.split_terminator('\n'));
|
||||
let skip = output.clone().count().saturating_sub(DETAIL_PREVIEW_LINES);
|
||||
let tail = output
|
||||
.skip(skip)
|
||||
.map(|text| {
|
||||
// Bound allocation and grapheme scanning before clipping to display width.
|
||||
let end = text.floor_char_boundary(16 * 1024);
|
||||
let mut text_preview = text[..end].to_owned();
|
||||
if end < text.len() {
|
||||
text_preview.push('…');
|
||||
}
|
||||
Line::from(text_preview)
|
||||
})
|
||||
.collect();
|
||||
(skip, tail)
|
||||
}
|
||||
_ => (0, data.output_lines()),
|
||||
};
|
||||
if skip > 0 {
|
||||
lines.push(clipped_line(
|
||||
format!(" … {skip} earlier lines hidden").dim().into(),
|
||||
width,
|
||||
));
|
||||
}
|
||||
for (index, mut line) in output.into_iter().enumerate() {
|
||||
line.spans.insert(
|
||||
/*index*/ 0,
|
||||
if index == 0 { " └ " } else { " " }.dim(),
|
||||
);
|
||||
lines.push(clipped_line(line.dim(), width));
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
fn transcript_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
let data = self
|
||||
.data
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let mut lines = vec![data.header().into()];
|
||||
let args = serde_json::to_string_pretty(&data.arguments)
|
||||
.unwrap_or_else(|_| data.arguments.to_string());
|
||||
let details = raw_lines_from_source(&format!("Arguments: {args}"))
|
||||
.into_iter()
|
||||
.chain(data.output_lines())
|
||||
.collect();
|
||||
lines.extend(adaptive_wrap_hyperlink_lines(
|
||||
&plain_hyperlink_lines(details),
|
||||
RtOptions::new(usize::from(width).max(/*other*/ 1))
|
||||
.initial_indent(" └ ".dim().into())
|
||||
.subsequent_indent(" ".into()),
|
||||
));
|
||||
lines
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
let data = self
|
||||
.data
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let mut lines = vec![data.header()];
|
||||
lines.extend(raw_lines_from_source(&format!(
|
||||
"Arguments: {}",
|
||||
data.arguments
|
||||
)));
|
||||
lines.extend(data.output_lines());
|
||||
super::plain_lines(lines)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "dynamic_tests.rs"]
|
||||
mod tests;
|
||||
116
codex-rs/tui/src/history_cell/dynamic_tests.rs
Normal file
116
codex-rs/tui/src/history_cell/dynamic_tests.rs
Normal file
@@ -0,0 +1,116 @@
|
||||
//! Dynamic tool projections keep truthful status and bounded previews without losing detail.
|
||||
|
||||
use super::*;
|
||||
use crate::test_support::PathBufExt;
|
||||
use crate::test_support::test_path_buf;
|
||||
use crate::thread_transcript::RawReasoningVisibility;
|
||||
use crate::thread_transcript::thread_items_to_transcript_cells;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
fn item(status: DynamicToolCallStatus, output: Option<&str>) -> ThreadItemPayload {
|
||||
ThreadItemPayload::DynamicToolCall {
|
||||
id: "dynamic-1".to_string(),
|
||||
namespace: Some("example".to_string()),
|
||||
tool: "inspect".to_string(),
|
||||
arguments: json!({"path": "src/main.rs"}),
|
||||
status,
|
||||
content_items: output.map(|text| {
|
||||
vec![DynamicToolCallOutputContentItem::InputText {
|
||||
text: text.to_string(),
|
||||
}]
|
||||
}),
|
||||
success: None,
|
||||
duration_ms: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dynamic_status_and_output_match_persisted_presentations() {
|
||||
let cwd = test_path_buf("/workspace").abs();
|
||||
let mut snapshots = Vec::new();
|
||||
for (label, status, output) in [
|
||||
("pending", DynamicToolCallStatus::InProgress, None),
|
||||
(
|
||||
"success",
|
||||
DynamicToolCallStatus::Completed,
|
||||
Some("Found the definition"),
|
||||
),
|
||||
(
|
||||
"failure",
|
||||
DynamicToolCallStatus::Failed,
|
||||
Some("Permission denied"),
|
||||
),
|
||||
("unavailable", DynamicToolCallStatus::Completed, None),
|
||||
] {
|
||||
let replayed = thread_items_to_transcript_cells(
|
||||
/*thread_id*/ None,
|
||||
&cwd,
|
||||
[item(status, output)],
|
||||
RawReasoningVisibility::Hidden,
|
||||
/*config*/ None,
|
||||
);
|
||||
assert_eq!(replayed.len(), 1);
|
||||
let cell = &replayed[0];
|
||||
for (mode, lines) in [
|
||||
("compact", cell.display_lines(/*width*/ 80)),
|
||||
(
|
||||
"full",
|
||||
visible_lines(cell.transcript_hyperlink_lines(/*width*/ 80)),
|
||||
),
|
||||
("raw", cell.raw_lines()),
|
||||
] {
|
||||
let text = lines
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
if mode == "compact" || label == "success" {
|
||||
snapshots.push(format!("{label}, {mode}\n{text}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
insta::assert_snapshot!(snapshots.join("\n\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dynamic_preview_reports_hidden_lines_and_retains_full_output() {
|
||||
let mut snapshots = Vec::new();
|
||||
for count in [3, 4] {
|
||||
let output = (1..=count)
|
||||
.map(|index| format!("Result line {index}: retained content"))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
let cell =
|
||||
DynamicToolCallCell::from_item(item(DynamicToolCallStatus::Completed, Some(&output)))
|
||||
.unwrap();
|
||||
for width in [20, 80] {
|
||||
let compact = cell.display_lines(width);
|
||||
assert!(
|
||||
compact
|
||||
.iter()
|
||||
.all(|line| line.width() <= usize::from(width))
|
||||
);
|
||||
let text = compact
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
snapshots.push(format!("lines={count}, width={width}\n{text}"));
|
||||
}
|
||||
let raw = cell
|
||||
.raw_lines()
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
assert!(raw.ends_with(&output));
|
||||
let detailed = visible_lines(cell.transcript_hyperlink_lines(/*width*/ 80))
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
assert!(output.lines().all(|line| detailed.contains(line)));
|
||||
}
|
||||
insta::assert_snapshot!(snapshots.join("\n\n"));
|
||||
}
|
||||
261
codex-rs/tui/src/history_cell/exec.rs
Normal file
261
codex-rs/tui/src/history_cell/exec.rs
Normal file
@@ -0,0 +1,261 @@
|
||||
//! Background terminal interaction and process-summary history cells.
|
||||
//!
|
||||
//! Polling and stdin bookkeeping stay in detailed and raw history; the normal chat view
|
||||
//! relies on command output and the background-process status instead of repeating notices.
|
||||
|
||||
use super::*;
|
||||
use crate::style::accent_color;
|
||||
use crate::terminal_hyperlinks::adaptive_wrap_hyperlink_lines;
|
||||
use crate::width::display_width;
|
||||
|
||||
#[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>> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
fn transcript_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
visible_lines(self.transcript_hyperlink_lines(width))
|
||||
}
|
||||
|
||||
fn transcript_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
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 = adaptive_wrap_hyperlink_lines(&[header.into()], RtOptions::new(wrap_width));
|
||||
|
||||
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_hyperlink_lines(
|
||||
&plain_hyperlink_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 = display_width(prefix);
|
||||
let truncation_suffix = " [...]";
|
||||
let truncation_suffix_width = display_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 max_graphemes = 80;
|
||||
let mut graphemes = command.graphemes(true);
|
||||
let snippet: String = graphemes
|
||||
.by_ref()
|
||||
.take(max_graphemes)
|
||||
.map(|grapheme| match grapheme {
|
||||
"\n" | "\r\n" => "↵",
|
||||
_ => grapheme,
|
||||
})
|
||||
.collect();
|
||||
(snippet, graphemes.next().is_some())
|
||||
};
|
||||
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.fg(accent_color()),
|
||||
truncation_suffix.dim(),
|
||||
]
|
||||
.into(),
|
||||
);
|
||||
} else {
|
||||
let (truncated, _, _) = take_prefix_by_width(&snippet, budget);
|
||||
out.push(vec![prefix.dim(), truncated.fg(accent_color())].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 = display_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)])
|
||||
}
|
||||
783
codex-rs/tui/src/history_cell/hook_cell.rs
Normal file
783
codex-rs/tui/src/history_cell/hook_cell.rs
Normal file
@@ -0,0 +1,783 @@
|
||||
//! History cell for hook execution.
|
||||
//!
|
||||
//! Hooks are intentionally quieter than normal tool calls. A hook that starts and finishes
|
||||
//! successfully without user-facing output should not leave a transcript artifact, and very fast
|
||||
//! hooks should not flash in the viewport. Model-facing hook context never appears in the TUI. This
|
||||
//! cell keeps that policy local by treating each hook run as a small rendering state machine:
|
||||
//!
|
||||
//! 1. New runs begin hidden in `PendingReveal`.
|
||||
//! 2. Revealed runs contribute to the compact activity summary, never transcript lines.
|
||||
//! 3. Quiet completions leave the summary immediately but retain their existing cleanup timer
|
||||
//! for exec-flush and usage-output ordering.
|
||||
//! 4. Completed runs only persist when they have user-facing output or a non-success status.
|
||||
use super::HistoryCell;
|
||||
use super::plain_lines;
|
||||
use codex_ansi_escape::ansi_escape;
|
||||
use codex_app_server_protocol::HookOutputEntry;
|
||||
use codex_app_server_protocol::HookOutputEntryKind;
|
||||
use codex_app_server_protocol::HookRunStatus;
|
||||
use codex_app_server_protocol::HookRunSummary;
|
||||
use ratatui::prelude::*;
|
||||
use ratatui::style::Stylize;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct HookCell {
|
||||
/// Hook runs that are active, lingering, or have persistent output to render.
|
||||
runs: Vec<HookRunCell>,
|
||||
}
|
||||
|
||||
/// Minimum runtime before a hook is allowed to draw.
|
||||
///
|
||||
/// Avoids flashing activity for work that was effectively instant.
|
||||
const HOOK_RUN_REVEAL_DELAY: Duration = Duration::from_millis(300);
|
||||
|
||||
/// Minimum interval after reveal before quiet-completion bookkeeping is removed.
|
||||
///
|
||||
/// The activity summary clears on completion; retain the existing cleanup timing
|
||||
/// used by exec flushing and deferred usage output.
|
||||
const QUIET_HOOK_MIN_VISIBLE: Duration = Duration::from_millis(600);
|
||||
|
||||
const HOOK_OUTPUT_INDENT: &str = " ";
|
||||
const HOOK_OUTPUT_BODY_INDENT: &str = " ";
|
||||
|
||||
#[derive(Debug)]
|
||||
struct HookRunCell {
|
||||
/// Stable protocol id used to match begin/end updates for the same hook invocation.
|
||||
id: String,
|
||||
/// Optional hook-supplied detail shown next to the running header.
|
||||
status_message: Option<String>,
|
||||
/// Rendering lifecycle for this run.
|
||||
state: HookRunState,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum HookRunState {
|
||||
/// A newly-started run that is active but deliberately hidden until `reveal_deadline`.
|
||||
PendingReveal {
|
||||
/// First instant at which the run may become visible.
|
||||
reveal_deadline: Instant,
|
||||
},
|
||||
/// A run that survived the reveal delay and is currently shown as running.
|
||||
VisibleRunning {
|
||||
/// First instant the run was actually rendered, used by quiet-success linger.
|
||||
visible_since: Instant,
|
||||
},
|
||||
/// A visible run that completed successfully without output but is still lingering briefly.
|
||||
QuietLinger {
|
||||
/// Instant after which the quiet success can be removed entirely.
|
||||
removal_deadline: Instant,
|
||||
},
|
||||
/// A completed run with output or a status worth preserving in history.
|
||||
Completed {
|
||||
/// Final protocol status for the hook invocation.
|
||||
status: HookRunStatus,
|
||||
/// Hook output entries rendered below the completed header.
|
||||
entries: Vec<HookOutputEntry>,
|
||||
},
|
||||
}
|
||||
|
||||
impl HookCell {
|
||||
/// Creates a cell around a hook that has just started.
|
||||
fn new_active(run: HookRunSummary) -> Self {
|
||||
let mut cell = Self { runs: Vec::new() };
|
||||
cell.start_run(run);
|
||||
cell
|
||||
}
|
||||
|
||||
/// Creates a cell around an already-completed hook from transcript/history data.
|
||||
fn new_completed(run: HookRunSummary) -> Self {
|
||||
let mut cell = Self { runs: Vec::new() };
|
||||
cell.add_completed_run(run);
|
||||
cell
|
||||
}
|
||||
|
||||
pub(crate) fn is_empty(&self) -> bool {
|
||||
self.runs.is_empty()
|
||||
}
|
||||
|
||||
/// Returns true while any run can still change due to an end event or timer.
|
||||
pub(crate) fn is_active(&self) -> bool {
|
||||
self.runs.iter().any(|run| run.state.is_active())
|
||||
}
|
||||
|
||||
/// Completed hook cells are flushed out of the active slot once no timers remain.
|
||||
pub(crate) fn should_flush(&self) -> bool {
|
||||
!self.is_active() && !self.is_empty()
|
||||
}
|
||||
|
||||
/// Splits durable completed runs from ephemeral active-cell bookkeeping.
|
||||
///
|
||||
/// Quiet successes are left behind so they can disappear from the active cell, while failures,
|
||||
/// blocked/stopped hooks, and hooks with emitted output become a persistent history cell.
|
||||
pub(crate) fn take_completed_persistent_runs(&mut self) -> Option<Self> {
|
||||
let mut completed = Vec::new();
|
||||
let mut remaining = Vec::new();
|
||||
for run in self.runs.drain(..) {
|
||||
if run.state.has_persistent_output() {
|
||||
completed.push(run);
|
||||
} else {
|
||||
remaining.push(run);
|
||||
}
|
||||
}
|
||||
self.runs = remaining;
|
||||
(!completed.is_empty()).then_some(Self { runs: completed })
|
||||
}
|
||||
|
||||
/// Returns true for revealed runs still participating in lifecycle bookkeeping.
|
||||
pub(crate) fn has_visible_running_run(&self) -> bool {
|
||||
self.runs.iter().any(|run| run.state.is_running_visible())
|
||||
}
|
||||
|
||||
/// Describes revealed hooks without implying per-handler completion progress.
|
||||
/// Synchronous completions can arrive together after the whole batch finishes.
|
||||
pub(crate) fn running_status_summary(&self) -> Option<String> {
|
||||
let mut messages = self
|
||||
.runs
|
||||
.iter()
|
||||
.filter(|run| matches!(run.state, HookRunState::VisibleRunning { .. }))
|
||||
.map(|run| {
|
||||
run.status_message
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|message| !message.is_empty())
|
||||
})
|
||||
.peekable();
|
||||
let message = messages.next()?;
|
||||
let multiple = messages.peek().is_some();
|
||||
Some(
|
||||
if let Some(message) = message
|
||||
&& messages.all(|other| other == Some(message))
|
||||
{
|
||||
message.to_string()
|
||||
} else if multiple {
|
||||
"Running hooks".to_string()
|
||||
} else {
|
||||
"Running hook".to_string()
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// Advances reveal/removal timers and reports whether rendering should be refreshed.
|
||||
pub(crate) fn advance_time(&mut self, now: Instant) -> bool {
|
||||
let old_len = self.runs.len();
|
||||
let mut changed = false;
|
||||
for run in &mut self.runs {
|
||||
changed |= run.state.reveal_if_due(now);
|
||||
}
|
||||
self.runs.retain(|run| !run.state.quiet_linger_expired(now));
|
||||
changed || self.runs.len() != old_len
|
||||
}
|
||||
|
||||
/// Inserts or refreshes a started hook run.
|
||||
///
|
||||
/// A duplicate begin event resets the reveal timer rather than adding a second row, because
|
||||
/// matching by id is the invariant that keeps begin/end events paired.
|
||||
pub(crate) fn start_run(&mut self, run: HookRunSummary) {
|
||||
let now = Instant::now();
|
||||
if let Some(existing) = self.runs.iter_mut().find(|existing| existing.id == run.id) {
|
||||
existing.status_message = run.status_message;
|
||||
existing.state = HookRunState::pending(now);
|
||||
return;
|
||||
}
|
||||
self.runs.push(HookRunCell {
|
||||
id: run.id,
|
||||
status_message: run.status_message,
|
||||
state: HookRunState::pending(now),
|
||||
});
|
||||
}
|
||||
|
||||
/// Completes a run and returns whether the run was already present in this cell.
|
||||
///
|
||||
/// Quiet successes intentionally avoid persistent output. If they were never visible, they
|
||||
/// disappear immediately; if they had already drawn, they move into `QuietLinger`.
|
||||
pub(crate) fn complete_run(&mut self, run: HookRunSummary) -> bool {
|
||||
let Some(index) = self.runs.iter().position(|existing| existing.id == run.id) else {
|
||||
return false;
|
||||
};
|
||||
if hook_run_is_quiet_success(&run) {
|
||||
if !self.runs[index]
|
||||
.state
|
||||
.complete_quiet_success(Instant::now())
|
||||
{
|
||||
self.runs.remove(index);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
let HookRunSummary {
|
||||
status_message,
|
||||
status,
|
||||
entries,
|
||||
..
|
||||
} = run;
|
||||
let existing = &mut self.runs[index];
|
||||
existing.status_message = status_message;
|
||||
existing.state = HookRunState::completed(status, entries);
|
||||
true
|
||||
}
|
||||
|
||||
/// Adds a completed hook that did not pass through this live cell.
|
||||
///
|
||||
/// This is used for replay/restoration paths where the final run summary is already known.
|
||||
pub(crate) fn add_completed_run(&mut self, run: HookRunSummary) {
|
||||
if hook_run_is_quiet_success(&run) {
|
||||
return;
|
||||
}
|
||||
let HookRunSummary {
|
||||
id,
|
||||
status_message,
|
||||
status,
|
||||
entries,
|
||||
..
|
||||
} = run;
|
||||
self.runs.push(HookRunCell {
|
||||
id,
|
||||
status_message,
|
||||
state: HookRunState::completed(status, entries),
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) fn next_timer_deadline(&self) -> Option<Instant> {
|
||||
self.runs
|
||||
.iter()
|
||||
.filter_map(|run| run.state.next_timer_deadline())
|
||||
.min()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn expire_quiet_runs_now_for_test(&mut self) {
|
||||
for run in &mut self.runs {
|
||||
run.expire_quiet_linger_now_for_test();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn reveal_running_runs_now_for_test(&mut self) {
|
||||
let now = Instant::now();
|
||||
for run in &mut self.runs {
|
||||
run.reveal_running_now_for_test(now);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn reveal_running_runs_after_delayed_redraw_for_test(&mut self) {
|
||||
let now = Instant::now();
|
||||
for run in &mut self.runs {
|
||||
run.reveal_running_after_delayed_redraw_for_test(now);
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds only durable completion output; active hooks use the activity summary.
|
||||
fn output_lines(&self) -> Vec<Line<'static>> {
|
||||
let mut lines = Vec::new();
|
||||
for run in &self.runs {
|
||||
let HookRunState::Completed { status, entries } = &run.state else {
|
||||
continue;
|
||||
};
|
||||
if !lines.is_empty() {
|
||||
lines.push("".into());
|
||||
}
|
||||
let system_message = entries
|
||||
.iter()
|
||||
.find(|entry| entry.kind == HookOutputEntryKind::Warning);
|
||||
let mut system_message_lines = system_message.map(|entry| {
|
||||
let mut lines = ansi_escape(&entry.text).lines;
|
||||
if entry.text.ends_with('\n') {
|
||||
lines.push("".into());
|
||||
}
|
||||
lines.into_iter()
|
||||
});
|
||||
if *status == HookRunStatus::Completed
|
||||
&& let Some(mut first_line) = system_message_lines.as_mut().and_then(Iterator::next)
|
||||
{
|
||||
first_line.spans.insert(/*index*/ 0, "↳ Hook · ".dim());
|
||||
lines.push(first_line);
|
||||
} else {
|
||||
let header_text = match status {
|
||||
HookRunStatus::Completed => "Hook completed",
|
||||
HookRunStatus::Failed => "Hook failed",
|
||||
HookRunStatus::Blocked => "Blocked by hook",
|
||||
HookRunStatus::Stopped => "Hook stopped",
|
||||
HookRunStatus::Running => "Hook running",
|
||||
};
|
||||
lines.push(
|
||||
vec![
|
||||
hook_completed_bullet(*status),
|
||||
" ".into(),
|
||||
header_text.into(),
|
||||
]
|
||||
.into(),
|
||||
);
|
||||
if let Some(mut first_line) = system_message_lines.as_mut().and_then(Iterator::next)
|
||||
{
|
||||
first_line
|
||||
.spans
|
||||
.insert(/*index*/ 0, format!("{HOOK_OUTPUT_INDENT}└ ").into());
|
||||
lines.push(first_line);
|
||||
}
|
||||
}
|
||||
if let Some(system_message_lines) = system_message_lines {
|
||||
for mut line in system_message_lines {
|
||||
if line.spans.is_empty() {
|
||||
lines.push("".into());
|
||||
} else {
|
||||
line.spans
|
||||
.insert(/*index*/ 0, HOOK_OUTPUT_BODY_INDENT.into());
|
||||
lines.push(line);
|
||||
}
|
||||
}
|
||||
}
|
||||
for entry in entries {
|
||||
if matches!(
|
||||
entry.kind,
|
||||
HookOutputEntryKind::Warning | HookOutputEntryKind::Context
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
push_full_hook_output_entry(&mut lines, entry);
|
||||
}
|
||||
}
|
||||
lines
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryCell for HookCell {
|
||||
fn display_lines(&self, _width: u16) -> Vec<Line<'static>> {
|
||||
self.output_lines()
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
plain_lines(self.output_lines())
|
||||
}
|
||||
}
|
||||
|
||||
impl HookRunCell {
|
||||
#[cfg(test)]
|
||||
fn expire_quiet_linger_now_for_test(&mut self) {
|
||||
if let HookRunState::QuietLinger {
|
||||
removal_deadline, ..
|
||||
} = &mut self.state
|
||||
{
|
||||
*removal_deadline = Instant::now();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn reveal_running_now_for_test(&mut self, now: Instant) {
|
||||
if let HookRunState::PendingReveal {
|
||||
reveal_deadline, ..
|
||||
} = &mut self.state
|
||||
{
|
||||
*reveal_deadline = now;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn reveal_running_after_delayed_redraw_for_test(&mut self, now: Instant) {
|
||||
if let HookRunState::PendingReveal {
|
||||
reveal_deadline, ..
|
||||
} = &mut self.state
|
||||
{
|
||||
let delayed_deadline = now
|
||||
.checked_sub(QUIET_HOOK_MIN_VISIBLE + Duration::from_millis(100))
|
||||
.unwrap_or(now);
|
||||
*reveal_deadline = delayed_deadline;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn push_full_hook_output_entry(lines: &mut Vec<Line<'static>>, entry: &HookOutputEntry) {
|
||||
let mut output_lines = entry.text.split('\n');
|
||||
if let Some(first_line) = output_lines.next() {
|
||||
lines.push(format!("{HOOK_OUTPUT_INDENT}└ {first_line}").into());
|
||||
}
|
||||
for line in output_lines {
|
||||
if line.is_empty() {
|
||||
lines.push("".into());
|
||||
} else {
|
||||
lines.push(format!("{HOOK_OUTPUT_BODY_INDENT}{line}").into());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HookRunState {
|
||||
/// Creates the hidden initial state for a live hook run.
|
||||
fn pending(start_time: Instant) -> Self {
|
||||
Self::PendingReveal {
|
||||
reveal_deadline: start_time + HOOK_RUN_REVEAL_DELAY,
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates the persistent final state for a hook with visible output or a notable status.
|
||||
fn completed(status: HookRunStatus, entries: Vec<HookOutputEntry>) -> Self {
|
||||
Self::Completed { status, entries }
|
||||
}
|
||||
|
||||
/// Returns true while the run is still waiting for a completion event or timer cleanup.
|
||||
fn is_active(&self) -> bool {
|
||||
match self {
|
||||
HookRunState::PendingReveal { .. }
|
||||
| HookRunState::VisibleRunning { .. }
|
||||
| HookRunState::QuietLinger { .. } => true,
|
||||
HookRunState::Completed { .. } => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true for completed runs that should survive outside the active cell.
|
||||
fn has_persistent_output(&self) -> bool {
|
||||
match self {
|
||||
HookRunState::Completed { status, entries } => {
|
||||
*status != HookRunStatus::Completed
|
||||
|| entries
|
||||
.iter()
|
||||
.any(|entry| entry.kind != HookOutputEntryKind::Context)
|
||||
}
|
||||
HookRunState::PendingReveal { .. }
|
||||
| HookRunState::VisibleRunning { .. }
|
||||
| HookRunState::QuietLinger { .. } => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true for revealed runs whose lifecycle bookkeeping is still active.
|
||||
fn is_running_visible(&self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
HookRunState::VisibleRunning { .. } | HookRunState::QuietLinger { .. }
|
||||
)
|
||||
}
|
||||
|
||||
/// Reveals a pending run once its deadline has passed.
|
||||
///
|
||||
/// Returns true only when this call changes the state, allowing timer callbacks to avoid
|
||||
/// unnecessary redraws.
|
||||
fn reveal_if_due(&mut self, now: Instant) -> bool {
|
||||
let HookRunState::PendingReveal { reveal_deadline } = self else {
|
||||
return false;
|
||||
};
|
||||
if now < *reveal_deadline {
|
||||
return false;
|
||||
}
|
||||
*self = HookRunState::VisibleRunning { visible_since: now };
|
||||
true
|
||||
}
|
||||
|
||||
/// Returns the next state-machine deadline owned by this run.
|
||||
fn next_timer_deadline(&self) -> Option<Instant> {
|
||||
match self {
|
||||
HookRunState::PendingReveal {
|
||||
reveal_deadline, ..
|
||||
} => Some(*reveal_deadline),
|
||||
HookRunState::QuietLinger {
|
||||
removal_deadline, ..
|
||||
} => Some(*removal_deadline),
|
||||
HookRunState::VisibleRunning { .. } | HookRunState::Completed { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true once a quiet success has lingered for long enough.
|
||||
fn quiet_linger_expired(&self, now: Instant) -> bool {
|
||||
match self {
|
||||
HookRunState::QuietLinger {
|
||||
removal_deadline, ..
|
||||
} => now >= *removal_deadline,
|
||||
HookRunState::PendingReveal { .. }
|
||||
| HookRunState::VisibleRunning { .. }
|
||||
| HookRunState::Completed { .. } => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a visible quiet success into a temporary linger state.
|
||||
///
|
||||
/// Returns false when the success should be removed immediately: either it was never visible or
|
||||
/// it has already stayed visible for the minimum duration.
|
||||
fn complete_quiet_success(&mut self, now: Instant) -> bool {
|
||||
let HookRunState::VisibleRunning { visible_since, .. } = self else {
|
||||
return false;
|
||||
};
|
||||
let minimum_deadline = *visible_since + QUIET_HOOK_MIN_VISIBLE;
|
||||
if now >= minimum_deadline {
|
||||
return false;
|
||||
}
|
||||
*self = HookRunState::QuietLinger {
|
||||
removal_deadline: minimum_deadline,
|
||||
};
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn new_active_hook_cell(run: HookRunSummary) -> HookCell {
|
||||
HookCell::new_active(run)
|
||||
}
|
||||
|
||||
pub(crate) fn new_completed_hook_cell(run: HookRunSummary) -> HookCell {
|
||||
HookCell::new_completed(run)
|
||||
}
|
||||
|
||||
/// Returns true for hook completions that should be invisible in history.
|
||||
fn hook_run_is_quiet_success(run: &HookRunSummary) -> bool {
|
||||
run.status == HookRunStatus::Completed
|
||||
&& run
|
||||
.entries
|
||||
.iter()
|
||||
.all(|entry| entry.kind == HookOutputEntryKind::Context)
|
||||
}
|
||||
|
||||
fn hook_completed_bullet(status: HookRunStatus) -> Span<'static> {
|
||||
match status {
|
||||
HookRunStatus::Completed => "•".green().bold(),
|
||||
HookRunStatus::Blocked | HookRunStatus::Failed | HookRunStatus::Stopped => "•".red().bold(),
|
||||
HookRunStatus::Running => "•".into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_support::PathBufExt;
|
||||
use crate::test_support::test_path_buf;
|
||||
use codex_app_server_protocol::HookEventName;
|
||||
use pretty_assertions::assert_eq;
|
||||
use ratatui::style::Color;
|
||||
use ratatui::style::Modifier;
|
||||
|
||||
#[test]
|
||||
fn completed_hook_system_message_uses_dim_provenance_and_hides_context() {
|
||||
let cell = completed_hook_cell(
|
||||
HookEventName::SessionStart,
|
||||
HookRunStatus::Completed,
|
||||
vec![
|
||||
HookOutputEntry {
|
||||
kind: HookOutputEntryKind::Warning,
|
||||
text: "Heads up from the hook".to_string(),
|
||||
},
|
||||
HookOutputEntry {
|
||||
kind: HookOutputEntryKind::Context,
|
||||
text: "Private model-facing project instructions".to_string(),
|
||||
},
|
||||
],
|
||||
);
|
||||
let lines = cell.display_lines(/*width*/ 80);
|
||||
let expected = vec!["↳ Hook · Heads up from the hook".to_string()];
|
||||
|
||||
assert_eq!(line_texts(&lines), expected);
|
||||
assert_eq!(line_texts(&cell.transcript_lines(/*width*/ 80)), expected);
|
||||
assert_eq!(line_texts(&cell.raw_lines()), expected);
|
||||
assert!(lines[0].spans[0].style.add_modifier.contains(Modifier::DIM));
|
||||
assert_eq!(lines[0].spans[1].style, Style::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completed_hook_system_message_renders_ansi_styles() {
|
||||
let cell = completed_hook_cell(
|
||||
HookEventName::UserPromptSubmit,
|
||||
HookRunStatus::Completed,
|
||||
vec![HookOutputEntry {
|
||||
kind: HookOutputEntryKind::Warning,
|
||||
text: "\x1b[1;92mStyled output\nacross lines\x1b[0m plain".to_string(),
|
||||
}],
|
||||
);
|
||||
|
||||
let lines = cell.display_lines(/*width*/ 80);
|
||||
|
||||
assert_eq!(
|
||||
line_texts(&cell.raw_lines()),
|
||||
vec![
|
||||
"↳ Hook · Styled output".to_string(),
|
||||
" across lines plain".to_string(),
|
||||
],
|
||||
);
|
||||
insta::assert_debug_snapshot!("completed_hook_system_message_ansi_styles", lines);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completed_hook_with_only_context_is_quiet_on_every_tui_surface() {
|
||||
let cell = completed_hook_cell(
|
||||
HookEventName::SessionStart,
|
||||
HookRunStatus::Completed,
|
||||
vec![HookOutputEntry {
|
||||
kind: HookOutputEntryKind::Context,
|
||||
text: "## Working Memory Recall\n\nSource: Codex compaction".to_string(),
|
||||
}],
|
||||
);
|
||||
|
||||
assert!(cell.is_empty());
|
||||
assert!(cell.display_lines(/*width*/ 80).is_empty());
|
||||
assert!(cell.transcript_lines(/*width*/ 80).is_empty());
|
||||
assert!(cell.raw_lines().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn running_hook_summary_uses_only_revealed_messages() {
|
||||
for (messages, expected) in [
|
||||
(vec![None], "Running hook"),
|
||||
(vec![Some(" ")], "Running hook"),
|
||||
(vec![None, None], "Running hooks"),
|
||||
(vec![Some("checking policy")], "checking policy"),
|
||||
(
|
||||
vec![Some(" checking policy "), Some("checking policy")],
|
||||
"checking policy",
|
||||
),
|
||||
(vec![Some("checking policy"), None], "Running hooks"),
|
||||
(vec![None, Some("checking policy")], "Running hooks"),
|
||||
(
|
||||
vec![Some("checking policy"), Some("scanning secrets")],
|
||||
"Running hooks",
|
||||
),
|
||||
] {
|
||||
let mut first = hook_run_summary("0");
|
||||
first.status_message = messages[0].map(str::to_string);
|
||||
let mut cell = HookCell::new_active(first);
|
||||
for (index, message) in messages.iter().enumerate().skip(1) {
|
||||
let mut run = hook_run_summary(&index.to_string());
|
||||
run.status_message = message.map(str::to_string);
|
||||
cell.start_run(run);
|
||||
}
|
||||
assert_eq!(cell.running_status_summary(), None);
|
||||
cell.reveal_running_runs_now_for_test();
|
||||
cell.advance_time(Instant::now());
|
||||
assert_eq!(cell.running_status_summary().as_deref(), Some(expected));
|
||||
|
||||
// A new hook must not change the summary before its own reveal delay.
|
||||
let mut fast = hook_run_summary("fast");
|
||||
fast.status_message = Some("another message".to_string());
|
||||
cell.start_run(fast.clone());
|
||||
assert_eq!(cell.running_status_summary().as_deref(), Some(expected));
|
||||
fast.status = HookRunStatus::Completed;
|
||||
cell.complete_run(fast);
|
||||
assert_eq!(cell.running_status_summary().as_deref(), Some(expected));
|
||||
|
||||
// Synchronous completion notifications arrive after the batch finishes.
|
||||
for index in 0..messages.len() {
|
||||
let mut completed = hook_run_summary(&index.to_string());
|
||||
completed.status = HookRunStatus::Completed;
|
||||
cell.complete_run(completed);
|
||||
}
|
||||
assert_eq!(cell.running_status_summary(), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completed_hook_non_context_entries_are_not_truncated() {
|
||||
for kind in [
|
||||
HookOutputEntryKind::Warning,
|
||||
HookOutputEntryKind::Stop,
|
||||
HookOutputEntryKind::Feedback,
|
||||
HookOutputEntryKind::Error,
|
||||
] {
|
||||
let cell = completed_hook_cell(
|
||||
HookEventName::UserPromptSubmit,
|
||||
HookRunStatus::Stopped,
|
||||
vec![HookOutputEntry {
|
||||
kind,
|
||||
text: "first\nsecond\nthird\nfourth\nfifth".to_string(),
|
||||
}],
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
line_texts(&cell.display_lines(/*width*/ 20)).join("\n"),
|
||||
"• Hook stopped\n └ first\n second\n third\n fourth\n fifth",
|
||||
"expected {kind:?} output to remain complete",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsuccessful_hooks_use_bold_red_bullets_and_actionable_details() {
|
||||
for (status, expected_header) in [
|
||||
(HookRunStatus::Failed, "• Hook failed"),
|
||||
(HookRunStatus::Blocked, "• Blocked by hook"),
|
||||
(HookRunStatus::Stopped, "• Hook stopped"),
|
||||
] {
|
||||
let detail = "Policy prevented this action.";
|
||||
let cell = completed_hook_cell(
|
||||
HookEventName::PreToolUse,
|
||||
status,
|
||||
vec![HookOutputEntry {
|
||||
kind: HookOutputEntryKind::Error,
|
||||
text: detail.to_string(),
|
||||
}],
|
||||
);
|
||||
let lines = cell.display_lines(/*width*/ 80);
|
||||
|
||||
assert_eq!(
|
||||
line_texts(&lines),
|
||||
vec![expected_header.to_string(), format!(" └ {detail}")],
|
||||
);
|
||||
assert_eq!(lines[0].spans[0].style.fg, Some(Color::Red));
|
||||
assert!(
|
||||
lines[0].spans[0]
|
||||
.style
|
||||
.add_modifier
|
||||
.contains(Modifier::BOLD)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completed_stop_hook_multiline_system_message_prefixes_first_line_only() {
|
||||
let cell = completed_hook_cell(
|
||||
HookEventName::Stop,
|
||||
HookRunStatus::Completed,
|
||||
vec![HookOutputEntry {
|
||||
kind: HookOutputEntryKind::Warning,
|
||||
text: "Heads up\n\u{301}\nReview generated files\n".to_string(),
|
||||
}],
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
line_texts(&cell.display_lines(/*width*/ 80)),
|
||||
vec![
|
||||
"↳ Hook · Heads up".to_string(),
|
||||
" \u{301}".to_string(),
|
||||
" Review generated files".to_string(),
|
||||
"".to_string(),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
fn completed_hook_cell(
|
||||
event_name: HookEventName,
|
||||
status: HookRunStatus,
|
||||
entries: Vec<HookOutputEntry>,
|
||||
) -> HookCell {
|
||||
let mut run = hook_run_summary("hook-1");
|
||||
run.event_name = event_name;
|
||||
run.status = status;
|
||||
run.status_message = None;
|
||||
run.completed_at = Some(2);
|
||||
run.duration_ms = Some(1);
|
||||
run.entries = entries;
|
||||
HookCell::new_completed(run)
|
||||
}
|
||||
|
||||
fn line_texts(lines: &[Line<'_>]) -> Vec<String> {
|
||||
lines.iter().map(line_text).collect()
|
||||
}
|
||||
|
||||
fn line_text(line: &Line<'_>) -> String {
|
||||
line.spans
|
||||
.iter()
|
||||
.map(|span| span.content.as_ref())
|
||||
.collect::<String>()
|
||||
}
|
||||
|
||||
fn hook_run_summary(id: &str) -> HookRunSummary {
|
||||
HookRunSummary {
|
||||
id: id.to_string(),
|
||||
event_name: HookEventName::PostToolUse,
|
||||
handler_type: codex_app_server_protocol::HookHandlerType::Command,
|
||||
execution_mode: codex_app_server_protocol::HookExecutionMode::Sync,
|
||||
scope: codex_app_server_protocol::HookScope::Turn,
|
||||
source_path: test_path_buf("/tmp/hooks.json").abs().into(),
|
||||
source: codex_app_server_protocol::HookSource::User,
|
||||
display_order: 0,
|
||||
status: HookRunStatus::Running,
|
||||
status_message: Some("checking output policy".to_string()),
|
||||
started_at: 1,
|
||||
completed_at: None,
|
||||
duration_ms: None,
|
||||
entries: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
53
codex-rs/tui/src/history_cell/markdown_render_cache.rs
Normal file
53
codex-rs/tui/src/history_cell/markdown_render_cache.rs
Normal file
@@ -0,0 +1,53 @@
|
||||
//! Single-width render cache shared by finalized source-backed markdown history cells.
|
||||
|
||||
use crate::markdown_render::ListSpacing;
|
||||
use crate::terminal_hyperlinks::HyperlinkLine;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::PoisonError;
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub(super) struct MarkdownRenderCache {
|
||||
pub(super) cached: Mutex<Option<(MarkdownRenderCacheKey, Vec<HyperlinkLine>)>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(super) struct MarkdownRenderCacheKey {
|
||||
pub(super) width: u16,
|
||||
pub(super) list_spacing: ListSpacing,
|
||||
pub(super) syntax_theme_revision: u64,
|
||||
pub(super) terminal_fg: Option<(u8, u8, u8)>,
|
||||
pub(super) terminal_bg: Option<(u8, u8, u8)>,
|
||||
pub(super) color_level: crate::terminal_palette::StdoutColorLevel,
|
||||
}
|
||||
|
||||
impl MarkdownRenderCache {
|
||||
/// Return lines cached for this width and terminal render state, rendering on a cache miss.
|
||||
///
|
||||
/// Only the most recent entry is retained, so changing width, syntax theme, or terminal colors
|
||||
/// replaces the cached render.
|
||||
pub(super) fn render(
|
||||
&self,
|
||||
width: u16,
|
||||
list_spacing: ListSpacing,
|
||||
render: impl FnOnce() -> Vec<HyperlinkLine>,
|
||||
) -> Vec<HyperlinkLine> {
|
||||
let key = MarkdownRenderCacheKey {
|
||||
width,
|
||||
list_spacing,
|
||||
syntax_theme_revision: crate::render::highlight::syntax_theme_revision(),
|
||||
terminal_fg: crate::terminal_palette::default_fg(),
|
||||
terminal_bg: crate::terminal_palette::default_bg(),
|
||||
color_level: crate::terminal_palette::stdout_color_level(),
|
||||
};
|
||||
let mut cached = self.cached.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some((cached_key, lines)) = cached.as_ref()
|
||||
&& *cached_key == key
|
||||
{
|
||||
return lines.clone();
|
||||
}
|
||||
|
||||
let lines = render();
|
||||
*cached = Some((key, lines.clone()));
|
||||
lines
|
||||
}
|
||||
}
|
||||
856
codex-rs/tui/src/history_cell/mcp.rs
Normal file
856
codex-rs/tui/src/history_cell/mcp.rs
Normal file
@@ -0,0 +1,856 @@
|
||||
//! MCP tool-call, inventory, and output history cells.
|
||||
//! Tool output previews share a three-row budget across all result blocks;
|
||||
//! the expanded transcript retains the full text.
|
||||
//! Invocation and result rows retain exact logical source ranges through wrapping and gutters.
|
||||
|
||||
use super::*;
|
||||
use crate::line_truncation::truncate_line_with_ellipsis_if_overflow;
|
||||
|
||||
use codex_protocol::mcp::is_node_repl_backed_server;
|
||||
|
||||
#[path = "mcp_result.rs"]
|
||||
mod result;
|
||||
|
||||
#[path = "mcp_preview.rs"]
|
||||
mod preview;
|
||||
|
||||
#[path = "computer_activity.rs"]
|
||||
mod computer_activity;
|
||||
pub(crate) use computer_activity::ComputerActivityCell;
|
||||
|
||||
use crate::style::StatusTone;
|
||||
use crate::style::accent_color;
|
||||
use crate::style::accent_style;
|
||||
use crate::style::status_style;
|
||||
use crate::terminal_hyperlinks::LogicalLineSource;
|
||||
use crate::terminal_hyperlinks::adaptive_wrap_hyperlink_lines;
|
||||
use crate::terminal_hyperlinks::prefix_hyperlink_lines;
|
||||
use crate::terminal_hyperlinks::remap_source_wrapped_line;
|
||||
use crate::text_formatting::format_json_compact;
|
||||
use crate::tool_output::ToolOutputPreview;
|
||||
use codex_app_server_protocol::McpServerConnectionStatus;
|
||||
use result::McpContentBlock;
|
||||
use result::McpResultKind;
|
||||
use result::McpToolResult;
|
||||
use std::borrow::Cow;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "mcp_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
fn mcp_auth_status_label(status: McpAuthStatus) -> &'static str {
|
||||
match status {
|
||||
McpAuthStatus::Unknown => "Unknown",
|
||||
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<McpToolResult, 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 McpInvocation {
|
||||
pub(crate) fn is_computer_activity(&self) -> bool {
|
||||
self.server == "cua_repl"
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Eq, PartialEq)]
|
||||
enum McpToolCallRenderMode {
|
||||
/// Compact presentation used in normal conversation history.
|
||||
Display,
|
||||
/// Complete invocation and result used by the Ctrl+T transcript.
|
||||
Transcript,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct NodeReplExecOutput {
|
||||
exit_code: i64,
|
||||
output: String,
|
||||
}
|
||||
|
||||
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>,
|
||||
) {
|
||||
let result = result.map(|result| McpToolResult::new(result, self.result_kind()));
|
||||
self.duration = Some(duration);
|
||||
self.result = Some(result);
|
||||
}
|
||||
|
||||
fn success(&self) -> Option<bool> {
|
||||
match self.result.as_ref() {
|
||||
Some(Ok(result)) => Some(!result.is_error),
|
||||
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()));
|
||||
}
|
||||
|
||||
pub(crate) fn freeze_snapshot(&mut self) {
|
||||
self.animations_enabled = false;
|
||||
}
|
||||
|
||||
fn result_kind(&self) -> McpResultKind {
|
||||
if self.invocation.is_computer_activity()
|
||||
|| (is_node_repl_backed_server(&self.invocation.server) && self.invocation.tool == "js")
|
||||
{
|
||||
McpResultKind::NodeRepl
|
||||
} else {
|
||||
McpResultKind::Standard
|
||||
}
|
||||
}
|
||||
|
||||
fn render_hyperlink_lines(
|
||||
&self,
|
||||
width: u16,
|
||||
mode: McpToolCallRenderMode,
|
||||
) -> Vec<HyperlinkLine> {
|
||||
let mut lines: Vec<HyperlinkLine> = Vec::new();
|
||||
let status = self.success();
|
||||
let node_repl = self.result_kind() == McpResultKind::NodeRepl;
|
||||
let compact = node_repl && mode == McpToolCallRenderMode::Display;
|
||||
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 title = self
|
||||
.invocation
|
||||
.arguments
|
||||
.as_ref()
|
||||
.filter(|_| compact)
|
||||
.and_then(|arguments| arguments.get("title"))
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.map(|title| title.split_whitespace().collect::<Vec<_>>().join(" "))
|
||||
.filter(|title| !title.is_empty());
|
||||
let invocation_line = if compact {
|
||||
Line::from(
|
||||
title
|
||||
.clone()
|
||||
.unwrap_or_else(|| {
|
||||
format!("{}.{}", self.invocation.server, self.invocation.tool)
|
||||
})
|
||||
.fg(accent_color()),
|
||||
)
|
||||
} else {
|
||||
line_to_static(&format_mcp_invocation(&self.invocation))
|
||||
};
|
||||
let mut compact_spans = vec![bullet.clone(), " ".into()];
|
||||
if title.is_none() {
|
||||
compact_spans.extend([header_text.bold(), " ".into()]);
|
||||
}
|
||||
let mut compact_header = Line::from(compact_spans.clone());
|
||||
let reserved = compact_header.width();
|
||||
|
||||
let inline_invocation =
|
||||
compact || invocation_line.width() <= (width as usize).saturating_sub(reserved);
|
||||
|
||||
if inline_invocation {
|
||||
compact_header.extend(invocation_line.spans.clone());
|
||||
lines.push(mcp_header_line(if compact {
|
||||
truncate_line_with_ellipsis_if_overflow(compact_header, width as usize)
|
||||
} else {
|
||||
compact_header
|
||||
}));
|
||||
} else {
|
||||
compact_spans.pop(); // drop trailing space for standalone header
|
||||
lines.push(mcp_header_line(Line::from(compact_spans)));
|
||||
|
||||
let opts = RtOptions::new((width as usize).saturating_sub(/*rhs*/ 4))
|
||||
.initial_indent("".into())
|
||||
.subsequent_indent(" ".into());
|
||||
let body_lines =
|
||||
adaptive_wrap_hyperlink_lines(&[HyperlinkLine::new(invocation_line)], opts);
|
||||
lines.extend(prefix_hyperlink_lines(
|
||||
body_lines,
|
||||
" └ ".dim(),
|
||||
" ".into(),
|
||||
));
|
||||
}
|
||||
|
||||
let detail_lines = self.render_detail_lines(width, mode);
|
||||
if !detail_lines.is_empty() {
|
||||
let initial_prefix = if inline_invocation {
|
||||
" └ ".dim()
|
||||
} else {
|
||||
" ".into()
|
||||
};
|
||||
lines.extend(prefix_hyperlink_lines(
|
||||
detail_lines,
|
||||
initial_prefix,
|
||||
" ".into(),
|
||||
));
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
/// Share one bounded preview across result blocks while retaining full transcript sources.
|
||||
fn render_detail_lines(&self, width: u16, mode: McpToolCallRenderMode) -> Vec<HyperlinkLine> {
|
||||
let detail_width = usize::from(width)
|
||||
.saturating_sub(/*rhs*/ 4)
|
||||
.max(/*other*/ 1);
|
||||
let options = RtOptions::new(detail_width).subsequent_indent(" ".into());
|
||||
let mut lines = Vec::new();
|
||||
let mut preview = ToolOutputPreview::new(detail_width, /*omitted*/ 0);
|
||||
match &self.result {
|
||||
Some(Ok(result)) => {
|
||||
for block in &result.content {
|
||||
// Image blocks can carry text as well as their image indication.
|
||||
if self.result_kind() == McpResultKind::NodeRepl
|
||||
&& block.is_image
|
||||
&& block.text().is_some()
|
||||
{
|
||||
let marker = HyperlinkLine::new("Returned image".dim().into());
|
||||
if mode == McpToolCallRenderMode::Display {
|
||||
preview.push_hyperlink_line(marker);
|
||||
} else {
|
||||
lines.extend(remap_source_wrapped_line(
|
||||
&marker,
|
||||
crate::wrapping::word_wrap_line_with_source(
|
||||
&marker.line,
|
||||
detail_width,
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
let Some(text) = self.result_block_text(block, mode) else {
|
||||
continue;
|
||||
};
|
||||
for segment in text.lines() {
|
||||
if mode == McpToolCallRenderMode::Display {
|
||||
preview.push_line(Line::from(segment.dim()));
|
||||
} else {
|
||||
let line = Line::from(segment.to_owned().dim());
|
||||
lines.extend(adaptive_wrap_hyperlink_lines(
|
||||
&[HyperlinkLine::new(line)],
|
||||
options.clone(),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(Err(error)) => {
|
||||
let text = format!("Error: {error}");
|
||||
for segment in text.lines() {
|
||||
if mode == McpToolCallRenderMode::Display {
|
||||
preview.push_line(Line::from(segment.dim()));
|
||||
} else {
|
||||
let line = Line::from(segment.to_owned().dim());
|
||||
lines.extend(adaptive_wrap_hyperlink_lines(
|
||||
&[HyperlinkLine::new(line)],
|
||||
options.clone(),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
if mode == McpToolCallRenderMode::Display {
|
||||
preview.finish_hyperlink_lines()
|
||||
} else {
|
||||
lines
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep compact code-mode summaries while retaining complete transcript code and output.
|
||||
fn result_block_text<'a>(
|
||||
&self,
|
||||
block: &'a McpContentBlock,
|
||||
mode: McpToolCallRenderMode,
|
||||
) -> Option<Cow<'a, str>> {
|
||||
let node_repl = self.result_kind() == McpResultKind::NodeRepl;
|
||||
if mode == McpToolCallRenderMode::Transcript {
|
||||
return Some(Cow::Borrowed(block.render_full()));
|
||||
}
|
||||
if node_repl && self.success() == Some(true) {
|
||||
let meaningful_output = block.text().and_then(|text| {
|
||||
if text.starts_with("Script completed\n") {
|
||||
return text
|
||||
.split_once("\nOutput:\n")
|
||||
.map(|(_, output)| Cow::Borrowed(output));
|
||||
}
|
||||
serde_json::from_str::<NodeReplExecOutput>(text)
|
||||
.ok()
|
||||
.filter(|output| output.exit_code == 0)
|
||||
.map(|output| Cow::Owned(output.output))
|
||||
});
|
||||
match meaningful_output {
|
||||
Some(output) if output.is_empty() => None,
|
||||
Some(output) => Some(
|
||||
format_json_compact(&output)
|
||||
.map(Cow::Owned)
|
||||
.unwrap_or(output),
|
||||
),
|
||||
None => Some(block.text().map_or_else(
|
||||
|| block.render(),
|
||||
|text| {
|
||||
format_json_compact(text)
|
||||
.map(Cow::Owned)
|
||||
.unwrap_or(Cow::Borrowed(text))
|
||||
},
|
||||
)),
|
||||
}
|
||||
} else if node_repl && let Some(output) = block.text() {
|
||||
Some(
|
||||
format_json_compact(output)
|
||||
.map(Cow::Owned)
|
||||
.unwrap_or(Cow::Borrowed(output)),
|
||||
)
|
||||
} else {
|
||||
Some(block.render())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryCell for McpToolCallCell {
|
||||
fn activity_ids(&self) -> Vec<String> {
|
||||
vec![format!("mcp:{}", self.call_id)]
|
||||
}
|
||||
|
||||
fn compact_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
self.compact_mcp_lines(width)
|
||||
}
|
||||
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
visible_lines(self.display_hyperlink_lines(width))
|
||||
}
|
||||
|
||||
fn transcript_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
visible_lines(self.transcript_hyperlink_lines(width))
|
||||
}
|
||||
|
||||
fn display_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
self.render_hyperlink_lines(width, McpToolCallRenderMode::Display)
|
||||
}
|
||||
|
||||
fn transcript_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
self.render_hyperlink_lines(width, McpToolCallRenderMode::Transcript)
|
||||
}
|
||||
|
||||
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)
|
||||
))];
|
||||
|
||||
if let Some(result) = &self.result {
|
||||
match result {
|
||||
Ok(McpToolResult { content, .. }) => {
|
||||
for block in content {
|
||||
let text = block.render_full();
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
/// The first two spans are the status bullet and its space, not invocation source text.
|
||||
fn mcp_header_line(line: Line<'static>) -> HyperlinkLine {
|
||||
let mut source = LogicalLineSource::from_line(&Line::from(
|
||||
line.spans.iter().skip(/*n*/ 2).cloned().collect::<Vec<_>>(),
|
||||
));
|
||||
source.prefix_bytes = line
|
||||
.spans
|
||||
.iter()
|
||||
.take(/*n*/ 2)
|
||||
.map(|span| span.content.len())
|
||||
.sum();
|
||||
let mut line = HyperlinkLine::new(line);
|
||||
line.source = Some(source);
|
||||
line
|
||||
}
|
||||
|
||||
pub(crate) fn new_active_mcp_tool_call(
|
||||
call_id: String,
|
||||
invocation: McpInvocation,
|
||||
animations_enabled: bool,
|
||||
) -> McpToolCallCell {
|
||||
McpToolCallCell::new(call_id, invocation, animations_enabled)
|
||||
}
|
||||
/// Render a summary of configured MCP servers from the current `Config`.
|
||||
pub(crate) fn empty_mcp_output() -> WebHyperlinkHistoryCell {
|
||||
let mut docs_line = HyperlinkLine::new(Line::from(" See the "));
|
||||
docs_line.push_span(
|
||||
"MCP docs".underlined(),
|
||||
Some("https://developers.openai.com/codex/mcp"),
|
||||
);
|
||||
docs_line.push_span(" to configure them.".into(), /*destination*/ None);
|
||||
|
||||
let lines = vec![
|
||||
HyperlinkLine::new("/mcp".magenta().into()),
|
||||
HyperlinkLine::from(""),
|
||||
HyperlinkLine::new(vec!["🔌 ".into(), "MCP Tools".bold()].into()),
|
||||
HyperlinkLine::from(""),
|
||||
HyperlinkLine::new(" • No MCP servers configured.".italic().into()),
|
||||
docs_line.style(Style::default().add_modifier(Modifier::DIM)),
|
||||
];
|
||||
|
||||
WebHyperlinkHistoryCell::new_hyperlink_lines(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_key(|(server, _)| *server);
|
||||
|
||||
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.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_key(|(name, _)| *name);
|
||||
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_key(|(name, _)| *name);
|
||||
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. The TUI deliberately does not enrich these rows from
|
||||
/// client-local config because the app-server owns the remote MCP state.
|
||||
///
|
||||
/// Normal output is a compact connection summary. Full detail preserves the
|
||||
/// tool, auth, resource, and resource-template inventory.
|
||||
pub(crate) fn new_mcp_tools_output_from_statuses(
|
||||
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 = statuses.iter().collect::<Vec<_>>();
|
||||
statuses.sort_by(|a, b| a.name.cmp(&b.name));
|
||||
|
||||
let has_any_tools = statuses.iter().any(|status| !status.tools.is_empty());
|
||||
if !has_any_tools && matches!(detail, McpServerStatusDetail::Full) {
|
||||
lines.push(" • No MCP tools available.".italic().into());
|
||||
lines.push("".into());
|
||||
}
|
||||
|
||||
for status in statuses {
|
||||
let (label, style) = match status.runtime_status {
|
||||
Some(McpServerConnectionStatus::Connected) => {
|
||||
("connected", status_style(StatusTone::Success))
|
||||
}
|
||||
Some(McpServerConnectionStatus::Starting) => ("starting", accent_style()),
|
||||
Some(McpServerConnectionStatus::AuthenticationRequired) => (
|
||||
"authentication required",
|
||||
status_style(StatusTone::Attention),
|
||||
),
|
||||
Some(McpServerConnectionStatus::Failed) => {
|
||||
("failed", status_style(StatusTone::Failure))
|
||||
}
|
||||
Some(McpServerConnectionStatus::NotStarted) => ("not started", Style::default().dim()),
|
||||
Some(McpServerConnectionStatus::Disabled) => ("disabled", Style::default().dim()),
|
||||
Some(McpServerConnectionStatus::Cancelled) => ("cancelled", Style::default().dim()),
|
||||
None if matches!(
|
||||
status.auth_status,
|
||||
codex_app_server_protocol::McpAuthStatus::NotLoggedIn
|
||||
) =>
|
||||
{
|
||||
(
|
||||
"authentication required",
|
||||
status_style(StatusTone::Attention),
|
||||
)
|
||||
}
|
||||
None => ("unknown", Style::default().dim()),
|
||||
};
|
||||
let count = status.tools.len();
|
||||
let unit = if count == 1 { "tool" } else { "tools" };
|
||||
lines.push(
|
||||
vec![
|
||||
" • ".set_style(style),
|
||||
status.name.clone().bold(),
|
||||
": ".into(),
|
||||
label.set_style(style),
|
||||
format!(" ({count} {unit})").dim(),
|
||||
]
|
||||
.into(),
|
||||
);
|
||||
if matches!(detail, McpServerStatusDetail::ToolsAndAuthOnly) {
|
||||
continue;
|
||||
}
|
||||
let auth_status = match status.auth_status {
|
||||
codex_app_server_protocol::McpAuthStatus::Unknown => McpAuthStatus::Unknown,
|
||||
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,
|
||||
};
|
||||
lines.push(
|
||||
vec![
|
||||
" • Auth: ".into(),
|
||||
mcp_auth_status_label(auth_status).into(),
|
||||
]
|
||||
.into(),
|
||||
);
|
||||
|
||||
let mut names = status.tools.keys().cloned().collect::<Vec<_>>();
|
||||
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.resources.clone();
|
||||
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.resource_templates.clone();
|
||||
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(""));
|
||||
}
|
||||
|
||||
if matches!(detail, McpServerStatusDetail::ToolsAndAuthOnly) {
|
||||
lines.push("".into());
|
||||
lines.push(" Use /mcp verbose for tools and resources.".dim().into());
|
||||
}
|
||||
|
||||
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(invocation: &McpInvocation) -> Line<'_> {
|
||||
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.as_str().fg(accent_color()),
|
||||
".".into(),
|
||||
invocation.tool.as_str().fg(accent_color()),
|
||||
"(".into(),
|
||||
args_str.dim(),
|
||||
")".into(),
|
||||
];
|
||||
invocation_spans.into()
|
||||
}
|
||||
132
codex-rs/tui/src/history_cell/mcp_preview.rs
Normal file
132
codex-rs/tui/src/history_cell/mcp_preview.rs
Normal file
@@ -0,0 +1,132 @@
|
||||
//! Compact MCP and code-mode activity previews, independent of retained detail rendering.
|
||||
|
||||
use super::McpToolCallCell;
|
||||
use super::NodeReplExecOutput;
|
||||
use super::result::McpResultKind;
|
||||
use crate::history_cell::activity_preview::DETAIL_PREVIEW_LINES;
|
||||
use crate::history_cell::activity_preview::clipped_line;
|
||||
use crate::live_wrap::take_prefix_by_width;
|
||||
use crate::motion::MotionMode;
|
||||
use crate::motion::ReducedMotionIndicator;
|
||||
use crate::motion::activity_indicator;
|
||||
use crate::style::accent_color;
|
||||
use crate::terminal_hyperlinks::HyperlinkLine;
|
||||
use ratatui::style::Stylize;
|
||||
use ratatui::text::Line;
|
||||
use std::borrow::Cow;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
impl McpToolCallCell {
|
||||
pub(super) fn compact_mcp_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
let status = self.success();
|
||||
let (marker, verb) = match status {
|
||||
Some(true) => ("•".green().bold(), "Called"),
|
||||
Some(false) => ("•".red().bold(), "Failed"),
|
||||
None => (
|
||||
activity_indicator(
|
||||
Some(self.start_time),
|
||||
MotionMode::from_animations_enabled(self.animations_enabled),
|
||||
ReducedMotionIndicator::StaticBullet,
|
||||
)
|
||||
.unwrap_or_else(|| "•".dim()),
|
||||
"Calling",
|
||||
),
|
||||
};
|
||||
let title = self
|
||||
.invocation
|
||||
.arguments
|
||||
.as_ref()
|
||||
.filter(|_| self.result_kind() == McpResultKind::NodeRepl)
|
||||
.and_then(|arguments| arguments.get("title"))
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.map(|title| title.split_whitespace().collect::<Vec<_>>().join(" "))
|
||||
.filter(|title| !title.is_empty())
|
||||
.unwrap_or_else(|| format!("{}.{}", self.invocation.server, self.invocation.tool));
|
||||
let mut lines = vec![clipped_line(
|
||||
Line::from(vec![
|
||||
marker,
|
||||
" ".into(),
|
||||
verb.bold(),
|
||||
" ".into(),
|
||||
title.fg(accent_color()),
|
||||
]),
|
||||
width,
|
||||
)];
|
||||
let mut details = VecDeque::with_capacity(DETAIL_PREVIEW_LINES);
|
||||
let push_tail = |details: &mut VecDeque<String>, text: &str| {
|
||||
for line in text
|
||||
.lines()
|
||||
.rev()
|
||||
.take(DETAIL_PREVIEW_LINES - details.len())
|
||||
{
|
||||
// Bound selected rows before allocating; retained output may be megabytes.
|
||||
let bounded = &line[..line.floor_char_boundary(16 * 1024)];
|
||||
let (prefix, rest, _) = take_prefix_by_width(bounded, usize::from(width) + 1);
|
||||
let mut detail = prefix.to_owned();
|
||||
if !rest.is_empty() || bounded.len() < line.len() {
|
||||
detail.push('…');
|
||||
}
|
||||
details.push_front(detail);
|
||||
}
|
||||
};
|
||||
if let Some(result) = &self.result {
|
||||
match result {
|
||||
Ok(result) => {
|
||||
for block in result.content.iter().rev() {
|
||||
let output = if self.result_kind() == McpResultKind::NodeRepl
|
||||
&& status == Some(true)
|
||||
&& let Some(text) = block.text()
|
||||
{
|
||||
if text.starts_with("Script completed\n")
|
||||
&& let Some((_, output)) = text.split_once("\nOutput:\n")
|
||||
{
|
||||
Cow::Borrowed(output)
|
||||
} else if let Ok(output) =
|
||||
serde_json::from_str::<NodeReplExecOutput>(text)
|
||||
&& output.exit_code == 0
|
||||
{
|
||||
Cow::Owned(output.output)
|
||||
} else {
|
||||
Cow::Borrowed(block.render_full())
|
||||
}
|
||||
} else {
|
||||
Cow::Borrowed(block.render_full())
|
||||
};
|
||||
push_tail(&mut details, &output);
|
||||
// A code-mode image can also carry text; its marker precedes that output.
|
||||
if block.is_image
|
||||
&& block.text().is_some()
|
||||
&& details.len() < DETAIL_PREVIEW_LINES
|
||||
{
|
||||
details.push_front("Returned image".to_owned());
|
||||
}
|
||||
if details.len() == DETAIL_PREVIEW_LINES {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
push_tail(&mut details, error);
|
||||
if error.lines().take(DETAIL_PREVIEW_LINES + 1).count() <= DETAIL_PREVIEW_LINES
|
||||
{
|
||||
if let Some(first) = details.front_mut() {
|
||||
first.insert_str(0, "Error: ");
|
||||
} else {
|
||||
details.push_front("Error: ".to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (index, detail) in details.into_iter().enumerate() {
|
||||
lines.push(clipped_line(
|
||||
Line::from(vec![
|
||||
if index == 0 { " └ " } else { " " }.dim(),
|
||||
detail.dim(),
|
||||
]),
|
||||
width,
|
||||
));
|
||||
}
|
||||
lines
|
||||
}
|
||||
}
|
||||
188
codex-rs/tui/src/history_cell/mcp_result.rs
Normal file
188
codex-rs/tui/src/history_cell/mcp_result.rs
Normal file
@@ -0,0 +1,188 @@
|
||||
//! Width-independent display content retained after an MCP call completes.
|
||||
//!
|
||||
//! The wire result can contain multi-megabyte image, audio, or resource bodies. Validate each
|
||||
//! block once with the MCP model, then retain only what history rendering actually displays.
|
||||
|
||||
use crate::text_formatting::format_json_compact;
|
||||
use base64::Engine;
|
||||
use codex_protocol::mcp::CallToolResult;
|
||||
use image::DynamicImage;
|
||||
use image::ImageReader;
|
||||
use rmcp::model::ContentBlock;
|
||||
use rmcp::model::ResourceContents;
|
||||
use serde::Deserialize;
|
||||
use std::borrow::Cow;
|
||||
use std::io::Cursor;
|
||||
use tracing::error;
|
||||
|
||||
#[derive(Clone, Copy, Eq, PartialEq)]
|
||||
pub(super) enum McpResultKind {
|
||||
Standard,
|
||||
NodeRepl,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct McpToolResult {
|
||||
pub(super) content: Vec<McpContentBlock>,
|
||||
pub(super) is_error: bool,
|
||||
pub(super) has_image: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct McpContentBlock {
|
||||
display: McpContentDisplay,
|
||||
pub(super) is_image: bool,
|
||||
/// Code mode uses a top-level `text` field even on malformed or non-text blocks.
|
||||
original_text: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum McpContentDisplay {
|
||||
Text(String),
|
||||
Summary(Cow<'static, str>),
|
||||
Json(String),
|
||||
}
|
||||
|
||||
impl McpToolResult {
|
||||
/// Consumes a wire result, dropping bodies represented only by media or resource summaries.
|
||||
///
|
||||
/// Canonical MCP deserialization preserves full text and the exact JSON fallback for malformed
|
||||
/// or unknown blocks. Every block is projected, but image decoding stops at the first fully
|
||||
/// valid image.
|
||||
pub(super) fn new(result: CallToolResult, kind: McpResultKind) -> Self {
|
||||
let mut has_image = false;
|
||||
let content = result
|
||||
.content
|
||||
.into_iter()
|
||||
.map(|block| {
|
||||
// Deserialize by reference so malformed blocks remain available for the exact
|
||||
// JSON fallback. Successful blocks no longer retain their wire representation.
|
||||
let parsed = ContentBlock::deserialize(&block);
|
||||
let is_image = matches!(&parsed, Ok(ContentBlock::Image(_)));
|
||||
let original_text = match (&parsed, kind) {
|
||||
(Ok(ContentBlock::Text(_)), _) | (_, McpResultKind::Standard) => None,
|
||||
(_, McpResultKind::NodeRepl) => block
|
||||
.get("text")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.map(str::to_owned),
|
||||
};
|
||||
let display = match parsed {
|
||||
Ok(ContentBlock::Text(text)) => McpContentDisplay::Text(text.text),
|
||||
Ok(ContentBlock::Image(image)) => {
|
||||
// Computer activity previews require a valid image. Stop decoding once
|
||||
// one has been found; the result text only retains a readable marker.
|
||||
if !has_image {
|
||||
has_image = decode_mcp_image(&image.data).is_some();
|
||||
}
|
||||
McpContentDisplay::Summary("Returned image".into())
|
||||
}
|
||||
Ok(ContentBlock::Audio(_)) => {
|
||||
McpContentDisplay::Summary("<audio content>".into())
|
||||
}
|
||||
Ok(ContentBlock::Resource(resource)) => {
|
||||
let summary = match resource.resource {
|
||||
ResourceContents::TextResourceContents { uri, .. }
|
||||
| ResourceContents::BlobResourceContents { uri, .. } => {
|
||||
format!("embedded resource: {uri}").into()
|
||||
}
|
||||
_ => "<unknown embedded resource>".into(),
|
||||
};
|
||||
McpContentDisplay::Summary(summary)
|
||||
}
|
||||
Ok(ContentBlock::ResourceLink(link)) => {
|
||||
McpContentDisplay::Summary(format!("link: {}", link.uri).into())
|
||||
}
|
||||
Ok(_) | Err(_) => McpContentDisplay::Json(block.to_string()),
|
||||
};
|
||||
McpContentBlock {
|
||||
display,
|
||||
is_image,
|
||||
original_text,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
Self {
|
||||
content,
|
||||
is_error: result.is_error.unwrap_or(false),
|
||||
has_image,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl McpContentBlock {
|
||||
/// Returns all retained text, with honest markers for media and embedded resource bodies.
|
||||
pub(super) fn render_full(&self) -> &str {
|
||||
if let Some(text) = &self.original_text {
|
||||
return text.trim_end_matches('\n');
|
||||
}
|
||||
match &self.display {
|
||||
McpContentDisplay::Text(text) | McpContentDisplay::Json(text) => {
|
||||
text.trim_end_matches('\n')
|
||||
}
|
||||
McpContentDisplay::Summary(summary) => summary,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the untruncated top-level text used by node_repl and cua_repl's compact and
|
||||
/// transcript views.
|
||||
///
|
||||
/// Valid text blocks reuse their display storage. Only node_repl and cua_repl retain this extra
|
||||
/// field on malformed or non-text blocks, where it takes precedence over the usual display
|
||||
/// content.
|
||||
pub(super) fn text(&self) -> Option<&str> {
|
||||
match &self.display {
|
||||
McpContentDisplay::Text(text) => Some(text),
|
||||
McpContentDisplay::Summary(_) | McpContentDisplay::Json(_) => {
|
||||
self.original_text.as_deref()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Formats the complete text or fallback JSON. The caller applies a single preview limit
|
||||
/// across all blocks, while transcript and raw output retain the full result.
|
||||
pub(super) fn render(&self) -> Cow<'_, str> {
|
||||
match &self.display {
|
||||
McpContentDisplay::Text(text) | McpContentDisplay::Json(text) => {
|
||||
format_json_compact(text)
|
||||
.map(Cow::Owned)
|
||||
.unwrap_or(Cow::Borrowed(text))
|
||||
}
|
||||
McpContentDisplay::Summary(summary) => Cow::Borrowed(summary),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Fully decodes an MCP image before exposing an image preview in computer activity.
|
||||
///
|
||||
/// A header-only check would accept images whose decoder rejects their pixel data. Preserve the
|
||||
/// existing behavior for invalid base64, unknown formats, corrupt images, and data URLs.
|
||||
fn decode_mcp_image(data: &str) -> Option<DynamicImage> {
|
||||
let base64_data = if let Some(data_url) = data.strip_prefix("data:") {
|
||||
data_url.split_once(',')?.1
|
||||
} else {
|
||||
data
|
||||
};
|
||||
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()
|
||||
}
|
||||
667
codex-rs/tui/src/history_cell/mcp_tests.rs
Normal file
667
codex-rs/tui/src/history_cell/mcp_tests.rs
Normal file
@@ -0,0 +1,667 @@
|
||||
use super::*;
|
||||
use base64::Engine;
|
||||
use codex_protocol::mcp::CallToolResult;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
|
||||
const PNG: &str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==";
|
||||
|
||||
#[test]
|
||||
fn mcp_inventory_connection_states() {
|
||||
use McpServerConnectionStatus as Status;
|
||||
|
||||
let statuses = [
|
||||
("unknown", None),
|
||||
("starting", Some(Status::Starting)),
|
||||
("failed", Some(Status::Failed)),
|
||||
("disabled", Some(Status::Disabled)),
|
||||
("deferred", Some(Status::NotStarted)),
|
||||
("connected-empty", Some(Status::Connected)),
|
||||
("cancelled", Some(Status::Cancelled)),
|
||||
("auth", Some(Status::AuthenticationRequired)),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(name, runtime_status)| McpServerStatus {
|
||||
server_capabilities: None,
|
||||
tool_list_meta: None,
|
||||
name: name.to_string(),
|
||||
runtime_status,
|
||||
plugin_id: None,
|
||||
http_origin: None,
|
||||
server_info: None,
|
||||
tools: HashMap::new(),
|
||||
tools_error: None,
|
||||
resources: Vec::new(),
|
||||
resource_templates: Vec::new(),
|
||||
auth_status: McpAuthStatus::Unknown,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let cell =
|
||||
new_mcp_tools_output_from_statuses(&statuses, McpServerStatusDetail::ToolsAndAuthOnly);
|
||||
let rendered = cell
|
||||
.display_lines(/*width*/ 100)
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
insta::assert_snapshot!(rendered);
|
||||
for (name, expected) in [
|
||||
("auth", status_style(StatusTone::Attention)),
|
||||
("cancelled", Style::default().dim()),
|
||||
("connected-empty", status_style(StatusTone::Success)),
|
||||
("deferred", Style::default().dim()),
|
||||
("disabled", Style::default().dim()),
|
||||
("failed", status_style(StatusTone::Failure)),
|
||||
("starting", accent_style()),
|
||||
("unknown", Style::default().dim()),
|
||||
] {
|
||||
let row = cell
|
||||
.lines
|
||||
.iter()
|
||||
.find(|line| line.spans.get(1).is_some_and(|span| span.content == name))
|
||||
.expect("connection-state row");
|
||||
assert_eq!(
|
||||
(row.spans[0].style, row.spans[3].style),
|
||||
(expected, expected)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_inventory_older_app_server_authentication() {
|
||||
let statuses = serde_json::from_value::<Vec<McpServerStatus>>(json!([
|
||||
{
|
||||
"name": "legacy-auth",
|
||||
"tools": {},
|
||||
"resources": [],
|
||||
"resourceTemplates": [],
|
||||
"authStatus": "notLoggedIn"
|
||||
},
|
||||
{
|
||||
"name": "legacy-healthy",
|
||||
"tools": {"lookup": {"name": "lookup", "inputSchema": {"type": "object"}}},
|
||||
"resources": [],
|
||||
"resourceTemplates": [],
|
||||
"authStatus": "oAuth"
|
||||
},
|
||||
{
|
||||
"name": "runtime-disabled",
|
||||
"runtimeStatus": "disabled",
|
||||
"tools": {},
|
||||
"resources": [],
|
||||
"resourceTemplates": [],
|
||||
"authStatus": "notLoggedIn"
|
||||
}
|
||||
]))
|
||||
.expect("mixed-version MCP statuses");
|
||||
let cell =
|
||||
new_mcp_tools_output_from_statuses(&statuses, McpServerStatusDetail::ToolsAndAuthOnly);
|
||||
let rendered = cell
|
||||
.display_lines(/*width*/ 100)
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
insta::assert_snapshot!(rendered);
|
||||
let styles = cell
|
||||
.lines
|
||||
.iter()
|
||||
.filter(|line| {
|
||||
line.spans
|
||||
.get(1)
|
||||
.is_some_and(|span| statuses.iter().any(|status| span.content == status.name))
|
||||
})
|
||||
.map(|line| (line.spans[0].style, line.spans[3].style))
|
||||
.collect::<Vec<_>>();
|
||||
let attention = status_style(StatusTone::Attention);
|
||||
let neutral = Style::default().dim();
|
||||
assert_eq!(
|
||||
styles,
|
||||
vec![
|
||||
(attention, attention),
|
||||
(neutral, neutral),
|
||||
(neutral, neutral)
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
fn result(content: Vec<Value>) -> CallToolResult {
|
||||
CallToolResult {
|
||||
content,
|
||||
structured_content: None,
|
||||
is_error: None,
|
||||
meta: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_preview_shares_one_limit_across_blocks_and_preserves_transcript() {
|
||||
let mut cell = new_active_mcp_tool_call(
|
||||
"call-preview".into(),
|
||||
McpInvocation {
|
||||
server: "search".into(),
|
||||
tool: "lookup".into(),
|
||||
arguments: Some(json!({"title": "Search query"})),
|
||||
},
|
||||
/*animations_enabled*/ false,
|
||||
);
|
||||
cell.complete(
|
||||
Duration::ZERO,
|
||||
Ok(result(vec![
|
||||
json!({"type": "text", "text": "first\nsecond"}),
|
||||
json!({"type": "text", "text": "third\nfourth\nfifth"}),
|
||||
])),
|
||||
);
|
||||
let display = cell.display_lines(/*width*/ 80);
|
||||
let transcript = cell.transcript_lines(/*width*/ 80);
|
||||
insta::assert_snapshot!(format!(
|
||||
"compact:\n{}\n\nhistory:\n{}\n\ntranscript:\n{}",
|
||||
visible_lines(cell.compact_hyperlink_lines(/*width*/ 80))
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n"),
|
||||
display
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n"),
|
||||
transcript
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n"),
|
||||
));
|
||||
assert_eq!(
|
||||
cell.raw_lines()
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>(),
|
||||
[
|
||||
"Called search.lookup({\"title\":\"Search query\"})",
|
||||
"first",
|
||||
"second",
|
||||
"third",
|
||||
"fourth",
|
||||
"fifth"
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_mode_output_shares_a_row_budget_across_blocks() {
|
||||
let mut cell = new_active_mcp_tool_call(
|
||||
"browser-call".to_string(),
|
||||
McpInvocation {
|
||||
server: "node_repl".to_string(),
|
||||
tool: "js".to_string(),
|
||||
arguments: Some(json!({"title": "Inspect page", "code": "await tab.snapshot()"})),
|
||||
},
|
||||
/*animations_enabled*/ false,
|
||||
);
|
||||
cell.complete(
|
||||
Duration::ZERO,
|
||||
Ok(result(vec![
|
||||
json!({"type": "text", "text": "Script completed\nOutput:\n"}),
|
||||
json!({"type": "text", "text": "Page title\nNavigation\nMain content"}),
|
||||
json!({"type": "text", "text": "Button\nLink\nFooter"}),
|
||||
])),
|
||||
);
|
||||
|
||||
let display = cell
|
||||
.display_lines(/*width*/ 40)
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
insta::assert_snapshot!(display, @"
|
||||
• Inspect page
|
||||
└ Page title
|
||||
Navigation
|
||||
Main content
|
||||
+3 lines (⌃t to view transcript)
|
||||
");
|
||||
let transcript = cell
|
||||
.transcript_lines(/*width*/ 100)
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
assert!(transcript.contains("await tab.snapshot()"));
|
||||
assert!(transcript.ends_with(" Button\n Link\n Footer"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_mode_output_preserves_trailing_failure_diagnostics_in_transcript() {
|
||||
let mut cell = new_active_mcp_tool_call(
|
||||
"browser-error".to_string(),
|
||||
McpInvocation {
|
||||
server: "node_repl".to_string(),
|
||||
tool: "js".to_string(),
|
||||
arguments: Some(json!({"title": "Inspect page"})),
|
||||
},
|
||||
/*animations_enabled*/ false,
|
||||
);
|
||||
cell.complete(
|
||||
Duration::ZERO,
|
||||
Ok(CallToolResult {
|
||||
is_error: Some(true),
|
||||
..result(vec![
|
||||
json!({"type": "text", "text": "Script failed"}),
|
||||
json!({"type": "text", "text": "Page title\nNavigation\nMain content\nButton\nLink\nFooter"}),
|
||||
json!({"type": "text", "text": "Script error:\npermission denied"}),
|
||||
])
|
||||
}),
|
||||
);
|
||||
let display = cell
|
||||
.display_lines(/*width*/ 40)
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
insta::assert_snapshot!(display, @"
|
||||
• Inspect page
|
||||
└ Script failed
|
||||
Page title
|
||||
Navigation
|
||||
+6 lines (⌃t to view transcript)
|
||||
");
|
||||
let transcript = cell
|
||||
.transcript_lines(/*width*/ 80)
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
assert!(transcript.ends_with(" Script error:\n permission denied"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_mode_output_row_budget_applies_after_wrapping_and_to_errors() {
|
||||
let output = format!("{}\ntranscript tail", "Browser 页面 👩💻\n".repeat(40));
|
||||
for server in ["node_repl", "cua_repl"] {
|
||||
for completion in [
|
||||
Ok(result(vec![json!({"type": "text", "text": output})])),
|
||||
Ok(result(vec![json!({
|
||||
"type": "text",
|
||||
"text": format!("https://example.com/{}\ntranscript tail", "页面".repeat(100)),
|
||||
})])),
|
||||
Ok(CallToolResult {
|
||||
is_error: Some(true),
|
||||
..result(vec![json!({"type": "text", "text": output})])
|
||||
}),
|
||||
Err(output.clone()),
|
||||
] {
|
||||
let mut cell = new_active_mcp_tool_call(
|
||||
"browser-call".to_string(),
|
||||
McpInvocation {
|
||||
server: server.to_string(),
|
||||
tool: "js".to_string(),
|
||||
arguments: Some(json!({"title": "Inspect"})),
|
||||
},
|
||||
/*animations_enabled*/ false,
|
||||
);
|
||||
cell.complete(Duration::ZERO, completion);
|
||||
for width in [20, 40, 80] {
|
||||
let compact = cell.compact_hyperlink_lines(width);
|
||||
assert!(compact.len() <= 4);
|
||||
assert!(
|
||||
compact
|
||||
.last()
|
||||
.unwrap()
|
||||
.line
|
||||
.to_string()
|
||||
.ends_with("transcript tail")
|
||||
);
|
||||
let display = cell.display_lines(width);
|
||||
assert_eq!(display.len(), 5); // Header, three output rows, and omission hint.
|
||||
assert!(
|
||||
display
|
||||
.iter()
|
||||
.all(|line| line.width() <= usize::from(width))
|
||||
);
|
||||
assert!(display.last().unwrap().to_string().starts_with(" +"));
|
||||
let transcript = cell
|
||||
.transcript_lines(width)
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
assert!(
|
||||
transcript
|
||||
.split_whitespace()
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
.contains("transcript tail")
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn projected_content_preserves_full_rendering() {
|
||||
let text = "{\"result\": [1, 2, 3], \"text\": \"long output 🦀\"}";
|
||||
let malformed = json!({"type": "image", "data": PNG});
|
||||
let invalid_metadata =
|
||||
json!({"type": "text", "text": "not a valid block", "annotations": {"priority": "high"}});
|
||||
let unknown = json!({"type": "future_block", "text": "unknown output 🦀"});
|
||||
let projected = McpToolResult::new(
|
||||
result(vec![
|
||||
json!({"type": "text", "text": text}),
|
||||
json!({"type": "image", "mimeType": "image/png", "data": PNG}),
|
||||
json!({"type": "audio", "mimeType": "audio/wav", "data": "audio data"}),
|
||||
json!({"type": "resource", "resource": {"uri": "file:///text.txt", "text": "resource body"}}),
|
||||
json!({"type": "resource", "resource": {"uri": "file:///blob.bin", "blob": "binary data"}}),
|
||||
json!({"type": "resource_link", "uri": "file:///linked.txt", "name": "linked"}),
|
||||
malformed.clone(),
|
||||
invalid_metadata.clone(),
|
||||
unknown.clone(),
|
||||
]),
|
||||
McpResultKind::Standard,
|
||||
);
|
||||
|
||||
let format_text = |text: &str| format_json_compact(text).unwrap_or_else(|| text.to_owned());
|
||||
assert_eq!(
|
||||
projected
|
||||
.content
|
||||
.iter()
|
||||
.map(result::McpContentBlock::render)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![
|
||||
format_text(text),
|
||||
"Returned image".to_string(),
|
||||
"<audio content>".to_string(),
|
||||
"embedded resource: file:///text.txt".to_string(),
|
||||
"embedded resource: file:///blob.bin".to_string(),
|
||||
"link: file:///linked.txt".to_string(),
|
||||
format_text(&malformed.to_string()),
|
||||
format_text(&invalid_metadata.to_string()),
|
||||
format_text(&unknown.to_string()),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn projected_image_marker_still_requires_a_complete_image() {
|
||||
let bytes = base64::engine::general_purpose::STANDARD
|
||||
.decode(PNG)
|
||||
.expect("decode PNG fixture");
|
||||
let truncated = base64::engine::general_purpose::STANDARD.encode(&bytes[..33]);
|
||||
let invalid = json!({"type": "image", "mimeType": "image/png", "data": truncated});
|
||||
let valid = json!({"type": "image", "mimeType": "image/png", "data": format!("data:image/png;base64,{PNG}")});
|
||||
|
||||
let projected = McpToolResult::new(result(vec![invalid.clone()]), McpResultKind::Standard);
|
||||
assert!(!projected.has_image);
|
||||
assert_eq!(projected.content[0].render(), "Returned image");
|
||||
|
||||
let projected = McpToolResult::new(result(vec![invalid, valid]), McpResultKind::Standard);
|
||||
assert!(projected.has_image);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_mode_preserves_text_fields_on_nontext_and_unknown_blocks() {
|
||||
let mut cell = new_active_mcp_tool_call(
|
||||
"call-code-mode".to_string(),
|
||||
McpInvocation {
|
||||
server: "node_repl".to_string(),
|
||||
tool: "js".to_string(),
|
||||
arguments: Some(json!({"title": "Inspect results"})),
|
||||
},
|
||||
/*animations_enabled*/ false,
|
||||
);
|
||||
let unknown =
|
||||
json!({"type": "future_block", "text": "Script completed\nOutput:\nunknown-side output"});
|
||||
let tool_result = result(vec![
|
||||
json!({"type": "image", "mimeType": "image/png", "data": PNG, "text": "Script completed\nOutput:\nimage-side output"}),
|
||||
unknown,
|
||||
]);
|
||||
cell.complete(Duration::ZERO, Ok(tool_result.clone()));
|
||||
|
||||
let narrow = cell.display_lines(/*width*/ 16);
|
||||
assert!(narrow.iter().all(|line| line.width() <= 16));
|
||||
assert_eq!(
|
||||
narrow
|
||||
.iter()
|
||||
.skip(1)
|
||||
.take(2)
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![" └ Returned", " image"],
|
||||
);
|
||||
|
||||
let compact = cell.compact_hyperlink_lines(/*width*/ 80);
|
||||
let compact = visible_lines(compact)
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
let narrow_compact = cell.compact_hyperlink_lines(/*width*/ 16);
|
||||
assert!(narrow_compact.iter().all(|line| line.width() <= 16));
|
||||
|
||||
let display = cell
|
||||
.display_lines(/*width*/ 200)
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
let transcript = cell
|
||||
.transcript_lines(/*width*/ 200)
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
insta::assert_snapshot!(format!("compact:\n{compact}\n\nhistory:\n{display}\n\ntranscript:\n{transcript}"), @r#"
|
||||
compact:
|
||||
• Called Inspect results
|
||||
└ Returned image
|
||||
image-side output
|
||||
unknown-side output
|
||||
|
||||
history:
|
||||
• Inspect results
|
||||
└ Returned image
|
||||
image-side output
|
||||
unknown-side output
|
||||
|
||||
transcript:
|
||||
• Called node_repl.js({"title":"Inspect results"})
|
||||
└ Returned image
|
||||
Script completed
|
||||
Output:
|
||||
image-side output
|
||||
Script completed
|
||||
Output:
|
||||
unknown-side output
|
||||
"#);
|
||||
assert_eq!(
|
||||
cell.raw_lines(),
|
||||
vec![
|
||||
Line::from("Called node_repl.js({\"title\":\"Inspect results\"})"),
|
||||
Line::from("Script completed"),
|
||||
Line::from("Output:"),
|
||||
Line::from("image-side output"),
|
||||
Line::from("Script completed"),
|
||||
Line::from("Output:"),
|
||||
Line::from("unknown-side output"),
|
||||
],
|
||||
);
|
||||
|
||||
let mut cua_cell = new_active_mcp_tool_call(
|
||||
"call-cua-repl".to_string(),
|
||||
McpInvocation {
|
||||
server: "cua_repl".to_string(),
|
||||
tool: "js".to_string(),
|
||||
arguments: None,
|
||||
},
|
||||
/*animations_enabled*/ false,
|
||||
);
|
||||
cua_cell.complete(Duration::ZERO, Ok(tool_result));
|
||||
let display = cua_cell
|
||||
.display_lines(/*width*/ 200)
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
let transcript = cua_cell
|
||||
.transcript_lines(/*width*/ 200)
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
insta::assert_snapshot!(format!("history:\n{display}\n\ntranscript:\n{transcript}"), @r"
|
||||
history:
|
||||
• Called cua_repl.js
|
||||
└ Returned image
|
||||
image-side output
|
||||
unknown-side output
|
||||
|
||||
transcript:
|
||||
• Called cua_repl.js()
|
||||
└ Returned image
|
||||
Script completed
|
||||
Output:
|
||||
image-side output
|
||||
Script completed
|
||||
Output:
|
||||
unknown-side output
|
||||
");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn titled_image_call_keeps_error_and_full_title_when_narrow() {
|
||||
let title = "Inspect a very long screenshot title 🦀";
|
||||
let mut cell = new_active_mcp_tool_call(
|
||||
"call".into(),
|
||||
McpInvocation {
|
||||
server: "node_repl".into(),
|
||||
tool: "js".into(),
|
||||
arguments: Some(json!({"title": title})),
|
||||
},
|
||||
/*animations_enabled*/ false,
|
||||
);
|
||||
assert_eq!(
|
||||
cell.display_lines(/*width*/ 80)[0].to_string(),
|
||||
format!("• {title}")
|
||||
);
|
||||
cell.complete(
|
||||
Duration::ZERO,
|
||||
Ok(CallToolResult {
|
||||
is_error: Some(true),
|
||||
..result(vec![
|
||||
json!({"type": "text", "text": "Screenshot partially failed"}),
|
||||
json!({"type": "image", "mimeType": "image/png", "data": PNG}),
|
||||
])
|
||||
}),
|
||||
);
|
||||
let lines = cell.display_lines(/*width*/ 32);
|
||||
assert!(lines[0].width() <= 32);
|
||||
assert_eq!(lines[0].spans[0].style, "•".red().bold().style);
|
||||
insta::assert_snapshot!(
|
||||
lines
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
);
|
||||
assert!(cell.raw_lines()[0].to_string().contains(title));
|
||||
assert!(
|
||||
cell.transcript_lines(/*width*/ 200)[0]
|
||||
.to_string()
|
||||
.contains(title)
|
||||
);
|
||||
}
|
||||
|
||||
/// Reconstruct only from explicit provenance, checking every displayed source slice on the way.
|
||||
fn source_lines(lines: &[HyperlinkLine]) -> Vec<String> {
|
||||
let mut sources: Vec<Arc<str>> = Vec::new();
|
||||
for line in lines {
|
||||
let source = line.source.as_ref().expect("MCP row source");
|
||||
let visible = line.line.to_string();
|
||||
assert_eq!(
|
||||
&visible[source.prefix_bytes..source.prefix_bytes + source.range.len()],
|
||||
&source.text[source.range.clone()],
|
||||
);
|
||||
if !sources
|
||||
.last()
|
||||
.is_some_and(|previous| Arc::ptr_eq(previous, &source.text))
|
||||
{
|
||||
sources.push(Arc::clone(&source.text));
|
||||
}
|
||||
}
|
||||
sources
|
||||
.into_iter()
|
||||
.map(|source| source.to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_mode_transcript_preserves_long_code_and_indentation_across_wrapping() {
|
||||
let code = "const values = await tools.fetch_values({ project: 'selected-project', include_details: true });\n const total = values.reduce((sum, item) => sum + item.value, 0);\n\ntext({ total, label: 'exact code output' });";
|
||||
let mut cell = new_active_mcp_tool_call(
|
||||
"call-code".to_owned(),
|
||||
McpInvocation {
|
||||
server: "node_repl".to_owned(),
|
||||
tool: "js".to_owned(),
|
||||
arguments: None,
|
||||
},
|
||||
/*animations_enabled*/ false,
|
||||
);
|
||||
cell.complete(
|
||||
Duration::ZERO,
|
||||
Ok(result(vec![json!({"type": "text", "text": code})])),
|
||||
);
|
||||
let expected = code.split('\n').map(str::to_owned).collect::<Vec<_>>();
|
||||
for width in [16, 24, 40, 80] {
|
||||
let lines = cell.transcript_hyperlink_lines(width);
|
||||
let source = source_lines(&lines);
|
||||
assert!(source.ends_with(&expected), "{source:?}");
|
||||
assert!(
|
||||
lines.len() > expected.len(),
|
||||
"long code should wrap at width {width}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_result_preview_preserves_source_text_and_excludes_tree_gutters() {
|
||||
let text = "one long result line with repeated spaces and enough content to wrap across several narrow rows";
|
||||
let mut cell = new_active_mcp_tool_call(
|
||||
"call-mcp".to_owned(),
|
||||
McpInvocation {
|
||||
server: "docs".to_owned(),
|
||||
tool: "read".to_owned(),
|
||||
arguments: None,
|
||||
},
|
||||
/*animations_enabled*/ false,
|
||||
);
|
||||
cell.complete(
|
||||
Duration::ZERO,
|
||||
Ok(result(vec![json!({"type": "text", "text": text})])),
|
||||
);
|
||||
for width in [16, 24, 40, 80] {
|
||||
let lines = cell.display_hyperlink_lines(width);
|
||||
let backed = lines
|
||||
.into_iter()
|
||||
.filter(|line| line.source.is_some())
|
||||
.collect::<Vec<_>>();
|
||||
let source = source_lines(&backed);
|
||||
let output = source
|
||||
.iter()
|
||||
.find(|line| line.starts_with("one long result"))
|
||||
.expect("result source");
|
||||
assert!(
|
||||
text.starts_with(output),
|
||||
"preview must retain the original whitespace"
|
||||
);
|
||||
if width >= 40 {
|
||||
assert_eq!(output, text);
|
||||
}
|
||||
assert!(
|
||||
source
|
||||
.iter()
|
||||
.all(|line| !line.starts_with('•') && !line.starts_with(" └ "))
|
||||
);
|
||||
}
|
||||
}
|
||||
926
codex-rs/tui/src/history_cell/messages.rs
Normal file
926
codex-rs/tui/src/history_cell/messages.rs
Normal file
@@ -0,0 +1,926 @@
|
||||
//! User, assistant, reasoning, and streaming message history cells.
|
||||
//! Completed reasoning is retained in the expanded transcript, not compact scrollback.
|
||||
|
||||
use super::markdown_render_cache::MarkdownRenderCache;
|
||||
use super::*;
|
||||
use crate::async_question_reply::AsyncQuestionReply;
|
||||
use crate::style::accent_color_on;
|
||||
use crate::style::history_prompt_style;
|
||||
use crate::terminal_hyperlinks::annotate_web_urls;
|
||||
use crate::terminal_hyperlinks::lines_with_sources_eq;
|
||||
use crate::terminal_hyperlinks::remap_source_wrapped_line;
|
||||
use crate::wrapping::url_preserving_wrap_options;
|
||||
use crate::wrapping::word_wrap_line_with_source;
|
||||
use std::borrow::Cow;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct UserHistoryCell {
|
||||
pub message: String,
|
||||
pub text_elements: Vec<TextElement>,
|
||||
pub local_image_paths: Vec<PathBuf>,
|
||||
pub remote_image_urls: Vec<String>,
|
||||
pub(crate) presentation: UserMessagePresentation,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) enum UserMessagePresentation {
|
||||
#[default]
|
||||
Typed,
|
||||
Spoken,
|
||||
/// Render each submitted answer as Markdown beneath its question caption.
|
||||
AsyncReplies {
|
||||
/// Keep the decoded pairs so the two-row limit applies only to question captions.
|
||||
/// In the flattened message, an answer's own blockquotes can look like captions.
|
||||
replies: Vec<AsyncQuestionReply>,
|
||||
/// Capture the session directory so relative Markdown links resolve the same way on reflow.
|
||||
cwd: PathBuf,
|
||||
},
|
||||
}
|
||||
|
||||
/// Remove CSI sequences and control characters, preserving tabs and newlines.
|
||||
pub(crate) fn sanitize_user_text(text: Cow<'_, str>) -> Cow<'_, str> {
|
||||
fn sanitize_borrowed(text: &str) -> Cow<'_, str> {
|
||||
let mut remaining = Some(text);
|
||||
let mut spans = std::iter::from_fn(move || {
|
||||
let current = remaining.take()?;
|
||||
let mut escaped = false;
|
||||
let Some((prefix, suffix)) = current.split_once(|ch: char| {
|
||||
escaped = ch == '\x1b';
|
||||
escaped || ch.is_control() && !matches!(ch, '\n' | '\t')
|
||||
}) else {
|
||||
return Some(current);
|
||||
};
|
||||
|
||||
remaining = if escaped && let Some(sequence) = suffix.strip_prefix('[') {
|
||||
sequence
|
||||
.split_once(|ch: char| ('@'..='~').contains(&ch))
|
||||
.map(|(_, tail)| tail)
|
||||
} else {
|
||||
Some(suffix)
|
||||
};
|
||||
Some(prefix)
|
||||
})
|
||||
.filter(|span| !span.is_empty());
|
||||
|
||||
let first = spans.next().unwrap_or_default();
|
||||
let Some(second) = spans.next() else {
|
||||
return Cow::Borrowed(first);
|
||||
};
|
||||
|
||||
Cow::Owned([first, second].into_iter().chain(spans).fold(
|
||||
String::with_capacity(text.len()),
|
||||
|mut acc, span| {
|
||||
acc.push_str(span);
|
||||
acc
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
match text {
|
||||
Cow::Borrowed(text) => sanitize_borrowed(text),
|
||||
Cow::Owned(mut text) => match sanitize_borrowed(&text) {
|
||||
Cow::Owned(sanitized) => Cow::Owned(sanitized),
|
||||
Cow::Borrowed(retained) => {
|
||||
if retained.is_empty() {
|
||||
text.clear();
|
||||
} else if retained.len() != text.len() {
|
||||
// Cannot underflow because retained is a subslice of text.
|
||||
// I'd normally assert that here but this crate denies
|
||||
// clippy::expect_used.
|
||||
let start = retained.as_ptr().addr() - text.as_ptr().addr();
|
||||
let end = start + retained.len();
|
||||
|
||||
// Truncate before draining because truncate is constant
|
||||
// time while drain is linear in the size of the receiver.
|
||||
text.truncate(end);
|
||||
drop(text.drain(..start));
|
||||
}
|
||||
Cow::Owned(text)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 user_message_element_style(style: Style, accent: Color) -> Style {
|
||||
let unresolved_background = match style.bg {
|
||||
Some(Color::Indexed(index)) => index < 16,
|
||||
Some(Color::Rgb(..) | Color::Reset) | None => false,
|
||||
Some(_) => true,
|
||||
};
|
||||
if accent == Color::Reset || unresolved_background {
|
||||
style
|
||||
} else {
|
||||
style.fg(accent)
|
||||
}
|
||||
}
|
||||
|
||||
impl UserHistoryCell {
|
||||
pub(crate) fn with_async_replies(
|
||||
mut self,
|
||||
replies: Vec<AsyncQuestionReply>,
|
||||
cwd: &Path,
|
||||
) -> Self {
|
||||
if !replies.is_empty() {
|
||||
self.presentation = UserMessagePresentation::AsyncReplies {
|
||||
replies,
|
||||
cwd: cwd.to_owned(),
|
||||
};
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn is_spoken(&self) -> bool {
|
||||
matches!(self.presentation, UserMessagePresentation::Spoken)
|
||||
}
|
||||
|
||||
pub(crate) fn uses_markdown(&self) -> bool {
|
||||
// Inline elements use byte ranges in the literal prompt.
|
||||
matches!(self.presentation, UserMessagePresentation::Typed) && self.text_elements.is_empty()
|
||||
}
|
||||
|
||||
pub(crate) fn has_visible_content(&self) -> bool {
|
||||
!sanitize_user_text(Cow::Borrowed(&self.message))
|
||||
.trim()
|
||||
.is_empty()
|
||||
|| !self.text_elements.is_empty()
|
||||
|| !self.local_image_paths.is_empty()
|
||||
|| !self.remote_image_urls.is_empty()
|
||||
}
|
||||
|
||||
fn image_labels_not_in_message(&self) -> impl Iterator<Item = String> + '_ {
|
||||
// Composer images already have placeholders; command-line images may not.
|
||||
// Both kinds must keep an image-only user turn visible after submission.
|
||||
(1..=self.remote_image_urls.len() + self.local_image_paths.len())
|
||||
.map(local_image_label_text)
|
||||
.filter(|label| {
|
||||
!self
|
||||
.text_elements
|
||||
.iter()
|
||||
.any(|element| element.placeholder(&self.message) == Some(label.as_str()))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryCell for UserHistoryCell {
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
visible_lines(self.display_hyperlink_lines(width))
|
||||
}
|
||||
|
||||
fn display_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
let lines = self.transcript_hyperlink_lines(width);
|
||||
if self.is_spoken() || !self.text_elements.is_empty() {
|
||||
// Native history applies line styles over spans. Keep the prompt fill on the line
|
||||
// while resolving its foreground onto the text, marker, and inline elements.
|
||||
lines
|
||||
.into_iter()
|
||||
.map(HyperlinkLine::resolve_span_styles)
|
||||
.collect()
|
||||
} else {
|
||||
lines
|
||||
}
|
||||
}
|
||||
|
||||
fn transcript_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
let sanitized_message = sanitize_user_text((&self.message).into());
|
||||
// Speech transcripts can begin with whitespace; the marker already supplies its separator.
|
||||
let message = if self.is_spoken() {
|
||||
sanitized_message.trim_start()
|
||||
} else {
|
||||
sanitized_message.as_ref()
|
||||
};
|
||||
let text_elements = if message == self.message {
|
||||
self.text_elements.as_slice()
|
||||
} else {
|
||||
&[]
|
||||
};
|
||||
let wrap_width = width
|
||||
.saturating_sub(
|
||||
LIVE_PREFIX_COLS + 1, /* keep a one-column right margin for wrapping */
|
||||
)
|
||||
.max(/*other*/ 1);
|
||||
|
||||
let style = history_prompt_style();
|
||||
let element_style = user_message_element_style(style, accent_color_on(style.bg));
|
||||
|
||||
let wrapped_images = plain_hyperlink_lines(adaptive_wrap_lines(
|
||||
self.image_labels_not_in_message()
|
||||
.map(|label| Line::from(label).style(element_style)),
|
||||
RtOptions::new(usize::from(wrap_width))
|
||||
.wrap_algorithm(textwrap::WrapAlgorithm::FirstFit),
|
||||
));
|
||||
|
||||
let (wrapped_message, copy_as_prose) =
|
||||
if let UserMessagePresentation::AsyncReplies { replies, cwd } = &self.presentation {
|
||||
(
|
||||
super::async_replies::render(replies, cwd, usize::from(wrap_width)),
|
||||
false,
|
||||
)
|
||||
} else {
|
||||
let marker = if self.is_spoken() {
|
||||
"› ".red().bold()
|
||||
} else {
|
||||
"› ".bold().dim()
|
||||
};
|
||||
let markdown = if self.uses_markdown() {
|
||||
crate::markdown::render_markdown_for_viewport(message, wrap_width)
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let copy_as_prose = !crate::markdown_copy::has_visible_markup(&markdown, message);
|
||||
let body = if copy_as_prose {
|
||||
wrap_user_message(message, text_elements, style, wrap_width)
|
||||
} else {
|
||||
markdown
|
||||
.into_iter()
|
||||
.map(|line| {
|
||||
let mut line_style = style.patch(line.line.style);
|
||||
line_style.bg = style.bg;
|
||||
line.style(line_style).resolve_span_styles()
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
(
|
||||
prefix_hyperlink_lines(body, marker, " ".into()),
|
||||
copy_as_prose,
|
||||
)
|
||||
};
|
||||
if wrapped_images.is_empty() && wrapped_message.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut lines = vec![HyperlinkLine::new(Line::from("").style(style))];
|
||||
if !wrapped_images.is_empty() {
|
||||
lines.extend(prefix_hyperlink_lines(
|
||||
wrapped_images,
|
||||
" ".into(),
|
||||
" ".into(),
|
||||
));
|
||||
if !wrapped_message.is_empty() {
|
||||
lines.push(HyperlinkLine::new(Line::from("").style(style)));
|
||||
}
|
||||
}
|
||||
lines.extend(wrapped_message);
|
||||
lines.push(HyperlinkLine::new(Line::from("").style(style)));
|
||||
for source in lines.iter_mut().filter_map(|line| line.source.as_mut()) {
|
||||
source.right_reserve = 1;
|
||||
source.copy_as_prose |= copy_as_prose;
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
fn compact_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
self.transcript_hyperlink_lines(width)
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
let message = sanitize_user_text((&self.message).into());
|
||||
let mut lines = raw_lines_from_source(message.as_ref().trim_end_matches(['\r', '\n']));
|
||||
let mut image_labels = self.image_labels_not_in_message().peekable();
|
||||
if image_labels.peek().is_some() {
|
||||
if !lines.is_empty() {
|
||||
lines.push(Line::from(""));
|
||||
}
|
||||
lines.extend(image_labels.map(Line::from));
|
||||
}
|
||||
lines
|
||||
}
|
||||
}
|
||||
|
||||
/// Wrap a prompt body before the user-message gutter and background padding are added.
|
||||
fn wrap_user_message(
|
||||
message: &str,
|
||||
text_elements: &[TextElement],
|
||||
style: Style,
|
||||
wrap_width: u16,
|
||||
) -> Vec<HyperlinkLine> {
|
||||
let element_style = user_message_element_style(style, accent_color_on(style.bg));
|
||||
if message.is_empty() && text_elements.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let wrap_options =
|
||||
RtOptions::new(usize::from(wrap_width)).wrap_algorithm(textwrap::WrapAlgorithm::FirstFit);
|
||||
let logical_lines = if text_elements.is_empty() {
|
||||
let message_without_trailing_newlines = message.trim_end_matches(['\r', '\n']);
|
||||
message_without_trailing_newlines
|
||||
.split('\n')
|
||||
.map(|line| Line::from(line.to_owned()).style(style))
|
||||
.collect()
|
||||
} else {
|
||||
build_user_message_lines_with_elements(message, text_elements, style, element_style)
|
||||
};
|
||||
let mut wrapped = crate::terminal_hyperlinks::adaptive_wrap_hyperlink_lines(
|
||||
&annotate_web_urls(logical_lines),
|
||||
wrap_options,
|
||||
)
|
||||
.into_iter()
|
||||
.flat_map(|line| {
|
||||
if line.width() <= usize::from(wrap_width) {
|
||||
return vec![line];
|
||||
}
|
||||
|
||||
// Terminal autowrap loses the message gutter and background. Explicitly split
|
||||
// oversized URL tokens while retaining their complete OSC-8 destination.
|
||||
let forced_lines = word_wrap_line_with_source(
|
||||
&line.line,
|
||||
url_preserving_wrap_options(RtOptions::new(usize::from(wrap_width)))
|
||||
.break_words(/*break_words*/ true),
|
||||
);
|
||||
remap_source_wrapped_line(&line, forced_lines)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
while wrapped.last().is_some_and(|line| {
|
||||
line.line
|
||||
.spans
|
||||
.iter()
|
||||
.all(|span| span.content.trim().is_empty())
|
||||
}) {
|
||||
wrapped.pop();
|
||||
}
|
||||
wrapped
|
||||
}
|
||||
|
||||
#[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,
|
||||
/// Persisted identity verifies page folds without comparing rendered reasoning text.
|
||||
source_item_id: Option<String>,
|
||||
}
|
||||
|
||||
impl ReasoningSummaryCell {
|
||||
pub(crate) fn markdown_source(&self) -> &str {
|
||||
&self.content
|
||||
}
|
||||
|
||||
pub(crate) fn set_source_item_id(&mut self, id: String) {
|
||||
self.source_item_id = Some(id);
|
||||
}
|
||||
|
||||
pub(crate) fn source_item_id(&self) -> Option<&str> {
|
||||
self.source_item_id.as_deref()
|
||||
}
|
||||
|
||||
pub(crate) fn is_transcript_only(&self) -> bool {
|
||||
self.transcript_only
|
||||
}
|
||||
|
||||
/// 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,
|
||||
source_item_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
let lines = crate::markdown_render::render_markdown_lines_with_width_and_cwd(
|
||||
&self.content,
|
||||
crate::width::usable_content_width_u16(width, /*reserved_cols*/ 2),
|
||||
Some(self.cwd.as_path()),
|
||||
);
|
||||
let summary_style = Style::default().dim().italic();
|
||||
let summary_lines = lines
|
||||
.into_iter()
|
||||
.map(|mut line| {
|
||||
line.line.spans = line
|
||||
.line
|
||||
.spans
|
||||
.into_iter()
|
||||
.map(|span| span.patch_style(summary_style))
|
||||
.collect();
|
||||
if let Some(source) = &mut line.source {
|
||||
source.span_style = source.span_style.patch(summary_style);
|
||||
}
|
||||
line
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
crate::terminal_hyperlinks::adaptive_wrap_hyperlink_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>> {
|
||||
visible_lines(self.display_hyperlink_lines(width))
|
||||
}
|
||||
|
||||
fn display_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
if self.transcript_only {
|
||||
Vec::new()
|
||||
} else {
|
||||
self.lines(width)
|
||||
}
|
||||
}
|
||||
|
||||
fn transcript_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
visible_lines(self.transcript_hyperlink_lines(width))
|
||||
}
|
||||
|
||||
fn transcript_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
self.lines(width)
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
if self.transcript_only {
|
||||
Vec::new()
|
||||
} else {
|
||||
raw_lines_from_source(self.markdown_source().trim())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct AgentMessageCell {
|
||||
lines: Vec<HyperlinkLine>,
|
||||
is_first_line: bool,
|
||||
}
|
||||
|
||||
impl AgentMessageCell {
|
||||
#[cfg(test)]
|
||||
pub(crate) fn new(lines: Vec<Line<'static>>, is_first_line: bool) -> Self {
|
||||
Self {
|
||||
lines: plain_hyperlink_lines(lines),
|
||||
is_first_line,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn new_hyperlink_lines(lines: Vec<HyperlinkLine>, is_first_line: bool) -> Self {
|
||||
Self {
|
||||
lines,
|
||||
is_first_line,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryCell for AgentMessageCell {
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
visible_lines(self.display_hyperlink_lines(width))
|
||||
}
|
||||
|
||||
fn display_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
let mut wrapped = Vec::new();
|
||||
for (index, line) in self.lines.iter().enumerate() {
|
||||
let initial_indent = if index == 0 && self.is_first_line {
|
||||
"• ".dim().into()
|
||||
} else {
|
||||
" ".into()
|
||||
};
|
||||
let mut subsequent_indent = Line::from(" ");
|
||||
subsequent_indent
|
||||
.spans
|
||||
.extend(crate::insert_history::leading_whitespace_prefix(&line.line).spans);
|
||||
wrapped.extend(crate::terminal_hyperlinks::adaptive_wrap_hyperlink_lines(
|
||||
std::slice::from_ref(line),
|
||||
RtOptions::new(width as usize)
|
||||
.initial_indent(initial_indent)
|
||||
.subsequent_indent(subsequent_indent),
|
||||
));
|
||||
}
|
||||
wrapped
|
||||
}
|
||||
|
||||
fn transcript_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
self.display_hyperlink_lines(width)
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
plain_lines(visible_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.
|
||||
///
|
||||
/// Ordinary markdown caches its latest rich render. Visualization directives bypass that cache
|
||||
/// because resolving their local file links depends on filesystem state that can change later.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct AgentMarkdownCell {
|
||||
/// Identifies an interrupted reply that can still receive its authoritative completion.
|
||||
pub(crate) interrupted_item: Option<(String, String)>,
|
||||
markdown_source: String,
|
||||
copy_source: Option<String>,
|
||||
cwd: PathBuf,
|
||||
inline_visualization_context: Option<crate::inline_visualization::InlineVisualizationContext>,
|
||||
rendered_lines: Option<MarkdownRenderCache>,
|
||||
spoken_artifacts: bool,
|
||||
question_titles: Vec<std::ops::Range<usize>>,
|
||||
}
|
||||
|
||||
impl AgentMarkdownCell {
|
||||
pub(crate) fn from_parsed_message(
|
||||
visible_markdown: String,
|
||||
source: String,
|
||||
cwd: &Path,
|
||||
context: Option<crate::inline_visualization::InlineVisualizationContext>,
|
||||
questions: &[codex_protocol::items::AsyncUserInputQuestion],
|
||||
) -> Self {
|
||||
Self::new_with_inline_visualizations(visible_markdown, cwd, context)
|
||||
.with_questions(questions)
|
||||
.with_copy_source(Some(source))
|
||||
}
|
||||
|
||||
pub(crate) fn with_copy_source(mut self, source: Option<String>) -> Self {
|
||||
self.copy_source = source;
|
||||
self
|
||||
}
|
||||
|
||||
/// 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.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn new(markdown_source: String, cwd: &Path) -> Self {
|
||||
Self::new_with_inline_visualizations(
|
||||
markdown_source,
|
||||
cwd,
|
||||
/*inline_visualization_context*/ None,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn new_with_inline_visualizations(
|
||||
markdown_source: String,
|
||||
cwd: &Path,
|
||||
inline_visualization_context: Option<
|
||||
crate::inline_visualization::InlineVisualizationContext,
|
||||
>,
|
||||
) -> Self {
|
||||
let rendered_lines =
|
||||
(!crate::inline_visualization::contains_inline_visualization(&markdown_source))
|
||||
.then(MarkdownRenderCache::default);
|
||||
Self {
|
||||
interrupted_item: None,
|
||||
markdown_source,
|
||||
copy_source: None,
|
||||
cwd: cwd.to_path_buf(),
|
||||
inline_visualization_context,
|
||||
rendered_lines,
|
||||
spoken_artifacts: false,
|
||||
question_titles: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn with_questions(
|
||||
mut self,
|
||||
questions: &[codex_protocol::items::AsyncUserInputQuestion],
|
||||
) -> Self {
|
||||
self.question_titles =
|
||||
super::async_questions::title_ranges(&self.markdown_source, questions);
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn new_spoken(markdown_source: String, cwd: &Path) -> Self {
|
||||
let mut cell = Self::new_with_inline_visualizations(
|
||||
markdown_source,
|
||||
cwd,
|
||||
/*inline_visualization_context*/ None,
|
||||
);
|
||||
cell.spoken_artifacts = true;
|
||||
cell
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn normalize_whitespace_only_hyperlink_lines(
|
||||
mut lines: Vec<HyperlinkLine>,
|
||||
) -> Vec<HyperlinkLine> {
|
||||
for line in &mut lines {
|
||||
if line
|
||||
.line
|
||||
.spans
|
||||
.iter()
|
||||
.all(|span| span.content.chars().all(char::is_whitespace))
|
||||
{
|
||||
line.line = Line::default().style(line.line.style);
|
||||
line.hyperlinks.clear();
|
||||
if let Some(source) = &mut line.source {
|
||||
source.prefix_bytes = 0;
|
||||
source.range.end = source.range.start;
|
||||
}
|
||||
}
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
impl AgentMarkdownCell {
|
||||
fn render_lines(
|
||||
&self,
|
||||
width: u16,
|
||||
list_spacing: crate::markdown_render::ListSpacing,
|
||||
) -> Vec<HyperlinkLine> {
|
||||
let render = || {
|
||||
let Some(wrap_width) =
|
||||
crate::width::usable_content_width_u16(width, /*reserved_cols*/ 2)
|
||||
else {
|
||||
return prefix_hyperlink_lines(
|
||||
vec![HyperlinkLine::new(Line::default())],
|
||||
"• ".dim(),
|
||||
" ".into(),
|
||||
);
|
||||
};
|
||||
|
||||
// Re-render markdown from source at the current width. Reserve 2 columns for the "• " /
|
||||
// " " prefix prepended below.
|
||||
let markdown = |source: &str| {
|
||||
crate::markdown::render_markdown_agent_with_list_spacing(
|
||||
source,
|
||||
Some(wrap_width),
|
||||
Some(self.cwd.as_path()),
|
||||
self.inline_visualization_context.as_ref(),
|
||||
list_spacing,
|
||||
)
|
||||
};
|
||||
let lines = if self.question_titles.is_empty() {
|
||||
let mut lines = markdown(&self.markdown_source);
|
||||
if self.spoken_artifacts {
|
||||
super::spoken_artifacts::annotate_spoken_artifacts(&mut lines, &self.cwd);
|
||||
}
|
||||
prefix_hyperlink_lines(lines, "• ".dim(), " ".into())
|
||||
} else {
|
||||
super::async_questions::render(
|
||||
&self.markdown_source,
|
||||
&self.question_titles,
|
||||
markdown,
|
||||
)
|
||||
};
|
||||
normalize_whitespace_only_hyperlink_lines(lines)
|
||||
};
|
||||
|
||||
if let Some(rendered_lines) = &self.rendered_lines {
|
||||
rendered_lines.render(width, list_spacing, render)
|
||||
} else {
|
||||
render()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryCell for AgentMarkdownCell {
|
||||
fn copy_source(&self) -> Option<&str> {
|
||||
Some(self.copy_source.as_deref().unwrap_or(&self.markdown_source))
|
||||
}
|
||||
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
visible_lines(self.display_hyperlink_lines(width))
|
||||
}
|
||||
|
||||
fn display_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
self.render_lines(width, crate::markdown_render::ListSpacing::AfterMultiline)
|
||||
}
|
||||
|
||||
fn retained_hyperlink_lines(&self, width: u16, _detailed: bool) -> Vec<HyperlinkLine> {
|
||||
self.render_lines(width, crate::markdown_render::ListSpacing::Uniform)
|
||||
}
|
||||
|
||||
fn transcript_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
self.display_hyperlink_lines(width)
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
raw_lines_from_source(&self.markdown_source)
|
||||
}
|
||||
|
||||
fn has_stable_transcript_height(&self) -> bool {
|
||||
self.rendered_lines.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "messages_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
/// 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
|
||||
/// deltas that change the visible tail or retained source, and cleared when the stream finalizes.
|
||||
#[derive(Debug, Eq)]
|
||||
pub(crate) struct StreamingAgentTailCell {
|
||||
lines: Vec<HyperlinkLine>,
|
||||
is_first_line: bool,
|
||||
}
|
||||
|
||||
impl PartialEq for StreamingAgentTailCell {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.is_first_line == other.is_first_line
|
||||
&& lines_with_sources_eq(&self.lines, &other.lines)
|
||||
}
|
||||
}
|
||||
|
||||
impl StreamingAgentTailCell {
|
||||
pub(crate) fn new(lines: Vec<HyperlinkLine>, is_first_line: bool) -> Self {
|
||||
Self {
|
||||
lines,
|
||||
is_first_line,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryCell for StreamingAgentTailCell {
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
visible_lines(self.display_hyperlink_lines(width))
|
||||
}
|
||||
|
||||
fn display_hyperlink_lines(&self, _width: u16) -> Vec<HyperlinkLine> {
|
||||
// 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.
|
||||
normalize_whitespace_only_hyperlink_lines(prefix_hyperlink_lines(
|
||||
self.lines.clone(),
|
||||
if self.is_first_line {
|
||||
"• ".dim()
|
||||
} else {
|
||||
" ".into()
|
||||
},
|
||||
" ".into(),
|
||||
))
|
||||
}
|
||||
|
||||
fn transcript_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
self.display_hyperlink_lines(width)
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
plain_lines(self.display_lines(/*width*/ 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,
|
||||
presentation: UserMessagePresentation::Typed,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn new_spoken_user_prompt(message: String) -> UserHistoryCell {
|
||||
let mut cell = new_user_prompt(message, Vec::new(), Vec::new(), Vec::new());
|
||||
cell.presentation = UserMessagePresentation::Spoken;
|
||||
cell
|
||||
}
|
||||
|
||||
/// Retain a completed reasoning block in the expanded transcript only.
|
||||
/// Activity headings belong to the live status row and must not accumulate in scrollback.
|
||||
///
|
||||
/// 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. Part
|
||||
/// boundaries are preserved so standalone empty placeholders can be removed without changing
|
||||
/// literal HTML comments or bold-only summary content.
|
||||
pub(crate) fn new_reasoning_summary_block(
|
||||
reasoning_parts: Vec<String>,
|
||||
cwd: &Path,
|
||||
) -> Box<ReasoningSummaryCell> {
|
||||
let (header, content) = split_reasoning_summary_parts(&reasoning_parts);
|
||||
Box::new(ReasoningSummaryCell::new(
|
||||
header, content, cwd, /*transcript_only*/ true,
|
||||
))
|
||||
}
|
||||
|
||||
/// Split structured reasoning-summary parts into the status header and renderable content.
|
||||
pub(crate) fn split_reasoning_summary_parts(reasoning_parts: &[String]) -> (String, String) {
|
||||
let mut leading_empty_part_header = None;
|
||||
let mut content_parts = Vec::with_capacity(reasoning_parts.len());
|
||||
|
||||
for part in reasoning_parts {
|
||||
let part = part.trim();
|
||||
if part.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let header_end = part.strip_prefix("**").and_then(|after_open| {
|
||||
after_open
|
||||
.find("**")
|
||||
.and_then(|close| (close > 0).then_some(close + 4))
|
||||
});
|
||||
let body = header_end.map_or(part, |header_end| &part[header_end..]);
|
||||
if body.trim() == "<!-- -->" {
|
||||
if content_parts.is_empty()
|
||||
&& leading_empty_part_header.is_none()
|
||||
&& let Some(header_end) = header_end
|
||||
{
|
||||
leading_empty_part_header = Some(part[..header_end].to_string());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
content_parts.push(part);
|
||||
}
|
||||
|
||||
let content = content_parts.join("\n\n");
|
||||
if content.is_empty() {
|
||||
return (leading_empty_part_header.unwrap_or_default(), content);
|
||||
}
|
||||
|
||||
if let Some(after_open) = content.strip_prefix("**")
|
||||
&& let Some(close) = after_open.find("**")
|
||||
{
|
||||
let after_close_idx = 2 + close + 2;
|
||||
let after_close = &content[after_close_idx..];
|
||||
if after_close.starts_with('\n') || after_close.starts_with('\r') {
|
||||
return (
|
||||
content[..after_close_idx].to_string(),
|
||||
after_close.to_string(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
(leading_empty_part_header.unwrap_or_default(), content)
|
||||
}
|
||||
440
codex-rs/tui/src/history_cell/messages_tests.rs
Normal file
440
codex-rs/tui/src/history_cell/messages_tests.rs
Normal file
@@ -0,0 +1,440 @@
|
||||
use super::*;
|
||||
use crate::history_cell::markdown_render_cache::MarkdownRenderCacheKey;
|
||||
use assert_matches::assert_matches;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn typed_prompt_markdown_keeps_the_prompt_gutter_and_links() {
|
||||
let message = "**testing** _hello_ [example documentation](https://example.test/docs)\n\n- Try the command\n\n```sh\necho '*literal*'\n```";
|
||||
let cell = new_user_prompt(message.into(), Vec::new(), Vec::new(), Vec::new());
|
||||
|
||||
let mut snapshots = Vec::new();
|
||||
for width in [64, 20] {
|
||||
let lines = cell.display_hyperlink_lines(width);
|
||||
assert_eq!(lines, cell.transcript_hyperlink_lines(width));
|
||||
assert!(lines.iter().all(|line| line.width() < usize::from(width)));
|
||||
for (text, modifier) in [("testing", Modifier::BOLD), ("hello", Modifier::ITALIC)] {
|
||||
assert!(lines.iter().flat_map(|line| &line.line.spans).any(|span| {
|
||||
span.content == text && span.style.add_modifier.contains(modifier)
|
||||
}));
|
||||
}
|
||||
let linked_text = lines
|
||||
.iter()
|
||||
.flat_map(|line| {
|
||||
line.hyperlinks
|
||||
.iter()
|
||||
.filter(|link| link.destination == "https://example.test/docs")
|
||||
.flat_map(|link| {
|
||||
line.line
|
||||
.to_string()
|
||||
.chars()
|
||||
.skip(link.columns.start)
|
||||
.take(link.columns.len())
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
})
|
||||
.filter(|ch| !ch.is_whitespace())
|
||||
.collect::<String>();
|
||||
assert_eq!(linked_text, "exampledocumentationhttps://example.test/docs");
|
||||
let rendered = ratatui::text::Text::from(visible_lines(lines)).to_string();
|
||||
let rendered = rendered
|
||||
.lines()
|
||||
.map(str::trim_end)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
snapshots.push(format!("width {width}\n{rendered}"));
|
||||
}
|
||||
insta::assert_snapshot!(snapshots.join("\n\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_prompt_urls_keep_destinations_across_widths() {
|
||||
let url = "https://example.test/terminal-link-wrapping/solid-octants";
|
||||
let placeholder = "[Image #1]";
|
||||
let message = format!(
|
||||
"from this site, write out the ascii for solid octants 18 columns {url}\n{placeholder} See (https://example.test/a)."
|
||||
);
|
||||
let image_start = message.find(placeholder).unwrap();
|
||||
let cell = new_user_prompt(
|
||||
message,
|
||||
vec![TextElement::new(
|
||||
(image_start..image_start + placeholder.len()).into(),
|
||||
Some(placeholder.to_string()),
|
||||
)],
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
);
|
||||
let mut snapshots = Vec::new();
|
||||
for width in [120, 60, 24] {
|
||||
let lines = cell.display_hyperlink_lines(width);
|
||||
let transcript = cell.transcript_hyperlink_lines(width);
|
||||
assert_eq!(
|
||||
transcript
|
||||
.into_iter()
|
||||
.map(HyperlinkLine::resolve_span_styles)
|
||||
.collect::<Vec<_>>(),
|
||||
lines
|
||||
);
|
||||
assert!(lines.iter().all(|line| line.width() <= usize::from(width)));
|
||||
for destination in [url, "https://example.test/a"] {
|
||||
let linked_text = lines
|
||||
.iter()
|
||||
.flat_map(|line| {
|
||||
line.hyperlinks
|
||||
.iter()
|
||||
.filter(|link| link.destination == destination)
|
||||
.flat_map(|link| {
|
||||
line.line
|
||||
.to_string()
|
||||
.chars()
|
||||
.skip(link.columns.start)
|
||||
.take(link.columns.len())
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
})
|
||||
.collect::<String>();
|
||||
assert_eq!(linked_text, destination, "width {width}");
|
||||
}
|
||||
snapshots.push(format!(
|
||||
"width {width}\n{}",
|
||||
ratatui::text::Text::from(visible_lines(lines))
|
||||
));
|
||||
}
|
||||
insta::assert_snapshot!(snapshots.join("\n\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_image_only_user_message_remains_visible() {
|
||||
let cell = new_user_prompt(
|
||||
String::new(),
|
||||
Vec::new(),
|
||||
vec![PathBuf::from("fixture.png")],
|
||||
Vec::new(),
|
||||
);
|
||||
let display = cell.display_lines(/*width*/ 40);
|
||||
|
||||
assert_eq!(cell.transcript_lines(/*width*/ 40), display);
|
||||
insta::assert_snapshot!(ratatui::text::Text::from(display));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_image_labels_preserve_existing_placeholders_without_duplicates() {
|
||||
let placeholder = "[Image #2]";
|
||||
let cell = new_user_prompt(
|
||||
format!("{placeholder} **compare** these"),
|
||||
vec![TextElement::new(
|
||||
(0..placeholder.len()).into(),
|
||||
Some(placeholder.to_string()),
|
||||
)],
|
||||
vec![PathBuf::from("one.png"), PathBuf::from("two.png")],
|
||||
vec!["https://example.test/remote.png".to_string()],
|
||||
);
|
||||
|
||||
insta::assert_snapshot!(ratatui::text::Text::from(cell.display_lines(/*width*/ 40)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitizer_borrows_clean_text_and_removes_control_sequences() {
|
||||
for (text, expected) in [
|
||||
("clean\ttext\n", "clean\ttext\n"),
|
||||
("\x07before", "before"),
|
||||
("before\x07", "before"),
|
||||
("\x1b[31mbefore", "before"),
|
||||
("before\x1b[31m", "before"),
|
||||
("before\x1b[31", "before"),
|
||||
("\x07[31m", "[31m"),
|
||||
("\x07", ""),
|
||||
] {
|
||||
assert_matches!(
|
||||
sanitize_user_text(text.into()),
|
||||
Cow::Borrowed(sanitized) => assert_eq!(sanitized, expected)
|
||||
);
|
||||
}
|
||||
assert_matches!(
|
||||
sanitize_user_text("before\x1b[31mafter\x07".into()),
|
||||
Cow::Owned(sanitized) => assert_eq!(sanitized, "beforeafter")
|
||||
);
|
||||
assert_eq!(sanitize_user_text("é\u{85}中".into()), "é中");
|
||||
assert_eq!(sanitize_user_text("before\x1bafter".into()), "beforeafter");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitizer_preserves_owned_buffer_for_clean_and_edge_trimmed_text() {
|
||||
for (text, expected) in [
|
||||
("clean\ttext\n", "clean\ttext\n"),
|
||||
("\x07before", "before"),
|
||||
("before\x07", "before"),
|
||||
("\x07before\x07", "before"),
|
||||
("\x1b[31mbefore", "before"),
|
||||
("before\x1b[31m", "before"),
|
||||
("\x07", ""),
|
||||
] {
|
||||
let owned = text.to_string();
|
||||
let original_pointer = owned.as_ptr();
|
||||
let original_capacity = owned.capacity();
|
||||
|
||||
assert_matches!(sanitize_user_text(owned.into()), Cow::Owned(sanitized) => {
|
||||
assert_eq!(sanitized, expected);
|
||||
assert_eq!(sanitized.as_ptr(), original_pointer);
|
||||
assert_eq!(sanitized.capacity(), original_capacity);
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitizer_preallocates_owned_multi_fragment_text() {
|
||||
let text = "before\x1b[31mafter\x07".to_string();
|
||||
let original_length = text.len();
|
||||
|
||||
assert_matches!(sanitize_user_text(text.into()), Cow::Owned(sanitized) => {
|
||||
assert_eq!(sanitized, "beforeafter");
|
||||
assert!(sanitized.capacity() >= original_length, "{} >= {}", sanitized.capacity(), original_length);
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spoken_user_messages_have_a_red_chevron_without_changing_raw_text() {
|
||||
let message = " hello from voice";
|
||||
let spoken = new_spoken_user_prompt(message.to_string());
|
||||
let typed = new_user_prompt(message.to_string(), Vec::new(), Vec::new(), Vec::new());
|
||||
let marker = spoken
|
||||
.display_hyperlink_lines(/*width*/ 40)
|
||||
.into_iter()
|
||||
.flat_map(|line| line.line.spans)
|
||||
.find(|span| span.content == "› ")
|
||||
.expect("spoken user marker");
|
||||
|
||||
assert!(
|
||||
spoken
|
||||
.display_lines(/*width*/ 40)
|
||||
.iter()
|
||||
.any(|line| line.to_string() == "› hello from voice")
|
||||
);
|
||||
assert_eq!(typed.raw_lines(), vec![Line::from(message)]);
|
||||
assert!(
|
||||
typed
|
||||
.display_lines(/*width*/ 40)
|
||||
.iter()
|
||||
.any(|line| line.to_string() == "› hello from voice")
|
||||
);
|
||||
assert_eq!(marker.style.fg, Some(Color::Red));
|
||||
assert!(marker.style.add_modifier.contains(Modifier::BOLD));
|
||||
assert_eq!(spoken.raw_lines(), vec![Line::from(message)]);
|
||||
assert_eq!(
|
||||
spoken.display_lines_for_mode(/*width*/ 40, HistoryRenderMode::Raw),
|
||||
vec![Line::from(message)]
|
||||
);
|
||||
assert!(typed.display_lines(/*width*/ 40).iter().any(|line| {
|
||||
line.spans
|
||||
.iter()
|
||||
.any(|span| span.content == "› " && span.style.fg != Some(Color::Red))
|
||||
}));
|
||||
|
||||
let area = Rect::new(
|
||||
/*x*/ 0, /*y*/ 0, /*width*/ 40, /*height*/ 3,
|
||||
);
|
||||
let mut buf = Buffer::empty(area);
|
||||
let lines = crate::terminal_palette::with_test_default_colors(/*colors*/ None, || {
|
||||
spoken.display_lines(area.width)
|
||||
});
|
||||
Paragraph::new(lines).render(area, &mut buf);
|
||||
insta::assert_snapshot!("spoken_user_prompt", format!("{buf:?}"));
|
||||
}
|
||||
|
||||
fn replace_cached_lines(
|
||||
cell: &AgentMarkdownCell,
|
||||
update_key: impl FnOnce(&mut MarkdownRenderCacheKey),
|
||||
) {
|
||||
let rendered_lines = cell
|
||||
.rendered_lines
|
||||
.as_ref()
|
||||
.expect("ordinary markdown should be cacheable");
|
||||
let mut rendered_lines = rendered_lines.cached.lock().expect("render cache lock");
|
||||
let (key, lines) = rendered_lines
|
||||
.as_mut()
|
||||
.expect("render cache should be populated");
|
||||
*lines = vec![HyperlinkLine::from("cached")];
|
||||
update_key(key);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finalized_markdown_reuses_rendered_transcript_lines() {
|
||||
let cell = AgentMarkdownCell::new("finalized **markdown**".to_string(), Path::new("/tmp"));
|
||||
let width = 48;
|
||||
|
||||
assert_eq!(
|
||||
visible_lines(cell.transcript_hyperlink_lines(width)),
|
||||
cell.display_lines(width)
|
||||
);
|
||||
replace_cached_lines(&cell, |_| {});
|
||||
|
||||
assert_eq!(
|
||||
visible_lines(cell.transcript_hyperlink_lines(width)),
|
||||
vec![Line::from("cached")]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finalized_assistant_file_citation_renders_as_local_path_snapshot() {
|
||||
let cwd = std::env::temp_dir();
|
||||
let output = cwd.join("Quarterly Report.xlsx").display().to_string();
|
||||
let cell = AgentMarkdownCell::new(
|
||||
format!(
|
||||
r#"Generated :codex-file-citation{{artifact_kind="workbook" path="{output}" purpose="output"}}."#
|
||||
),
|
||||
&cwd,
|
||||
);
|
||||
|
||||
let rendered = ratatui::text::Text::from(cell.display_lines(/*width*/ 80));
|
||||
|
||||
insta::assert_snapshot!(rendered, @"• Generated Quarterly Report.xlsx.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finalized_markdown_cache_misses_when_width_or_render_style_changes() {
|
||||
let cell = AgentMarkdownCell::new("finalized **markdown**".to_string(), Path::new("/tmp"));
|
||||
let width = 48;
|
||||
let expected = cell.display_lines(width);
|
||||
|
||||
replace_cached_lines(&cell, |key| key.width = key.width.saturating_sub(1));
|
||||
assert_eq!(cell.display_lines(width), expected);
|
||||
|
||||
replace_cached_lines(&cell, |key| {
|
||||
key.syntax_theme_revision = key.syntax_theme_revision.wrapping_sub(1);
|
||||
});
|
||||
assert_eq!(cell.display_lines(width), expected);
|
||||
|
||||
replace_cached_lines(&cell, |key| {
|
||||
key.terminal_fg = key
|
||||
.terminal_fg
|
||||
.map_or(Some((1, 2, 3)), |(r, g, b)| Some((r ^ 1, g, b)));
|
||||
});
|
||||
assert_eq!(cell.display_lines(width), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_markdown_bypasses_the_rich_render_cache() {
|
||||
let source = "finalized **markdown**";
|
||||
let cell = AgentMarkdownCell::new(source.to_string(), Path::new("/tmp"));
|
||||
let width = 48;
|
||||
|
||||
cell.display_lines(width);
|
||||
replace_cached_lines(&cell, |_| {});
|
||||
|
||||
assert_eq!(
|
||||
cell.display_lines_for_mode(width, HistoryRenderMode::Raw),
|
||||
vec![Line::from(source)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visualization_directives_are_not_cached() {
|
||||
for markdown in [
|
||||
"::codex-inline-vis{file=\"chart.html\"}",
|
||||
"\u{e200}visualize\u{e202}{\"path\":\"/tmp/chart.html\"}\u{e201}",
|
||||
] {
|
||||
let cell = AgentMarkdownCell::new(markdown.to_string(), Path::new("/tmp"));
|
||||
|
||||
cell.display_lines(/*width*/ 48);
|
||||
|
||||
assert!(cell.rendered_lines.is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spoken_artifacts_link_only_real_workspace_files_and_preserve_existing_urls() {
|
||||
let workspace = tempfile::tempdir().expect("workspace");
|
||||
let source_directory = workspace.path().join("src");
|
||||
std::fs::create_dir(&source_directory).expect("source directory");
|
||||
let source_file = source_directory.join("lib.rs");
|
||||
std::fs::write(&source_file, "fn example() {}\n").expect("source file");
|
||||
let markdown = "中 src/lib.rs:42 and https://example.com";
|
||||
let spoken = AgentMarkdownCell::new_spoken(markdown.to_string(), workspace.path());
|
||||
let lines = spoken.display_hyperlink_lines(/*width*/ 90);
|
||||
let line = &lines[0];
|
||||
|
||||
let expected_destination =
|
||||
url::Url::from_file_path(source_file.canonicalize().expect("canonical source file"))
|
||||
.expect("workspace file URL")
|
||||
.to_string();
|
||||
assert_eq!(
|
||||
line.hyperlinks
|
||||
.iter()
|
||||
.map(|link| (link.columns.clone(), link.destination.as_str()))
|
||||
.collect::<Vec<_>>(),
|
||||
vec![
|
||||
(5..18, expected_destination.as_str()),
|
||||
(23..42, "https://example.com"),
|
||||
]
|
||||
);
|
||||
assert!(line.line.spans.iter().any(|span| {
|
||||
span.content == "src/lib.rs:42" && span.style.add_modifier.contains(Modifier::UNDERLINED)
|
||||
}));
|
||||
assert_eq!(spoken.raw_lines(), vec![Line::from(markdown)]);
|
||||
for width in [90, 24] {
|
||||
for line in spoken.display_hyperlink_lines(width) {
|
||||
let source = line.source.expect("spoken source");
|
||||
assert!(
|
||||
source
|
||||
.styled_range(0..source.text.len())
|
||||
.spans
|
||||
.iter()
|
||||
.any(|span| {
|
||||
span.content == "src/lib.rs:42"
|
||||
&& span.style.add_modifier.contains(Modifier::UNDERLINED)
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
insta::assert_snapshot!(
|
||||
format!(
|
||||
"{}\n{:?} -> <workspace>/src/lib.rs\n{:?} -> https://example.com",
|
||||
line.line, line.hyperlinks[0].columns, line.hyperlinks[1].columns
|
||||
),
|
||||
@r"
|
||||
• 中 src/lib.rs:42 and https://example.com
|
||||
5..18 -> <workspace>/src/lib.rs
|
||||
23..42 -> https://example.com
|
||||
"
|
||||
);
|
||||
|
||||
let ordinary = AgentMarkdownCell::new(markdown.to_string(), workspace.path());
|
||||
assert_eq!(
|
||||
ordinary.display_hyperlink_lines(/*width*/ 90)[0].hyperlinks[0].destination,
|
||||
"https://example.com"
|
||||
);
|
||||
let bare = AgentMarkdownCell::new_spoken("src/lib.rs".to_string(), workspace.path());
|
||||
assert_eq!(
|
||||
bare.display_hyperlink_lines(/*width*/ 40)[0]
|
||||
.hyperlinks
|
||||
.len(),
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spoken_windows_relative_paths_keep_original_text_and_link_the_workspace_file() {
|
||||
let workspace = tempfile::tempdir().expect("workspace");
|
||||
let source_directory = workspace.path().join("src");
|
||||
std::fs::create_dir(&source_directory).expect("source directory");
|
||||
let source_file = source_directory.join("lib.rs");
|
||||
std::fs::write(&source_file, "fn example() {}\n").expect("source file");
|
||||
let markdown = "Updated src\\lib.rs:42";
|
||||
let spoken = AgentMarkdownCell::new_spoken(markdown.to_string(), workspace.path());
|
||||
let lines = spoken.display_hyperlink_lines(/*width*/ 80);
|
||||
let line = &lines[0];
|
||||
|
||||
assert_eq!(spoken.raw_lines(), vec![Line::from(markdown)]);
|
||||
assert_eq!(line.hyperlinks.len(), 1);
|
||||
assert_eq!(line.hyperlinks[0].columns, 10..23);
|
||||
assert_eq!(
|
||||
line.hyperlinks[0].destination,
|
||||
url::Url::from_file_path(source_file.canonicalize().expect("canonical source file"))
|
||||
.expect("workspace file URL")
|
||||
.to_string()
|
||||
);
|
||||
assert!(line.line.spans.iter().any(|span| {
|
||||
span.content == "src\\lib.rs:42" && span.style.add_modifier.contains(Modifier::UNDERLINED)
|
||||
}));
|
||||
insta::assert_snapshot!(line.line.to_string(), @"• Updated src\\lib.rs:42");
|
||||
}
|
||||
390
codex-rs/tui/src/history_cell/mod.rs
Normal file
390
codex-rs/tui/src/history_cell/mod.rs
Normal file
@@ -0,0 +1,390 @@
|
||||
//! 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.
|
||||
|
||||
mod activity_group;
|
||||
pub(crate) use activity_group::ActivityGroup;
|
||||
|
||||
use crate::diff_model::FileChange;
|
||||
use crate::diff_render::create_diff_summary;
|
||||
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::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::terminal_hyperlinks::HyperlinkLine;
|
||||
use crate::terminal_hyperlinks::HyperlinkParagraph;
|
||||
use crate::terminal_hyperlinks::plain_hyperlink_lines;
|
||||
use crate::terminal_hyperlinks::prefix_hyperlink_lines;
|
||||
use crate::terminal_hyperlinks::visible_lines;
|
||||
#[cfg(test)]
|
||||
use crate::test_support::PathBufExt;
|
||||
#[cfg(test)]
|
||||
use crate::test_support::test_path_buf;
|
||||
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 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;
|
||||
#[cfg(test)]
|
||||
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;
|
||||
#[cfg(test)]
|
||||
use codex_utils_cli::format_env_display;
|
||||
use ratatui::prelude::*;
|
||||
#[cfg(test)]
|
||||
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::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
use url::Url;
|
||||
|
||||
const RAW_DIFF_SUMMARY_WIDTH: usize = 10_000;
|
||||
|
||||
mod activity_details;
|
||||
pub(crate) mod activity_preview;
|
||||
mod approvals;
|
||||
mod async_questions;
|
||||
mod async_replies;
|
||||
mod base;
|
||||
mod delegated_message;
|
||||
mod dynamic;
|
||||
mod exec;
|
||||
mod hook_cell;
|
||||
mod markdown_render_cache;
|
||||
mod mcp;
|
||||
mod messages;
|
||||
mod notices;
|
||||
mod patches;
|
||||
mod plans;
|
||||
mod request_user_input;
|
||||
mod search;
|
||||
mod separators;
|
||||
mod session;
|
||||
mod spoken_artifacts;
|
||||
mod startup_warnings;
|
||||
mod warnings;
|
||||
|
||||
pub(crate) use activity_details::ActivityDetails;
|
||||
pub(crate) use activity_preview::ActivityDisclosure;
|
||||
pub(crate) use approvals::*;
|
||||
pub(crate) use base::*;
|
||||
pub(crate) use delegated_message::DelegatedMessageCell;
|
||||
pub(crate) use dynamic::DynamicToolCallCell;
|
||||
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::*;
|
||||
pub(crate) use startup_warnings::StartupWarningsCell;
|
||||
pub(crate) use warnings::WarningEntry;
|
||||
pub(crate) use warnings::WarningHistoryCell;
|
||||
pub(crate) use warnings::WarningId;
|
||||
pub(crate) use warnings::WarningKey;
|
||||
pub(crate) use warnings::warning_count;
|
||||
pub(crate) use warnings::warning_entries;
|
||||
|
||||
#[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 {
|
||||
/// Retain reasoning inside an activity group, or return it for normal insertion.
|
||||
/// Call positions stay fixed as in-flight calls complete; other history cells decline it.
|
||||
fn append_reasoning(&mut self, cell: Box<dyn HistoryCell>) -> Result<(), Box<dyn HistoryCell>> {
|
||||
Err(cell)
|
||||
}
|
||||
|
||||
/// Diagnostics exposed by the warnings picker, retaining their source and full text.
|
||||
fn warning_entries(&self) -> Vec<WarningEntry> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Stable diagnostic identities, independent of rendered wrapping and duplicate delivery.
|
||||
fn warning_keys(&self) -> Vec<WarningKey<'_>> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Original Markdown for semantic copy targets, independent of presentation.
|
||||
fn copy_source(&self) -> Option<&str> {
|
||||
None
|
||||
}
|
||||
|
||||
/// 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>>;
|
||||
|
||||
/// A local artifact the owned fullscreen viewport may preview. Text surfaces ignore it.
|
||||
fn image_path(&self) -> Option<AbsolutePathBuf> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Raw live presentation may omit transcript-only diagnostics without losing their source.
|
||||
fn live_raw_lines(&self) -> Vec<Line<'static>> {
|
||||
self.raw_lines()
|
||||
}
|
||||
|
||||
/// Returns rich visible lines plus terminal hyperlink metadata.
|
||||
fn display_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
plain_hyperlink_lines(self.display_lines(width))
|
||||
}
|
||||
|
||||
/// Compact presentation for the owned transcript, which can reveal details in place.
|
||||
#[allow(dead_code, reason = "Used by later layers of the TUI refresh stack.")]
|
||||
fn compact_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
self.display_hyperlink_lines(width)
|
||||
}
|
||||
|
||||
/// Rich presentation in a viewport that can redraw previously visible rows.
|
||||
fn retained_hyperlink_lines(&self, width: u16, detailed: bool) -> Vec<HyperlinkLine> {
|
||||
if detailed {
|
||||
self.transcript_hyperlink_lines(width)
|
||||
} else {
|
||||
self.compact_hyperlink_lines(width)
|
||||
}
|
||||
}
|
||||
|
||||
/// Stable, namespaced member identities used to retain disclosure across grouping and replay.
|
||||
/// Empty identities indicate ordinary content without a local disclosure control.
|
||||
fn activity_ids(&self) -> Vec<String> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Available activity details, preserving source order and any upstream truncation notices.
|
||||
fn expanded_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
self.transcript_hyperlink_lines(width)
|
||||
}
|
||||
|
||||
/// Details an activity offers beyond its compact presentation, if any.
|
||||
/// Prefer source metadata so collapsed rendering does not materialize hidden content.
|
||||
fn activity_disclosure(&self, _width: u16) -> Option<ActivityDisclosure> {
|
||||
Some(ActivityDisclosure::Generic)
|
||||
}
|
||||
|
||||
fn display_lines_for_mode(&self, width: u16, mode: HistoryRenderMode) -> Vec<Line<'static>> {
|
||||
match mode {
|
||||
HistoryRenderMode::Rich => visible_lines(self.display_hyperlink_lines(width)),
|
||||
HistoryRenderMode::Raw => self.live_raw_lines(),
|
||||
}
|
||||
}
|
||||
|
||||
fn display_hyperlink_lines_for_mode(
|
||||
&self,
|
||||
width: u16,
|
||||
mode: HistoryRenderMode,
|
||||
) -> Vec<HyperlinkLine> {
|
||||
match mode {
|
||||
HistoryRenderMode::Rich => self.display_hyperlink_lines(width),
|
||||
HistoryRenderMode::Raw => plain_hyperlink_lines(self.live_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 transcript-overlay lines plus terminal hyperlink metadata.
|
||||
///
|
||||
/// Defaults to the plain transcript representation because some cells render different
|
||||
/// display and transcript content. Rich cells whose transcript mirrors their display should
|
||||
/// delegate to `display_hyperlink_lines`.
|
||||
fn transcript_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
plain_hyperlink_lines(self.transcript_lines(width))
|
||||
}
|
||||
|
||||
/// Whether the cached transcript layout remains valid across later frames.
|
||||
///
|
||||
/// Cells backed by external state should return `false` so the shared viewport refreshes
|
||||
/// their rendered text and source mapping each frame instead of reusing stale content.
|
||||
fn has_stable_transcript_height(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
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 hyperlink_lines = self.display_hyperlink_lines(area.width);
|
||||
let paragraph = HyperlinkParagraph::new(&hyperlink_lines, Style::default());
|
||||
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).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
|
||||
}
|
||||
}
|
||||
487
codex-rs/tui/src/history_cell/notices.rs
Normal file
487
codex-rs/tui/src/history_cell/notices.rs
Normal file
@@ -0,0 +1,487 @@
|
||||
//! Informational, warning, update, and policy notice history cells.
|
||||
|
||||
use super::*;
|
||||
use crate::style::accent_color;
|
||||
use crate::terminal_hyperlinks::LineWrapPolicy;
|
||||
use crate::terminal_hyperlinks::remap_source_wrapped_line;
|
||||
use crate::wrapping::adaptive_wrap_line_to_width;
|
||||
|
||||
#[cfg_attr(not(test), allow(dead_code))]
|
||||
const RECAP_HEADING: &str = "Conversation recap";
|
||||
|
||||
#[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().fg(accent_color()),
|
||||
" to update."
|
||||
]
|
||||
} else {
|
||||
line![
|
||||
"See ",
|
||||
"https://github.com/openai/codex"
|
||||
.fg(accent_color())
|
||||
.underlined(),
|
||||
" for installation options."
|
||||
]
|
||||
};
|
||||
|
||||
let content = text![
|
||||
line![
|
||||
"✨\u{200A}".bold().fg(accent_color()),
|
||||
"Update available!".bold().fg(accent_color()),
|
||||
" ",
|
||||
format!("{CODEX_CLI_VERSION} -> {}", self.latest_version).bold(),
|
||||
],
|
||||
update_instruction,
|
||||
"",
|
||||
"See full release notes:",
|
||||
"https://github.com/openai/codex/releases/latest"
|
||||
.fg(accent_color())
|
||||
.underlined(),
|
||||
];
|
||||
|
||||
let inner_width = content
|
||||
.width()
|
||||
.min(usize::from(width.saturating_sub(4)))
|
||||
.max(1);
|
||||
let lines = adaptive_wrap_lines(content.lines, RtOptions::new(inner_width));
|
||||
with_border_with_inner_width(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"),
|
||||
]
|
||||
}
|
||||
|
||||
fn display_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
crate::terminal_hyperlinks::annotate_web_urls(self.display_lines(width))
|
||||
}
|
||||
|
||||
fn transcript_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
self.display_hyperlink_lines(width)
|
||||
}
|
||||
}
|
||||
pub(crate) fn new_warning_event(message: String) -> WarningHistoryCell {
|
||||
let style = crate::style::status_style(crate::style::StatusTone::Attention);
|
||||
WarningHistoryCell {
|
||||
server_version_notice: false,
|
||||
visible_in_transcript: false,
|
||||
key: message.clone(),
|
||||
diagnostic: message.clone(),
|
||||
details: PrefixedWrappedHistoryCell::new(
|
||||
message.set_style(style),
|
||||
"⚠ ".set_style(style),
|
||||
" ",
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn new_visible_warning_event(message: String) -> WarningHistoryCell {
|
||||
WarningHistoryCell {
|
||||
visible_in_transcript: true,
|
||||
..new_warning_event(message)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn new_server_version_warning(
|
||||
notice: crate::status::remote_connection::ServerVersionNotice,
|
||||
) -> WarningHistoryCell {
|
||||
let key = notice.message.clone();
|
||||
let style = crate::style::status_style(crate::style::StatusTone::Attention);
|
||||
let mut lines = vec![Line::from(notice.message.set_style(style))];
|
||||
if notice.offer_update {
|
||||
lines.push(Line::from(
|
||||
"Use /daemon to manage the local background server.".fg(accent_color()),
|
||||
));
|
||||
lines.push(Line::from(
|
||||
"Updating may interrupt active or queued work.".set_style(style),
|
||||
));
|
||||
}
|
||||
WarningHistoryCell {
|
||||
server_version_notice: true,
|
||||
visible_in_transcript: false,
|
||||
key,
|
||||
diagnostic: lines
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n"),
|
||||
details: PrefixedWrappedHistoryCell::new(Text::from(lines), "⚠ ".set_style(style), " "),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct SafetyAccessBlockCell {
|
||||
title: &'static str,
|
||||
pub(crate) explanation: Option<String>,
|
||||
body: &'static str,
|
||||
actions: &'static [(&'static str, &'static str)],
|
||||
}
|
||||
|
||||
const SAFETY_ACCESS_BLOCK_LEARN_MORE_URL: &str = "https://help.openai.com/en/articles/20001326";
|
||||
|
||||
pub(crate) fn new_safety_access_block_event() -> SafetyAccessBlockCell {
|
||||
SafetyAccessBlockCell {
|
||||
title: "This content can't be shown",
|
||||
explanation: Some("We take extra caution with requests involving biological research and applications that could pose safety risks.".into()),
|
||||
body: "Eligible researchers can apply for Trusted Access.",
|
||||
actions: &[
|
||||
(
|
||||
"Trusted Access",
|
||||
"https://chatgpt.com/r/b749fb02595e04c3007a54375f3f4374",
|
||||
),
|
||||
("Learn more", SAFETY_ACCESS_BLOCK_LEARN_MORE_URL),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn new_cyber_policy_error_event(
|
||||
notice: crate::daybreak::Notice,
|
||||
) -> SafetyAccessBlockCell {
|
||||
use crate::daybreak::Notice;
|
||||
let (body, actions): (_, &'static [(&str, &str)]) = match notice {
|
||||
Notice::Apply => (
|
||||
"If you’re doing authorized security work, apply for Daybreak to get broader access.",
|
||||
&[
|
||||
("Learn more", SAFETY_ACCESS_BLOCK_LEARN_MORE_URL),
|
||||
(
|
||||
"Apply for Daybreak",
|
||||
"https://openai.com/form/enterprise-trusted-access-for-cyber/",
|
||||
),
|
||||
],
|
||||
),
|
||||
Notice::Disabled => (
|
||||
"Daybreak is currently off. If you’re doing authorized security work, turn it on and try your request again.",
|
||||
&[("Learn more", SAFETY_ACCESS_BLOCK_LEARN_MORE_URL)],
|
||||
),
|
||||
Notice::Astra => (
|
||||
"Daybreak isn’t available for Astra. Some cybersecurity requests may still be limited.",
|
||||
&[("Learn more", SAFETY_ACCESS_BLOCK_LEARN_MORE_URL)],
|
||||
),
|
||||
Notice::Enabled => (
|
||||
"Some cybersecurity requests are still limited, even when Daybreak is on.",
|
||||
&[("Learn more", SAFETY_ACCESS_BLOCK_LEARN_MORE_URL)],
|
||||
),
|
||||
};
|
||||
SafetyAccessBlockCell {
|
||||
title: "This content can’t be shown",
|
||||
explanation: (notice == Notice::Apply)
|
||||
.then(|| "We take extra care with some cybersecurity requests.".into()),
|
||||
body,
|
||||
actions,
|
||||
}
|
||||
}
|
||||
|
||||
impl SafetyAccessBlockCell {
|
||||
fn message(&self) -> String {
|
||||
match &self.explanation {
|
||||
Some(explanation) => format!("{explanation} {}", self.body),
|
||||
None => self.body.to_owned(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryCell for SafetyAccessBlockCell {
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
visible_lines(self.display_hyperlink_lines(width))
|
||||
}
|
||||
|
||||
fn display_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
let mut lines = vec![HyperlinkLine::new(
|
||||
vec!["ⓘ ".fg(accent_color()), self.title.bold()].into(),
|
||||
)];
|
||||
let body = Line::from(vec![" ".into(), self.message().dim()]);
|
||||
let wrap_width = width.saturating_sub(2).max(1) as usize;
|
||||
let wrapped = adaptive_wrap_line(
|
||||
&body,
|
||||
RtOptions::new(wrap_width).subsequent_indent(" ".into()),
|
||||
);
|
||||
let mut wrapped_body = Vec::new();
|
||||
push_owned_lines(&wrapped, &mut wrapped_body);
|
||||
lines.extend(plain_hyperlink_lines(wrapped_body));
|
||||
|
||||
for &(label, url) in self.actions {
|
||||
let source = crate::terminal_hyperlinks::annotate_web_urls_in_line(
|
||||
vec![
|
||||
format!(" {label}: ").dim(),
|
||||
url.fg(accent_color()).underlined(),
|
||||
]
|
||||
.into(),
|
||||
);
|
||||
let wrapped = crate::wrapping::word_wrap_line(
|
||||
&source.line,
|
||||
RtOptions::new(wrap_width).subsequent_indent(" ".into()),
|
||||
);
|
||||
let mut wrapped_links = Vec::new();
|
||||
push_owned_lines(&wrapped, &mut wrapped_links);
|
||||
lines.extend(crate::terminal_hyperlinks::remap_wrapped_line(
|
||||
&source,
|
||||
wrapped_links,
|
||||
));
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
let mut lines = vec![Line::from(self.title), Line::from(self.message())];
|
||||
lines.extend(
|
||||
self.actions
|
||||
.iter()
|
||||
.map(|(label, target)| Line::from(format!("{label}: {target}"))),
|
||||
);
|
||||
lines
|
||||
}
|
||||
|
||||
fn transcript_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
self.display_hyperlink_lines(width)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Eq, PartialEq)]
|
||||
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 warning_entries(&self) -> Vec<WarningEntry> {
|
||||
vec![WarningEntry {
|
||||
id: WarningId::Message(self.summary.clone()),
|
||||
source: "Deprecation".into(),
|
||||
details: self
|
||||
.raw_lines()
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n"),
|
||||
}]
|
||||
}
|
||||
|
||||
fn live_raw_lines(&self) -> Vec<Line<'static>> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
fn display_lines(&self, _width: u16) -> Vec<Line<'static>> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
fn warning_keys(&self) -> Vec<WarningKey<'_>> {
|
||||
vec![WarningKey::Message(&self.summary)]
|
||||
}
|
||||
|
||||
fn transcript_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 }
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ThreadRecapLoadingCell {
|
||||
start_time: Instant,
|
||||
animations_enabled: bool,
|
||||
}
|
||||
|
||||
impl ThreadRecapLoadingCell {
|
||||
pub(crate) fn new(animations_enabled: bool) -> Self {
|
||||
Self {
|
||||
start_time: Instant::now(),
|
||||
animations_enabled,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryCell for ThreadRecapLoadingCell {
|
||||
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(),
|
||||
"Generating conversation recap".bold(),
|
||||
"…".dim(),
|
||||
]
|
||||
.into(),
|
||||
]
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
vec![Line::from("Generating conversation recap...")]
|
||||
}
|
||||
|
||||
fn transcript_animation_tick(&self) -> Option<u64> {
|
||||
if !self.animations_enabled {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some((self.start_time.elapsed().as_millis() / 50) as u64)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(not(test), allow(dead_code))]
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ThreadRecapHistoryCell {
|
||||
recap: String,
|
||||
next_action: Option<String>,
|
||||
}
|
||||
|
||||
#[cfg_attr(not(test), allow(dead_code))]
|
||||
impl ThreadRecapHistoryCell {
|
||||
pub(crate) fn new(recap: String) -> Self {
|
||||
Self {
|
||||
recap,
|
||||
next_action: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn with_next_action(mut self, next_action: Option<String>) -> Self {
|
||||
self.next_action = next_action;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryCell for ThreadRecapHistoryCell {
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
visible_lines(self.display_hyperlink_lines(width))
|
||||
}
|
||||
|
||||
fn display_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
if width == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let wrap_width = usize::from(width.saturating_sub(/*rhs*/ 2).max(/*other*/ 1));
|
||||
let mut body = raw_lines_from_source(&self.recap);
|
||||
if let Some(action) = &self.next_action {
|
||||
body.extend(prefix_lines(
|
||||
raw_lines_from_source(action),
|
||||
"Next: ".bold().fg(accent_color()),
|
||||
"".into(),
|
||||
));
|
||||
}
|
||||
let mut body = body.into_iter().map(Line::italic).collect::<Vec<_>>();
|
||||
let prefix = Line::from(vec![" ".into(), "↳ ".dim(), "Recap: ".bold()]).italic();
|
||||
let mut options = if wrap_width <= prefix.width() {
|
||||
// Keep the text readable when the terminal cannot fit the hanging indent.
|
||||
body.insert(
|
||||
/*index*/ 0,
|
||||
Line::from(vec!["↳ ".dim(), "Recap:".bold()]).italic(),
|
||||
);
|
||||
RtOptions::new(wrap_width)
|
||||
} else {
|
||||
RtOptions::new(wrap_width)
|
||||
.subsequent_indent(" ".repeat(prefix.width()).into())
|
||||
.initial_indent(prefix)
|
||||
};
|
||||
let mut lines = Vec::new();
|
||||
for line in body {
|
||||
let line = HyperlinkLine::new(line);
|
||||
let mut wrapped = remap_source_wrapped_line(
|
||||
&line,
|
||||
adaptive_wrap_line_to_width(&line.line, options.clone()),
|
||||
);
|
||||
for source in wrapped.iter_mut().filter_map(|line| line.source.as_mut()) {
|
||||
source.wrap_policy = LineWrapPolicy::UrlAware;
|
||||
source.continuation_indent = options.subsequent_indent.clone();
|
||||
source.right_reserve = 2;
|
||||
}
|
||||
lines.extend(wrapped);
|
||||
options.initial_indent = options.subsequent_indent.clone();
|
||||
}
|
||||
for line in &mut lines {
|
||||
let style = line.line.style.dim();
|
||||
*line = std::mem::take(line).style(style);
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
fn transcript_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
self.display_hyperlink_lines(width)
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
let mut lines = vec![Line::from(RECAP_HEADING)];
|
||||
lines.extend(raw_lines_from_source(&self.recap));
|
||||
if let Some(action) = &self.next_action {
|
||||
lines.extend(raw_lines_from_source(&format!("Next: {action}")));
|
||||
}
|
||||
lines
|
||||
}
|
||||
}
|
||||
299
codex-rs/tui/src/history_cell/patches.rs
Normal file
299
codex-rs/tui/src/history_cell/patches.rs
Normal file
@@ -0,0 +1,299 @@
|
||||
//! Patch summaries and image-tool transcript helpers.
|
||||
|
||||
use super::*;
|
||||
use crate::line_truncation::truncate_line_with_ellipsis_if_overflow;
|
||||
use crate::terminal_hyperlinks::TerminalHyperlink;
|
||||
use crate::terminal_hyperlinks::adaptive_wrap_hyperlink_lines;
|
||||
use codex_ansi_escape::ansi_escape;
|
||||
use codex_utils_path_uri::LegacyAppPathString;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "patches_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct PatchHistoryCell {
|
||||
activity_id: String,
|
||||
changes: HashMap<PathBuf, FileChange>,
|
||||
cwd: PathBuf,
|
||||
}
|
||||
|
||||
impl PatchHistoryCell {
|
||||
pub(crate) fn with_activity_id(mut self, id: String) -> Self {
|
||||
self.activity_id = format!("patch:{id}");
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryCell for PatchHistoryCell {
|
||||
fn activity_ids(&self) -> Vec<String> {
|
||||
vec![self.activity_id.clone()]
|
||||
}
|
||||
|
||||
fn compact_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
crate::diff_render::create_diff_preview_with_links(
|
||||
&self.changes,
|
||||
&self.cwd,
|
||||
usize::from(width),
|
||||
super::activity_preview::DETAIL_PREVIEW_LINES,
|
||||
)
|
||||
}
|
||||
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
visible_lines(self.display_hyperlink_lines(width))
|
||||
}
|
||||
|
||||
fn display_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
crate::diff_render::create_diff_summary_with_links(
|
||||
&self.changes,
|
||||
&self.cwd,
|
||||
usize::from(width),
|
||||
)
|
||||
}
|
||||
|
||||
fn transcript_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
self.display_hyperlink_lines(width)
|
||||
}
|
||||
|
||||
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 {
|
||||
activity_id: format!("patch:{}", uuid::Uuid::new_v4()),
|
||||
changes,
|
||||
cwd: cwd.to_path_buf(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn new_patch_apply_failure(stderr: String) -> PatchFailureCell {
|
||||
PatchFailureCell {
|
||||
activity_id: format!("patch-failure:{}", uuid::Uuid::new_v4()),
|
||||
stderr,
|
||||
}
|
||||
}
|
||||
|
||||
/// Failed patch attempts retain available diagnostics for local disclosure and full transcript.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct PatchFailureCell {
|
||||
activity_id: String,
|
||||
stderr: String,
|
||||
}
|
||||
|
||||
impl HistoryCell for PatchFailureCell {
|
||||
fn activity_ids(&self) -> Vec<String> {
|
||||
vec![self.activity_id.clone()]
|
||||
}
|
||||
|
||||
fn compact_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
let mut lines = self.transcript_hyperlink_lines(width);
|
||||
lines.truncate(1 + super::activity_preview::DETAIL_PREVIEW_LINES);
|
||||
lines
|
||||
.into_iter()
|
||||
.map(|line| super::activity_preview::clipped_line(line.line, width))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn transcript_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
let mut lines = vec![Line::from("✘ Failed to apply patch".magenta().bold()).into()];
|
||||
let error = if self.stderr.trim().is_empty() {
|
||||
"(error details unavailable)"
|
||||
} else {
|
||||
&self.stderr
|
||||
};
|
||||
let mut diagnostics = ansi_escape(&error.replace('\t', " ")).lines;
|
||||
for line in &mut diagnostics {
|
||||
for span in &mut line.spans {
|
||||
span.style = span.style.add_modifier(Modifier::DIM);
|
||||
}
|
||||
}
|
||||
lines.extend(crate::terminal_hyperlinks::adaptive_wrap_hyperlink_lines(
|
||||
&plain_hyperlink_lines(diagnostics),
|
||||
RtOptions::new(usize::from(width).max(/*other*/ 1))
|
||||
.initial_indent(" └ ".dim().into())
|
||||
.subsequent_indent(" ".into()),
|
||||
));
|
||||
lines
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
let mut lines = vec![Line::from("Failed to apply patch")];
|
||||
lines.extend(plain_lines(ansi_escape(&self.stderr).lines));
|
||||
lines
|
||||
}
|
||||
|
||||
fn display_lines(&self, _width: u16) -> Vec<Line<'static>> {
|
||||
let mut lines: Vec<Line<'static>> = Vec::new();
|
||||
|
||||
// Failure title
|
||||
lines.push(Line::from("✘ Failed to apply patch".magenta().bold()));
|
||||
|
||||
if !self.stderr.trim().is_empty() {
|
||||
let output = output_lines(
|
||||
Some(&CommandOutput::new(
|
||||
/*exit_code*/ 1,
|
||||
self.stderr.clone(),
|
||||
)),
|
||||
OutputLinesParams {
|
||||
line_limit: TOOL_CALL_MAX_LINES,
|
||||
only_err: true,
|
||||
include_angle_pipe: true,
|
||||
include_prefix: true,
|
||||
},
|
||||
);
|
||||
lines.extend(output.lines);
|
||||
}
|
||||
|
||||
lines
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ViewImageHistoryCell {
|
||||
activity_id: String,
|
||||
filename: String,
|
||||
path_label: String,
|
||||
link: Option<TerminalHyperlink>,
|
||||
}
|
||||
|
||||
impl ViewImageHistoryCell {
|
||||
pub(crate) fn link_local_image(&mut self) {
|
||||
let start = "Viewed image ".len();
|
||||
let end = start + crate::width::display_width(&self.path_label);
|
||||
self.link = self
|
||||
.image_path()
|
||||
.and_then(|path| TerminalHyperlink::viewed_image(start..end, path.as_path()));
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryCell for ViewImageHistoryCell {
|
||||
fn activity_ids(&self) -> Vec<String> {
|
||||
vec![self.activity_id.clone()]
|
||||
}
|
||||
|
||||
fn image_path(&self) -> Option<AbsolutePathBuf> {
|
||||
LegacyAppPathString::from_string(self.path_label.clone()).to_inferred_abs_path()
|
||||
}
|
||||
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
let line = vec![
|
||||
"• ".dim(),
|
||||
"Viewed image ".bold(),
|
||||
self.filename.replace(['\n', '\r', '\t'], " ").dim(),
|
||||
]
|
||||
.into();
|
||||
vec![truncate_line_with_ellipsis_if_overflow(
|
||||
line,
|
||||
width as usize,
|
||||
)]
|
||||
}
|
||||
|
||||
fn display_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
let mut lines = plain_hyperlink_lines(self.display_lines(width));
|
||||
if let ([line], Some(link)) = (lines.as_mut_slice(), &self.link) {
|
||||
let start = crate::width::display_width("• Viewed image ");
|
||||
if start < line.width() {
|
||||
line.hyperlinks.push(link.with_columns(start..line.width()));
|
||||
}
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
fn transcript_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
visible_lines(self.transcript_hyperlink_lines(width))
|
||||
}
|
||||
|
||||
fn transcript_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
if width == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut line = HyperlinkLine::new(Line::from(vec![
|
||||
"Viewed image ".bold(),
|
||||
self.path_label.clone().dim(),
|
||||
]));
|
||||
line.hyperlinks.extend(self.link.iter().cloned());
|
||||
adaptive_wrap_hyperlink_lines(
|
||||
&[line],
|
||||
RtOptions::new(usize::from(width))
|
||||
.initial_indent("• ".dim().into())
|
||||
.subsequent_indent(" ".into()),
|
||||
)
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
vec![Line::from(format!("Viewed image {}", self.path_label))]
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn new_view_image_tool_call(
|
||||
id: String,
|
||||
path: LegacyAppPathString,
|
||||
) -> ViewImageHistoryCell {
|
||||
let filename = path
|
||||
.to_inferred_path_uri()
|
||||
.and_then(|path| path.basename())
|
||||
.unwrap_or_else(|| path.render_for_ui());
|
||||
ViewImageHistoryCell {
|
||||
activity_id: format!("image-view:{id}"),
|
||||
filename,
|
||||
path_label: path.into_string(),
|
||||
link: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn new_image_generation_call(
|
||||
call_id: String,
|
||||
status: &str,
|
||||
revised_prompt: Option<String>,
|
||||
saved_path: Option<AbsolutePathBuf>,
|
||||
) -> ImageGenerationHistoryCell {
|
||||
let detail = revised_prompt.unwrap_or(call_id);
|
||||
let heading = if status == "failed" {
|
||||
vec!["✗ ".red().bold(), "Image generation failed".bold()].into()
|
||||
} else {
|
||||
vec!["• ".dim(), "Generated Image:".bold()].into()
|
||||
};
|
||||
let mut lines: Vec<Line<'static>> = vec![heading, 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());
|
||||
}
|
||||
|
||||
ImageGenerationHistoryCell {
|
||||
lines,
|
||||
saved_path: saved_path.filter(|_| status != "failed"),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ImageGenerationHistoryCell {
|
||||
lines: Vec<Line<'static>>,
|
||||
saved_path: Option<AbsolutePathBuf>,
|
||||
}
|
||||
|
||||
impl HistoryCell for ImageGenerationHistoryCell {
|
||||
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 image_path(&self) -> Option<AbsolutePathBuf> {
|
||||
self.saved_path.clone()
|
||||
}
|
||||
}
|
||||
107
codex-rs/tui/src/history_cell/patches_tests.rs
Normal file
107
codex-rs/tui/src/history_cell/patches_tests.rs
Normal file
@@ -0,0 +1,107 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn compact_patches_retain_full_changes_and_failure_details() {
|
||||
let patch = new_patch_event(
|
||||
HashMap::from([
|
||||
(
|
||||
PathBuf::from("new.txt"),
|
||||
FileChange::Add {
|
||||
content: "one\ntwo\nthree\nfour\nfive\n".into(),
|
||||
},
|
||||
),
|
||||
(
|
||||
PathBuf::from("existing.txt"),
|
||||
FileChange::Update {
|
||||
unified_diff: "@@ -1,3 +1,3 @@\n context\n-before\n+after\n tail\n".into(),
|
||||
move_path: None,
|
||||
},
|
||||
),
|
||||
]),
|
||||
Path::new("."),
|
||||
);
|
||||
let failure = new_patch_apply_failure("first\nsecond\nthird\nfourth diagnostic".into());
|
||||
let missing = new_patch_apply_failure(String::new());
|
||||
let mut snapshots = Vec::new();
|
||||
for (label, cell) in [
|
||||
("patch", &patch as &dyn HistoryCell),
|
||||
("failure", &failure),
|
||||
("missing diagnostics", &missing),
|
||||
] {
|
||||
let compact = visible_lines(cell.compact_hyperlink_lines(/*width*/ 40));
|
||||
let full = visible_lines(cell.transcript_hyperlink_lines(/*width*/ 40));
|
||||
snapshots.push(format!(
|
||||
"{label}\nCompact\n{}\nFull\n{}",
|
||||
Text::from(compact),
|
||||
Text::from(full)
|
||||
));
|
||||
}
|
||||
insta::assert_snapshot!(snapshots.join("\n\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn viewed_image_retains_original_path_in_details() {
|
||||
for path in [
|
||||
"/workspace/assets/example.png",
|
||||
r"C:\workspace\assets\example.png",
|
||||
] {
|
||||
let cell =
|
||||
new_view_image_tool_call("view".to_string(), LegacyAppPathString::from_string(path));
|
||||
assert_eq!(
|
||||
cell.display_lines(/*width*/ 80)
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["• Viewed image example.png"]
|
||||
);
|
||||
assert_eq!(
|
||||
cell.raw_lines(),
|
||||
vec![Line::from(format!("Viewed image {path}"))]
|
||||
);
|
||||
assert_eq!(
|
||||
cell.transcript_lines(/*width*/ 200)
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![format!("• Viewed image {path}")]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn viewed_image_narrow_summary() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("very-long-screenshot #5.png");
|
||||
image::RgbaImage::new(1, 1).save(&path).unwrap();
|
||||
let url = Url::from_file_path(path.canonicalize().unwrap()).unwrap();
|
||||
let mut cell = new_view_image_tool_call("view".into(), LegacyAppPathString::from_path(&path));
|
||||
cell.link_local_image();
|
||||
let compact = cell.compact_hyperlink_lines(/*width*/ 32);
|
||||
let expanded = cell.expanded_hyperlink_lines(u16::MAX);
|
||||
for row in [&compact[0], &expanded[0]] {
|
||||
let [link] = row.hyperlinks.as_slice() else {
|
||||
panic!("expected one image link")
|
||||
};
|
||||
assert_eq!(
|
||||
(link.columns.clone(), link.terminal_destination()),
|
||||
(15..row.width(), Some(url.to_string()))
|
||||
);
|
||||
}
|
||||
insta::assert_snapshot!(compact[0].line.to_string());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_patch_keeps_diagnostics_beyond_the_legacy_preview() {
|
||||
let diagnostics = (1..=12)
|
||||
.map(|line| format!("diagnostic line {line}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
let cell = new_patch_apply_failure(diagnostics.clone());
|
||||
assert_eq!(
|
||||
cell.raw_lines(),
|
||||
std::iter::once(Line::from("Failed to apply patch"))
|
||||
.chain(diagnostics.lines().map(|line| Line::from(line.to_owned())))
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
395
codex-rs/tui/src/history_cell/plans.rs
Normal file
395
codex-rs/tui/src/history_cell/plans.rs
Normal file
@@ -0,0 +1,395 @@
|
||||
//! Proposed-plan and plan-update history cells, including foreground contrast on the plan fill.
|
||||
|
||||
use super::markdown_render_cache::MarkdownRenderCache;
|
||||
use super::*;
|
||||
use crate::style::accent_color;
|
||||
use crate::terminal_hyperlinks::lines_with_sources_eq;
|
||||
|
||||
/// Apply the plan surface after Markdown layout, keeping retained reflow styles in sync.
|
||||
pub(crate) fn style_proposed_plan_line(
|
||||
mut line: HyperlinkLine,
|
||||
plan_style: Style,
|
||||
) -> HyperlinkLine {
|
||||
if plan_style.bg.is_none() {
|
||||
return line.style(plan_style);
|
||||
}
|
||||
let adapt = |mut style: Style, background| {
|
||||
style.fg = style
|
||||
.fg
|
||||
.map(|foreground| crate::style::readable_color_on(foreground, style.bg.or(background)));
|
||||
style
|
||||
};
|
||||
line.line.style = adapt(line.line.style.patch(plan_style), plan_style.bg);
|
||||
for span in &mut line.line.spans {
|
||||
span.style = adapt(span.style, line.line.style.bg);
|
||||
}
|
||||
if let Some(source) = &mut line.source {
|
||||
source.line_style = adapt(source.line_style.patch(plan_style), plan_style.bg);
|
||||
source.span_style = adapt(source.span_style, source.line_style.bg);
|
||||
for (_, style) in std::sync::Arc::make_mut(&mut source.styles) {
|
||||
*style = adapt(*style, source.span_style.bg.or(source.line_style.bg));
|
||||
}
|
||||
}
|
||||
line
|
||||
}
|
||||
|
||||
/// 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, Eq)]
|
||||
pub(crate) struct StreamingPlanTailCell {
|
||||
lines: Vec<HyperlinkLine>,
|
||||
is_stream_continuation: bool,
|
||||
}
|
||||
|
||||
impl PartialEq for StreamingPlanTailCell {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.is_stream_continuation == other.is_stream_continuation
|
||||
&& lines_with_sources_eq(&self.lines, &other.lines)
|
||||
}
|
||||
}
|
||||
|
||||
impl StreamingPlanTailCell {
|
||||
pub(crate) fn new(lines: Vec<HyperlinkLine>, is_stream_continuation: bool) -> Self {
|
||||
Self {
|
||||
lines,
|
||||
is_stream_continuation,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryCell for StreamingPlanTailCell {
|
||||
fn display_lines(&self, _width: u16) -> Vec<Line<'static>> {
|
||||
visible_lines(self.lines.clone())
|
||||
}
|
||||
|
||||
fn display_hyperlink_lines(&self, _width: u16) -> Vec<HyperlinkLine> {
|
||||
self.lines.clone()
|
||||
}
|
||||
|
||||
fn transcript_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
self.display_hyperlink_lines(width)
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
plain_lines(visible_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 {
|
||||
activity_id: format!("plan:{}", uuid::Uuid::new_v4()),
|
||||
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(),
|
||||
rendered_lines: MarkdownRenderCache::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<impl Into<HyperlinkLine>>,
|
||||
is_stream_continuation: bool,
|
||||
) -> ProposedPlanStreamCell {
|
||||
ProposedPlanStreamCell {
|
||||
lines: lines.into_iter().map(Into::into).collect(),
|
||||
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,
|
||||
rendered_lines: MarkdownRenderCache,
|
||||
}
|
||||
|
||||
/// 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<HyperlinkLine>,
|
||||
is_stream_continuation: bool,
|
||||
}
|
||||
|
||||
impl ProposedPlanCell {
|
||||
fn render_lines(
|
||||
&self,
|
||||
width: u16,
|
||||
list_spacing: crate::markdown_render::ListSpacing,
|
||||
) -> Vec<HyperlinkLine> {
|
||||
self.rendered_lines.render(width, list_spacing, || {
|
||||
let mut lines = vec![
|
||||
HyperlinkLine::new(vec!["• ".dim(), "Proposed Plan".bold()].into()),
|
||||
HyperlinkLine::new(Line::from(" ")),
|
||||
];
|
||||
|
||||
let mut plan_lines = vec![HyperlinkLine::new(Line::from(" "))];
|
||||
let plan_style = proposed_plan_style();
|
||||
let wrap_width = width.saturating_sub(4).max(1) as usize;
|
||||
let mut body = crate::markdown::render_markdown_agent_with_list_spacing(
|
||||
&self.plan_markdown,
|
||||
Some(wrap_width),
|
||||
Some(self.cwd.as_path()),
|
||||
/*inline_visualization_context*/ None,
|
||||
list_spacing,
|
||||
);
|
||||
if body.is_empty() {
|
||||
body.push(HyperlinkLine::new(Line::from("(empty)".dim().italic())));
|
||||
}
|
||||
plan_lines.extend(prefix_hyperlink_lines(body, " ".into(), " ".into()));
|
||||
plan_lines.push(HyperlinkLine::new(Line::from(" ")));
|
||||
|
||||
lines.extend(
|
||||
plan_lines
|
||||
.into_iter()
|
||||
.map(|line| style_proposed_plan_line(line, plan_style)),
|
||||
);
|
||||
lines
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryCell for ProposedPlanCell {
|
||||
fn copy_source(&self) -> Option<&str> {
|
||||
Some(&self.plan_markdown)
|
||||
}
|
||||
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
visible_lines(self.display_hyperlink_lines(width))
|
||||
}
|
||||
|
||||
fn display_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
self.render_lines(width, crate::markdown_render::ListSpacing::AfterMultiline)
|
||||
}
|
||||
|
||||
fn retained_hyperlink_lines(&self, width: u16, _detailed: bool) -> Vec<HyperlinkLine> {
|
||||
self.render_lines(width, crate::markdown_render::ListSpacing::Uniform)
|
||||
}
|
||||
|
||||
fn transcript_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
self.display_hyperlink_lines(width)
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
raw_lines_from_source(&self.plan_markdown)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "plans_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
impl HistoryCell for ProposedPlanStreamCell {
|
||||
fn display_lines(&self, _width: u16) -> Vec<Line<'static>> {
|
||||
visible_lines(self.lines.clone())
|
||||
}
|
||||
|
||||
fn display_hyperlink_lines(&self, _width: u16) -> Vec<HyperlinkLine> {
|
||||
self.lines.clone()
|
||||
}
|
||||
|
||||
fn transcript_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
self.display_hyperlink_lines(width)
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
plain_lines(visible_lines(self.lines.clone()))
|
||||
}
|
||||
|
||||
fn is_stream_continuation(&self) -> bool {
|
||||
self.is_stream_continuation
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct PlanUpdateCell {
|
||||
activity_id: String,
|
||||
explanation: Option<String>,
|
||||
plan: Vec<PlanItemArg>,
|
||||
}
|
||||
|
||||
impl HistoryCell for PlanUpdateCell {
|
||||
fn activity_ids(&self) -> Vec<String> {
|
||||
vec![self.activity_id.clone()]
|
||||
}
|
||||
|
||||
fn activity_disclosure(&self, width: u16) -> Option<super::ActivityDisclosure> {
|
||||
(self
|
||||
.explanation
|
||||
.as_ref()
|
||||
.is_some_and(|explanation| !explanation.trim().is_empty())
|
||||
|| self.plan.len() > super::activity_preview::DETAIL_PREVIEW_LINES
|
||||
|| self.plan.iter().any(|item| {
|
||||
let step = item.step.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
// The compact row reserves four columns for indentation and two for its marker.
|
||||
Line::from(step).width() + 6 > usize::from(width)
|
||||
}))
|
||||
.then_some(super::ActivityDisclosure::Generic)
|
||||
}
|
||||
|
||||
fn compact_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
use super::activity_preview::DETAIL_PREVIEW_LINES;
|
||||
use super::activity_preview::clipped_line;
|
||||
|
||||
let completed = self
|
||||
.plan
|
||||
.iter()
|
||||
.filter(|item| matches!(item.status, StepStatus::Completed))
|
||||
.count();
|
||||
let total = self.plan.len();
|
||||
let mut lines = vec![clipped_line(
|
||||
Line::from(vec![
|
||||
"• ".dim(),
|
||||
"Updated Plan".bold(),
|
||||
format!(" · {completed}/{total} complete").dim(),
|
||||
]),
|
||||
width,
|
||||
)];
|
||||
let mut steps: Vec<_> = self.plan.iter().collect();
|
||||
steps.sort_by_key(|item| match item.status {
|
||||
StepStatus::InProgress => 0,
|
||||
StepStatus::Pending => 1,
|
||||
StepStatus::Completed => 2,
|
||||
});
|
||||
for (index, item) in steps.into_iter().take(DETAIL_PREVIEW_LINES).enumerate() {
|
||||
let (marker, style) = match item.status {
|
||||
StepStatus::Completed => ("✔ ", Style::default().crossed_out().dim()),
|
||||
StepStatus::InProgress => ("□ ", Style::default().fg(accent_color()).bold()),
|
||||
StepStatus::Pending => ("□ ", Style::default().dim()),
|
||||
};
|
||||
let step = item.step.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
lines.push(clipped_line(
|
||||
Line::from(vec![
|
||||
if index == 0 { " └ " } else { " " }.dim(),
|
||||
marker.set_style(style),
|
||||
step.set_style(style),
|
||||
]),
|
||||
width,
|
||||
));
|
||||
}
|
||||
if self.plan.is_empty() {
|
||||
lines.push(clipped_line(
|
||||
Line::from(" └ (no steps provided)".dim()),
|
||||
width,
|
||||
));
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
visible_lines(self.display_hyperlink_lines(width))
|
||||
}
|
||||
|
||||
fn display_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
let render_note = |text: &str| -> Vec<HyperlinkLine> {
|
||||
let wrap_width = width.saturating_sub(4).max(1) as usize;
|
||||
let note = HyperlinkLine::new(Line::from(text.to_string().dim().italic()));
|
||||
crate::terminal_hyperlinks::adaptive_wrap_hyperlink_lines(
|
||||
&[note],
|
||||
RtOptions::new(wrap_width),
|
||||
)
|
||||
};
|
||||
|
||||
let render_step = |status: &StepStatus, text: &str| -> Vec<HyperlinkLine> {
|
||||
let (box_str, step_style) = match status {
|
||||
StepStatus::Completed => ("✔ ", Style::default().crossed_out().dim()),
|
||||
StepStatus::InProgress => ("□ ", Style::default().fg(accent_color()).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 = HyperlinkLine::new(Line::from(text.to_string().set_style(step_style)));
|
||||
let mut wrapped =
|
||||
crate::terminal_hyperlinks::adaptive_wrap_hyperlink_lines(&[step], opts);
|
||||
crate::terminal_hyperlinks::retain_initial_prefix(&mut wrapped, box_str);
|
||||
wrapped
|
||||
};
|
||||
|
||||
let mut lines = vec![HyperlinkLine::new(
|
||||
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(HyperlinkLine::new(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_hyperlink_lines(
|
||||
indented_lines,
|
||||
" └ ".dim(),
|
||||
" ".into(),
|
||||
));
|
||||
|
||||
lines
|
||||
}
|
||||
|
||||
fn transcript_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
self.display_hyperlink_lines(width)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
41
codex-rs/tui/src/history_cell/plans_tests.rs
Normal file
41
codex-rs/tui/src/history_cell/plans_tests.rs
Normal file
@@ -0,0 +1,41 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn finalized_plan_reuses_rendered_transcript_lines() {
|
||||
let cell = new_proposed_plan("1. Inspect **markdown**".to_string(), Path::new("/tmp"));
|
||||
let width = 48;
|
||||
|
||||
assert_eq!(
|
||||
visible_lines(cell.transcript_hyperlink_lines(width)),
|
||||
cell.display_lines(width)
|
||||
);
|
||||
cell.rendered_lines
|
||||
.cached
|
||||
.lock()
|
||||
.expect("render cache lock")
|
||||
.as_mut()
|
||||
.expect("render cache should be populated")
|
||||
.1 = vec![HyperlinkLine::from("cached")];
|
||||
|
||||
assert_eq!(
|
||||
visible_lines(cell.transcript_hyperlink_lines(width)),
|
||||
vec![Line::from("cached")]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finalized_plan_file_citation_renders_as_local_path_snapshot() {
|
||||
let cwd = std::env::temp_dir();
|
||||
let output = cwd.join("Quarterly Report.xlsx").display().to_string();
|
||||
let plan = new_proposed_plan(
|
||||
format!(
|
||||
"- :codex-file-citation{{path=\"{output}\" purpose=\"output\" artifact_kind=\"workbook\"}}\n"
|
||||
),
|
||||
&cwd,
|
||||
);
|
||||
|
||||
let rendered = ratatui::text::Text::from(plan.display_lines(/*width*/ 80));
|
||||
|
||||
insta::assert_snapshot!(rendered, @"• Proposed Plan\n \n \n • Quarterly Report.xlsx");
|
||||
}
|
||||
217
codex-rs/tui/src/history_cell/request_user_input.rs
Normal file
217
codex-rs/tui/src/history_cell/request_user_input.rs
Normal file
@@ -0,0 +1,217 @@
|
||||
//! Completed request-user-input transcript rendering.
|
||||
|
||||
use super::*;
|
||||
use crate::style::accent_color;
|
||||
|
||||
/// 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>> {
|
||||
visible_lines(self.display_hyperlink_lines(width))
|
||||
}
|
||||
|
||||
fn display_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
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)".fg(accent_color()));
|
||||
}
|
||||
|
||||
let mut lines = vec![HyperlinkLine::new(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() {
|
||||
let suffix = " (unanswered)";
|
||||
last.line.spans.push(suffix.dim());
|
||||
if let Some(source) = &mut last.source {
|
||||
// The suffix is deliberately appended after wrapping, matching the existing UI.
|
||||
let mut logical = source.styled_range(0..source.range.end);
|
||||
logical.spans.push(suffix.dim());
|
||||
let logical =
|
||||
crate::terminal_hyperlinks::LogicalLineSource::from_line(&logical);
|
||||
source.range.end = logical.text.len();
|
||||
for line in &mut question_lines {
|
||||
if let Some(source) = &mut line.source {
|
||||
source.text = std::sync::Arc::clone(&logical.text);
|
||||
source.styles = std::sync::Arc::clone(&logical.styles);
|
||||
source.line_style = logical.line_style;
|
||||
source.span_style = Style::default();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
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(accent_color()),
|
||||
));
|
||||
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(accent_color()),
|
||||
));
|
||||
}
|
||||
if let Some(note) = note {
|
||||
let (label, continuation, style) = if question.options.is_some() {
|
||||
(
|
||||
" note: ".dim(),
|
||||
" ".dim(),
|
||||
Style::default().fg(accent_color()),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
" answer: ".dim(),
|
||||
" ".dim(),
|
||||
Style::default().fg(accent_color()),
|
||||
)
|
||||
};
|
||||
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,
|
||||
" ↳ ".fg(accent_color()),
|
||||
" ".dim(),
|
||||
Style::default().fg(accent_color()),
|
||||
));
|
||||
}
|
||||
|
||||
lines
|
||||
}
|
||||
|
||||
fn transcript_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
self.display_hyperlink_lines(width)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
/// Retain the first-line label as text, keeping continuation alignment display-only.
|
||||
fn wrap_with_prefix(
|
||||
text: &str,
|
||||
width: usize,
|
||||
initial_prefix: Span<'static>,
|
||||
subsequent_prefix: Span<'static>,
|
||||
style: Style,
|
||||
) -> Vec<HyperlinkLine> {
|
||||
let label = initial_prefix.content.trim_start_matches(' ').to_owned();
|
||||
let line = HyperlinkLine::new(Line::from(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 mut wrapped = crate::terminal_hyperlinks::adaptive_wrap_hyperlink_lines(&[line], opts);
|
||||
crate::terminal_hyperlinks::retain_initial_prefix(&mut wrapped, &label);
|
||||
wrapped
|
||||
}
|
||||
|
||||
/// 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)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "request_user_input_tests.rs"]
|
||||
mod tests;
|
||||
58
codex-rs/tui/src/history_cell/request_user_input_tests.rs
Normal file
58
codex-rs/tui/src/history_cell/request_user_input_tests.rs
Normal file
@@ -0,0 +1,58 @@
|
||||
//! Result rendering preserves answer styles and wrapped unanswered questions.
|
||||
|
||||
use super::*;
|
||||
use codex_app_server_protocol::ToolRequestUserInputOption;
|
||||
use ratatui::buffer::Buffer;
|
||||
use ratatui::layout::Rect;
|
||||
|
||||
#[test]
|
||||
fn completed_and_interrupted_results() {
|
||||
let question = ToolRequestUserInputQuestion {
|
||||
id: "choice".into(),
|
||||
header: "Approach".into(),
|
||||
question: "Which approach should we use for the next step?".into(),
|
||||
is_other: true,
|
||||
is_secret: false,
|
||||
options: Some(vec![ToolRequestUserInputOption {
|
||||
label: "Keep it small".into(),
|
||||
description: "Use the existing helper".into(),
|
||||
}]),
|
||||
};
|
||||
let mut cell = RequestUserInputResultCell {
|
||||
questions: vec![question],
|
||||
answers: HashMap::from([(
|
||||
"choice".into(),
|
||||
ToolRequestUserInputAnswer {
|
||||
answers: vec![
|
||||
"Keep it small".into(),
|
||||
"user_note: Preserve the behavior".into(),
|
||||
],
|
||||
},
|
||||
)]),
|
||||
interrupted: false,
|
||||
};
|
||||
crate::terminal_palette::with_test_default_colors(
|
||||
crate::terminal_probe::DefaultColors {
|
||||
fg: (240, 240, 240),
|
||||
bg: (24, 24, 24),
|
||||
},
|
||||
|| {
|
||||
let mut snapshots = Vec::new();
|
||||
for state in ["completed", "interrupted"] {
|
||||
let lines = cell.display_lines(/*width*/ 40);
|
||||
let area = Rect::new(
|
||||
/*x*/ 0,
|
||||
/*y*/ 0,
|
||||
/*width*/ 40,
|
||||
lines.len() as u16,
|
||||
);
|
||||
let mut buffer = Buffer::empty(area);
|
||||
Paragraph::new(lines).render(area, &mut buffer);
|
||||
snapshots.push(format!("{state}: {buffer:?}"));
|
||||
cell.answers.clear();
|
||||
cell.interrupted = true;
|
||||
}
|
||||
insta::assert_snapshot!(snapshots.join("\n"));
|
||||
},
|
||||
);
|
||||
}
|
||||
182
codex-rs/tui/src/history_cell/search.rs
Normal file
182
codex-rs/tui/src/history_cell/search.rs
Normal file
@@ -0,0 +1,182 @@
|
||||
//! Compact web activity summaries with complete details in the transcript and raw output.
|
||||
|
||||
use super::*;
|
||||
use crate::line_truncation::truncate_line_with_ellipsis_if_overflow;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "search_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
fn web_search_action_detail(action: &WebSearchAction) -> String {
|
||||
match action {
|
||||
WebSearchAction::Search { query, queries } => query
|
||||
.clone()
|
||||
.filter(|q| !q.is_empty())
|
||||
.unwrap_or_else(|| queries.as_deref().unwrap_or_default().join(", ")),
|
||||
WebSearchAction::OpenPage { url } => url.clone().unwrap_or_default(),
|
||||
WebSearchAction::FindInPage { url, pattern } => match (
|
||||
pattern.as_deref().filter(|pattern| !pattern.is_empty()),
|
||||
url.as_deref().filter(|url| !url.is_empty()),
|
||||
) {
|
||||
(Some(pattern), Some(url)) => format!("'{pattern}' in {url}"),
|
||||
(Some(pattern), None) => format!("'{pattern}'"),
|
||||
(None, Some(url)) => url.to_string(),
|
||||
(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;
|
||||
}
|
||||
|
||||
fn summary(&self) -> Line<'static> {
|
||||
let detail = web_search_detail(self.action.as_ref(), &self.query);
|
||||
let (header, separator) = match (&self.action, self.completed) {
|
||||
(Some(WebSearchAction::OpenPage { .. }), completed) => (
|
||||
match (completed, detail.is_empty()) {
|
||||
(true, true) => "Opened page",
|
||||
(true, false) => "Opened",
|
||||
(false, true) => "Opening page",
|
||||
(false, false) => "Opening",
|
||||
},
|
||||
" ",
|
||||
),
|
||||
(Some(WebSearchAction::FindInPage { pattern, .. }), completed) => {
|
||||
let has_pattern = pattern.as_ref().is_some_and(|pattern| !pattern.is_empty());
|
||||
(
|
||||
match (completed, has_pattern) {
|
||||
(true, true) => "Searched for",
|
||||
(true, false) => "Searched page",
|
||||
(false, true) => "Searching for",
|
||||
(false, false) => "Searching page",
|
||||
},
|
||||
" ",
|
||||
)
|
||||
}
|
||||
(None | Some(WebSearchAction::Other), false) if detail.is_empty() => {
|
||||
("Browsing the web", " ")
|
||||
}
|
||||
(Some(WebSearchAction::Search { .. } | WebSearchAction::Other) | None, completed) => (
|
||||
if completed {
|
||||
"Searched the web"
|
||||
} else {
|
||||
"Searching the web"
|
||||
},
|
||||
" for ",
|
||||
),
|
||||
};
|
||||
let mut line = Line::from(header.bold());
|
||||
if !detail.is_empty() {
|
||||
line.extend([separator.into(), detail.into()]);
|
||||
}
|
||||
line
|
||||
}
|
||||
}
|
||||
|
||||
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 mut line = Line::from(vec![bullet, " ".into()]);
|
||||
let mut summary = self.summary();
|
||||
for span in &mut summary.spans {
|
||||
span.content = span.content.replace(['\n', '\r', '\t'], " ").into();
|
||||
}
|
||||
line.extend(summary);
|
||||
vec![truncate_line_with_ellipsis_if_overflow(
|
||||
line,
|
||||
width as usize,
|
||||
)]
|
||||
}
|
||||
|
||||
fn transcript_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
PrefixedWrappedHistoryCell::new(self.summary(), vec!["• ".dim()], " ").display_lines(width)
|
||||
}
|
||||
|
||||
fn transcript_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
PrefixedWrappedHistoryCell::new(self.summary(), vec!["• ".dim()], " ")
|
||||
.display_hyperlink_lines(width)
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
plain_lines(vec![self.summary()])
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
97
codex-rs/tui/src/history_cell/search_tests.rs
Normal file
97
codex-rs/tui/src/history_cell/search_tests.rs
Normal file
@@ -0,0 +1,97 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn web_action_labels_and_missing_details() {
|
||||
let url = "https://example.com/docs";
|
||||
let actions = [
|
||||
WebSearchAction::OpenPage {
|
||||
url: Some(url.into()),
|
||||
},
|
||||
WebSearchAction::OpenPage { url: None },
|
||||
WebSearchAction::FindInPage {
|
||||
url: Some(url.into()),
|
||||
pattern: Some("needle".into()),
|
||||
},
|
||||
WebSearchAction::FindInPage {
|
||||
url: None,
|
||||
pattern: Some("needle".into()),
|
||||
},
|
||||
WebSearchAction::FindInPage {
|
||||
url: Some(url.into()),
|
||||
pattern: Some(String::new()),
|
||||
},
|
||||
WebSearchAction::FindInPage {
|
||||
url: None,
|
||||
pattern: None,
|
||||
},
|
||||
];
|
||||
let rendered = actions
|
||||
.into_iter()
|
||||
.flat_map(|action| {
|
||||
new_web_search_call("call".into(), String::new(), action)
|
||||
.display_lines(/*width*/ 80)
|
||||
})
|
||||
.map(|line| line.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
insta::assert_snapshot!(rendered);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn web_action_compact_display_preserves_transcript_and_raw_details() {
|
||||
let url = "https://example.com/docs/very-long-page?section=narrowing#details";
|
||||
let cell = new_web_search_call(
|
||||
"call".into(),
|
||||
String::new(),
|
||||
WebSearchAction::FindInPage {
|
||||
url: Some(url.into()),
|
||||
pattern: Some("日本語 🦀 needle".into()),
|
||||
},
|
||||
);
|
||||
let display = cell.display_lines(/*width*/ 32);
|
||||
assert_eq!(display.len(), 1);
|
||||
assert!(display[0].width() <= 32);
|
||||
insta::assert_snapshot!(display[0].to_string());
|
||||
let full = format!("Searched for '日本語 🦀 needle' in {url}");
|
||||
assert_eq!(cell.raw_lines(), vec![Line::from(full.clone())]);
|
||||
assert_eq!(
|
||||
cell.transcript_lines(/*width*/ 200)
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![format!("• {full}")]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_web_action_and_legacy_query() {
|
||||
let cell = new_active_web_search_call(
|
||||
"call".into(),
|
||||
String::new(),
|
||||
/*animations_enabled*/ false,
|
||||
);
|
||||
insta::assert_snapshot!(cell.display_lines(/*width*/ 80)[0].to_string(), @"• Browsing the web");
|
||||
let legacy = new_web_search_call("call".into(), "old query".into(), WebSearchAction::Other);
|
||||
assert_eq!(
|
||||
legacy.raw_lines(),
|
||||
vec![Line::from("Searched the web for old query")]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batched_search_retains_each_query() {
|
||||
let cell = new_web_search_call(
|
||||
"call".into(),
|
||||
String::new(),
|
||||
WebSearchAction::Search {
|
||||
query: None,
|
||||
queries: Some(vec!["first query".into(), "second query".into()]),
|
||||
},
|
||||
);
|
||||
assert_eq!(
|
||||
cell.raw_lines(),
|
||||
vec![Line::from("Searched the web for first query, second query")]
|
||||
);
|
||||
insta::assert_snapshot!(cell.display_lines(/*width*/ 80)[0].to_string(), @"• Searched the web for first query, second query");
|
||||
}
|
||||
254
codex-rs/tui/src/history_cell/separators.rs
Normal file
254
codex-rs/tui/src/history_cell/separators.rs
Normal file
@@ -0,0 +1,254 @@
|
||||
//! Subtle completion timestamps, elapsed durations, and runtime metrics for transcript history.
|
||||
|
||||
use super::*;
|
||||
use crate::clock_format::ClockFormat;
|
||||
use chrono::DateTime;
|
||||
use chrono::Datelike;
|
||||
use chrono::Local;
|
||||
use chrono::NaiveDate;
|
||||
use codex_app_server_protocol::Turn;
|
||||
use std::collections::HashSet;
|
||||
|
||||
/// Completion metadata shown after the assistant's final response.
|
||||
///
|
||||
/// The timestamp records when the turn actually finished, including when restored from history.
|
||||
/// Times use the host's clock preference; other local days include the date and other years the year.
|
||||
/// Known durations are always shown; sub-second durations display as less than one second.
|
||||
/// Absent metadata occupies no transcript rows.
|
||||
/// The display date is fixed at construction so crossing midnight cannot invalidate cached heights;
|
||||
/// restoring the conversation constructs new cells and refreshes whether the timestamp needs a date.
|
||||
#[derive(Debug)]
|
||||
pub struct FinalMessageSeparator {
|
||||
elapsed_seconds: Option<u64>,
|
||||
runtime_metrics: Option<RuntimeMetricsSummary>,
|
||||
completed_at: Option<DateTime<Local>>,
|
||||
display_date: NaiveDate,
|
||||
clock_format: ClockFormat,
|
||||
}
|
||||
impl FinalMessageSeparator {
|
||||
pub(crate) fn from_turn_once(
|
||||
turn: &Turn,
|
||||
rendered_turn_ids: &mut HashSet<String>,
|
||||
fallback_elapsed: Option<std::time::Duration>,
|
||||
fallback_completed_at: Option<DateTime<Local>>,
|
||||
) -> Option<Self> {
|
||||
let elapsed_seconds = turn
|
||||
.duration_ms
|
||||
.and_then(|duration| u64::try_from(duration).ok())
|
||||
.map(|duration| duration / 1_000)
|
||||
.or_else(|| fallback_elapsed.map(|elapsed| elapsed.as_secs()));
|
||||
let completed_at = turn
|
||||
.completed_at
|
||||
.and_then(|timestamp| DateTime::from_timestamp(timestamp, /*nsecs*/ 0))
|
||||
.map(|timestamp| timestamp.with_timezone(&Local))
|
||||
.or(fallback_completed_at);
|
||||
if completed_at.is_none() && elapsed_seconds.is_none() {
|
||||
return None;
|
||||
}
|
||||
if !rendered_turn_ids.insert(turn.id.clone()) {
|
||||
return None;
|
||||
}
|
||||
let cell = Self::new(elapsed_seconds, /*runtime_metrics*/ None);
|
||||
Some(match completed_at {
|
||||
Some(completed_at) => cell.with_completed_at(completed_at, ClockFormat::system()),
|
||||
None => cell,
|
||||
})
|
||||
}
|
||||
|
||||
/// Creates completion metadata using the protocol turn duration when available.
|
||||
pub(crate) fn new(
|
||||
elapsed_seconds: Option<u64>,
|
||||
runtime_metrics: Option<RuntimeMetricsSummary>,
|
||||
) -> Self {
|
||||
Self {
|
||||
elapsed_seconds,
|
||||
runtime_metrics,
|
||||
completed_at: None,
|
||||
display_date: Local::now().date_naive(),
|
||||
clock_format: ClockFormat::TwelveHour,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn with_completed_at(
|
||||
mut self,
|
||||
completed_at: DateTime<Local>,
|
||||
clock_format: ClockFormat,
|
||||
) -> Self {
|
||||
self.completed_at = Some(completed_at);
|
||||
self.clock_format = clock_format;
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn with_runtime_metrics(
|
||||
mut self,
|
||||
runtime_metrics: Option<RuntimeMetricsSummary>,
|
||||
) -> Self {
|
||||
self.runtime_metrics = runtime_metrics;
|
||||
self
|
||||
}
|
||||
|
||||
fn label(&self, today: NaiveDate) -> Option<String> {
|
||||
let mut label_parts = Vec::new();
|
||||
if let Some(elapsed_seconds) = self.elapsed_seconds {
|
||||
let hours = elapsed_seconds / 3_600;
|
||||
let minutes = (elapsed_seconds % 3_600) / 60;
|
||||
let seconds = elapsed_seconds % 60;
|
||||
let elapsed = if hours > 0 {
|
||||
format!("{hours}h {minutes}m {seconds}s")
|
||||
} else if minutes > 0 {
|
||||
format!("{minutes}m {seconds}s")
|
||||
} else if seconds == 0 {
|
||||
"<1s".to_string()
|
||||
} else {
|
||||
format!("{seconds}s")
|
||||
};
|
||||
label_parts.push(format!("Worked for {elapsed}"));
|
||||
}
|
||||
if let Some(completed_at) = self.completed_at {
|
||||
let date_format = if completed_at.date_naive() == today {
|
||||
""
|
||||
} else if completed_at.year() == today.year() {
|
||||
"%b %-d at "
|
||||
} else {
|
||||
"%b %-d, %Y at "
|
||||
};
|
||||
label_parts.push(format!(
|
||||
"{}{}",
|
||||
completed_at.format(date_format),
|
||||
completed_at.format(self.clock_format.time_format()),
|
||||
));
|
||||
}
|
||||
if let Some(metrics_label) = self.runtime_metrics.and_then(runtime_metrics_label) {
|
||||
label_parts.push(metrics_label);
|
||||
}
|
||||
(!label_parts.is_empty()).then(|| label_parts.join(" • "))
|
||||
}
|
||||
}
|
||||
impl HistoryCell for FinalMessageSeparator {
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
if width == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
self.label(self.display_date)
|
||||
.map(|label| {
|
||||
let indent = if width > 2 { " " } else { "" };
|
||||
let options = textwrap::Options::new(usize::from(width))
|
||||
.initial_indent(indent)
|
||||
.subsequent_indent(indent);
|
||||
textwrap::wrap(&label, options)
|
||||
.into_iter()
|
||||
.map(|line| Line::from(line.into_owned()).dim())
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
self.label(self.display_date)
|
||||
.map(|label| vec![Line::from(label)])
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "separators_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
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.0
|
||||
|| summary.responses_api_engine_service_tbt_ms > 0.0
|
||||
{
|
||||
let mut tbt_parts = Vec::new();
|
||||
if summary.responses_api_engine_iapi_tbt_ms > 0.0 {
|
||||
let duration =
|
||||
format_duration_ms(summary.responses_api_engine_iapi_tbt_ms.round() as u64);
|
||||
tbt_parts.push(format!("{duration} (iapi)"));
|
||||
}
|
||||
if summary.responses_api_engine_service_tbt_ms > 0.0 {
|
||||
let duration =
|
||||
format_duration_ms(summary.responses_api_engine_service_tbt_ms.round() as u64);
|
||||
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 }
|
||||
}
|
||||
201
codex-rs/tui/src/history_cell/separators_tests.rs
Normal file
201
codex-rs/tui/src/history_cell/separators_tests.rs
Normal file
@@ -0,0 +1,201 @@
|
||||
//! Completion metadata rendering, date selection, and muted styling coverage.
|
||||
|
||||
use super::*;
|
||||
use chrono::NaiveDateTime;
|
||||
use chrono::TimeZone;
|
||||
use chrono::Timelike;
|
||||
use codex_otel::RuntimeMetricTotals;
|
||||
use pretty_assertions::assert_eq;
|
||||
use ratatui::buffer::Buffer;
|
||||
use ratatui::layout::Rect;
|
||||
|
||||
fn completed_at() -> DateTime<Local> {
|
||||
let datetime = NaiveDateTime::parse_from_str("2000-09-06 14:32:00", "%Y-%m-%d %H:%M:%S")
|
||||
.expect("valid completion time");
|
||||
Local
|
||||
.from_local_datetime(&datetime)
|
||||
.single()
|
||||
.expect("unambiguous completion time")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completion_label_shows_known_durations_including_short_turns() {
|
||||
let completed_at = completed_at();
|
||||
let labels = [
|
||||
None,
|
||||
Some(0),
|
||||
Some(12),
|
||||
Some(60),
|
||||
Some(61),
|
||||
Some(125),
|
||||
Some(3_605),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|elapsed_seconds| {
|
||||
FinalMessageSeparator::new(elapsed_seconds, /*runtime_metrics*/ None)
|
||||
.with_completed_at(completed_at, ClockFormat::TwelveHour)
|
||||
.label(completed_at.date_naive())
|
||||
.expect("completion label")
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
insta::assert_snapshot!(labels.join("\n"), @"
|
||||
2:32 PM
|
||||
Worked for <1s • 2:32 PM
|
||||
Worked for 12s • 2:32 PM
|
||||
Worked for 1m 0s • 2:32 PM
|
||||
Worked for 1m 1s • 2:32 PM
|
||||
Worked for 2m 5s • 2:32 PM
|
||||
Worked for 1h 0m 5s • 2:32 PM
|
||||
");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completion_label_includes_date_when_viewed_on_another_day() {
|
||||
let completed_at = completed_at();
|
||||
let cell = FinalMessageSeparator::new(
|
||||
/*elapsed_seconds*/ Some(125),
|
||||
/*runtime_metrics*/ None,
|
||||
)
|
||||
.with_completed_at(completed_at, ClockFormat::TwelveHour);
|
||||
let tomorrow = completed_at.date_naive().succ_opt().expect("next day");
|
||||
|
||||
insta::assert_snapshot!(cell.label(tomorrow).expect("completion label"), @"Worked for 2m 5s • Sep 6 at 2:32 PM");
|
||||
let next_year = tomorrow.with_year(/*year*/ 2001).expect("valid next year");
|
||||
insta::assert_snapshot!(cell.label(next_year).expect("completion label"), @"Worked for 2m 5s • Sep 6, 2000 at 2:32 PM");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completion_uses_twelve_hour_time_at_midnight_noon_and_afternoon() {
|
||||
let labels = [0, 12, 15].map(|hour| {
|
||||
let completed_at = completed_at().with_hour(hour).expect("valid hour");
|
||||
FinalMessageSeparator::new(/*elapsed_seconds*/ None, /*runtime_metrics*/ None)
|
||||
.with_completed_at(completed_at, ClockFormat::TwelveHour)
|
||||
.label(completed_at.date_naive())
|
||||
.expect("completion label")
|
||||
});
|
||||
insta::assert_snapshot!(labels.join("\n"), @"
|
||||
12:32 AM
|
||||
12:32 PM
|
||||
3:32 PM
|
||||
");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completion_uses_twenty_four_hour_time_with_dates_and_wrapping() {
|
||||
let today = completed_at().date_naive();
|
||||
let tomorrow = today.succ_opt().unwrap();
|
||||
let next_year = today.with_year(/*year*/ 2001).unwrap();
|
||||
let mut labels = Vec::new();
|
||||
for hour in [0, 12, 23] {
|
||||
let completed_at = completed_at()
|
||||
.with_hour(hour)
|
||||
.unwrap()
|
||||
.with_minute(/*min*/ 25)
|
||||
.unwrap();
|
||||
let mut cell = FinalMessageSeparator::new(Some(125), /*runtime_metrics*/ None)
|
||||
.with_completed_at(completed_at, ClockFormat::TwentyFourHour);
|
||||
for date in [today, tomorrow, next_year] {
|
||||
labels.push(cell.label(date).unwrap());
|
||||
}
|
||||
cell.display_date = next_year;
|
||||
labels.push(
|
||||
cell.display_lines(/*width*/ 24)
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n"),
|
||||
);
|
||||
assert_eq!(
|
||||
cell.raw_lines(),
|
||||
vec![Line::from(cell.label(next_year).unwrap())]
|
||||
);
|
||||
}
|
||||
insta::assert_snapshot!(labels.join("\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completion_without_metadata_has_no_visible_or_raw_lines() {
|
||||
let cell =
|
||||
FinalMessageSeparator::new(/*elapsed_seconds*/ None, /*runtime_metrics*/ None);
|
||||
assert_eq!(cell.display_lines(/*width*/ 80), Vec::<Line>::new());
|
||||
assert_eq!(cell.raw_lines(), Vec::<Line>::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completion_without_timestamp_retains_known_elapsed_duration() {
|
||||
let cell = FinalMessageSeparator::new(
|
||||
/*elapsed_seconds*/ Some(125),
|
||||
/*runtime_metrics*/ None,
|
||||
);
|
||||
insta::assert_snapshot!(cell.raw_lines()[0].to_string(), @"Worked for 2m 5s");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completion_wraps_metadata_and_preserves_unwrapped_raw_text() {
|
||||
let cell = FinalMessageSeparator::new(
|
||||
/*elapsed_seconds*/ Some(125),
|
||||
/*runtime_metrics*/ None,
|
||||
)
|
||||
.with_completed_at(completed_at(), ClockFormat::TwelveHour)
|
||||
.with_runtime_metrics(Some(RuntimeMetricsSummary {
|
||||
tool_calls: RuntimeMetricTotals {
|
||||
count: 3,
|
||||
duration_ms: 2_450,
|
||||
},
|
||||
..RuntimeMetricsSummary::default()
|
||||
}));
|
||||
let lines = cell.display_lines(/*width*/ 24);
|
||||
let rendered = lines.iter().map(ToString::to_string).collect::<Vec<_>>();
|
||||
|
||||
insta::assert_snapshot!(rendered.join("\n"), @r"
|
||||
Worked for 2m 5s • Sep
|
||||
6, 2000 at 2:32 PM •
|
||||
Local tools: 3 calls
|
||||
(2.5s)
|
||||
");
|
||||
insta::assert_snapshot!(cell.raw_lines()[0].to_string(), @"Worked for 2m 5s • Sep 6, 2000 at 2:32 PM • Local tools: 3 calls (2.5s)");
|
||||
for width in [0, 1, 5, 24] {
|
||||
assert!(
|
||||
cell.display_lines(width)
|
||||
.iter()
|
||||
.all(|line| line.width() <= usize::from(width))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completion_renders_with_dim_default_colors() {
|
||||
let cell: Box<dyn HistoryCell> = Box::new(
|
||||
FinalMessageSeparator::new(/*elapsed_seconds*/ None, /*runtime_metrics*/ None)
|
||||
.with_completed_at(completed_at(), ClockFormat::TwelveHour),
|
||||
);
|
||||
let area = Rect::new(
|
||||
/*x*/ 0, /*y*/ 0, /*width*/ 80, /*height*/ 1,
|
||||
);
|
||||
let mut buffer = Buffer::empty(area);
|
||||
cell.render(area, &mut buffer);
|
||||
let text_width = cell.display_lines(area.width)[0].width();
|
||||
let styles = (0..text_width)
|
||||
.map(|x| {
|
||||
let rendered = &buffer[(x as u16, 0)];
|
||||
(rendered.fg, rendered.bg, rendered.modifier)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
styles,
|
||||
vec![(Color::Reset, Color::Reset, Modifier::DIM); text_width]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completion_rendering_uses_the_captured_display_date() {
|
||||
let completed_at = completed_at();
|
||||
let mut cell =
|
||||
FinalMessageSeparator::new(/*elapsed_seconds*/ None, /*runtime_metrics*/ None)
|
||||
.with_completed_at(completed_at, ClockFormat::TwelveHour);
|
||||
cell.display_date = completed_at.date_naive();
|
||||
|
||||
insta::assert_snapshot!(cell.display_lines(/*width*/ 80)[0].to_string(), @" 2:32 PM");
|
||||
assert_eq!(cell.raw_lines(), vec![Line::from("2:32 PM")]);
|
||||
}
|
||||
431
codex-rs/tui/src/history_cell/session.rs
Normal file
431
codex-rs/tui/src/history_cell/session.rs
Normal file
@@ -0,0 +1,431 @@
|
||||
//! Session headers, onboarding guidance, and transcript cards.
|
||||
|
||||
use super::*;
|
||||
use crate::line_truncation::line_width;
|
||||
use crate::line_truncation::truncate_line_with_ellipsis_if_overflow;
|
||||
use crate::style::accent_color;
|
||||
use crate::width::display_width;
|
||||
|
||||
/// 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>> {
|
||||
let max_line_width = lines.iter().map(line_width).max().unwrap_or(0);
|
||||
let content_width = inner_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 = line_width(&line);
|
||||
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);
|
||||
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
|
||||
}
|
||||
|
||||
/// Brand title shared by the session header and the status card; each owns its own indentation.
|
||||
pub(crate) fn codex_title(version: &str) -> Vec<Span<'static>> {
|
||||
vec![
|
||||
">_ ".fg(accent_color()),
|
||||
"OpenAI Codex".bold(),
|
||||
format!(" (v{version})").dim(),
|
||||
]
|
||||
}
|
||||
|
||||
#[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>> {
|
||||
visible_lines(self.display_hyperlink_lines(width))
|
||||
}
|
||||
|
||||
fn display_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
let indent = " ";
|
||||
let indent_width = display_width(indent);
|
||||
let wrap_width = usize::from(width.max(1))
|
||||
.saturating_sub(indent_width)
|
||||
.max(1);
|
||||
let lines = crate::tooltips::render_tooltip_lines(&self.tip, wrap_width, &self.cwd);
|
||||
|
||||
prefix_hyperlink_lines(lines, indent.into(), indent.into())
|
||||
}
|
||||
|
||||
fn transcript_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
self.display_hyperlink_lines(width)
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
vec![Line::from(format!("Tip: {}", self.tip))]
|
||||
}
|
||||
}
|
||||
|
||||
/// Startup metadata, including prior-session summaries and available usage resets.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct SessionNoticeCell(pub(crate) PlainHistoryCell);
|
||||
|
||||
impl HistoryCell for SessionNoticeCell {
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
self.0.display_lines(width)
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
self.0.raw_lines()
|
||||
}
|
||||
}
|
||||
|
||||
/// Fork lineage that stays with the session header when older history is prepended.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ForkedThreadHistoryCell(pub(crate) PlainHistoryCell);
|
||||
|
||||
impl HistoryCell for ForkedThreadHistoryCell {
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
self.0.display_lines(width)
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
self.0.raw_lines()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct SessionInfoCell(CompositeHistoryCell);
|
||||
|
||||
/// Fullscreen transcript presentation omits tips; scrollback retains the original cells.
|
||||
pub(crate) fn fullscreen_session_lines(
|
||||
cell: &dyn HistoryCell,
|
||||
width: u16,
|
||||
detailed: bool,
|
||||
mode: HistoryRenderMode,
|
||||
) -> Vec<HyperlinkLine> {
|
||||
if let Some(info) = cell.as_any().downcast_ref::<SessionInfoCell>() {
|
||||
let mut lines = Vec::new();
|
||||
for part in &info.0.parts {
|
||||
if part.as_any().is::<TooltipHistoryCell>() {
|
||||
continue;
|
||||
}
|
||||
let part_lines = fullscreen_session_lines(part.as_ref(), width, detailed, mode);
|
||||
if !part_lines.is_empty() {
|
||||
if !lines.is_empty() {
|
||||
lines.push(HyperlinkLine::from(""));
|
||||
}
|
||||
lines.extend(part_lines);
|
||||
}
|
||||
}
|
||||
lines
|
||||
} else if detailed || mode == HistoryRenderMode::Rich {
|
||||
cell.retained_hyperlink_lines(width, detailed)
|
||||
} else {
|
||||
cell.display_hyperlink_lines_for_mode(width, mode)
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryCell for SessionInfoCell {
|
||||
fn compact_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
self.0.compact_hyperlink_lines(width)
|
||||
}
|
||||
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
self.0.display_lines(width)
|
||||
}
|
||||
|
||||
fn display_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
self.0.display_hyperlink_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 transcript_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
self.0.transcript_hyperlink_lines(width)
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
self.0.raw_lines()
|
||||
}
|
||||
}
|
||||
|
||||
/// Session-level cells that stay ahead of every loaded transcript page.
|
||||
pub(crate) fn is_session_history_prefix_cell(cell: &dyn HistoryCell) -> bool {
|
||||
cell.as_any().is::<SessionInfoCell>()
|
||||
|| cell.as_any().is::<SessionHeaderHistoryCell>()
|
||||
|| cell.as_any().is::<ForkedThreadHistoryCell>()
|
||||
}
|
||||
|
||||
#[expect(
|
||||
clippy::too_many_arguments,
|
||||
reason = "keep local preferences separate while the legacy Config parameter is still required"
|
||||
)]
|
||||
pub(crate) fn new_session_info(
|
||||
config: &Config,
|
||||
local_settings: &crate::local_settings::LocalSettings,
|
||||
requested_model: &str,
|
||||
model_display_name: &str,
|
||||
session: &ThreadSessionState,
|
||||
is_first_event: bool,
|
||||
tooltip_override: Option<String>,
|
||||
auth_plan: Option<PlanType>,
|
||||
) -> SessionInfoCell {
|
||||
// Header rendered as history (so it appears at the very top).
|
||||
let header = SessionHeaderHistoryCell::new(
|
||||
model_display_name.to_string(),
|
||||
session.reasoning_effort.clone(),
|
||||
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 && local_settings.tui.show_tooltips {
|
||||
// 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 !is_first_event {
|
||||
if local_settings.tui.show_tooltips
|
||||
&& let Some(tooltips) = tooltip_override
|
||||
.or_else(|| tooltips::get_tooltip(auth_plan, &local_settings.tui.keymap))
|
||||
.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,
|
||||
}
|
||||
)
|
||||
}
|
||||
/// The fresh terminal header marks the start of visible scrollback after Ctrl+L.
|
||||
/// It has no transcript representation because the original session header is still retained.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ClearScreenHeader(pub(crate) SessionHeaderHistoryCell);
|
||||
|
||||
impl HistoryCell for ClearScreenHeader {
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
self.0.display_lines(width)
|
||||
}
|
||||
|
||||
fn live_raw_lines(&self) -> Vec<Line<'static>> {
|
||||
self.0.raw_lines()
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
fn transcript_lines(&self, _width: u16) -> Vec<Line<'static>> {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// Session banner with a model label already resolved for presentation by its caller.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct SessionHeaderHistoryCell {
|
||||
version: &'static str,
|
||||
model: String,
|
||||
reasoning_effort: Option<ReasoningEffortConfig>,
|
||||
directory: PathBuf,
|
||||
yolo_mode: bool,
|
||||
}
|
||||
|
||||
impl SessionHeaderHistoryCell {
|
||||
pub(crate) fn new(
|
||||
model: String,
|
||||
reasoning_effort: Option<ReasoningEffortConfig>,
|
||||
directory: PathBuf,
|
||||
version: &'static str,
|
||||
) -> Self {
|
||||
Self {
|
||||
version,
|
||||
model,
|
||||
reasoning_effort,
|
||||
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 display_width(formatted.as_str()) > max_width {
|
||||
return crate::text_formatting::center_truncate_path(&formatted, max_width);
|
||||
}
|
||||
}
|
||||
|
||||
formatted
|
||||
}
|
||||
|
||||
fn reasoning_label(&self) -> Option<&str> {
|
||||
self.reasoning_effort
|
||||
.as_ref()
|
||||
.map(ReasoningEffortConfig::as_str)
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryCell for SessionHeaderHistoryCell {
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
let width = usize::from(width);
|
||||
let mut title = vec![" ".into()];
|
||||
title.extend(codex_title(self.version));
|
||||
let mut lines = vec![
|
||||
Line::default(),
|
||||
Line::from(title),
|
||||
Line::from(vec![
|
||||
" ".into(),
|
||||
self.format_directory(Some(width.saturating_sub(/*rhs*/ 5)))
|
||||
.dim(),
|
||||
]),
|
||||
];
|
||||
if self.yolo_mode {
|
||||
lines.push(Line::from(vec![
|
||||
" permissions: ".dim(),
|
||||
"YOLO mode".magenta().bold(),
|
||||
]));
|
||||
}
|
||||
lines
|
||||
.into_iter()
|
||||
.map(|line| truncate_line_with_ellipsis_if_overflow(line, width))
|
||||
.collect()
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "session_transcript_tests.rs"]
|
||||
mod transcript_tests;
|
||||
108
codex-rs/tui/src/history_cell/session_transcript_tests.rs
Normal file
108
codex-rs/tui/src/history_cell/session_transcript_tests.rs
Normal file
@@ -0,0 +1,108 @@
|
||||
//! Session information appears only once all older transcript pages are available.
|
||||
|
||||
use super::*;
|
||||
use crate::pager_overlay::TranscriptHistoryState;
|
||||
use crate::transcript_view::TranscriptView;
|
||||
use crossterm::event::KeyModifiers;
|
||||
use crossterm::event::MouseEvent;
|
||||
use crossterm::event::MouseEventKind;
|
||||
use pretty_assertions::assert_eq;
|
||||
use ratatui::buffer::Buffer;
|
||||
use ratatui::layout::Rect;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[test]
|
||||
fn wheel_at_hidden_session_header_keeps_the_loaded_message_anchor() {
|
||||
let header: Arc<dyn HistoryCell> = Arc::new(SessionInfoCell(CompositeHistoryCell {
|
||||
parts: vec![Box::new(PlainHistoryCell::new(vec![
|
||||
"session announcement".into(),
|
||||
]))],
|
||||
}));
|
||||
let recent: Arc<dyn HistoryCell> = Arc::new(PlainHistoryCell::new(
|
||||
(0..6)
|
||||
.map(|row| format!("recent row {row}").into())
|
||||
.collect(),
|
||||
));
|
||||
let mut cells = vec![header, recent];
|
||||
let area = Rect::new(
|
||||
/*x*/ 0, /*y*/ 0, /*width*/ 30, /*height*/ 3,
|
||||
);
|
||||
let mut view = TranscriptView::default();
|
||||
view.history = TranscriptHistoryState::Partial;
|
||||
let mut before = Buffer::empty(area);
|
||||
view.render(area, &mut before, &cells);
|
||||
for _ in 0..2 {
|
||||
view.handle_mouse(
|
||||
MouseEvent {
|
||||
kind: MouseEventKind::ScrollUp,
|
||||
column: 0,
|
||||
row: 0,
|
||||
modifiers: KeyModifiers::NONE,
|
||||
},
|
||||
&cells,
|
||||
);
|
||||
view.render(area, &mut before, &cells);
|
||||
}
|
||||
assert!(view.needs_history(&cells));
|
||||
let page = (0..3).map(|row| {
|
||||
Arc::new(PlainHistoryCell::new(vec![
|
||||
format!("older row {row}").into(),
|
||||
])) as Arc<dyn HistoryCell>
|
||||
});
|
||||
cells.splice(1..1, page);
|
||||
view.history_loaded(&cells, 1..4);
|
||||
assert!(
|
||||
!view.needs_history(&cells),
|
||||
"one wheel gesture must not keep requesting older pages"
|
||||
);
|
||||
let mut after = Buffer::empty(area);
|
||||
view.render(area, &mut after, &cells);
|
||||
assert_eq!(after, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_information_waits_for_older_pages_and_reappears_after_completion() {
|
||||
let header: Arc<dyn HistoryCell> = Arc::new(SessionInfoCell(CompositeHistoryCell {
|
||||
parts: vec![Box::new(PlainHistoryCell::new(vec![
|
||||
"session announcement".into(),
|
||||
]))],
|
||||
}));
|
||||
let cells = vec![header];
|
||||
let area = Rect::new(
|
||||
/*x*/ 0, /*y*/ 0, /*width*/ 30, /*height*/ 2,
|
||||
);
|
||||
let mut view = TranscriptView::default();
|
||||
let mut output = Vec::new();
|
||||
for history in [
|
||||
TranscriptHistoryState::Complete,
|
||||
TranscriptHistoryState::Partial,
|
||||
TranscriptHistoryState::LoadingOlder,
|
||||
TranscriptHistoryState::LoadingBeginning,
|
||||
TranscriptHistoryState::Failed,
|
||||
TranscriptHistoryState::Complete,
|
||||
] {
|
||||
view.history = history;
|
||||
let mut buffer = Buffer::empty(area);
|
||||
view.render(area, &mut buffer, &cells);
|
||||
output.push(
|
||||
buffer
|
||||
.content
|
||||
.iter()
|
||||
.map(ratatui::buffer::Cell::symbol)
|
||||
.collect::<String>()
|
||||
.trim()
|
||||
.to_owned(),
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
output,
|
||||
[
|
||||
"session announcement",
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"session announcement"
|
||||
]
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
---
|
||||
source: tui/src/history_cell/dynamic_tests.rs
|
||||
assertion_line: 95
|
||||
expression: "snapshots.join(\"\\n\\n\")"
|
||||
---
|
||||
lines=3, width=20
|
||||
• Called example.in…
|
||||
└ Result line 1: …
|
||||
Result line 2: …
|
||||
Result line 3: …
|
||||
|
||||
lines=3, width=80
|
||||
• Called example.inspect
|
||||
└ Result line 1: retained content
|
||||
Result line 2: retained content
|
||||
Result line 3: retained content
|
||||
|
||||
lines=4, width=20
|
||||
• Called example.in…
|
||||
… 1 earlier lines…
|
||||
└ Result line 2: …
|
||||
Result line 3: …
|
||||
Result line 4: …
|
||||
|
||||
lines=4, width=80
|
||||
• Called example.inspect
|
||||
… 1 earlier lines hidden
|
||||
└ Result line 2: retained content
|
||||
Result line 3: retained content
|
||||
Result line 4: retained content
|
||||
@@ -0,0 +1,31 @@
|
||||
---
|
||||
source: tui/src/history_cell/dynamic_tests.rs
|
||||
assertion_line: 81
|
||||
expression: "snapshots.join(\"\\n\\n\")"
|
||||
---
|
||||
pending, compact
|
||||
• Calling example.inspect
|
||||
|
||||
success, compact
|
||||
• Called example.inspect
|
||||
└ Found the definition
|
||||
|
||||
success, full
|
||||
• Called example.inspect
|
||||
└ Arguments: {
|
||||
"path": "src/main.rs"
|
||||
}
|
||||
Found the definition
|
||||
|
||||
success, raw
|
||||
• Called example.inspect
|
||||
Arguments: {"path":"src/main.rs"}
|
||||
Found the definition
|
||||
|
||||
failure, compact
|
||||
• Failed example.inspect
|
||||
└ Permission denied
|
||||
|
||||
unavailable, compact
|
||||
• Called example.inspect
|
||||
└ (output unavailable)
|
||||
@@ -0,0 +1,15 @@
|
||||
---
|
||||
source: tui/src/history_cell/hook_cell.rs
|
||||
expression: lines
|
||||
---
|
||||
[
|
||||
Line::from_iter([
|
||||
Span::from("↳ Hook · ").dim(),
|
||||
Span::from("Styled output").light_green().bold(),
|
||||
]),
|
||||
Line::from_iter([
|
||||
Span::from(" "),
|
||||
Span::from("across lines").light_green().bold(),
|
||||
Span::from(" plain").fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).not_bold().not_dim().not_italic().not_underlined().not_slow_blink().not_rapid_blink().not_reversed().not_hidden().not_crossed_out(),
|
||||
]),
|
||||
]
|
||||
@@ -0,0 +1,6 @@
|
||||
---
|
||||
source: tui/src/history_cell/computer_activity_tests.rs
|
||||
expression: "render(&cell, 80)"
|
||||
---
|
||||
• Using computer · 2 actions
|
||||
└ Load the terminal
|
||||
@@ -0,0 +1,9 @@
|
||||
---
|
||||
source: tui/src/history_cell/computer_activity_tests.rs
|
||||
assertion_line: 118
|
||||
expression: "cell.compact_hyperlink_lines(24).iter().map(|line|\nline.line.to_string()).collect::<Vec<_>>().join(\"\\n\")"
|
||||
---
|
||||
• Used computer · 5
|
||||
actions · 1 failed
|
||||
├ Failed: No browser …
|
||||
└ Captured screenshot…
|
||||
@@ -0,0 +1,18 @@
|
||||
---
|
||||
source: tui/src/history_cell/computer_activity_tests.rs
|
||||
expression: transcript
|
||||
---
|
||||
• Called cua_repl.js({"title":"Open browser","code":"await cua.getState()"})
|
||||
└ Error: No browser is available
|
||||
|
||||
## Computer Use
|
||||
Full tool documentation
|
||||
• Called cua_repl.js({"title":"Connect to Chrome","code":"await cua.getState()"})
|
||||
└ connected
|
||||
• Called cua_repl.js({"title":"Reproduce the clear-command bug","code":"await cua.getState()"})
|
||||
└ reproduced
|
||||
• Called cua_repl.js({"title":"Capture the reproduced bug","code":"await cua.getState()"})
|
||||
└ screenshot metadata
|
||||
Returned image
|
||||
• Called cua_repl.js({"title":"Check the final page","code":"await cua.getState()"})
|
||||
└ checked
|
||||
@@ -0,0 +1,8 @@
|
||||
---
|
||||
source: tui/src/history_cell/computer_activity_tests.rs
|
||||
expression: "render(&cell, 90)"
|
||||
---
|
||||
• Used computer · 3 actions · 1 failed
|
||||
├ Inspect page
|
||||
├ Reload page
|
||||
└ Failed: Inspect refreshed page — Browser state changed
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
source: tui/src/history_cell/computer_activity_tests.rs
|
||||
expression: "render(&cell, 80)"
|
||||
---
|
||||
• Used computer · 2 actions · 1 failed
|
||||
├ Opened Chrome
|
||||
└ Failed: Load the terminal — interrupted
|
||||
@@ -0,0 +1,8 @@
|
||||
---
|
||||
source: tui/src/history_cell/computer_activity_tests.rs
|
||||
expression: "render(&cell, 90)"
|
||||
---
|
||||
• Used computer · 5 actions · 1 failed
|
||||
├ Failed: Open browser — No browser is available
|
||||
├ Captured screenshot · Capture the reproduced bug
|
||||
└ 3 more · ⌃t
|
||||
@@ -0,0 +1,9 @@
|
||||
---
|
||||
source: tui/src/history_cell/computer_activity_tests.rs
|
||||
expression: "render(&cell, 24)"
|
||||
---
|
||||
• Used computer · 5
|
||||
actions · 1 failed
|
||||
├ Failed: No browser …
|
||||
├ Captured screenshot…
|
||||
└ 3 more · ⌃t
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
source: tui/src/history_cell/computer_activity_tests.rs
|
||||
expression: "render(&cell, 80)"
|
||||
---
|
||||
• Used computer · 2 actions
|
||||
├ Inspect page
|
||||
└ Reload page
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
source: tui/src/history_cell/computer_activity_tests.rs
|
||||
expression: "render(&cell, 24)"
|
||||
---
|
||||
• Used computer · 1
|
||||
action · 1 failed
|
||||
└ Failed: diagnostic …
|
||||
@@ -0,0 +1,18 @@
|
||||
---
|
||||
source: tui/src/history_cell/mcp_tests.rs
|
||||
expression: rendered
|
||||
---
|
||||
/mcp
|
||||
|
||||
🔌 MCP Tools
|
||||
|
||||
• auth: authentication required (0 tools)
|
||||
• cancelled: cancelled (0 tools)
|
||||
• connected-empty: connected (0 tools)
|
||||
• deferred: not started (0 tools)
|
||||
• disabled: disabled (0 tools)
|
||||
• failed: failed (0 tools)
|
||||
• starting: starting (0 tools)
|
||||
• unknown: unknown (0 tools)
|
||||
|
||||
Use /mcp verbose for tools and resources.
|
||||
@@ -0,0 +1,13 @@
|
||||
---
|
||||
source: tui/src/history_cell/mcp_tests.rs
|
||||
expression: rendered
|
||||
---
|
||||
/mcp
|
||||
|
||||
🔌 MCP Tools
|
||||
|
||||
• legacy-auth: authentication required (0 tools)
|
||||
• legacy-healthy: unknown (1 tool)
|
||||
• runtime-disabled: disabled (0 tools)
|
||||
|
||||
Use /mcp verbose for tools and resources.
|
||||
@@ -0,0 +1,24 @@
|
||||
---
|
||||
source: tui/src/history_cell/mcp_tests.rs
|
||||
expression: "format!(\"compact:\\n{}\\n\\nhistory:\\n{}\\n\\ntranscript:\\n{}\",\nvisible_lines(cell.compact_hyperlink_lines(80)).iter().map(ToString::to_string).collect::<Vec<_>>().join(\"\\n\"),\ndisplay.iter().map(ToString::to_string).collect::<Vec<_>>().join(\"\\n\"),\ntranscript.iter().map(ToString::to_string).collect::<Vec<_>>().join(\"\\n\"),)"
|
||||
---
|
||||
compact:
|
||||
• Called search.lookup
|
||||
└ third
|
||||
fourth
|
||||
fifth
|
||||
|
||||
history:
|
||||
• Called search.lookup({"title":"Search query"})
|
||||
└ first
|
||||
second
|
||||
third
|
||||
+2 lines (⌃t to view transcript)
|
||||
|
||||
transcript:
|
||||
• Called search.lookup({"title":"Search query"})
|
||||
└ first
|
||||
second
|
||||
third
|
||||
fourth
|
||||
fifth
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
source: tui/src/history_cell/mcp_tests.rs
|
||||
expression: "lines.iter().map(ToString::to_string).collect::<Vec<_>>().join(\"\\n\")"
|
||||
---
|
||||
• Inspect a very long screensho…
|
||||
└ Screenshot partially failed
|
||||
Returned image
|
||||
@@ -0,0 +1,6 @@
|
||||
---
|
||||
source: tui/src/history_cell/messages_tests.rs
|
||||
expression: "ratatui::text::Text::from(display)"
|
||||
---
|
||||
|
||||
[Image #1]
|
||||
@@ -0,0 +1,9 @@
|
||||
---
|
||||
source: tui/src/history_cell/messages_tests.rs
|
||||
expression: "ratatui::text::Text::from(cell.display_lines(40))"
|
||||
---
|
||||
|
||||
[Image #1]
|
||||
[Image #3]
|
||||
|
||||
› [Image #2] **compare** these
|
||||
@@ -0,0 +1,18 @@
|
||||
---
|
||||
source: tui/src/history_cell/messages_tests.rs
|
||||
expression: "format!(\"{buf:?}\")"
|
||||
---
|
||||
Buffer {
|
||||
area: Rect { x: 0, y: 0, width: 40, height: 3 },
|
||||
content: [
|
||||
" ",
|
||||
"› hello from voice ",
|
||||
" ",
|
||||
],
|
||||
styles: [
|
||||
x: 0, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
|
||||
x: 0, y: 1, fg: Red, bg: Rgb(68, 68, 68), underline: Reset, modifier: BOLD,
|
||||
x: 2, y: 1, fg: Rgb(238, 238, 238), bg: Rgb(68, 68, 68), underline: Reset, modifier: NONE,
|
||||
x: 18, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
source: tui/src/history_cell/messages_tests.rs
|
||||
expression: "snapshots.join(\"\\n\\n\")"
|
||||
---
|
||||
width 64
|
||||
|
||||
› testing hello example documentation
|
||||
(https://example.test/docs)
|
||||
|
||||
• Try the command
|
||||
|
||||
echo '*literal*'
|
||||
|
||||
width 20
|
||||
|
||||
› testing hello
|
||||
example
|
||||
documentation
|
||||
(https://
|
||||
example.test/
|
||||
docs)
|
||||
|
||||
• Try the command
|
||||
|
||||
echo '*literal*'
|
||||
@@ -0,0 +1,31 @@
|
||||
---
|
||||
source: tui/src/history_cell/messages_tests.rs
|
||||
expression: "snapshots.join(\"\\n\\n\")"
|
||||
---
|
||||
width 120
|
||||
|
||||
› from this site, write out the ascii for solid octants 18 columns
|
||||
https://example.test/terminal-link-wrapping/solid-octants
|
||||
[Image #1] See (https://example.test/a).
|
||||
|
||||
|
||||
width 60
|
||||
|
||||
› from this site, write out the ascii for solid octants 18
|
||||
columns
|
||||
https://example.test/terminal-link-wrapping/solid-octants
|
||||
[Image #1] See (https://example.test/a).
|
||||
|
||||
|
||||
width 24
|
||||
|
||||
› from this site, write
|
||||
out the ascii for
|
||||
solid octants 18
|
||||
columns
|
||||
https://example.test/
|
||||
terminal-link-wrappin
|
||||
g/solid-octants
|
||||
[Image #1] See
|
||||
(https://example.test
|
||||
/a).
|
||||
@@ -0,0 +1,51 @@
|
||||
---
|
||||
source: tui/src/history_cell/patches_tests.rs
|
||||
assertion_line: 28
|
||||
expression: "snapshots.join(\"\\n\\n\")"
|
||||
---
|
||||
patch
|
||||
Compact
|
||||
• Edited 2 files (+6 -1)
|
||||
└ existing.txt (+1 -1)
|
||||
2 -before
|
||||
2 +after
|
||||
|
||||
└ new.txt (+5 -0)
|
||||
1 +one
|
||||
2 +two
|
||||
3 +three
|
||||
Full
|
||||
• Edited 2 files (+6 -1)
|
||||
└ existing.txt (+1 -1)
|
||||
1 context
|
||||
2 -before
|
||||
2 +after
|
||||
3 tail
|
||||
|
||||
└ new.txt (+5 -0)
|
||||
1 +one
|
||||
2 +two
|
||||
3 +three
|
||||
4 +four
|
||||
5 +five
|
||||
|
||||
failure
|
||||
Compact
|
||||
✘ Failed to apply patch
|
||||
└ first
|
||||
second
|
||||
third
|
||||
Full
|
||||
✘ Failed to apply patch
|
||||
└ first
|
||||
second
|
||||
third
|
||||
fourth diagnostic
|
||||
|
||||
missing diagnostics
|
||||
Compact
|
||||
✘ Failed to apply patch
|
||||
└ (error details unavailable)
|
||||
Full
|
||||
✘ Failed to apply patch
|
||||
└ (error details unavailable)
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
source: tui/src/history_cell/patches_tests.rs
|
||||
expression: "cell.display_lines(32)[0].to_string()"
|
||||
---
|
||||
• Viewed image very-long-screen…
|
||||
@@ -0,0 +1,49 @@
|
||||
---
|
||||
source: tui/src/history_cell/request_user_input_tests.rs
|
||||
assertion_line: 44
|
||||
expression: "snapshots.join(\"\\n\")"
|
||||
---
|
||||
completed: Buffer {
|
||||
area: Rect { x: 0, y: 0, width: 40, height: 5 },
|
||||
content: [
|
||||
"• Questions 1/1 answered ",
|
||||
" • Which approach should we use for the",
|
||||
" next step? ",
|
||||
" answer: Keep it small ",
|
||||
" note: Preserve the behavior ",
|
||||
],
|
||||
styles: [
|
||||
x: 0, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
|
||||
x: 1, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
|
||||
x: 2, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: BOLD,
|
||||
x: 11, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
|
||||
x: 24, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
|
||||
x: 0, y: 3, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
|
||||
x: 12, y: 3, fg: Rgb(99, 168, 248), bg: Reset, underline: Reset, modifier: NONE,
|
||||
x: 25, y: 3, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
|
||||
x: 0, y: 4, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
|
||||
x: 10, y: 4, fg: Rgb(99, 168, 248), bg: Reset, underline: Reset, modifier: NONE,
|
||||
x: 31, y: 4, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
|
||||
]
|
||||
}
|
||||
interrupted: Buffer {
|
||||
area: Rect { x: 0, y: 0, width: 40, height: 4 },
|
||||
content: [
|
||||
"• Questions 0/1 answered (interrupted) ",
|
||||
" • Which approach should we use for the",
|
||||
" next step? (unanswered) ",
|
||||
" ↳ interrupted with 1 unanswered ",
|
||||
],
|
||||
styles: [
|
||||
x: 0, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
|
||||
x: 1, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
|
||||
x: 2, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: BOLD,
|
||||
x: 11, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
|
||||
x: 24, y: 0, fg: Rgb(99, 168, 248), bg: Reset, underline: Reset, modifier: NONE,
|
||||
x: 38, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
|
||||
x: 14, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
|
||||
x: 27, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
|
||||
x: 0, y: 3, fg: Rgb(99, 168, 248), bg: Reset, underline: Reset, modifier: NONE,
|
||||
x: 33, y: 3, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
source: tui/src/history_cell/search_tests.rs
|
||||
expression: "display[0].to_string()"
|
||||
---
|
||||
• Searched for '日本語 🦀 needl…
|
||||
@@ -0,0 +1,10 @@
|
||||
---
|
||||
source: tui/src/history_cell/search_tests.rs
|
||||
expression: rendered
|
||||
---
|
||||
• Opened https://example.com/docs
|
||||
• Opened page
|
||||
• Searched for 'needle' in https://example.com/docs
|
||||
• Searched for 'needle'
|
||||
• Searched page https://example.com/docs
|
||||
• Searched page
|
||||
@@ -0,0 +1,19 @@
|
||||
---
|
||||
source: tui/src/history_cell/separators_tests.rs
|
||||
expression: "labels.join(\"\\n\")"
|
||||
---
|
||||
Worked for 2m 5s • 00:25
|
||||
Worked for 2m 5s • Sep 6 at 00:25
|
||||
Worked for 2m 5s • Sep 6, 2000 at 00:25
|
||||
Worked for 2m 5s • Sep
|
||||
6, 2000 at 00:25
|
||||
Worked for 2m 5s • 12:25
|
||||
Worked for 2m 5s • Sep 6 at 12:25
|
||||
Worked for 2m 5s • Sep 6, 2000 at 12:25
|
||||
Worked for 2m 5s • Sep
|
||||
6, 2000 at 12:25
|
||||
Worked for 2m 5s • 23:25
|
||||
Worked for 2m 5s • Sep 6 at 23:25
|
||||
Worked for 2m 5s • Sep 6, 2000 at 23:25
|
||||
Worked for 2m 5s • Sep
|
||||
6, 2000 at 23:25
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
source: tui/src/history_cell.rs
|
||||
expression: rendered
|
||||
---
|
||||
• Calling search.find_docs({"query":"ratatui styling","limit":3})
|
||||
@@ -0,0 +1,6 @@
|
||||
---
|
||||
source: tui/src/history_cell.rs
|
||||
expression: rendered
|
||||
---
|
||||
• Explored
|
||||
└ Read auth.rs, shimmer.rs
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
source: tui/src/history_cell.rs
|
||||
expression: rendered
|
||||
---
|
||||
• Explored
|
||||
└ Search shimmer_spans
|
||||
Read shimmer.rs, status_indicator_widget.rs
|
||||
@@ -0,0 +1,8 @@
|
||||
---
|
||||
source: tui/src/history_cell.rs
|
||||
expression: rendered
|
||||
---
|
||||
• Explored
|
||||
└ Search shimmer_spans
|
||||
Read shimmer.rs
|
||||
Read status_indicator_widget.rs
|
||||
@@ -0,0 +1,6 @@
|
||||
---
|
||||
source: tui/src/history_cell/tests.rs
|
||||
expression: rendered
|
||||
---
|
||||
• Called image.generate({"prompt":"tiny image"})
|
||||
└ Returned image
|
||||
@@ -0,0 +1,6 @@
|
||||
---
|
||||
source: tui/src/history_cell.rs
|
||||
expression: rendered
|
||||
---
|
||||
• Called search.find_docs({"query":"ratatui styling","limit":3})
|
||||
└ Error: network timeout
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
source: tui/src/history_cell/tests.rs
|
||||
expression: rendered
|
||||
---
|
||||
• Called image.generate({"prompt":"tiny image"})
|
||||
└ Here is the image:
|
||||
Returned image
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
source: tui/src/history_cell/tests.rs
|
||||
expression: rendered
|
||||
---
|
||||
• Called image.generate({"prompt":"tiny image"})
|
||||
└ Returned image
|
||||
Returned image
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
source: tui/src/history_cell.rs
|
||||
expression: rendered
|
||||
---
|
||||
• Called metrics.summary({"metric":"trace.latency","window":"15m"})
|
||||
└ Latency summary: p50=120ms, p95=480ms.
|
||||
No anomalies detected.
|
||||
@@ -0,0 +1,10 @@
|
||||
---
|
||||
source: tui/src/history_cell/tests.rs
|
||||
expression: rendered
|
||||
---
|
||||
• Called
|
||||
└ search.find_docs({"query":"ratatui
|
||||
styling","limit":3})
|
||||
Found styling guidance in styles.md and
|
||||
additional notes in CONTRIBUTING.md.
|
||||
link: file:///docs/styles.md
|
||||
@@ -0,0 +1,6 @@
|
||||
---
|
||||
source: tui/src/history_cell.rs
|
||||
expression: rendered
|
||||
---
|
||||
• Called search.find_docs({"query":"ratatui styling","limit":3})
|
||||
└ Found styling guidance in styles.md
|
||||
@@ -0,0 +1,13 @@
|
||||
---
|
||||
source: tui/src/history_cell/tests.rs
|
||||
expression: rendered
|
||||
---
|
||||
• Called
|
||||
└ metrics.get_nearby_metric({"query":"
|
||||
very_long_query_that_needs_wrapp
|
||||
ing_to_display_properly_in_the_h
|
||||
istory","limit":1})
|
||||
Line one of the response, which is
|
||||
quite long and needs wrapping.
|
||||
Line two continues the response with
|
||||
+1 line (⌃t to view transcript)
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
source: tui/src/history_cell/tests.rs
|
||||
expression: "render_lines(&cell.display_lines(100)).join(\"\\n\")"
|
||||
---
|
||||
⚠ A background Codex service is running v0.152.1, older than your Codex CLI v0.153.0.
|
||||
@@ -0,0 +1,8 @@
|
||||
---
|
||||
source: tui/src/history_cell/tests.rs
|
||||
expression: rendered
|
||||
---
|
||||
ⓘ This content can’t be shown
|
||||
Daybreak isn’t available for Astra. Some cybersecurity requests may still be
|
||||
limited.
|
||||
Learn more: https://help.openai.com/en/articles/20001326
|
||||
@@ -0,0 +1,12 @@
|
||||
---
|
||||
source: tui/src/history_cell/tests.rs
|
||||
expression: rendered
|
||||
---
|
||||
ⓘ This content can’t be shown
|
||||
Daybreak is currently off. If you’re doing authorized security work, turn it
|
||||
on and try your request again.
|
||||
Learn more: https://help.openai.com/en/articles/20001326
|
||||
|
||||
ⓘ This content can’t be shown
|
||||
Some cybersecurity requests are still limited, even when Daybreak is on.
|
||||
Learn more: https://help.openai.com/en/articles/20001326
|
||||
@@ -0,0 +1,17 @@
|
||||
---
|
||||
source: tui/src/history_cell/tests.rs
|
||||
assertion_line: 821
|
||||
expression: rendered
|
||||
---
|
||||
ⓘ This content can’t be shown
|
||||
We take extra care with some
|
||||
cybersecurity requests. If
|
||||
you’re doing authorized security
|
||||
work, apply for Daybreak to get
|
||||
broader access.
|
||||
Learn more: https://
|
||||
help.openai.com/en/
|
||||
articles/20001326
|
||||
Apply for Daybreak: https://
|
||||
openai.com/form/enterprise-
|
||||
trusted-access-for-cyber/
|
||||
@@ -0,0 +1,11 @@
|
||||
---
|
||||
source: tui/src/history_cell/tests.rs
|
||||
assertion_line: 774
|
||||
expression: rendered
|
||||
---
|
||||
ⓘ This content can’t be shown
|
||||
We take extra care with some cybersecurity requests. If you’re doing
|
||||
authorized security work, apply for Daybreak to get broader access.
|
||||
Learn more: https://help.openai.com/en/articles/20001326
|
||||
Apply for Daybreak: https://openai.com/form/enterprise-trusted-access-for-
|
||||
cyber/
|
||||
@@ -0,0 +1,19 @@
|
||||
---
|
||||
source: tui/src/history_cell/tests.rs
|
||||
---
|
||||
Scrollback
|
||||
• Sent by Codex from task other
|
||||
• One
|
||||
• This item has enough words
|
||||
to wrap
|
||||
|
||||
• Three
|
||||
|
||||
Redrawable transcript
|
||||
• Sent by Codex from task other
|
||||
• One
|
||||
|
||||
• This item has enough words
|
||||
to wrap
|
||||
|
||||
• Three
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
source: tui/src/history_cell/tests.rs
|
||||
expression: rendered
|
||||
---
|
||||
■ Amazon Bedrock rejected the request because its AWS signature has expired. Refresh your AWS credentials and retry. If `AWS_BEARER_TOKEN_BEDROCK` is set, update or unset it, then restart Codex, url: https://bedrock-mantle.us-east-2.api.aws/openai/v1/responses
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
source: tui/src/history_cell.rs
|
||||
expression: rendered
|
||||
---
|
||||
■ Message exceeds the maximum length of 1048576 characters (1048577 provided).
|
||||
@@ -0,0 +1,8 @@
|
||||
---
|
||||
source: tui/src/history_cell/tests.rs
|
||||
expression: "render_lines(&cell.transcript_lines(80)).join(\"\\n\")"
|
||||
---
|
||||
⚠ `[features].shell_zsh_fork` is deprecated and ignored.
|
||||
The patched zsh backend has been removed. Shell commands now use the
|
||||
standard shell executor. Remove `shell_zsh_fork` from [features] in
|
||||
config.toml or profile configuration files.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
source: tui/src/history_cell/tests.rs
|
||||
expression: "render_lines(&cell.display_lines(100)).join(\"\\n\")"
|
||||
---
|
||||
⚠ A background Codex service is running v0.156.0, different from your Codex CLI v0.155.0-alpha.12.
|
||||
Use /daemon to manage the local background server.
|
||||
Updating may interrupt active or queued work.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
source: tui/src/history_cell/tests.rs
|
||||
expression: "render_lines(&cell.display_lines(100)).join(\"\\n\")"
|
||||
---
|
||||
⚠ A background Codex service is running v0.156.0, different from your Codex CLI v0.0.0.
|
||||
Use /daemon to manage the local background server.
|
||||
Updating may interrupt active or queued work.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
source: tui/src/history_cell/tests.rs
|
||||
expression: "render_lines(&cell.display_lines(100)).join(\"\\n\")"
|
||||
---
|
||||
⚠ A background Codex service is running v0.152.1, older than your Codex CLI v0.153.0.
|
||||
Use /daemon to manage the local background server.
|
||||
Updating may interrupt active or queued work.
|
||||
@@ -0,0 +1,6 @@
|
||||
---
|
||||
source: tui/src/history_cell.rs
|
||||
assertion_line: 3477
|
||||
expression: rendered
|
||||
---
|
||||
• Loading MCP inventory…
|
||||
@@ -0,0 +1,11 @@
|
||||
---
|
||||
source: tui/src/history_cell/tests.rs
|
||||
expression: rendered
|
||||
---
|
||||
/mcp
|
||||
|
||||
🔌 MCP Tools
|
||||
|
||||
• plugin_docs: unknown (1 tool)
|
||||
|
||||
Use /mcp verbose for tools and resources.
|
||||
@@ -0,0 +1,13 @@
|
||||
---
|
||||
source: tui/src/history_cell/tests.rs
|
||||
expression: rendered
|
||||
---
|
||||
/mcp
|
||||
|
||||
🔌 MCP Tools
|
||||
|
||||
• plugin_docs: unknown (1 tool)
|
||||
• Auth: Unsupported
|
||||
• Tools: lookup
|
||||
• Resources: Docs (file:///docs)
|
||||
• Resource templates: Doc Template (file:///docs/{id})
|
||||
@@ -0,0 +1,16 @@
|
||||
---
|
||||
source: tui/src/history_cell.rs
|
||||
assertion_line: 3310
|
||||
expression: rendered
|
||||
---
|
||||
/mcp
|
||||
|
||||
🔌 MCP Tools
|
||||
|
||||
• some-server
|
||||
• Status: enabled
|
||||
• Auth: Unsupported
|
||||
• Command: docs-server --stdio
|
||||
• Tools: lookup
|
||||
• Resources: (none)
|
||||
• Resource templates: (none)
|
||||
@@ -0,0 +1,26 @@
|
||||
---
|
||||
source: tui/src/history_cell.rs
|
||||
expression: rendered
|
||||
---
|
||||
/mcp
|
||||
|
||||
🔌 MCP Tools
|
||||
|
||||
• docs
|
||||
• Status: enabled
|
||||
• Auth: Unsupported
|
||||
• Command: docs-server
|
||||
• Env: TOKEN=*****, APP_TOKEN=*****
|
||||
• Tools: list
|
||||
• Resources: (none)
|
||||
• Resource templates: (none)
|
||||
|
||||
• http
|
||||
• Status: enabled
|
||||
• Auth: Unsupported
|
||||
• URL: https://example.com/mcp
|
||||
• HTTP headers: Authorization=*****
|
||||
• Env HTTP headers: X-API-Key=API_KEY_ENV
|
||||
• Tools: ping
|
||||
• Resources: (none)
|
||||
• Resource templates: (none)
|
||||
@@ -0,0 +1,9 @@
|
||||
---
|
||||
source: tui/src/history_cell.rs
|
||||
expression: rendered
|
||||
---
|
||||
• Ran first_token_is_long_en
|
||||
│ ough_to_wrap
|
||||
│ second_token_is_also_lon
|
||||
│ … +1 line
|
||||
└ (no output)
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
source: tui/src/history_cell.rs
|
||||
expression: rendered
|
||||
---
|
||||
• Ran echo one
|
||||
│ echo two
|
||||
└ (no output)
|
||||
@@ -0,0 +1,8 @@
|
||||
---
|
||||
source: tui/src/history_cell.rs
|
||||
expression: rendered
|
||||
---
|
||||
• Ran set -o pipefail
|
||||
│ cargo test -p codex-tui
|
||||
│ --quiet
|
||||
└ (no output)
|
||||
@@ -0,0 +1,30 @@
|
||||
---
|
||||
source: tui/src/history_cell/tests.rs
|
||||
assertion_line: 2632
|
||||
expression: rendered
|
||||
---
|
||||
Compact
|
||||
• Updated Plan · 1/4 complete
|
||||
└ □ Harden Grafana client err…
|
||||
□ Add tests for transient f…
|
||||
□ Document the retry behavi…
|
||||
|
||||
Full
|
||||
• Updated Plan
|
||||
└ I’ll update Grafana call
|
||||
error handling by adding
|
||||
retries and clearer messages
|
||||
when the backend is
|
||||
unreachable.
|
||||
✔ Investigate existing error
|
||||
paths and logging around
|
||||
HTTP timeouts
|
||||
□ Harden Grafana client
|
||||
error handling with retry/
|
||||
backoff and user‑friendly
|
||||
messages
|
||||
□ Add tests for transient
|
||||
failure scenarios and
|
||||
surfacing to the UI
|
||||
□ Document the retry
|
||||
behavior
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
source: tui/src/history_cell.rs
|
||||
expression: rendered
|
||||
---
|
||||
• Updated Plan
|
||||
└ □ Define error taxonomy
|
||||
□ Implement mapping to user messages
|
||||
@@ -0,0 +1,11 @@
|
||||
---
|
||||
source: tui/src/history_cell/tests.rs
|
||||
expression: rendered
|
||||
---
|
||||
╭─────────────────────────────────────────────────╮
|
||||
│ ✨ Update available! 0.0.0 -> 9.9.9 │
|
||||
│ Run pnpm add -g @openai/codex to update. │
|
||||
│ │
|
||||
│ See full release notes: │
|
||||
│ https://github.com/openai/codex/releases/latest │
|
||||
╰─────────────────────────────────────────────────╯
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
source: tui/src/history_cell/tests.rs
|
||||
expression: "render_lines(&cell.raw_lines()).join(\"\\n\")"
|
||||
---
|
||||
[Image #1] describe inline image
|
||||
@@ -0,0 +1,42 @@
|
||||
---
|
||||
source: tui/src/history_cell/tests.rs
|
||||
expression: lines
|
||||
---
|
||||
[
|
||||
Line::from_iter([
|
||||
Span::from("• ").dim(),
|
||||
Span::from("Proposed Plan").bold(),
|
||||
]),
|
||||
Line::from(" "),
|
||||
Line::from(" ").bg(Color::Rgb(244, 244, 244)),
|
||||
Line::from_iter([
|
||||
Span::from(" "),
|
||||
Span::from("## ").fg(Color::Rgb(191, 74, 7)).bold(),
|
||||
Span::from("Plan").fg(Color::Rgb(191, 74, 7)).bold(),
|
||||
]).bg(Color::Rgb(244, 244, 244)),
|
||||
Line::from(" ").bg(Color::Rgb(244, 244, 244)),
|
||||
Line::from_iter([
|
||||
Span::from(" "),
|
||||
Span::from(" "),
|
||||
Span::from("Step"),
|
||||
Span::from(" "),
|
||||
Span::from(" "),
|
||||
Span::from(" "),
|
||||
Span::from(" "),
|
||||
Span::from("Owner"),
|
||||
]).fg(Color::Rgb(156, 99, 20)).bg(Color::Rgb(244, 244, 244)).bold(),
|
||||
Line::from_iter([
|
||||
Span::from(" "),
|
||||
Span::from("━━━━━━━━ ━━━━━━━").dim(),
|
||||
]).bg(Color::Rgb(244, 244, 244)),
|
||||
Line::from_iter([
|
||||
Span::from(" "),
|
||||
Span::from(" "),
|
||||
Span::from("Verify"),
|
||||
Span::from(" "),
|
||||
Span::from(" "),
|
||||
Span::from(" "),
|
||||
Span::from("Codex"),
|
||||
]).bg(Color::Rgb(244, 244, 244)),
|
||||
Line::from(" ").bg(Color::Rgb(244, 244, 244)),
|
||||
]
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user