working draft

This commit is contained in:
Roy Han
2026-02-26 19:36:13 -08:00
parent 448fb6ac22
commit c800db5cd5
5 changed files with 243 additions and 121 deletions

View File

@@ -612,6 +612,7 @@ pub(crate) struct App {
primary_thread_id: Option<ThreadId>,
primary_session_configured: Option<SessionConfiguredEvent>,
pending_primary_events: VecDeque<Event>,
startup_header_pending_replacement: bool,
}
#[derive(Default)]
@@ -712,6 +713,57 @@ impl App {
.add_info_message(format!("Opened {url} in your browser."), None);
}
fn insert_history_cell(&mut self, tui: &mut tui::Tui, cell: Arc<dyn HistoryCell>) {
if let Some(Overlay::Transcript(t)) = &mut self.overlay {
t.insert_cell(cell.clone());
tui.frame_requester().schedule_frame();
}
self.transcript_cells.push(cell.clone());
let mut display = cell.display_lines(tui.terminal.last_known_screen_size.width);
if !display.is_empty() {
if !cell.is_stream_continuation() {
if self.has_emitted_history_lines {
display.insert(0, Line::from(""));
} else {
self.has_emitted_history_lines = true;
}
}
if self.overlay.is_some() {
self.deferred_history_lines.extend(display);
} else {
tui.insert_history_lines(display);
}
}
}
fn insert_startup_header(&mut self, tui: &mut tui::Tui) {
let header = Arc::new(history_cell::new_loading_session_header(
self.config.cwd.clone(),
)) as Arc<dyn HistoryCell>;
self.insert_history_cell(tui, header);
self.startup_header_pending_replacement = true;
}
fn replace_startup_header(
&mut self,
tui: &mut tui::Tui,
cell: Arc<dyn HistoryCell>,
) -> Result<()> {
if !self.startup_header_pending_replacement || self.transcript_cells.is_empty() {
return Ok(());
}
self.transcript_cells[0] = cell.clone();
if matches!(&self.overlay, Some(Overlay::Transcript(_))) {
self.overlay = Some(Overlay::new_transcript(self.transcript_cells.clone()));
tui.frame_requester().schedule_frame();
}
let display = cell.display_lines(tui.terminal.last_known_screen_size.width);
tui.replace_top_visible_history_lines(display)?;
self.startup_header_pending_replacement = false;
Ok(())
}
fn clear_ui_header_lines_with_version(
&self,
width: u16,
@@ -773,6 +825,7 @@ impl App {
self.transcript_cells.clear();
self.deferred_history_lines.clear();
self.has_emitted_history_lines = false;
self.startup_header_pending_replacement = false;
self.backtrack = BacktrackState::default();
self.backtrack_render_pending = false;
}
@@ -1078,6 +1131,7 @@ impl App {
self.transcript_cells.clear();
self.deferred_history_lines.clear();
self.has_emitted_history_lines = false;
self.startup_header_pending_replacement = false;
self.backtrack = BacktrackState::default();
self.backtrack_render_pending = false;
tui.terminal.clear_scrollback()?;
@@ -1125,6 +1179,7 @@ impl App {
};
self.chat_widget = ChatWidget::new(init, self.server.clone());
self.reset_thread_event_state();
self.insert_startup_header(tui);
if let Some(summary) = summary {
let mut lines: Vec<Line<'static>> = vec![summary.usage_line.clone().into()];
if let Some(command) = summary.resume_command {
@@ -1237,7 +1292,8 @@ impl App {
use tokio_stream::StreamExt;
let (app_event_tx, mut app_event_rx) = unbounded_channel();
let app_event_tx = AppEventSender::new(app_event_tx);
emit_project_config_warnings(&app_event_tx, &config);
let should_insert_startup_header =
matches!(&session_selection, SessionSelection::StartFresh);
tui.set_notification_method(config.tui_notification_method);
let harness_overrides =
@@ -1405,6 +1461,7 @@ impl App {
let file_search = FileSearchManager::new(config.cwd.clone(), app_event_tx.clone());
#[cfg(not(debug_assertions))]
let upgrade_version = crate::updates::get_upgrade_version(&config);
emit_project_config_warnings(&app_event_tx, &config);
let mut app = Self {
server: thread_manager.clone(),
@@ -1441,8 +1498,13 @@ impl App {
primary_thread_id: None,
primary_session_configured: None,
pending_primary_events: VecDeque::new(),
startup_header_pending_replacement: false,
};
if should_insert_startup_header {
app.insert_startup_header(tui);
}
// On startup, if Agent mode (workspace-write) or ReadOnly is active, warn about world-writable dirs on Windows.
#[cfg(target_os = "windows")]
{
@@ -1793,29 +1855,7 @@ impl App {
}
AppEvent::InsertHistoryCell(cell) => {
let cell: Arc<dyn HistoryCell> = cell.into();
if let Some(Overlay::Transcript(t)) = &mut self.overlay {
t.insert_cell(cell.clone());
tui.frame_requester().schedule_frame();
}
self.transcript_cells.push(cell.clone());
let mut display = cell.display_lines(tui.terminal.last_known_screen_size.width);
if !display.is_empty() {
// Only insert a separating blank line for new cells that are not
// part of an ongoing stream. Streaming continuations should not
// accrue extra blank lines between chunks.
if !cell.is_stream_continuation() {
if self.has_emitted_history_lines {
display.insert(0, Line::from(""));
} else {
self.has_emitted_history_lines = true;
}
}
if self.overlay.is_some() {
self.deferred_history_lines.extend(display);
} else {
tui.insert_history_lines(display);
}
}
self.insert_history_cell(tui, cell);
}
AppEvent::ApplyThreadRollback { num_turns } => {
if self.apply_non_pending_thread_rollback(num_turns) {
@@ -2906,6 +2946,15 @@ impl App {
// thread, so unrelated shutdowns cannot consume this marker.
self.pending_shutdown_exit_thread_id = None;
}
if let EventMsg::SessionConfigured(session) = &event.msg {
let header = Arc::new(history_cell::SessionHeaderHistoryCell::new(
session.model.clone(),
session.reasoning_effort,
session.cwd.clone(),
CODEX_CLI_VERSION,
)) as Arc<dyn HistoryCell>;
self.replace_startup_header(tui, header)?;
}
self.handle_codex_event_now(event);
if self.backtrack_render_pending {
tui.frame_requester().schedule_frame();
@@ -3736,6 +3785,7 @@ mod tests {
primary_thread_id: None,
primary_session_configured: None,
pending_primary_events: VecDeque::new(),
startup_header_pending_replacement: false,
}
}
@@ -3795,6 +3845,7 @@ mod tests {
primary_thread_id: None,
primary_session_configured: None,
pending_primary_events: VecDeque::new(),
startup_header_pending_replacement: false,
},
rx,
op_rx,

View File

@@ -143,8 +143,6 @@ use rand::Rng;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Color;
use ratatui::style::Modifier;
use ratatui::style::Style;
use ratatui::style::Stylize;
use ratatui::text::Line;
use ratatui::widgets::Paragraph;
@@ -1137,16 +1135,17 @@ impl ChatWidget {
);
self.refresh_model_display();
self.sync_personality_command_enabled();
let session_info_cell = history_cell::new_session_info(
if let Some(session_info_body) = history_cell::new_session_info_body(
&self.config,
&model_for_header,
event,
&event,
self.show_welcome_banner,
self.auth_manager
.auth_cached()
.and_then(|auth| auth.account_plan_type()),
);
self.apply_session_info_cell(session_info_cell);
) {
self.add_boxed_history(session_info_body);
}
if let Some(messages) = initial_messages {
self.replay_initial_messages(messages);
@@ -2779,7 +2778,7 @@ impl ChatWidget {
settings: fallback_default,
};
let active_cell = Some(Self::placeholder_session_header_cell(&config));
let active_cell = None;
let current_cwd = Some(config.cwd.clone());
let queued_message_edit_binding =
@@ -2808,7 +2807,7 @@ impl ChatWidget {
auth_manager,
models_manager,
otel_manager,
session_header: SessionHeader::new(header_model),
session_header: SessionHeader::new(DEFAULT_MODEL_DISPLAY_NAME.to_string()),
initial_user_message,
token_info: None,
rate_limit_snapshots_by_limit_id: BTreeMap::new(),
@@ -2956,7 +2955,7 @@ impl ChatWidget {
settings: fallback_default,
};
let active_cell = Some(Self::placeholder_session_header_cell(&config));
let active_cell = None;
let current_cwd = Some(config.cwd.clone());
let queued_message_edit_binding =
@@ -2985,7 +2984,7 @@ impl ChatWidget {
auth_manager,
models_manager,
otel_manager,
session_header: SessionHeader::new(header_model),
session_header: SessionHeader::new(DEFAULT_MODEL_DISPLAY_NAME.to_string()),
initial_user_message,
token_info: None,
rate_limit_snapshots_by_limit_id: BTreeMap::new(),
@@ -3948,15 +3947,7 @@ impl ChatWidget {
}
fn add_boxed_history(&mut self, cell: Box<dyn HistoryCell>) {
// Keep the placeholder session header as the active cell until real session info arrives,
// so we can merge headers instead of committing a duplicate box to history.
let keep_placeholder_header_active = !self.is_session_configured()
&& self
.active_cell
.as_ref()
.is_some_and(|c| c.as_any().is::<history_cell::SessionHeaderHistoryCell>());
if !keep_placeholder_header_active && !cell.display_lines(u16::MAX).is_empty() {
if !cell.display_lines(u16::MAX).is_empty() {
// Only break exec grouping if the cell renders visible lines.
self.flush_active_cell();
self.needs_final_message_separator = true;
@@ -6760,7 +6751,9 @@ impl ChatWidget {
fn refresh_model_display(&mut self) {
let effective = self.effective_collaboration_mode();
self.session_header.set_model(effective.model());
if self.is_session_configured() {
self.session_header.set_model(effective.model());
}
// Keep composer paste affordances aligned with the currently effective model.
self.sync_image_paste_enabled();
}
@@ -6891,46 +6884,6 @@ impl ChatWidget {
}
}
/// Build a placeholder header cell while the session is configuring.
fn placeholder_session_header_cell(config: &Config) -> Box<dyn HistoryCell> {
let placeholder_style = Style::default().add_modifier(Modifier::DIM | Modifier::ITALIC);
Box::new(history_cell::SessionHeaderHistoryCell::new_with_style(
DEFAULT_MODEL_DISPLAY_NAME.to_string(),
placeholder_style,
None,
config.cwd.clone(),
CODEX_CLI_VERSION,
))
}
/// Merge the real session info cell with any placeholder header to avoid double boxes.
fn apply_session_info_cell(&mut self, cell: history_cell::SessionInfoCell) {
let mut session_info_cell = Some(Box::new(cell) as Box<dyn HistoryCell>);
let merged_header = if let Some(active) = self.active_cell.take() {
if active
.as_any()
.is::<history_cell::SessionHeaderHistoryCell>()
{
// Reuse the existing placeholder header to avoid rendering two boxes.
if let Some(cell) = session_info_cell.take() {
self.active_cell = Some(cell);
}
true
} else {
self.active_cell = Some(active);
false
}
} else {
false
};
self.flush_active_cell();
if !merged_header && let Some(cell) = session_info_cell {
self.add_boxed_history(cell);
}
}
pub(crate) fn add_info_message(&mut self, message: String, hint: Option<String>) {
self.add_to_history(history_cell::new_info_event(message, hint));
self.request_redraw();

View File

@@ -1037,6 +1037,7 @@ impl HistoryCell for SessionInfoCell {
}
}
#[cfg(test)]
pub(crate) fn new_session_info(
config: &Config,
requested_model: &str,
@@ -1112,6 +1113,82 @@ pub(crate) fn new_session_info(
SessionInfoCell(CompositeHistoryCell { parts })
}
pub(crate) fn new_loading_session_header(directory: PathBuf) -> SessionHeaderHistoryCell {
let placeholder_style = Style::default().add_modifier(Modifier::DIM | Modifier::ITALIC);
SessionHeaderHistoryCell::new_with_style(
"loading".to_string(),
placeholder_style,
None,
directory,
CODEX_CLI_VERSION,
)
}
pub(crate) fn new_session_info_body(
config: &Config,
requested_model: &str,
event: &SessionConfiguredEvent,
is_first_event: bool,
auth_plan: Option<PlanType>,
) -> Option<Box<dyn HistoryCell>> {
let mut parts: Vec<Box<dyn HistoryCell>> = Vec::new();
if is_first_event {
let help_lines: Vec<Line<'static>> = vec![
" To get started, describe a task or try one of these commands:"
.dim()
.into(),
Line::from(""),
Line::from(vec![
" ".into(),
"/init".into(),
" - create an AGENTS.md file with instructions for Codex".dim(),
]),
Line::from(vec![
" ".into(),
"/status".into(),
" - show current session configuration".dim(),
]),
Line::from(vec![
" ".into(),
"/permissions".into(),
" - choose what Codex is allowed to do".dim(),
]),
Line::from(vec![
" ".into(),
"/model".into(),
" - choose what model and reasoning effort to use".dim(),
]),
Line::from(vec![
" ".into(),
"/review".into(),
" - review any changes and find issues".dim(),
]),
];
parts.push(Box::new(PlainHistoryCell { lines: help_lines }));
} else {
if config.show_tooltips
&& let Some(tooltips) = tooltips::get_tooltip(auth_plan).map(TooltipHistoryCell::new)
{
parts.push(Box::new(tooltips));
}
if requested_model != event.model {
let lines = vec![
"model changed:".magenta().bold().into(),
format!("requested: {requested_model}").into(),
format!("used: {}", event.model).into(),
];
parts.push(Box::new(PlainHistoryCell { lines }));
}
}
match parts.len() {
0 => None,
1 => parts.into_iter().next(),
_ => Some(Box::new(CompositeHistoryCell::new(parts))),
}
}
pub(crate) fn new_user_prompt(
message: String,
text_elements: Vec<TextElement>,

View File

@@ -126,43 +126,7 @@ where
for line in wrapped {
queue!(writer, Print("\r\n"))?;
// URL lines can be wider than the terminal and will
// character-wrap onto continuation rows. Pre-clear those rows
// so stale content from a previously longer line is erased.
let physical_rows = line.width().max(1).div_ceil(wrap_width);
if physical_rows > 1 {
queue!(writer, SavePosition)?;
for _ in 1..physical_rows {
queue!(writer, MoveDown(1), MoveToColumn(0))?;
queue!(writer, Clear(ClearType::UntilNewLine))?;
}
queue!(writer, RestorePosition)?;
}
queue!(
writer,
SetColors(Colors::new(
line.style
.fg
.map(std::convert::Into::into)
.unwrap_or(CColor::Reset),
line.style
.bg
.map(std::convert::Into::into)
.unwrap_or(CColor::Reset)
))
)?;
queue!(writer, Clear(ClearType::UntilNewLine))?;
// Merge line-level style into each span so that ANSI colors reflect
// line styles (e.g., blockquotes with green fg).
let merged_spans: Vec<Span> = line
.spans
.iter()
.map(|s| Span {
style: s.style.patch(line.style),
content: s.content.clone(),
})
.collect();
write_spans(writer, merged_spans.iter())?;
write_line(writer, &line, wrap_width)?;
}
queue!(writer, ResetScrollRegion)?;
@@ -181,6 +145,36 @@ where
Ok(())
}
pub fn replace_top_visible_history_lines<B>(
terminal: &mut crate::custom_terminal::Terminal<B>,
lines: Vec<Line>,
) -> io::Result<()>
where
B: Backend + Write,
{
if lines.is_empty() {
return Ok(());
}
let top = terminal
.viewport_area
.top()
.saturating_sub(terminal.visible_history_rows());
let wrap_width = terminal.viewport_area.width.max(1) as usize;
let last_cursor_pos = terminal.last_known_cursor_pos;
let writer = terminal.backend_mut();
for (index, line) in lines.iter().enumerate() {
let y = top.saturating_add(index as u16);
queue!(writer, MoveTo(0, y))?;
write_line(writer, line, wrap_width)?;
}
queue!(writer, MoveTo(last_cursor_pos.x, last_cursor_pos.y))?;
std::io::Write::flush(writer)?;
Ok(())
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SetScrollRegion(pub std::ops::Range<u16>);
@@ -329,6 +323,43 @@ where
)
}
fn write_line(mut writer: &mut impl Write, line: &Line<'_>, wrap_width: usize) -> io::Result<()> {
// URL lines can be wider than the terminal and will character-wrap onto continuation rows.
// Pre-clear those rows so stale content from a previously longer line is erased.
let physical_rows = line.width().max(1).div_ceil(wrap_width);
if physical_rows > 1 {
queue!(writer, SavePosition)?;
for _ in 1..physical_rows {
queue!(writer, MoveDown(1), MoveToColumn(0))?;
queue!(writer, Clear(ClearType::UntilNewLine))?;
}
queue!(writer, RestorePosition)?;
}
queue!(
writer,
SetColors(Colors::new(
line.style
.fg
.map(std::convert::Into::into)
.unwrap_or(CColor::Reset),
line.style
.bg
.map(std::convert::Into::into)
.unwrap_or(CColor::Reset)
))
)?;
queue!(writer, Clear(ClearType::UntilNewLine))?;
let merged_spans: Vec<Span> = line
.spans
.iter()
.map(|s| Span {
style: s.style.patch(line.style),
content: s.content.clone(),
})
.collect();
write_spans(&mut writer, merged_spans.iter())
}
#[cfg(test)]
mod tests {
use super::*;

View File

@@ -445,6 +445,16 @@ impl Tui {
self.frame_requester().schedule_frame();
}
pub fn replace_top_visible_history_lines(&mut self, lines: Vec<Line<'static>>) -> Result<()> {
let line_count = lines.len();
if self.terminal.visible_history_rows() >= line_count as u16 {
crate::insert_history::replace_top_visible_history_lines(&mut self.terminal, lines)?;
} else if self.pending_history_lines.len() >= line_count {
self.pending_history_lines.splice(0..line_count, lines);
}
Ok(())
}
pub fn clear_pending_history_lines(&mut self) {
self.pending_history_lines.clear();
}