Base: codex-main originale (prima del fork aKode)

This commit is contained in:
Andrea
2026-11-09 10:37:42 +01:00
commit 7874033c81
10166 changed files with 2728937 additions and 0 deletions

View File

@@ -0,0 +1,132 @@
//! Owned-transcript command previews with full command/output retained for local disclosure.
use super::model::ExecCell;
use crate::exec_command::strip_bash_lc_and_escape;
use crate::history_cell::ActivityDisclosure;
use crate::history_cell::HistoryRenderMode;
use crate::history_cell::activity_preview::DETAIL_PREVIEW_LINES;
use crate::history_cell::activity_preview::clipped_line;
use crate::motion::MotionMode;
use crate::motion::ReducedMotionIndicator;
use crate::motion::activity_indicator;
use crate::render::highlight::highlight_bash_to_lines;
use crate::terminal_hyperlinks::HyperlinkLine;
use codex_ansi_escape::ansi_escape_line;
use ratatui::style::Modifier;
use ratatui::style::Stylize;
use ratatui::text::Line;
impl ExecCell {
pub(super) fn command_disclosure(&self, width: u16) -> Option<ActivityDisclosure> {
let [call] = self.group.calls.as_slice() else {
return None;
};
// Interaction output is intentionally absent from the expanded transcript.
if !call.is_unified_exec_interaction()
&& let Some(output) = &call.output
{
let retained = output.line_counts().1;
let clipped = output
.lines()
.rev()
.take(DETAIL_PREVIEW_LINES)
.filter(|raw| ansi_escape_line(raw.as_ref()).width() + 4 > usize::from(width))
.count();
let hidden = retained.saturating_sub(DETAIL_PREVIEW_LINES) + clipped;
if hidden > 0 {
return Some(ActivityDisclosure::OutputLines(hidden));
}
}
if !self
.group
.details
.lines_after(/*after_calls*/ 1, width, HistoryRenderMode::Rich)
.is_empty()
{
return Some(ActivityDisclosure::Generic);
}
let script = strip_bash_lc_and_escape(&call.command);
if script.lines().nth(/*n*/ 1).is_some()
|| self
.compact_command_lines(u16::MAX)
.first()
.is_some_and(|header| header.width() > usize::from(width))
{
return Some(ActivityDisclosure::Generic);
}
call.output
.as_ref()
.is_some_and(|output| {
output.line_counts().1 > DETAIL_PREVIEW_LINES
|| output.transcript_lines().any(|line| {
ansi_escape_line(line.as_ref()).width() + 4 > usize::from(width)
})
})
.then_some(ActivityDisclosure::Generic)
}
pub(super) fn compact_command_lines(&self, width: u16) -> Vec<HyperlinkLine> {
let [call] = self.group.calls.as_slice() else {
return Vec::new();
};
if call.is_unified_exec_interaction()
&& !self.is_active()
&& call.output.as_ref().is_some_and(|output| {
output.exit_code == 0 && output.lines().all(|line| line.trim().is_empty())
})
{
return Vec::new();
}
let nonzero_exit = call.output.as_ref().filter(|output| output.exit_code != 0);
let marker = if nonzero_exit.is_some() {
"•".bold()
} else if self.is_active() {
activity_indicator(
call.start_time,
MotionMode::from_animations_enabled(self.animations_enabled()),
ReducedMotionIndicator::StaticBullet,
)
.unwrap_or_else(|| "•".dim())
} else {
"•".green().bold()
};
let title = if let Some(output) = nonzero_exit {
format!("Exited (status {})", output.exit_code)
} else if self.is_active() {
"Running".to_owned()
} else if call.is_unified_exec_interaction() {
"Background output".to_owned()
} else {
"Ran".to_owned()
};
let script = strip_bash_lc_and_escape(&call.command);
// Highlight before clipping so the compact row keeps the same shell token colors.
let mut command_lines = highlight_bash_to_lines(&script).into_iter();
let mut header = command_lines.next().unwrap_or_default();
header
.spans
.splice(0..0, [marker, " ".into(), title.bold(), " ".into()]);
if command_lines.next().is_some() {
header.push_span(" …");
}
let mut lines = vec![clipped_line(header, width)];
if let Some(output) = &call.output {
let tail: Vec<_> = output.lines().rev().take(DETAIL_PREVIEW_LINES).collect();
for (index, raw) in tail.into_iter().rev().enumerate() {
let mut line = ansi_escape_line(raw.as_ref());
line.spans.insert(
/*index*/ 0,
if index == 0 { " └ " } else { " " }.dim(),
);
line.spans.iter_mut().for_each(|span| {
span.style = span.style.add_modifier(Modifier::DIM);
});
lines.push(clipped_line(line, width));
}
if lines.len() == 1 && !call.is_unified_exec_interaction() {
lines.push(clipped_line(Line::from(" └ (no output)".dim()), width));
}
}
lines
}
}

