Show background command launches and late results in the TUI (#64015)

## Why

A background command can outlive the turn that launched it. Its result
could be dropped when no turn was active or appear as a separate
transcript entry if later output had already displaced its running row.

## What changed

- Show background commands as they start, including commands that don't
  match a recognized tool action. Keep tracking their exits after a
  turn ends or is interrupted.
- Update the original transcript row with the exit status and output,
  including when the command finishes in a parked side conversation.
- In rich terminal scrollback, label an unfinished launch `Started`.
  If the launch has already printed, append the result in order.
  Otherwise, replace the queued launch with the completed entry.

## Testing

Cover late exits after turn completion and interruption, completion
during a side conversation handoff, and result ordering behind queued
scrollback.

GitOrigin-RevId: 65f069af28c112078d85613da2c95e5c1c4f29bf
This commit is contained in:
Eric Traut
2026-11-25 22:54:56 +00:00
committed by copyberry
parent 2f83e4843f
commit ad07f04e47
34 changed files with 347 additions and 150 deletions
+54 -11
View File
@@ -1,13 +1,57 @@
//! Repair activity groups split by transport pages without rewriting terminal scrollback.
//! Update committed command activity and join groups split by transport pages.
//!
//! Only persisted member adjacency within one turn permits joins. Overlay callbacks retain the
//! displayed source revision before canonical cells are replaced or absorbed into the live tail.
use super::*;
use crate::exec_cell::ExecCell;
use crate::thread_transcript::join_computer_groups;
use crate::thread_transcript::join_exploration_groups;
/// Locate an unfinished call and preserve its neighbors and transcript details.
pub(super) fn pending_command_group(
cells: &[Arc<dyn HistoryCell>],
id: &str,
) -> Option<(usize, usize, ExecCell)> {
cells.iter().enumerate().rev().find_map(|(index, cell)| {
let group = cell.as_any().downcast_ref::<ExecCell>()?;
let member = group
.iter_calls()
.position(|call| call.call_id == id && call.duration.is_none())?;
Some((index, member, group.clone()))
})
}
impl App {
pub(crate) fn complete_background_command(
&mut self,
tui: &mut tui::Tui,
mut completed: Box<ExecCell>,
) {
let Some((index, member, mut group)) =
pending_command_group(&self.transcript_cells, &completed.group.calls[0].call_id)
else {
// The transcript may have been cleared while the command was running.
self.insert_history_cell(tui, completed);
return;
};
// Consolidation replaces an unprinted launch. Otherwise append just this result.
let owner = &self.transcript_cells[index];
if !tui.is_owned_screen()
&& !self.native_history.contains(owner)
&& !self.native_history.defer_command_result(owner, &completed)
{
let width = self
.chat_widget
.history_wrap_width(tui.terminal.last_known_screen_size.width);
self.insert_history_cell_lines(tui, completed.as_ref(), width);
self.last_rendered_history_tail = None;
}
group.group.calls[member] = completed.group.calls.remove(0);
self.replace_activity_group(index..index + 1, Arc::new(group));
tui.frame_requester().schedule_frame();
}
pub(super) fn join_older_activity_group(&mut self, boundary: usize, turns: &[Turn]) {
let Some(start) = self.transcript_cells[..boundary]
.iter()
@@ -29,15 +73,7 @@ impl App {
) else {
return;
};
let range = start..newer_index;
self.native_history
.consolidate(&self.transcript_cells[range.clone()], &older);
self.transcript_view
.replace_group(&self.transcript_cells, range.clone(), &older);
if let Some(Overlay::Transcript(overlay)) = self.overlay.as_mut() {
overlay.regroup_cells(range.clone(), Arc::clone(&older));
}
self.transcript_cells.splice(range, [older]);
self.replace_activity_group(start..newer_index, older);
newer_index = start + 1;
}
if newer_index == self.transcript_cells.len() {
@@ -73,7 +109,14 @@ impl App {
else {
return;
};
let range = start..newer_index + 1;
self.replace_activity_group(start..newer_index + 1, group);
}
fn replace_activity_group(
&mut self,
range: std::ops::Range<usize>,
group: Arc<dyn HistoryCell>,
) {
self.native_history
.consolidate(&self.transcript_cells[range.clone()], &group);
self.transcript_view
+2
View File
@@ -141,6 +141,7 @@ impl App {
| AppEvent::ConfirmDaemonUpdate(_)
| AppEvent::RunDaemonUpdate(_)
| AppEvent::InsertHistoryCell(_)
| AppEvent::CompleteBackgroundCommand(_)
| AppEvent::CommitRealtimeTranscriptHistory
| AppEvent::ParkSideCompanion { .. }
| AppEvent::SideCreated { .. }
@@ -1270,6 +1271,7 @@ impl App {
self.prepare_collab_history(app_server, cell.as_mut());
self.insert_history_cell(tui, cell);
}
AppEvent::CompleteBackgroundCommand(cell) => self.complete_background_command(tui, cell),
AppEvent::TurnTipReady { thread_id, turn_id } => {
self.turn_tips.ready(thread_id, &turn_id, self.transcript_cells.last());
tui.frame_requester().schedule_frame();
+2 -2
View File
@@ -34,7 +34,7 @@ impl App {
}
}
pub(super) fn insert_history_cell(
pub(crate) fn insert_history_cell(
&mut self,
tui: &mut tui::Tui,
mut cell: Box<dyn HistoryCell>,
@@ -97,7 +97,7 @@ impl App {
// Owned replay must not eagerly format every historical entry. Composite status cards are
// the only committed cells whose mutable usage data needs insertion-time bookkeeping.
let lines = if !deferred || cell.as_any().is::<history_cell::CompositeHistoryCell>() {
cell.display_hyperlink_lines_for_mode(width, self.chat_widget.history_render_mode())
cell.scrollback_lines(width, self.chat_widget.history_render_mode())
} else {
Vec::new()
};
+22 -1
View File
@@ -10,6 +10,7 @@ use super::*;
const CELLS_PER_FRAME: usize = 32;
struct PendingCell {
appended_result: bool,
source: Arc<dyn HistoryCell>,
owner: std::sync::Weak<dyn HistoryCell>,
}
@@ -43,11 +44,29 @@ impl NativeHistory {
pub(super) fn defer(&mut self, cell: &Arc<dyn HistoryCell>) {
self.pending.push_back(PendingCell {
appended_result: false,
source: cell.clone(),
owner: Arc::downgrade(cell),
});
}
/// A printed launch owns the result even when later entries delay its emission.
pub(super) fn defer_command_result(
&mut self,
owner: &Arc<dyn HistoryCell>,
result: &crate::exec_cell::ExecCell,
) -> bool {
if self.pending.is_empty() {
return false;
}
self.pending.push_back(PendingCell {
appended_result: true,
source: Arc::new(result.clone()),
owner: Arc::downgrade(owner),
});
true
}
/// Replace an entirely unprinted stream with final source. For a partly printed stream, keep
/// only its remaining fragments; never replay the prefix already owned by the terminal.
pub(super) fn consolidate(
@@ -67,6 +86,7 @@ impl NativeHistory {
self.pending.insert(
index,
PendingCell {
appended_result: false,
source: consolidated.clone(),
owner: Arc::downgrade(consolidated),
},
@@ -109,7 +129,8 @@ impl NativeHistory {
let mut blocked = false;
self.pending.retain(|entry| {
blocked |= is_pending(entry.source.as_ref());
blocked
// Printed launches precede the blocker and replay with their results in place.
blocked && !entry.appended_result
});
}
}
@@ -70,6 +70,16 @@ async fn settled_tool_precedes_queued_output_and_is_not_emitted_twice() -> Resul
.push(Arc::new(history_cell::PlainHistoryCell::new(vec![
"past context".into(),
])));
let mut command = crate::exec_cell::new_active_exec_command(
"cmd".into(),
vec!["build".into()],
Vec::new(),
codex_app_server_protocol::CommandExecutionSource::UnifiedExecStartup,
/*interaction_input*/ None,
/*animations_enabled*/ false,
);
app.insert_history_cell(&mut tui, Box::new(command.clone()));
tui.clear_pending_history_lines();
app.insert_history_cell(&mut tui, Box::new(cell.clone()));
app.flush_native_history(&mut tui);
assert!(tui.pending_history_lines_for_test().is_empty());
@@ -122,6 +132,13 @@ async fn settled_tool_precedes_queued_output_and_is_not_emitted_twice() -> Resul
.iter()
.any(|line| line.line.to_string().contains("Calling lookup"))
);
command.complete_call(
"cmd",
crate::exec_cell::CommandOutput::new(/*exit_code*/ 0, "built".into()),
Duration::ZERO,
);
app.complete_background_command(&mut tui, Box::new(command));
assert!(tui.pending_history_lines_for_test().is_empty());
cell.update_from_item(item(DynamicToolCallStatus::Completed));
for _ in 0..=4097 / CELLS_PER_FRAME {
app.flush_native_history(&mut tui);
@@ -134,6 +151,12 @@ async fn settled_tool_precedes_queued_output_and_is_not_emitted_twice() -> Resul
.join("\n");
assert_eq!(text.matches("unique result").count(), 1);
assert_eq!(text.matches("later output").count(), 4097);
insta::assert_snapshot!(&text[text.find("later output 4096").unwrap()..], @"
later output 4096
• Ran build
└ built
");
let answer = text.find("Introduction and conclusion").unwrap();
let error = text.find("Paste failed").unwrap();
assert_eq!(text.matches("Introduction").count(), 1);
+4 -12
View File
@@ -93,8 +93,7 @@ impl App {
cell: &dyn HistoryCell,
width: u16,
) -> Vec<HyperlinkLine> {
let mut display =
cell.display_hyperlink_lines_for_mode(width, self.chat_widget.history_render_mode());
let mut display = cell.scrollback_lines(width, self.chat_widget.history_render_mode());
if !display.is_empty() && !cell.is_stream_continuation() {
if self.has_emitted_history_lines {
display.insert(/*index*/ 0, HyperlinkLine::new(Line::from("")));
@@ -547,10 +546,7 @@ impl App {
.iter()
.rev()
.find_map(|cell| {
let lines = cell.display_hyperlink_lines_for_mode(
width,
self.chat_widget.history_render_mode(),
);
let lines = cell.scrollback_lines(width, self.chat_widget.history_render_mode());
(!lines.is_empty()).then(|| super::history_ui::RenderedHistoryTail {
cell: Arc::downgrade(cell),
lines,
@@ -660,8 +656,7 @@ impl App {
while start > 0 {
start -= 1;
let cell = self.transcript_cells[start].clone();
let lines = cell
.display_hyperlink_lines_for_mode(width, self.chat_widget.history_render_mode());
let lines = cell.scrollback_lines(width, self.chat_widget.history_render_mode());
rendered_rows += lines.len();
cell_displays.push_front(ReflowCellDisplay {
lines,
@@ -685,10 +680,7 @@ impl App {
start -= 1;
let cell = self.transcript_cells[start].clone();
cell_displays.push_front(ReflowCellDisplay {
lines: cell.display_hyperlink_lines_for_mode(
width,
self.chat_widget.history_render_mode(),
),
lines: cell.scrollback_lines(width, self.chat_widget.history_render_mode()),
is_stream_continuation: cell.is_stream_continuation(),
});
}
+26 -11
View File
@@ -252,15 +252,11 @@ impl SideCompanion {
duration_ms,
..
} => {
let Some(cell) = self.display.active.as_mut().and_then(|active| {
active
.as_any_mut()
.downcast_mut::<crate::exec_cell::ExecCell>()
}) else {
if *status == codex_app_server_protocol::CommandExecutionStatus::InProgress {
return false;
};
if *status == codex_app_server_protocol::CommandExecutionStatus::InProgress
|| !cell.complete_call(
}
let complete = |cell: &mut crate::exec_cell::ExecCell| {
cell.complete_call(
id,
crate::exec_cell::CommandOutput::from_execution(
status.clone(),
@@ -270,9 +266,28 @@ impl SideCompanion {
),
Duration::from_millis(duration_ms.unwrap_or_default().max(0) as u64),
)
{
return false;
}
};
let active = self.display.active.as_mut().and_then(|active| {
active
.as_any_mut()
.downcast_mut::<crate::exec_cell::ExecCell>()
});
let Some(cell) =
active.filter(|cell| cell.iter_calls().any(|call| call.call_id == *id))
else {
let Some((index, _, mut group)) =
super::activity_groups::pending_command_group(&self.cells, id)
else {
return false;
};
complete(&mut group);
let group: Arc<dyn HistoryCell> = Arc::new(group);
self.view
.replace_group(&self.cells, index..index + 1, &group);
self.cells[index] = group;
return true;
};
complete(cell);
if !cell.is_active()
&& let Some(active) = self.display.active.take()
{
+35 -22
View File
@@ -5176,12 +5176,12 @@ async fn handle_start_side_seeds_navigation_before_thread_started() -> Result<()
// A command already running at handoff belongs before replies received while parked.
let turn = "command-turn";
let cwd = app.config.cwd.clone();
let command = |status| ThreadItemPayload::CommandExecution {
id: "cmd".into(),
command: "echo sidebar-check".into(),
let command = |id: &str, status| ThreadItemPayload::CommandExecution {
id: id.into(),
command: format!("echo {id}"),
cwd: cwd.clone().into(),
status,
source: Default::default(),
source: codex_app_server_protocol::CommandExecutionSource::UnifiedExecStartup,
command_actions: Vec::new(),
model_context: None,
sandbox_type: None,
@@ -5193,15 +5193,20 @@ async fn handle_start_side_seeds_navigation_before_thread_started() -> Result<()
duration_ms: None,
};
use codex_app_server_protocol::CommandExecutionStatus;
for event in [
turn_started_notification(parent, turn),
ServerNotification::ItemStarted(ItemStartedNotification::new(
app.enqueue_thread_notification(parent, turn_started_notification(parent, turn))
.await?;
// The second launch commits the first row before focus switches.
let commands = [
("background", CommandExecutionStatus::Failed),
("sidebar-check", CommandExecutionStatus::Completed),
];
for (id, _) in &commands {
let event = ServerNotification::ItemStarted(ItemStartedNotification::new(
parent.to_string(),
turn.into(),
command(CommandExecutionStatus::InProgress),
command(id, CommandExecutionStatus::InProgress),
/*started_at_ms*/ 0,
)),
] {
));
app.enqueue_thread_notification(parent, event).await?;
}
keys!(prefix, side);
@@ -5213,23 +5218,31 @@ async fn handle_start_side_seeds_navigation_before_thread_started() -> Result<()
)
.await?;
side_frame(&mut app, &mut tui, size)?;
app.enqueue_thread_notification(
parent,
ServerNotification::ItemCompleted(
codex_app_server_protocol::ItemCompletedNotification::new(
parent.to_string(),
turn.into(),
command(CommandExecutionStatus::Completed),
/*started_at_ms*/ None,
/*completed_at_ms*/ 0,
for (id, status) in commands {
app.enqueue_thread_notification(
parent,
ServerNotification::ItemCompleted(
codex_app_server_protocol::ItemCompletedNotification::new(
parent.to_string(),
turn.into(),
command(id, status),
/*started_at_ms*/ None,
/*completed_at_ms*/ 0,
),
),
),
)
.await?;
)
.await?;
}
let finished = side_frame(&mut app, &mut tui, size)?;
let (_, after_command) = finished
.split_once("Ran echo sidebar-check")
.unwrap_or_else(|| panic!("{finished}"));
// Compact activity groups show the latest command. Inspect the earlier row in place.
let pane = &app.side_companions[&parent_thread_id];
insta::assert_snapshot!(
lines_to_single_string(&pane.cells[pane.parked_tail - 1].transcript_lines(/*width*/ 80)),
@"$ echo background\n✗ (1) • 0ms"
);
assert!(after_command.contains("Command finished."), "{finished}");
assert_eq!(
finished.matches("echo sidebar-check").count(),
+2
View File
@@ -1419,6 +1419,8 @@ pub(crate) enum AppEvent {
FollowTranscript,
InsertHistoryCell(Box<dyn HistoryCell>),
/// Finish a command whose running cell has already been committed to history.
CompleteBackgroundCommand(Box<crate::exec_cell::ExecCell>),
/// FIFO barrier after the completed turn's history insertions.
TurnTipReady {
thread_id: ThreadId,
@@ -30,10 +30,10 @@ impl ChatWidget {
self.bump_active_cell_revision();
return Ok(());
}
if let Some(exploration) = active.as_any_mut().downcast_mut::<ExecCell>()
&& exploration.is_exploring_cell()
if let Some(exec) = active.as_any_mut().downcast_mut::<ExecCell>()
&& !exec.should_flush()
{
exploration.group.push_detail(Arc::from(cell));
exec.group.push_detail(Arc::from(cell));
self.bump_active_cell_revision();
return Ok(());
}
@@ -29,13 +29,11 @@ impl ChatWidget {
command,
process_id,
source,
command_actions,
..
} = &item
else {
return;
};
let (_command, parsed_cmd) = command_execution_command_and_parsed(command, command_actions);
self.flush_answer_stream_with_separator();
if is_unified_exec_source(*source) {
if *source == ExecCommandSource::UnifiedExecStartup && !render_source.is_replay() {
@@ -44,11 +42,10 @@ impl ChatWidget {
if !self.bottom_pane.is_task_running() {
return;
}
// Unified exec may be parsed as Unknown; keep the working indicator visible regardless.
self.bottom_pane.ensure_status_indicator();
if !is_standard_tool_call(&parsed_cmd) {
return;
if *source == ExecCommandSource::UnifiedExecStartup {
self.transcript.pending_command_rows.insert(id.clone());
}
self.bottom_pane.ensure_status_indicator();
}
self.defer_or_handle(
item,
@@ -157,7 +154,9 @@ impl ChatWidget {
self.flush_unified_exec_wait_streak();
}
self.track_unified_exec_process_end(id, process_id.as_deref());
if !self.bottom_pane.is_task_running() {
if !self.bottom_pane.is_task_running()
&& *source != ExecCommandSource::UnifiedExecStartup
{
return;
}
}
@@ -305,6 +304,10 @@ impl ChatWidget {
};
let (command, parsed_cmd) =
command_execution_command_and_parsed(&command, &command_actions);
let is_wait_interaction = matches!(source, ExecCommandSource::UnifiedExecInteraction);
if is_wait_interaction && !is_standard_tool_call(&parsed_cmd) {
return;
}
// Ensure the status indicator is visible while the command runs.
self.bottom_pane.ensure_status_indicator();
let parsed_cmd = self.annotate_skill_reads_in_parsed_cmd(parsed_cmd);
@@ -316,7 +319,6 @@ impl ChatWidget {
source,
},
);
let is_wait_interaction = matches!(source, ExecCommandSource::UnifiedExecInteraction);
let command_display = command.join(" ");
let should_suppress_unified_wait = is_wait_interaction
&& self
@@ -407,6 +409,7 @@ impl ChatWidget {
if self.suppressed_exec_calls.remove(&id) {
return;
}
let was_running = self.transcript.pending_command_rows.remove(&id) || running.is_some();
let (command, parsed, source) = match running {
Some(rc) => (rc.command, rc.parsed_cmd, rc.source),
None => (event_command, event_parsed, source),
@@ -420,6 +423,7 @@ impl ChatWidget {
.active_cell
.as_mut()
.and_then(|cell| cell.as_any_mut().downcast_mut::<ExecCell>())
&& !was_running
&& !cell.is_active()
&& !cell.should_flush()
&& !cell.iter_calls().any(|call| call.call_id == id)
@@ -473,22 +477,7 @@ impl ChatWidget {
}
}
}
ExecEndTarget::OrphanHistoryWhileActiveExec => {
let mut orphan = new_active_exec_command(
id.clone(),
command,
parsed,
source,
/*interaction_input*/ None,
self.local_settings.tui.animations && self.local_settings.tui.effects.progress,
);
let completed = orphan.complete_call(&id, output, duration);
debug_assert!(completed, "new orphan exec cell should contain {id}");
self.app_event_tx
.send(AppEvent::InsertHistoryCell(Box::new(orphan)));
self.request_redraw();
}
ExecEndTarget::NewCell => {
ExecEndTarget::OrphanHistoryWhileActiveExec | ExecEndTarget::NewCell => {
let mut cell = new_active_exec_command(
id.clone(),
command,
@@ -499,7 +488,15 @@ impl ChatWidget {
);
let completed = cell.complete_call(&id, output, duration);
debug_assert!(completed, "new exec cell should contain {id}");
if let Some(active) = self
if was_running {
// Another item committed the running cell to history before this exit.
self.app_event_tx
.send(AppEvent::CompleteBackgroundCommand(Box::new(cell)));
} else if matches!(end_target, ExecEndTarget::OrphanHistoryWhileActiveExec) {
self.app_event_tx
.send(AppEvent::InsertHistoryCell(Box::new(cell)));
self.request_redraw();
} else if let Some(active) = self
.transcript
.active_cell
.as_mut()
@@ -380,6 +380,7 @@ impl ChatWidget {
self.turn_lifecycle.reset_thread();
self.review = Default::default();
self.transcript.take_active_cell();
self.transcript.pending_command_rows.clear();
self.transcript.reset_copy_history();
self.transcript.reset_turn_flags();
for turn in retained_turns {
@@ -2,5 +2,8 @@
source: tui/src/chatwidget/tests/exec_flow.rs
expression: snapshot
---
cells=1
cells=2
• Running just fix
■ Conversation interrupted - use /feedback if something went wrong
@@ -4,6 +4,8 @@ expression: "format!(\"80 columns:\\n{}\\n120 columns:\\n{}\", hook_status_frame
---
80 columns:
" "
"• Running sleep 2 "
" "
"• Working (0s • esc to interrupt) · 1 background terminal running · /ps to view…"
" └ checking command policy for deployment commands, production credentials, an…"
" "
@@ -14,6 +16,8 @@ expression: "format!(\"80 columns:\\n{}\\n120 columns:\\n{}\", hook_status_frame
" ? for shortcuts "
120 columns:
" "
"• Running sleep 2 "
" "
"• Working (0s • esc to interrupt) · 1 background terminal running · /ps to view · /stop to close "
" └ checking command policy for deployment commands, production credentials, and paths containing 日本語 before continu…" Hidden by multi-width symbols: [(99, " "), (101, " "), (103, " ")]
" "
@@ -4,6 +4,8 @@ expression: "format!(\"80 columns:\\n{}\\n120 columns:\\n{}\", hook_status_frame
---
80 columns:
" "
"• Running sleep 2 "
" "
"• Working (0s • esc to interrupt) · 1 background terminal running · /ps to view…"
" └ Running hooks "
" "
@@ -14,6 +16,8 @@ expression: "format!(\"80 columns:\\n{}\\n120 columns:\\n{}\", hook_status_frame
" ? for shortcuts "
120 columns:
" "
"• Running sleep 2 "
" "
"• Working (0s • esc to interrupt) · 1 background terminal running · /ps to view · /stop to close · Running hooks "
" "
" "
@@ -1,9 +1,10 @@
---
source: tui/src/chatwidget/tests/status_and_layout.rs
assertion_line: 4833
expression: normalized_backend_snapshot(terminal.backend())
---
" "
"• Running sleep 2 "
" "
"• Checking files and preparing a response (0s • esc to interrupt) · 1 backgroun…"
" "
" "
@@ -4,6 +4,8 @@ expression: "format!(\"80 columns:\\n{}\\n120 columns:\\n{}\", hook_status_frame
---
80 columns:
" "
"• Running sleep 2 "
" "
"• Working (0s • esc to interrupt) · 1 background terminal running · /ps to view…"
" └ checking command policy "
" "
@@ -14,6 +16,8 @@ expression: "format!(\"80 columns:\\n{}\\n120 columns:\\n{}\", hook_status_frame
" ? for shortcuts "
120 columns:
" "
"• Running sleep 2 "
" "
"• Working (0s • esc to interrupt) · 1 background terminal running · /ps to view · /stop to close "
" └ checking command policy "
" "
@@ -3,6 +3,8 @@ source: tui/src/chatwidget/tests/exec_flow.rs
expression: normalized_backend_snapshot(terminal.backend())
---
" "
"• Running sleep 2 "
" "
"• Working (0s • esc to interrupt) · 1 background terminal running · /ps to view…"
" "
" "
@@ -1,7 +1,9 @@
---
source: tui/src/chatwidget/tests.rs
source: tui/src/chatwidget/tests/exec_flow.rs
expression: combined
---
$ just fix
• Waited for background terminal · just fix
↳ Interacted with background terminal · just fix
@@ -0,0 +1,26 @@
---
source: tui/src/chatwidget/tests/exec_flow.rs
expression: "format!(\"Active\\n{started}\\nNative scrollback\\n{native}\\nTranscript after exit\\n{finished}\")"
---
Active
• Running sleep 20; echo marker; exit 1
Native scrollback
• Started sleep 20; echo marker; exit 1
• Ran echo quick
└ quick
• Finished.
• Ran sleep 20; echo marker; exit 1
└ marker
Transcript after exit
$ sleep 20; echo marker; exit 1
marker
✗ (1) • 5ms
$ echo quick
quick
✓ • 5ms
• Finished.
@@ -1,6 +1,8 @@
---
source: tui/src/chatwidget/tests.rs
source: tui/src/chatwidget/tests/exec_flow.rs
expression: active_combined
---
$ just fix
↳ Interacted with background terminal · just fix
└ pwd
@@ -1,8 +1,9 @@
---
source: tui/src/chatwidget/tests/exec_flow.rs
assertion_line: 1309
expression: combined
---
$ just fix
↳ Interacted with background terminal · just fix
└ pwd
@@ -1,8 +1,9 @@
---
source: tui/src/chatwidget/tests/exec_flow.rs
assertion_line: 1068
expression: combined
---
$ cargo test -p codex-core
• Waited for background terminal · cargo test -p codex-core
• Final response.
@@ -1,8 +1,9 @@
---
source: tui/src/chatwidget/tests/exec_flow.rs
assertion_line: 1092
expression: combined
---
$ cargo test -p codex-core
• Waited for background terminal · cargo test -p codex-core
• Streaming response.
@@ -2,6 +2,9 @@
source: tui/src/chatwidget/tests/exec_flow.rs
expression: normalize_snapshot_paths(rendered)
---
• Running cargo test -p codex-core -- --exact
│ some::very::long::test::name
• Waiting for background terminal (0s • esc to …
└ cargo test -p codex-core -- --exact…
@@ -1,11 +1,13 @@
---
source: tui/src/chatwidget/tests/exec_flow.rs
assertion_line: 1229
expression: combined
---
Chat:
• Running just fix
Worked for [duration] • [completion time]
Transcript:
$ just fix
• Waited for background terminal · just fix
Worked for [duration] • [completion time]
+58 -41
View File
@@ -629,16 +629,14 @@ async fn exec_end_without_begin_uses_event_command() {
#[tokio::test]
async fn exec_end_without_begin_does_not_flush_unrelated_running_exploring_cell() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
let orphan =
begin_unified_exec_startup(&mut chat, "call-orphan", "proc-1", "echo repro-marker");
chat.on_task_started();
begin_exec(&mut chat, "call-exploring", "cat /dev/null");
assert!(drain_insert_history(&mut rx).is_empty());
assert!(active_blob(&chat).contains("Read null"));
let orphan =
begin_unified_exec_startup(&mut chat, "call-orphan", "proc-1", "echo repro-marker");
assert!(drain_insert_history(&mut rx).is_empty());
end_exec(
&mut chat,
orphan,
@@ -672,6 +670,7 @@ async fn exec_end_without_begin_does_not_flush_unrelated_running_exploring_cell(
#[tokio::test]
async fn exec_end_without_begin_flushes_completed_unrelated_exploring_cell() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
let orphan = begin_unified_exec_startup(&mut chat, "call-after", "proc-1", "echo after");
chat.on_task_started();
let begin_ls = begin_exec(&mut chat, "call-ls", "ls -la");
@@ -679,7 +678,6 @@ async fn exec_end_without_begin_flushes_completed_unrelated_exploring_cell() {
assert!(drain_insert_history(&mut rx).is_empty());
assert!(active_blob(&chat).contains("ls -la"));
let orphan = begin_unified_exec_startup(&mut chat, "call-after", "proc-1", "echo after");
end_exec(&mut chat, orphan, "after\n", "", /*exit_code*/ 0);
let cells = drain_insert_history(&mut rx);
@@ -793,11 +791,11 @@ async fn exec_history_shows_unified_exec_tool_calls() {
#[tokio::test]
async fn unified_exec_unknown_end_with_active_exploring_cell_snapshot() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
let orphan =
begin_unified_exec_startup(&mut chat, "call-orphan", "proc-1", "echo repro-marker");
chat.on_task_started();
begin_exec(&mut chat, "call-exploring", "cat /dev/null");
let orphan =
begin_unified_exec_startup(&mut chat, "call-orphan", "proc-1", "echo repro-marker");
end_exec(
&mut chat,
orphan,
@@ -820,28 +818,50 @@ async fn unified_exec_unknown_end_with_active_exploring_cell_snapshot() {
}
#[tokio::test]
async fn unified_exec_end_after_task_complete_is_suppressed() {
async fn unified_exec_late_exit_updates_the_original_row() -> color_eyre::Result<()> {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
chat.local_settings.tui.animations = false;
chat.on_task_started();
let begin = begin_exec_with_source(
&mut chat,
"call-startup",
"echo unified exec startup",
ExecCommandSource::UnifiedExecStartup,
);
drain_insert_history(&mut rx);
let slow = begin_unified_exec_startup(&mut chat, "slow", "1", "sleep 20; echo marker; exit 1");
let started = active_blob(&chat);
let quick = begin_unified_exec_startup(&mut chat, "quick", "2", "echo quick");
end_exec(&mut chat, quick, "quick\n", "", /*exit_code*/ 0);
complete_assistant_message(&mut chat, "msg-1", "Finished.", /*phase*/ None);
chat.on_task_complete(
/*last_agent_message*/ None, /*completion*/ None, /*from_replay*/ false,
);
end_exec(&mut chat, begin, "", "", /*exit_code*/ 0);
end_exec(&mut chat, slow, "marker\n", "", /*exit_code*/ 1);
assert!(chat.unified_exec_processes.is_empty());
assert!(!chat.is_task_running_for_test());
let cells = drain_insert_history(&mut rx);
assert!(
cells.is_empty(),
"expected unified exec end after task complete to be suppressed"
let mut app = crate::app::test_support::make_test_app().await;
let mut tui = crate::tui::test_support::make_test_tui()?;
// Opening the transcript buffers the actual native scrollback lines for inspection.
app.open_transcript_overlay(&mut tui);
while let Ok(event) = rx.try_recv() {
match event {
AppEvent::InsertHistoryCell(cell) => app.insert_history_cell(&mut tui, cell),
AppEvent::CompleteBackgroundCommand(cell) => {
app.complete_background_command(&mut tui, cell)
}
_ => {}
}
}
let native = lines_to_single_string(&crate::terminal_hyperlinks::visible_lines(
app.deferred_history_lines.clone(),
));
let finished = app
.transcript_cells
.iter()
.map(|cell| lines_to_single_string(&cell.transcript_lines(/*width*/ 80)))
.collect::<String>();
assert_chatwidget_snapshot!(
"unified_exec_late_exit",
format!(
"Active\n{started}\nNative scrollback\n{native}\nTranscript after exit\n{finished}"
)
);
Ok(())
}
#[tokio::test]
@@ -1071,6 +1091,7 @@ async fn unified_exec_empty_then_non_empty_snapshot() {
terminal_interaction(&mut chat, "call-wait-2a", "proc-2", "");
terminal_interaction(&mut chat, "call-wait-2b", "proc-2", "ls\n");
chat.flush_active_cell();
let cells = drain_insert_history_transcript(&mut rx);
let combined = cells
.iter()
@@ -1097,28 +1118,14 @@ async fn unified_exec_non_empty_then_empty_snapshots() {
.expect("status indicator should be visible");
assert_eq!(status.header(), "Waiting for background terminal");
assert_eq!(status.details(), Some("just fix"));
let pre_cells = drain_insert_history_transcript(&mut rx);
let active_combined = pre_cells
.iter()
.map(|lines| lines_to_single_string(lines))
.collect::<String>();
let active_combined =
lines_to_single_string(&chat.active_cell_transcript_lines(/*width*/ 80).unwrap());
assert_chatwidget_snapshot!("unified_exec_non_empty_then_empty_active", active_combined);
handle_turn_completed(&mut chat, "turn-1", /*duration_ms*/ None);
let post_cells = drain_insert_history_transcript_normalized(&mut rx);
let mut combined = pre_cells
.iter()
.map(|lines| lines_to_single_string(lines))
.collect::<String>();
let post = post_cells
.iter()
.map(|lines| lines_to_single_string(lines))
.collect::<String>();
if !combined.is_empty() && !post.is_empty() {
combined.push('\n');
}
combined.push_str(&post);
let combined =
lines_to_single_string(&drain_insert_history_transcript_normalized(&mut rx).concat());
assert_chatwidget_snapshot!("unified_exec_non_empty_then_empty_after", combined);
}
@@ -1350,6 +1357,11 @@ async fn bang_shell_enter_while_task_running_submits_run_user_shell_command() {
async fn user_message_during_user_shell_command_is_queued_not_steered() {
let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
chat.thread_id = Some(ThreadId::new());
chat.on_task_started();
begin_unified_exec_startup(&mut chat, "background", "1", "sleep 20");
chat.on_task_complete(
/*last_agent_message*/ None, /*completion*/ None, /*from_replay*/ false,
);
handle_turn_started(&mut chat, "turn-1");
let begin = begin_exec_with_source(
&mut chat,
@@ -1645,7 +1657,6 @@ async fn interrupt_preserves_unified_exec_wait_streak_snapshot() {
handle_turn_interrupted(&mut chat, "turn-1");
end_exec(&mut chat, begin, "", "", /*exit_code*/ 0);
let cells = drain_insert_history(&mut rx);
let combined = cells
.iter()
@@ -1654,6 +1665,12 @@ async fn interrupt_preserves_unified_exec_wait_streak_snapshot() {
.join("\n");
let snapshot = format!("cells={}\n{combined}", cells.len());
assert_chatwidget_snapshot!("interrupt_preserves_unified_exec_wait_streak", snapshot);
end_exec(&mut chat, begin, "", "", /*exit_code*/ 0);
assert!(
std::iter::from_fn(|| rx.try_recv().ok())
.any(|event| matches!(event, AppEvent::CompleteBackgroundCommand(_)))
);
}
#[tokio::test]
@@ -37,6 +37,8 @@ type ReplayedCloudItems = std::collections::HashMap<String, (bool, i64)>;
#[derive(Default)]
pub(super) struct TranscriptState {
pub(super) active_cell: Option<Box<dyn HistoryCell>>,
/// Background command rows awaiting an exit, even after turn cleanup or /stop.
pub(super) pending_command_rows: std::collections::HashSet<String>,
/// Shared retained rows for concurrently running dynamic tools, removed on completion.
pub(super) dynamic_calls:
std::collections::HashMap<String, crate::history_cell::DynamicToolCallCell>,
+1 -1
View File
@@ -16,7 +16,7 @@ const LIVE_COMMAND_OUTPUT_LINE_TAIL_BYTES: usize =
/// 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)]
#[derive(Clone, Debug, Default)]
pub(super) struct LiveCommandOutput {
full_output: String,
truncated: bool,
+5 -4
View File
@@ -18,7 +18,7 @@ use codex_app_server_protocol::CommandExecutionSource as ExecCommandSource;
use codex_protocol::parse_command::ParsedCommand;
use itertools::Either;
#[derive(Debug, Default)]
#[derive(Clone, Debug, Default)]
pub(crate) struct CommandOutput {
pub(crate) exit_code: i32,
/// The finalized, interleaved stderr and stdout that replaces any streamed preview.
@@ -83,7 +83,7 @@ impl CommandOutput {
}
}
#[derive(Debug)]
#[derive(Clone, Debug)]
pub(crate) struct ExecCall {
pub(crate) call_id: String,
pub(crate) command: Vec<String>,
@@ -95,7 +95,7 @@ pub(crate) struct ExecCall {
pub(crate) interaction_input: Option<String>,
}
#[derive(Debug)]
#[derive(Clone, Debug)]
pub(crate) struct ExecCell {
pub(crate) group: ActivityGroup<ExecCall>,
animations_enabled: bool,
@@ -187,7 +187,8 @@ impl ExecCell {
pub(crate) fn mark_failed(&mut self) {
for call in self.group.calls.iter_mut() {
if call.duration.is_none() {
// Unified exec processes survive turn interruption and report their own exit.
if call.duration.is_none() && call.source != ExecCommandSource::UnifiedExecStartup {
let elapsed = call
.start_time
.map(|st| st.elapsed())
+14 -8
View File
@@ -227,7 +227,7 @@ impl HistoryCell for ExecCell {
// User-shell previews already retain wrapped commands and up to fifty output rows.
// Reuse its actual truncation decision instead of comparing differently styled text.
return self
.command_display_lines_with_hidden_details(width)
.command_display(width, "Running")
.hidden_details
.then_some(ActivityDisclosure::Generic);
}
@@ -280,10 +280,20 @@ impl HistoryCell for ExecCell {
if self.is_exploring_cell() {
self.exploring_display_lines(width)
} else {
self.command_display_lines(width)
self.command_display(width, "Running").lines
}
}
fn scrollback_lines(&self, width: u16, mode: HistoryRenderMode) -> Vec<HyperlinkLine> {
if mode == HistoryRenderMode::Rich
&& !self.is_exploring_cell()
&& self.group.calls[0].source == ExecCommandSource::UnifiedExecStartup
{
return self.command_display(width, "Started").lines;
}
self.display_hyperlink_lines_for_mode(width, mode)
}
fn transcript_lines(&self, width: u16) -> Vec<Line<'static>> {
visible_lines(self.transcript_hyperlink_lines(width))
}
@@ -496,11 +506,7 @@ impl ExecCell {
out
}
fn command_display_lines(&self, width: u16) -> Vec<HyperlinkLine> {
self.command_display_lines_with_hidden_details(width).lines
}
fn command_display_lines_with_hidden_details(&self, width: u16) -> CommandDisplay {
fn command_display(&self, width: u16, running_title: &'static str) -> CommandDisplay {
let [call] = &self.group.calls.as_slice() else {
panic!("Expected exactly one call in a command display cell");
};
@@ -517,7 +523,7 @@ impl ExecCell {
let title = if is_interaction {
""
} else if self.is_active() {
"Running"
running_title
} else if call.is_user_shell_command() {
"You ran"
} else {
@@ -7,7 +7,7 @@ use super::ActivityDetails;
use super::HistoryCell;
use std::sync::Arc;
#[derive(Debug)]
#[derive(Clone, Debug)]
pub(crate) struct ActivityGroup<T> {
pub(crate) calls: Vec<T>,
pub(crate) details: ActivityDetails,
+5
View File
@@ -299,6 +299,11 @@ pub(crate) trait HistoryCell: std::fmt::Debug + Send + Sync + Any {
}
}
/// Render a permanent entry in terminal-owned scrollback.
fn scrollback_lines(&self, width: u16, mode: HistoryRenderMode) -> Vec<HyperlinkLine> {
self.display_hyperlink_lines_for_mode(width, mode)
}
/// Returns the number of viewport rows needed to render this cell.
///
/// The default delegates to `Paragraph::line_count` with
@@ -262,6 +262,7 @@ impl TurnDetails {
group.finish(rows, cells);
} else {
if let Some(exec) = any.downcast_ref::<crate::exec_cell::ExecCell>()
&& !exec.is_active()
&& exec.iter_calls().all(|call| {
call.output
.as_ref()