Move to onboarding stage

This commit is contained in:
Daniel Edrisian
2025-10-14 18:35:03 -07:00
parent 224e398f52
commit 762085fbf0
11 changed files with 422 additions and 184 deletions
-11
View File
@@ -160,12 +160,6 @@ impl App {
pending_update_action: None,
};
// Show an update approval popup at startup when an update is available.
#[cfg(not(debug_assertions))]
if crate::updates::get_upgrade_version(&app.config).is_some() {
app.chat_widget.handle_update_popup();
}
let tui_events = tui.event_stream();
tokio::pin!(tui_events);
@@ -302,11 +296,6 @@ impl App {
AppEvent::ExitRequest => {
return Ok(false);
}
#[cfg(not(debug_assertions))]
AppEvent::RunUpdateAndExit(action) => {
self.pending_update_action = Some(action);
return Ok(false);
}
AppEvent::CodexOp(op) => self.chat_widget.submit_op(op),
AppEvent::DiffResult(text) => {
// Clear the in-progress state in the bottom pane
-4
View File
@@ -87,8 +87,4 @@ pub(crate) enum AppEvent {
/// Open the approval popup.
FullScreenApprovalRequest(ApprovalRequest),
/// User approved to update Codex; run the update and exit.
#[cfg(not(debug_assertions))]
RunUpdateAndExit(crate::UpdateAction),
}
-49
View File
@@ -1829,55 +1829,6 @@ impl ChatWidget {
});
}
/// Open a simple modal asking to update Codex when an update action is available.
#[cfg(not(debug_assertions))]
pub(crate) fn handle_update_popup(&mut self) {
if let Some(update_action) = crate::get_update_action() {
self.show_update_popup(update_action);
}
}
#[cfg(not(debug_assertions))]
pub(crate) fn show_update_popup(&mut self, update_action: crate::UpdateAction) {
use ratatui::style::Stylize as _;
use ratatui::text::Line;
self.bottom_pane.show_selection_view(SelectionViewParams {
title: None,
footer_hint: Some(standard_popup_hint_line()),
items: vec![
SelectionItem {
name: "Yes, update now".to_string(),
actions: vec![Box::new(move |tx: &AppEventSender| {
tx.send(AppEvent::RunUpdateAndExit(update_action));
})],
dismiss_on_select: true,
..Default::default()
},
SelectionItem {
name: "No, not now".to_string(),
dismiss_on_select: true,
..Default::default()
},
],
header: Box::new(ratatui::widgets::Paragraph::new(vec![
Line::from(vec![
crate::history_cell::padded_emoji("✨").bold().cyan(),
"New version available! Would you like to update?".bold(),
]),
Line::from(""),
Line::from(vec![
"Full release notes: ".dim(),
"https://github.com/openai/codex/releases/latest"
.cyan()
.underlined(),
]),
Line::from(""),
])),
..Default::default()
});
}
/// Set the approval policy in the widget's config copy.
pub(crate) fn set_approval_policy(&mut self, policy: AskForApproval) {
self.config.approval_policy = policy;
@@ -9,5 +9,6 @@ expression: terminal.backend().vt100().screen().contents()
› 1. Yes, update now
2. No, not now
3. Don't remind me
Press enter to confirm or esc to go back
-90
View File
@@ -1620,96 +1620,6 @@ fn status_widget_active_snapshot() {
assert_snapshot!("status_widget_active", terminal.backend());
}
#[test]
#[cfg(not(debug_assertions))]
fn update_popup_snapshot() {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual();
chat.show_update_popup(crate::UpdateAction::NpmGlobalLatest);
let height = chat.desired_height(80);
let mut terminal =
crate::custom_terminal::Terminal::with_options(VT100Backend::new(80, height))
.expect("create terminal");
terminal.set_viewport_area(Rect::new(0, 0, 80, height));
terminal
.draw(|f| f.render_widget_ref(&chat, f.area()))
.expect("render update popup");
assert_snapshot!(
"update_popup",
terminal.backend().vt100().screen().contents()
);
}
#[test]
#[cfg(not(debug_assertions))]
fn update_popup_dismiss_option_closes_view() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual();
chat.show_update_popup(crate::UpdateAction::NpmGlobalLatest);
chat.handle_key_event(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE));
chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
let mut saw_run_update = false;
while let Ok(ev) = rx.try_recv() {
if matches!(ev, AppEvent::RunUpdateAndExit(_)) {
saw_run_update = true;
}
}
assert!(
!saw_run_update,
"dismiss option should not trigger an update event"
);
assert!(
chat.is_normal_backtrack_mode(),
"bottom pane should return to normal mode after dismissing the popup"
);
}
#[test]
#[cfg(not(debug_assertions))]
fn update_popup_confirm_triggers_update_event() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual();
chat.show_update_popup(crate::UpdateAction::NpmGlobalLatest);
chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
let mut run_update_action = None;
while let Ok(ev) = rx.try_recv() {
if let AppEvent::RunUpdateAndExit(action) = ev {
run_update_action = Some(action);
break;
}
}
assert_eq!(
run_update_action,
Some(crate::UpdateAction::NpmGlobalLatest),
"confirming the popup should request the expected update action"
);
assert!(
chat.is_normal_backtrack_mode(),
"popup should dismiss after confirming the update"
);
}
#[test]
#[cfg(not(debug_assertions))]
fn update_popup_skipped_without_update_action() {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual();
assert!(
chat.is_normal_backtrack_mode(),
"chat should start in normal backtrack mode"
);
chat.handle_update_popup();
assert!(
chat.is_normal_backtrack_mode(),
"popup should not appear when no update action is available"
);
}
#[test]
fn apply_patch_events_emit_history_cells() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual();
+22
View File
@@ -59,6 +59,7 @@ mod pager_overlay;
pub mod public_widgets;
mod render;
mod resume_picker;
mod selection_list;
mod session_log;
mod shimmer;
mod slash_command;
@@ -70,6 +71,7 @@ mod terminal_palette;
mod text_formatting;
mod tui;
mod ui_consts;
mod update_prompt;
mod version;
/// Update action the CLI should perform after the TUI exits.
@@ -329,6 +331,26 @@ async fn run_ratatui_app(
let mut tui = Tui::new(terminal);
#[cfg(not(debug_assertions))]
{
use crate::update_prompt::UpdatePromptOutcome;
let skip_update_prompt = cli.prompt.as_ref().is_some_and(|prompt| !prompt.is_empty());
if !skip_update_prompt {
match update_prompt::run_update_prompt_if_needed(&mut tui, &config).await? {
UpdatePromptOutcome::Continue => {}
UpdatePromptOutcome::RunUpdate(action) => {
crate::tui::restore()?;
return Ok(AppExitInfo {
token_usage: codex_core::protocol::TokenUsage::default(),
conversation_id: None,
update_action: Some(action),
});
}
}
}
}
// Show update banner in terminal history (instead of stderr) so it is visible
// within the TUI scrollback. Building spans keeps styling consistent.
#[cfg(not(debug_assertions))]
+2 -30
View File
@@ -7,8 +7,6 @@ use crossterm::event::KeyEvent;
use crossterm::event::KeyEventKind;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Style;
use ratatui::style::Styled as _;
use ratatui::style::Stylize;
use ratatui::text::Line;
use ratatui::widgets::Paragraph;
@@ -22,11 +20,9 @@ use crate::render::Insets;
use crate::render::renderable::ColumnRenderable;
use crate::render::renderable::Renderable;
use crate::render::renderable::RenderableExt as _;
use crate::render::renderable::RowRenderable;
use crate::selection_list::selection_option_row;
use super::onboarding_screen::StepState;
use unicode_width::UnicodeWidthStr;
pub(crate) struct TrustDirectoryWidget {
pub codex_home: PathBuf,
pub cwd: PathBuf,
@@ -88,7 +84,7 @@ impl WidgetRef for &TrustDirectoryWidget {
}
for (idx, (text, selection)) in options.iter().enumerate() {
column.push(new_option_row(
column.push(selection_option_row(
idx,
text.to_string(),
self.highlighted == *selection,
@@ -120,30 +116,6 @@ impl WidgetRef for &TrustDirectoryWidget {
}
}
fn new_option_row(index: usize, label: String, is_selected: bool) -> Box<dyn Renderable> {
let prefix = if is_selected {
format!("› {}. ", index + 1)
} else {
format!(" {}. ", index + 1)
};
let mut style = Style::default();
if is_selected {
style = style.cyan();
}
let mut row = RowRenderable::new();
row.push(prefix.width() as u16, prefix.set_style(style));
row.push(
u16::MAX,
Paragraph::new(label)
.style(style)
.wrap(Wrap { trim: false }),
);
row.into()
}
impl KeyboardHandler for TrustDirectoryWidget {
fn handle_key_event(&mut self, key_event: KeyEvent) {
if key_event.kind == KeyEventKind::Release {
+35
View File
@@ -0,0 +1,35 @@
use crate::render::renderable::Renderable;
use crate::render::renderable::RowRenderable;
use ratatui::style::Style;
use ratatui::style::Styled as _;
use ratatui::style::Stylize as _;
use ratatui::widgets::Paragraph;
use ratatui::widgets::Wrap;
use unicode_width::UnicodeWidthStr;
pub(crate) fn selection_option_row(
index: usize,
label: String,
is_selected: bool,
) -> Box<dyn Renderable> {
let prefix = if is_selected {
format!("› {}. ", index + 1)
} else {
format!(" {}. ", index + 1)
};
let style = if is_selected {
Style::default().cyan()
} else {
Style::default()
};
let prefix_width = UnicodeWidthStr::width(prefix.as_str()) as u16;
let mut row = RowRenderable::new();
row.push(prefix_width, prefix.set_style(style));
row.push(
u16::MAX,
Paragraph::new(label)
.style(style)
.wrap(Wrap { trim: false }),
);
row.into()
}
@@ -0,0 +1,13 @@
---
source: tui/src/update_prompt.rs
expression: terminal.backend()
---
✨ Update available! 0.0.0 -> 9.9.9
Release notes: https://github.com/openai/codex/releases/latest
› 1. Update now (runs `npm install -g @openai/codex@latest`)
2. Skip
3. Skip until next version
Press enter to continue
+313
View File
@@ -0,0 +1,313 @@
#![cfg(not(debug_assertions))]
use crate::UpdateAction;
use crate::history_cell::padded_emoji;
use crate::key_hint;
use crate::render::Insets;
use crate::render::renderable::ColumnRenderable;
use crate::render::renderable::Renderable;
use crate::render::renderable::RenderableExt as _;
use crate::selection_list::selection_option_row;
use crate::tui::FrameRequester;
use crate::tui::Tui;
use crate::tui::TuiEvent;
use crate::updates;
use codex_core::config::Config;
use color_eyre::Result;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use crossterm::event::KeyEventKind;
use crossterm::event::KeyModifiers;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::prelude::Widget;
use ratatui::style::Stylize as _;
use ratatui::text::Line;
use ratatui::widgets::Clear;
use ratatui::widgets::WidgetRef;
use tokio_stream::StreamExt;
pub(crate) enum UpdatePromptOutcome {
Continue,
RunUpdate(UpdateAction),
}
pub(crate) async fn run_update_prompt_if_needed(
tui: &mut Tui,
config: &Config,
) -> Result<UpdatePromptOutcome> {
let Some(latest_version) = updates::get_upgrade_version_for_popup(config) else {
return Ok(UpdatePromptOutcome::Continue);
};
let Some(update_action) = crate::get_update_action() else {
return Ok(UpdatePromptOutcome::Continue);
};
let mut screen =
UpdatePromptScreen::new(tui.frame_requester(), latest_version.clone(), update_action);
tui.draw(u16::MAX, |frame| {
frame.render_widget_ref(&screen, frame.area());
})?;
let events = tui.event_stream();
tokio::pin!(events);
while !screen.is_done() {
if let Some(event) = events.next().await {
match event {
TuiEvent::Key(key_event) => screen.handle_key(key_event),
TuiEvent::Paste(_) => {}
TuiEvent::Draw => {
tui.draw(u16::MAX, |frame| {
frame.render_widget_ref(&screen, frame.area());
})?;
}
}
} else {
break;
}
}
match screen.selection() {
Some(UpdateSelection::UpdateNow) => {
tui.terminal.clear()?;
Ok(UpdatePromptOutcome::RunUpdate(update_action))
}
Some(UpdateSelection::NotNow) | None => Ok(UpdatePromptOutcome::Continue),
Some(UpdateSelection::DontRemind) => {
if let Err(err) = updates::dismiss_version(config, screen.latest_version()).await {
tracing::error!("Failed to persist update dismissal: {err}");
}
Ok(UpdatePromptOutcome::Continue)
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum UpdateSelection {
UpdateNow,
NotNow,
DontRemind,
}
struct UpdatePromptScreen {
request_frame: FrameRequester,
latest_version: String,
current_version: String,
update_action: UpdateAction,
highlighted: UpdateSelection,
selection: Option<UpdateSelection>,
}
impl UpdatePromptScreen {
fn new(
request_frame: FrameRequester,
latest_version: String,
update_action: UpdateAction,
) -> Self {
Self {
request_frame,
latest_version,
current_version: env!("CARGO_PKG_VERSION").to_string(),
update_action,
highlighted: UpdateSelection::UpdateNow,
selection: None,
}
}
fn handle_key(&mut self, key_event: KeyEvent) {
if key_event.kind == KeyEventKind::Release {
return;
}
if key_event.modifiers.contains(KeyModifiers::CONTROL)
&& matches!(key_event.code, KeyCode::Char('c') | KeyCode::Char('d'))
{
self.select(UpdateSelection::NotNow);
return;
}
match key_event.code {
KeyCode::Up | KeyCode::Char('k') => self.set_highlight(self.highlighted.prev()),
KeyCode::Down | KeyCode::Char('j') => self.set_highlight(self.highlighted.next()),
KeyCode::Char('1') => self.select(UpdateSelection::UpdateNow),
KeyCode::Char('2') => self.select(UpdateSelection::NotNow),
KeyCode::Char('3') => self.select(UpdateSelection::DontRemind),
KeyCode::Enter => self.select(self.highlighted),
KeyCode::Esc => self.select(UpdateSelection::NotNow),
_ => {}
}
}
fn set_highlight(&mut self, highlight: UpdateSelection) {
if self.highlighted != highlight {
self.highlighted = highlight;
self.request_frame.schedule_frame();
}
}
fn select(&mut self, selection: UpdateSelection) {
self.highlighted = selection;
self.selection = Some(selection);
self.request_frame.schedule_frame();
}
fn is_done(&self) -> bool {
self.selection.is_some()
}
fn selection(&self) -> Option<UpdateSelection> {
self.selection
}
fn latest_version(&self) -> &str {
self.latest_version.as_str()
}
}
impl UpdateSelection {
fn next(self) -> Self {
match self {
UpdateSelection::UpdateNow => UpdateSelection::NotNow,
UpdateSelection::NotNow => UpdateSelection::DontRemind,
UpdateSelection::DontRemind => UpdateSelection::UpdateNow,
}
}
fn prev(self) -> Self {
match self {
UpdateSelection::UpdateNow => UpdateSelection::DontRemind,
UpdateSelection::NotNow => UpdateSelection::UpdateNow,
UpdateSelection::DontRemind => UpdateSelection::NotNow,
}
}
}
impl WidgetRef for &UpdatePromptScreen {
fn render_ref(&self, area: Rect, buf: &mut Buffer) {
Clear.render(area, buf);
let mut column = ColumnRenderable::new();
let update_command = self.update_action.command_str();
column.push("");
column.push(Line::from(vec![
padded_emoji(" ✨").bold().cyan(),
"Update available!".bold(),
" ".into(),
format!(
"{current} -> {latest}",
current = self.current_version,
latest = self.latest_version
)
.dim(),
]));
column.push("");
column.push(
Line::from(vec![
"Release notes: ".dim(),
"https://github.com/openai/codex/releases/latest"
.dim()
.underlined(),
])
.inset(Insets::tlbr(0, 2, 0, 0)),
);
column.push("");
column.push(selection_option_row(
0,
format!("Update now (runs `{update_command}`)"),
self.highlighted == UpdateSelection::UpdateNow,
));
column.push(selection_option_row(
1,
"Skip".to_string(),
self.highlighted == UpdateSelection::NotNow,
));
column.push(selection_option_row(
2,
"Skip until next version".to_string(),
self.highlighted == UpdateSelection::DontRemind,
));
column.push("");
column.push(
Line::from(vec![
"Press ".dim(),
key_hint::plain(KeyCode::Enter).into(),
" to continue".dim(),
])
.inset(Insets::tlbr(0, 2, 0, 0)),
);
column.render(area, buf);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_backend::VT100Backend;
use crate::tui::FrameRequester;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use crossterm::event::KeyModifiers;
use ratatui::Terminal;
fn new_prompt() -> UpdatePromptScreen {
UpdatePromptScreen::new(
FrameRequester::test_dummy(),
"9.9.9".into(),
UpdateAction::NpmGlobalLatest,
)
}
#[test]
fn update_prompt_snapshot() {
let screen = new_prompt();
let mut terminal = Terminal::new(VT100Backend::new(80, 12)).expect("terminal");
terminal
.draw(|frame| frame.render_widget_ref(&screen, frame.area()))
.expect("render update prompt");
insta::assert_snapshot!("update_prompt_modal", terminal.backend());
}
#[test]
fn update_prompt_confirm_selects_update() {
let mut screen = new_prompt();
screen.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
assert!(screen.is_done());
assert_eq!(screen.selection(), Some(UpdateSelection::UpdateNow));
}
#[test]
fn update_prompt_dismiss_option_leaves_prompt_in_normal_state() {
let mut screen = new_prompt();
screen.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE));
screen.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
assert!(screen.is_done());
assert_eq!(screen.selection(), Some(UpdateSelection::NotNow));
}
#[test]
fn update_prompt_dont_remind_selects_dismissal() {
let mut screen = new_prompt();
screen.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE));
screen.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE));
screen.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
assert!(screen.is_done());
assert_eq!(screen.selection(), Some(UpdateSelection::DontRemind));
}
#[test]
fn update_prompt_ctrl_c_skips_update() {
let mut screen = new_prompt();
screen.handle_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL));
assert!(screen.is_done());
assert_eq!(screen.selection(), Some(UpdateSelection::NotNow));
}
#[test]
fn update_prompt_navigation_wraps_between_entries() {
let mut screen = new_prompt();
screen.handle_key(KeyEvent::new(KeyCode::Up, KeyModifiers::NONE));
assert_eq!(screen.highlighted, UpdateSelection::DontRemind);
screen.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE));
assert_eq!(screen.highlighted, UpdateSelection::UpdateNow);
}
}
+36
View File
@@ -45,6 +45,8 @@ struct VersionInfo {
latest_version: String,
// ISO-8601 timestamp (RFC3339)
last_checked_at: DateTime<Utc>,
#[serde(default)]
dismissed_version: Option<String>,
}
#[derive(Deserialize, Debug, Clone)]
@@ -75,12 +77,15 @@ async fn check_for_update(version_file: &Path) -> anyhow::Result<()> {
.json::<ReleaseInfo>()
.await?;
// Preserve any previously dismissed version if present.
let prev_info = read_version_info(version_file).ok();
let info = VersionInfo {
latest_version: latest_tag_name
.strip_prefix("rust-v")
.ok_or_else(|| anyhow::anyhow!("Failed to parse latest tag name '{latest_tag_name}'"))?
.into(),
last_checked_at: Utc::now(),
dismissed_version: prev_info.and_then(|p| p.dismissed_version),
};
let json_line = format!("{}\n", serde_json::to_string(&info)?);
@@ -98,6 +103,37 @@ fn is_newer(latest: &str, current: &str) -> Option<bool> {
}
}
/// Returns the latest version to show in a popup, if it should be shown.
/// This respects the user's dismissal choice for the current latest version.
pub fn get_upgrade_version_for_popup(config: &Config) -> Option<String> {
let version_file = version_filepath(config);
let latest = get_upgrade_version(config)?;
// If the user dismissed this exact version previously, do not show the popup.
if let Ok(info) = read_version_info(&version_file)
&& info.dismissed_version.as_deref() == Some(latest.as_str())
{
return None;
}
Some(latest)
}
/// Persist a dismissal for the current latest version so we don't show
/// the update popup again for this version.
pub async fn dismiss_version(config: &Config, version: &str) -> anyhow::Result<()> {
let version_file = version_filepath(config);
let mut info = match read_version_info(&version_file) {
Ok(info) => info,
Err(_) => return Ok(()),
};
info.dismissed_version = Some(version.to_string());
let json_line = format!("{}\n", serde_json::to_string(&info)?);
if let Some(parent) = version_file.parent() {
tokio::fs::create_dir_all(parent).await?;
}
tokio::fs::write(version_file, json_line).await?;
Ok(())
}
fn parse_version(v: &str) -> Option<(u64, u64, u64)> {
let mut iter = v.trim().split('.');
let maj = iter.next()?.parse::<u64>().ok()?;