View File

@@ -0,0 +1,259 @@
use itertools::Either;
use std::borrow::Cow;
use std::collections::VecDeque;
const LIVE_COMMAND_OUTPUT_MAX_BYTES: usize = 1024 * 1024;
const LIVE_COMMAND_OUTPUT_MAX_LINES: usize = 50;
const LIVE_COMMAND_OUTPUT_MAX_LINE_BYTES: usize =
LIVE_COMMAND_OUTPUT_MAX_BYTES / (2 * LIVE_COMMAND_OUTPUT_MAX_LINES + 2);
const LIVE_COMMAND_OUTPUT_LINE_HEAD_BYTES: usize = LIVE_COMMAND_OUTPUT_MAX_LINE_BYTES / 2;
const LIVE_COMMAND_OUTPUT_LINE_TAIL_BYTES: usize =
LIVE_COMMAND_OUTPUT_MAX_LINE_BYTES - LIVE_COMMAND_OUTPUT_LINE_HEAD_BYTES;
/// A bounded, incremental preview of streamed command output.
///
/// All output is retained until the byte budget is exceeded. Once truncated, the first and last
/// 50 completed lines and any in-progress line are retained, and each line independently keeps a
/// prefix and suffix so commands that never emit a newline cannot grow the active cell without bound.
#[derive(Debug, Default)]
pub(super) struct LiveCommandOutput {
full_output: String,
truncated: bool,
head: Vec<String>,
tail: VecDeque<String>,
current: LiveCommandOutputLine,
completed_lines: usize,
has_partial_line: bool,
pending_carriage_return: bool,
}
impl LiveCommandOutput {
/// Appends a delta, preserving `str::lines` semantics across arbitrary chunk boundaries.
pub(super) fn push_str(&mut self, chunk: &str) {
if !self.truncated {
if self.full_output.len().saturating_add(chunk.len()) <= LIVE_COMMAND_OUTPUT_MAX_BYTES {
self.full_output.push_str(chunk);
self.completed_lines = self
.completed_lines
.saturating_add(chunk.bytes().filter(|byte| *byte == b'\n').count());
if !chunk.is_empty() {
self.has_partial_line = !chunk.ends_with('\n');
}
return;
}
self.truncated = true;
let full_output = std::mem::take(&mut self.full_output);
self.completed_lines = 0;
self.has_partial_line = false;
self.push_truncated_str(&full_output);
}
self.push_truncated_str(chunk);
}
/// Appends bounded output while treating a split CRLF as one terminator and retaining lone CRs.
fn push_truncated_str(&mut self, chunk: &str) {
for part in chunk.split_inclusive('\n') {
let Some(part) = part.strip_suffix('\n') else {
if part.is_empty() {
continue;
}
if self.pending_carriage_return {
self.current.push_str("\r");
self.pending_carriage_return = false;
}
let part = if let Some(part) = part.strip_suffix('\r') {
self.pending_carriage_return = true;
part
} else {
part
};
self.current.push_str(part);
self.has_partial_line |= !part.is_empty() || self.pending_carriage_return;
continue;
};
let has_carriage_return = part.ends_with('\r');
let part = part.strip_suffix('\r').unwrap_or(part);
if self.pending_carriage_return && (has_carriage_return || !part.is_empty()) {
self.current.push_str("\r");
}
self.pending_carriage_return = false;
self.current.push_str(part);
self.completed_lines = self.completed_lines.saturating_add(1);
self.has_partial_line = false;
let line = std::mem::take(&mut self.current).render();
if self.head.len() < LIVE_COMMAND_OUTPUT_MAX_LINES {
self.head.push(line);
} else {
if self.tail.len() == LIVE_COMMAND_OUTPUT_MAX_LINES {
self.tail.pop_front();
}
self.tail.push_back(line);
}
}
}
pub(super) fn total_lines(&self) -> usize {
self.completed_lines
.saturating_add(usize::from(self.has_partial_line))
}
pub(super) fn retained_lines(&self) -> usize {
if self.truncated {
self.head
.len()
.saturating_add(self.tail.len())
.saturating_add(usize::from(self.has_partial_line))
} else {
self.total_lines()
}
}
/// Returns reverse-capable preview lines, abbreviating long lines even below the byte budget.
pub(super) fn lines(&self) -> impl DoubleEndedIterator<Item = Cow<'_, str>> {
if self.truncated {
Either::Left(
self.head
.iter()
.chain(self.tail.iter())
.map(|line| Cow::Borrowed(line.as_str()))
.chain(
self.has_partial_line
.then(|| Cow::Owned(self.render_partial_line())),
),
)
} else {
Either::Right(self.full_output.lines().map(|line| {
if line.len() <= LIVE_COMMAND_OUTPUT_MAX_LINE_BYTES {
Cow::Borrowed(line)
} else {
let mut truncated = LiveCommandOutputLine::default();
truncated.push_str(line);
Cow::Owned(truncated.render())
}
}))
}
}
/// Returns lossless transcript lines until truncated, then inserts the omitted-line marker.
pub(super) fn transcript_lines(&self) -> impl Iterator<Item = Cow<'_, str>> {
let omitted = self.total_lines().saturating_sub(self.retained_lines());
if self.truncated {
Either::Left(
self.head
.iter()
.map(|line| Cow::Borrowed(line.as_str()))
.chain((omitted > 0).then(|| {
let noun = if omitted == 1 { "line" } else { "lines" };
Cow::Owned(format!("… +{omitted} {noun}"))
}))
.chain(self.tail.iter().map(|line| Cow::Borrowed(line.as_str())))
.chain(
self.has_partial_line
.then(|| Cow::Owned(self.render_partial_line())),
),
)
} else {
Either::Right(self.full_output.lines().map(Cow::Borrowed))
}
}
fn render_partial_line(&self) -> String {
let mut line = self.current.render();
if self.pending_carriage_return {
line.push('\r');
}
line
}
}
#[derive(Debug, Default)]
struct LiveCommandOutputLine {
head: String,
tail: String,
omitted_bytes: usize,
}
impl LiveCommandOutputLine {
fn push_str(&mut self, chunk: &str) {
let head_remaining = if self.tail.is_empty() && self.omitted_bytes == 0 {
LIVE_COMMAND_OUTPUT_LINE_HEAD_BYTES.saturating_sub(self.head.len())
} else {
0
};
let mut head_end = head_remaining.min(chunk.len());
while !chunk.is_char_boundary(head_end) {
head_end -= 1;
}
self.head.push_str(&chunk[..head_end]);
let chunk = &chunk[head_end..];
if chunk.is_empty() {
return;
}
if chunk.len() >= LIVE_COMMAND_OUTPUT_LINE_TAIL_BYTES {
let mut tail_start = chunk.len() - LIVE_COMMAND_OUTPUT_LINE_TAIL_BYTES;
while !chunk.is_char_boundary(tail_start) {
tail_start += 1;
}
self.omitted_bytes = self
.omitted_bytes
.saturating_add(self.tail.len())
.saturating_add(tail_start);
self.tail.clear();
self.tail.push_str(&chunk[tail_start..]);
return;
}
self.tail.push_str(chunk);
let mut tail_start = self
.tail
.len()
.saturating_sub(LIVE_COMMAND_OUTPUT_LINE_TAIL_BYTES);
while !self.tail.is_char_boundary(tail_start) {
tail_start += 1;
}
if tail_start > 0 {
self.tail.drain(..tail_start);
self.omitted_bytes = self.omitted_bytes.saturating_add(tail_start);
}
}
/// Renders the retained line, closing truncated ANSI sequences before the omission marker.
fn render(&self) -> String {
let omission_marker = (self.omitted_bytes > 0)
.then(|| format!("... {} bytes omitted ...", self.omitted_bytes));
let mut line = String::with_capacity(
self.head
.len()
.saturating_add(self.tail.len())
.saturating_add(omission_marker.as_ref().map_or(0, String::len))
.saturating_add(1),
);
line.push_str(&self.head);
if let Some(omission_marker) = omission_marker {
let terminator = self.head.rfind('\x1b').and_then(|start| {
let escape = &self.head.as_bytes()[start + 1..];
match escape.first() {
Some(b']') if !escape.contains(&b'\x07') => Some('\x07'),
Some(b'[') if !escape[1..].iter().any(u8::is_ascii_alphabetic) => Some('m'),
_ => None,
}
});
if let Some(terminator) = terminator {
line.push(terminator);
}
line.push_str("\x1b[0m");
line.push_str(&omission_marker);
}
line.push_str(&self.tail);
line
}
}
#[cfg(test)]
#[path = "live_output_tests.rs"]
mod tests;

View File

@@ -0,0 +1,135 @@
use super::LIVE_COMMAND_OUTPUT_LINE_HEAD_BYTES;
use super::LIVE_COMMAND_OUTPUT_LINE_TAIL_BYTES;
use super::LIVE_COMMAND_OUTPUT_MAX_BYTES;
use super::LiveCommandOutput;
use codex_ansi_escape::ansi_escape_line;
use pretty_assertions::assert_eq;
#[test]
fn keeps_all_short_lines_and_chunk_boundaries_within_the_live_byte_budget() {
let mut output = LiveCommandOutput::default();
for line in 1..=500 {
output.push_str(&format!("line {line}\n"));
}
for chunk in ["hell", "o\r", "\n\nwor", "ld"] {
output.push_str(chunk);
}
let expected: Vec<_> = (1..=500)
.map(|line| format!("line {line}"))
.chain(["hello".to_string(), String::new(), "world".to_string()])
.collect();
assert_eq!(output.total_lines(), expected.len());
assert_eq!(output.retained_lines(), expected.len());
assert_eq!(
output.transcript_lines().collect::<Vec<_>>(),
expected.iter().map(String::as_str).collect::<Vec<_>>()
);
}
#[test]
fn switches_to_bounded_storage_after_the_byte_budget_and_preserves_split_crlf() {
let mut output = LiveCommandOutput::default();
let line = "x".repeat(LIVE_COMMAND_OUTPUT_MAX_BYTES);
output.push_str(&line);
assert_eq!(output.transcript_lines().next().expect("full line"), line);
output.push_str("y");
let line = output.transcript_lines().next().expect("bounded line");
assert!(line.contains("bytes omitted"));
assert!(line.ends_with("xy"));
for carriage_returns in ["\r", "\r\r"] {
let body = "x".repeat(LIVE_COMMAND_OUTPUT_MAX_BYTES - carriage_returns.len());
let mut contiguous = LiveCommandOutput::default();
contiguous.push_str(&format!("{body}{carriage_returns}\n"));
let mut split = LiveCommandOutput::default();
split.push_str(&body);
split.push_str(carriage_returns);
assert!(
split
.transcript_lines()
.next()
.expect("partial line")
.ends_with('\r')
);
split.push_str("\n");
assert_eq!(split.total_lines(), 1);
assert_eq!(split.retained_lines(), 1);
assert_eq!(
split.lines().collect::<Vec<_>>(),
contiguous.lines().collect::<Vec<_>>()
);
}
}
#[test]
fn truncated_ansi_sequence_does_not_hide_the_retained_tail() {
let mut output = LiveCommandOutput::default();
let prefix = "x".repeat(LIVE_COMMAND_OUTPUT_LINE_HEAD_BYTES - 2);
let osc = format!("{prefix}\x1b]0;{}\x07visible-tail", "hidden".repeat(4_000));
output.push_str(&osc);
let line = output.lines().next().expect("partial line");
let rendered = ansi_escape_line(line.as_ref())
.spans
.into_iter()
.map(|span| span.content.into_owned())
.collect::<String>();
assert!(rendered.contains("bytes omitted"), "{rendered}");
assert!(rendered.ends_with("visible-tail"), "{rendered}");
assert_eq!(
output.transcript_lines().next().expect("transcript line"),
osc
);
}
#[test]
fn bounds_long_no_newline_output_and_preserves_utf8_head_and_tail() {
let mut output = LiveCommandOutput::default();
let chunk = "🦀".repeat(1024);
for _ in 0..600 {
output.push_str(&chunk);
}
let line = output.lines().next().expect("partial line");
let retained_bytes = LIVE_COMMAND_OUTPUT_LINE_HEAD_BYTES + LIVE_COMMAND_OUTPUT_LINE_TAIL_BYTES
- LIVE_COMMAND_OUTPUT_LINE_HEAD_BYTES % "🦀".len()
- LIVE_COMMAND_OUTPUT_LINE_TAIL_BYTES % "🦀".len();
assert_eq!(output.total_lines(), 1);
assert_eq!(output.retained_lines(), 1);
assert!(line.starts_with("🦀🦀🦀"));
assert!(line.ends_with("🦀🦀🦀"));
assert!(line.contains(&format!(
"... {} bytes omitted ...",
600 * chunk.len() - retained_bytes
)));
assert!(line.len() < LIVE_COMMAND_OUTPUT_MAX_BYTES);
}
#[test]
fn retained_output_stays_within_the_live_byte_budget() {
let mut output = LiveCommandOutput::default();
let body = "output ".repeat(4_000);
for line in 1..=180 {
output.push_str(&format!("head-{line} {body} tail-{line}\n"));
}
output.push_str(&format!("partial-head {body} partial-tail"));
let lines: Vec<_> = output.lines().collect();
assert_eq!(output.total_lines(), 181);
assert_eq!(output.retained_lines(), 101);
assert!(lines.first().expect("head line").starts_with("head-1 "));
assert!(lines[50].starts_with("head-131 "));
assert!(lines.last().expect("tail line").ends_with(" partial-tail"));
assert_eq!(
output.transcript_lines().nth(50).expect("omission line"),
"… +80 lines"
);
assert!(lines.iter().map(|line| line.len()).sum::<usize>() <= LIVE_COMMAND_OUTPUT_MAX_BYTES);
}

View File

@@ -0,0 +1,14 @@
mod compact;
mod live_output;
mod model;
mod render;
mod transcript;
pub(crate) use model::CommandOutput;
#[cfg(test)]
pub(crate) use model::ExecCall;
pub(crate) use model::ExecCell;
pub(crate) use render::OutputLinesParams;
pub(crate) use render::TOOL_CALL_MAX_LINES;
pub(crate) use render::new_active_exec_command;
pub(crate) use render::output_lines;

View File

@@ -0,0 +1,274 @@
//! Data model for grouped exec-call history cells in the TUI transcript.
//!
//! An `ExecCell` can represent either a single command or an "exploring" group of related read/
//! list/search commands. The chat widget relies on stable `call_id` matching to route progress and
//! end events into the right cell, and it treats "call id not found" as a real signal (for
//! example, an orphan end that should render as a separate history entry).
//! Transcript-only reasoning stays inside exploration groups so it does not split their
//! compact display, while the expanded transcript retains its position between commands.
use std::borrow::Cow;
use std::time::Duration;
use std::time::Instant;
use super::live_output::LiveCommandOutput;
use crate::history_cell::ActivityGroup;
use codex_app_server_protocol::CommandExecutionSource as ExecCommandSource;
use codex_protocol::parse_command::ParsedCommand;
use itertools::Either;
#[derive(Debug, Default)]
pub(crate) struct CommandOutput {
pub(crate) exit_code: i32,
/// The finalized, interleaved stderr and stdout that replaces any streamed preview.
aggregated_output: String,
/// The live preview while command-output deltas are still arriving.
live_output: Option<LiveCommandOutput>,
}
impl CommandOutput {
pub(crate) fn from_execution(
status: codex_app_server_protocol::CommandExecutionStatus,
exit_code: Option<i32>,
source: ExecCommandSource,
output: Option<String>,
) -> Self {
let exit_code = if status == codex_app_server_protocol::CommandExecutionStatus::Completed {
exit_code.unwrap_or_default()
} else {
exit_code.filter(|code| *code != 0).unwrap_or(1)
};
let output = if source == ExecCommandSource::UnifiedExecInteraction {
String::new()
} else {
output.unwrap_or_default()
};
Self::new(exit_code, output)
}
pub(crate) fn new(exit_code: i32, aggregated_output: String) -> Self {
Self {
exit_code,
aggregated_output,
live_output: None,
}
}
/// Returns the total number of logical lines and the number retained for rendering.
pub(super) fn line_counts(&self) -> (usize, usize) {
match self.live_output.as_ref() {
Some(output) => (output.total_lines(), output.retained_lines()),
None => {
let total = self.aggregated_output.lines().count();
(total, total)
}
}
}
/// Returns retained preview lines with reverse traversal for efficient tail rendering.
pub(super) fn lines(&self) -> impl DoubleEndedIterator<Item = Cow<'_, str>> {
match self.live_output.as_ref() {
Some(output) => Either::Left(output.lines()),
None => Either::Right(self.aggregated_output.lines().map(Cow::Borrowed)),
}
}
/// Returns lines for the expanded transcript, including any storage-level omission marker.
pub(super) fn transcript_lines(&self) -> impl Iterator<Item = Cow<'_, str>> {
match self.live_output.as_ref() {
Some(output) => Either::Left(output.transcript_lines()),
None => Either::Right(self.aggregated_output.lines().map(Cow::Borrowed)),
}
}
}
#[derive(Debug)]
pub(crate) struct ExecCall {
pub(crate) call_id: String,
pub(crate) command: Vec<String>,
pub(crate) parsed: Vec<ParsedCommand>,
pub(crate) output: Option<CommandOutput>,
pub(crate) source: ExecCommandSource,
pub(crate) start_time: Option<Instant>,
pub(crate) duration: Option<Duration>,
pub(crate) interaction_input: Option<String>,
}
#[derive(Debug)]
pub(crate) struct ExecCell {
pub(crate) group: ActivityGroup<ExecCall>,
animations_enabled: bool,
}
impl ExecCell {
pub(crate) fn new(call: ExecCall, animations_enabled: bool) -> Self {
Self {
group: ActivityGroup::new(vec![call]),
animations_enabled,
}
}
pub(crate) fn add_call(
&mut self,
call_id: String,
command: Vec<String>,
parsed: Vec<ParsedCommand>,
source: ExecCommandSource,
interaction_input: Option<String>,
) -> bool {
let call = ExecCall {
call_id,
command,
parsed,
output: None,
source,
start_time: Some(Instant::now()),
duration: None,
interaction_input,
};
if self.is_exploring_cell() && Self::is_exploring_call(&call) {
self.group.calls.push(call);
true
} else {
false
}
}
/// Historical grouping uses the same compatibility and failure boundary as live calls.
pub(crate) fn append_completed(&mut self, mut newer: Self) -> Result<(), Self> {
if !self.is_exploring_cell() || self.should_flush() || !newer.is_exploring_cell() {
return Err(newer);
}
newer.group.details.prepend(
std::mem::take(&mut self.group.details),
self.group.calls.len(),
);
self.group.details = newer.group.details;
self.group.calls.append(&mut newer.group.calls);
Ok(())
}
/// Preserve live clocks and pending output when a validated older page extends exploration.
pub(crate) fn prepend(&mut self, older: Self) {
self.group.prepend(older.group);
}
/// Marks the most recently matching call as finished and returns whether a call was found.
///
/// Callers should treat `false` as a routing mismatch rather than silently ignoring it. The
/// chat widget uses that signal to avoid attaching an orphan `exec_end` event to an unrelated
/// active exploring cell, which would incorrectly collapse two transcript entries together.
pub(crate) fn complete_call(
&mut self,
call_id: &str,
output: CommandOutput,
duration: Duration,
) -> bool {
let Some(call) = self
.group
.calls
.iter_mut()
.rev()
.find(|c| c.call_id == call_id)
else {
return false;
};
call.output = Some(output);
call.duration = Some(duration);
call.start_time = None;
true
}
pub(crate) fn should_flush(&self) -> bool {
// Exploration stays open for adjacent calls, including after a failed read/list/search.
!self.is_exploring_cell() && self.group.calls.iter().all(|c| c.duration.is_some())
}
pub(crate) fn mark_failed(&mut self) {
for call in self.group.calls.iter_mut() {
if call.duration.is_none() {
let elapsed = call
.start_time
.map(|st| st.elapsed())
.unwrap_or_else(|| Duration::from_millis(0));
call.start_time = None;
call.duration = Some(elapsed);
call.output
.get_or_insert_with(CommandOutput::default)
.exit_code = 1;
}
}
}
pub(crate) fn is_exploring_cell(&self) -> bool {
self.group.calls.iter().all(Self::is_exploring_call)
}
pub(crate) fn is_active(&self) -> bool {
self.group.calls.iter().any(|c| c.duration.is_none())
}
pub(crate) fn active_start_time(&self) -> Option<Instant> {
self.group
.calls
.iter()
.find(|c| c.duration.is_none())
.and_then(|c| c.start_time)
}
pub(crate) fn animations_enabled(&self) -> bool {
self.animations_enabled
}
pub(crate) fn freeze_snapshot(&mut self) {
self.animations_enabled = false;
}
pub(crate) fn iter_calls(&self) -> impl Iterator<Item = &ExecCall> {
self.group.calls.iter()
}
pub(crate) fn append_output(&mut self, call_id: &str, chunk: &str) -> bool {
if chunk.is_empty() {
return false;
}
let Some(call) = self
.group
.calls
.iter_mut()
.rev()
.find(|c| c.call_id == call_id)
else {
return false;
};
let output = call.output.get_or_insert_with(CommandOutput::default);
output
.live_output
.get_or_insert_with(LiveCommandOutput::default)
.push_str(chunk);
true
}
pub(super) fn is_exploring_call(call: &ExecCall) -> bool {
!matches!(call.source, ExecCommandSource::UserShell)
&& !call.parsed.is_empty()
&& call.parsed.iter().all(|p| {
matches!(
p,
ParsedCommand::Read { .. }
| ParsedCommand::ListFiles { .. }
| ParsedCommand::Search { .. }
)
})
}
}
impl ExecCall {
pub(crate) fn is_user_shell_command(&self) -> bool {
matches!(self.source, ExecCommandSource::UserShell)
}
pub(crate) fn is_unified_exec_interaction(&self) -> bool {
matches!(self.source, ExecCommandSource::UnifiedExecInteraction)
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,63 @@
---
source: tui/src/exec_cell/render.rs
assertion_line: 1100
expression: "(preview, compact, transcript)"
---
(
[
Line::from_iter([
Span::from("•").dim(),
Span::from(" "),
Span::from("Running").bold(),
Span::from(" "),
Span::from("echo").fg(Color::Rgb(137, 180, 250)),
Span::from(" output").fg(Color::Rgb(205, 214, 244)),
]),
Line::from_iter([
Span::from(" └ ").dim(),
Span::from("head error that wraps onto the next row").red().dim(),
Span::from("... 1189804 bytes").fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim().not_bold().not_italic().not_underlined().not_slow_blink().not_rapid_blink().not_reversed().not_hidden().not_crossed_out(),
]),
Line::from_iter([
Span::from(" "),
Span::from("omitted ...").fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim().not_bold().not_italic().not_underlined().not_slow_blink().not_rapid_blink().not_reversed().not_hidden().not_crossed_out(),
Span::from("tail output that also wraps").green().bg(Color::Reset).underline_color(Color::Reset).dim().not_bold().not_italic().not_underlined().not_slow_blink().not_rapid_blink().not_reversed().not_hidden().not_crossed_out(),
]),
],
[
Line::from_iter([
Span::from("•").bold(),
Span::from(" "),
Span::from("Exited (status 1)").bold(),
Span::from(" "),
Span::from("echo").fg(Color::Rgb(137, 180, 250)),
Span::from(" output").fg(Color::Rgb(205, 214, 244)),
]),
Line::from_iter([
Span::from(" └ ").dim(),
Span::from("head error that wraps onto the next row").red().dim(),
Span::from("... 1189804 byte").fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim().not_bold().not_italic().not_underlined().not_slow_blink().not_rapid_blink().not_reversed().not_hidden().not_crossed_out(),
Span::from("…").fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim().not_bold().not_italic().not_underlined().not_slow_blink().not_rapid_blink().not_reversed().not_hidden().not_crossed_out(),
]),
],
[
Line::from_iter([
Span::from("$ ").magenta(),
Span::from("echo").fg(Color::Rgb(137, 180, 250)),
Span::from(" output").fg(Color::Rgb(205, 214, 244)),
]),
Line::from_iter([
Span::from("head error that wraps onto the next row").red(),
Span::from("... 1189804 bytes").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(),
]),
Line::from_iter([
Span::from("omitted ...").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(),
Span::from("tail output that also wraps").green().bg(Color::Reset).underline_color(Color::Reset).dim().not_bold().not_italic().not_underlined().not_slow_blink().not_rapid_blink().not_reversed().not_hidden().not_crossed_out(),
]),
Line::from_iter([
Span::from("✗").red().bold(),
Span::from(" (1)"),
Span::from(" • 0ms").dim(),
]),
],
)

View File

@@ -0,0 +1,29 @@
---
source: tui/src/exec_cell/transcript_tests.rs
assertion_line: 73
expression: "format!(\"Rich\\n{rich}\\n\\nRaw\\n{}\", raw.join(\"\\n\"))"
---
Rich
$ cat first.txt
first output
✓ • 5ms
• Inspecting the next file
↳ Interacted with background terminal · cat first.txt
└ continue
$ cat second.txt
second output
✓ • 5ms
Raw
$ cat first.txt
first output
✓ • 5ms
Interacted with background terminal: cat first.txt
continue
$ cat second.txt
second output
✓ • 5ms

View File

@@ -0,0 +1,75 @@
//! Expanded command history with source-backed selection and chronological activity details.
//! Raw history omits transcript-only reasoning while retaining full command output.
use super::model::ExecCell;
use crate::exec_command::strip_bash_lc_and_escape;
use crate::history_cell::HistoryRenderMode;
use crate::render::highlight::highlight_bash_to_lines;
use crate::terminal_hyperlinks::HyperlinkLine;
use crate::terminal_hyperlinks::adaptive_wrap_hyperlink_lines;
use crate::terminal_hyperlinks::plain_hyperlink_lines;
use crate::wrapping::RtOptions;
use codex_ansi_escape::ansi_escape_line;
use codex_utils_elapsed::format_duration;
use ratatui::prelude::*;
impl ExecCell {
pub(super) fn detailed_hyperlink_lines(
&self,
width: u16,
mode: HistoryRenderMode,
) -> Vec<HyperlinkLine> {
let mut lines: Vec<HyperlinkLine> = vec![];
for (i, call) in self.iter_calls().enumerate() {
if i > 0 {
lines.push("".into());
}
let script = strip_bash_lc_and_escape(&call.command);
let highlighted_script = highlight_bash_to_lines(&script);
let cmd_display = adaptive_wrap_hyperlink_lines(
&plain_hyperlink_lines(highlighted_script),
RtOptions::new(width as usize)
.initial_indent("$ ".magenta().into())
.subsequent_indent(" ".into()),
);
lines.extend(cmd_display);
if let Some(output) = call.output.as_ref() {
if !call.is_unified_exec_interaction() {
let wrap_width = width.max(/*other*/ 1) as usize;
let wrap_opts = RtOptions::new(wrap_width);
for unwrapped in output
.transcript_lines()
.map(|line| ansi_escape_line(line.as_ref()))
{
lines.extend(adaptive_wrap_hyperlink_lines(
&[unwrapped.into()],
wrap_opts.clone(),
));
}
}
if call.duration.is_some() || output.exit_code != 0 {
let mut result: Line = if output.exit_code == 0 {
Line::from("✓".green().bold())
} else {
Line::from(vec![
"✗".red().bold(),
format!(" ({})", output.exit_code).into(),
])
};
if let Some(duration) = call.duration {
let duration = format_duration(duration);
result.push_span(format!(" • {duration}").dim());
}
lines.push(result.into());
}
}
lines.extend(self.group.details.lines_after(i + 1, width, mode));
}
lines
}
}
#[cfg(test)]
#[path = "transcript_tests.rs"]
mod tests;

View File

@@ -0,0 +1,90 @@
//! Grouped command details retain terminal input in raw output without exposing hidden reasoning.
use super::*;
use crate::exec_cell::CommandOutput;
use crate::exec_cell::model::ExecCall;
use crate::history_cell::HistoryCell;
use crate::history_cell::new_reasoning_summary_block;
use crate::history_cell::new_unified_exec_interaction;
use codex_app_server_protocol::CommandExecutionSource;
use pretty_assertions::assert_eq;
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;
fn completed_read(name: &str, output: &str) -> ExecCell {
let command = vec!["cat".to_owned(), name.to_owned()];
let parsed = codex_shell_command::parse_command::parse_command(&command);
ExecCell::new(
ExecCall {
call_id: name.to_owned(),
command,
parsed,
output: Some(CommandOutput::new(/*exit_code*/ 0, output.to_owned())),
source: CommandExecutionSource::UnifiedExecStartup,
start_time: None,
duration: Some(Duration::from_millis(/*millis*/ 5)),
interaction_input: None,
},
/*animations_enabled*/ false,
)
}
#[test]
fn raw_grouped_history_retains_terminal_input_and_omits_reasoning() {
let mut group = completed_read("first.txt", "first output");
group
.group
.push_detail(Arc::from(new_reasoning_summary_block(
vec!["Inspecting the next file".to_owned()],
Path::new("."),
) as Box<dyn HistoryCell>));
group
.group
.push_detail(Arc::new(new_unified_exec_interaction(
Some("cat first.txt".to_owned()),
"continue\n".to_owned(),
)));
group
.append_completed(completed_read("second.txt", "second output"))
.expect("adjacent reads stay grouped");
let raw = group
.raw_lines()
.iter()
.map(Line::to_string)
.collect::<Vec<_>>();
let rich = group
.transcript_lines(/*width*/ 80)
.iter()
.map(Line::to_string)
.collect::<Vec<_>>()
.join("\n");
insta::assert_snapshot!(format!("Rich\n{rich}\n\nRaw\n{}", raw.join("\n")));
let mut earlier = completed_read("earlier.txt", "earlier output");
earlier
.group
.push_detail(Arc::from(new_reasoning_summary_block(
vec!["Inspect the first file".to_owned()],
Path::new("."),
) as Box<dyn HistoryCell>));
earlier
.group
.push_detail(Arc::new(new_unified_exec_interaction(
Some("cat earlier.txt".to_owned()),
"next\n".to_owned(),
)));
let mut expected_raw = earlier.raw_lines();
expected_raw.push(Line::from(""));
expected_raw.extend(group.raw_lines());
let mut expected_rich = earlier.transcript_hyperlink_lines(/*width*/ 80);
expected_rich.push(HyperlinkLine::from(""));
expected_rich.extend(group.transcript_hyperlink_lines(/*width*/ 80));
group.prepend(earlier);
assert_eq!(group.raw_lines(), expected_raw);
assert_eq!(
group.transcript_hyperlink_lines(/*width*/ 80),
expected_rich
);
}