From 6c5471feb20f8a4b34f2efb9239e4e641149e77a Mon Sep 17 00:00:00 2001 From: jif-oai Date: Thu, 9 Apr 2026 14:21:27 +0100 Subject: [PATCH 01/82] feat: /resume per ID/name (#17222) Support `/resume 00000-0000-0000-00000000` from the TUI (equivalent for the name) --- codex-rs/tui/src/app.rs | 211 ++++++++++-------- codex-rs/tui/src/app_event.rs | 3 + codex-rs/tui/src/chatwidget.rs | 11 + .../src/chatwidget/tests/slash_commands.rs | 18 ++ codex-rs/tui/src/slash_command.rs | 1 + 5 files changed, 155 insertions(+), 89 deletions(-) diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 3ca5edb00d..6986b9e595 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -47,6 +47,7 @@ use crate::read_session_model; use crate::render::highlight::highlight_bash_to_lines; use crate::render::renderable::Renderable; use crate::resume_picker::SessionSelection; +use crate::resume_picker::SessionTarget; #[cfg(test)] use crate::test_support::PathBufExt; use crate::tui; @@ -4047,6 +4048,108 @@ impl App { Ok(AppRunControl::Continue) } + async fn resume_target_session( + &mut self, + tui: &mut tui::Tui, + app_server: &mut AppServerSession, + target_session: SessionTarget, + ) -> Result { + if self.ignore_same_thread_resume(&target_session) { + tui.frame_requester().schedule_frame(); + return Ok(AppRunControl::Continue); + } + + let current_cwd = self.config.cwd.to_path_buf(); + let resume_cwd = if self.remote_app_server_url.is_some() { + current_cwd.clone() + } else { + match crate::resolve_cwd_for_resume_or_fork( + tui, + &self.config, + ¤t_cwd, + target_session.thread_id, + target_session.path.as_deref(), + CwdPromptAction::Resume, + /*allow_prompt*/ true, + ) + .await? + { + crate::ResolveCwdOutcome::Continue(Some(cwd)) => cwd, + crate::ResolveCwdOutcome::Continue(None) => current_cwd.clone(), + crate::ResolveCwdOutcome::Exit => { + return Ok(AppRunControl::Exit(ExitReason::UserRequested)); + } + } + }; + + let mut resume_config = match self + .rebuild_config_for_resume_or_fallback(¤t_cwd, resume_cwd) + .await + { + Ok(cfg) => cfg, + Err(err) => { + self.chat_widget.add_error_message(format!( + "Failed to rebuild configuration for resume: {err}" + )); + return Ok(AppRunControl::Continue); + } + }; + self.apply_runtime_policy_overrides(&mut resume_config); + + let summary = session_summary( + self.chat_widget.token_usage(), + self.chat_widget.thread_id(), + self.chat_widget.thread_name(), + ); + match app_server + .resume_thread(resume_config.clone(), target_session.thread_id) + .await + { + Ok(resumed) => { + self.shutdown_current_thread(app_server).await; + self.config = resume_config; + tui.set_notification_settings( + self.config.tui_notifications.method, + self.config.tui_notifications.condition, + ); + self.file_search + .update_search_dir(self.config.cwd.to_path_buf()); + match self + .replace_chat_widget_with_app_server_thread(tui, app_server, resumed) + .await + { + Ok(()) => { + if let Some(summary) = summary { + let mut lines: Vec> = Vec::new(); + if let Some(usage_line) = summary.usage_line { + lines.push(usage_line.into()); + } + if let Some(command) = summary.resume_command { + let spans = + vec!["To continue this session, run ".into(), command.cyan()]; + lines.push(spans.into()); + } + self.chat_widget.add_plain_history_lines(lines); + } + } + Err(err) => { + self.chat_widget.add_error_message(format!( + "Failed to attach to resumed app-server thread: {err}" + )); + } + } + } + Err(err) => { + let path_display = target_session.display_label(); + self.chat_widget.add_error_message(format!( + "Failed to resume session from {path_display}: {err}" + )); + } + } + + Ok(AppRunControl::Continue) + } + async fn handle_event( &mut self, tui: &mut tui::Tui, @@ -4097,97 +4200,13 @@ impl App { .await? { SessionSelection::Resume(target_session) => { - if self.ignore_same_thread_resume(&target_session) { - tui.frame_requester().schedule_frame(); - return Ok(AppRunControl::Continue); - } - let current_cwd = self.config.cwd.to_path_buf(); - let resume_cwd = if self.remote_app_server_url.is_some() { - current_cwd.clone() - } else { - match crate::resolve_cwd_for_resume_or_fork( - tui, - &self.config, - ¤t_cwd, - target_session.thread_id, - target_session.path.as_deref(), - CwdPromptAction::Resume, - /*allow_prompt*/ true, - ) + match self + .resume_target_session(tui, app_server, target_session) .await? - { - crate::ResolveCwdOutcome::Continue(Some(cwd)) => cwd, - crate::ResolveCwdOutcome::Continue(None) => current_cwd.clone(), - crate::ResolveCwdOutcome::Exit => { - return Ok(AppRunControl::Exit(ExitReason::UserRequested)); - } - } - }; - let mut resume_config = match self - .rebuild_config_for_resume_or_fallback(¤t_cwd, resume_cwd) - .await { - Ok(cfg) => cfg, - Err(err) => { - self.chat_widget.add_error_message(format!( - "Failed to rebuild configuration for resume: {err}" - )); - return Ok(AppRunControl::Continue); - } - }; - self.apply_runtime_policy_overrides(&mut resume_config); - let summary = session_summary( - self.chat_widget.token_usage(), - self.chat_widget.thread_id(), - self.chat_widget.thread_name(), - ); - match app_server - .resume_thread(resume_config.clone(), target_session.thread_id) - .await - { - Ok(resumed) => { - self.shutdown_current_thread(app_server).await; - self.config = resume_config; - tui.set_notification_settings( - self.config.tui_notifications.method, - self.config.tui_notifications.condition, - ); - self.file_search - .update_search_dir(self.config.cwd.to_path_buf()); - match self - .replace_chat_widget_with_app_server_thread( - tui, app_server, resumed, - ) - .await - { - Ok(()) => { - if let Some(summary) = summary { - let mut lines: Vec> = Vec::new(); - if let Some(usage_line) = summary.usage_line { - lines.push(usage_line.into()); - } - if let Some(command) = summary.resume_command { - let spans = vec![ - "To continue this session, run ".into(), - command.cyan(), - ]; - lines.push(spans.into()); - } - self.chat_widget.add_plain_history_lines(lines); - } - } - Err(err) => { - self.chat_widget.add_error_message(format!( - "Failed to attach to resumed app-server thread: {err}" - )); - } - } - } - Err(err) => { - let path_display = target_session.display_label(); - self.chat_widget.add_error_message(format!( - "Failed to resume session from {path_display}: {err}" - )); + AppRunControl::Continue => {} + AppRunControl::Exit(reason) => { + return Ok(AppRunControl::Exit(reason)); } } } @@ -4199,6 +4218,20 @@ impl App { // Leaving alt-screen may blank the inline viewport; force a redraw either way. tui.frame_requester().schedule_frame(); } + AppEvent::ResumeSessionByIdOrName(id_or_name) => { + match crate::lookup_session_target_with_app_server(app_server, &id_or_name).await? { + Some(target_session) => { + return self + .resume_target_session(tui, app_server, target_session) + .await; + } + None => { + self.chat_widget.add_error_message(format!( + "No saved chat found matching '{id_or_name}'." + )); + } + } + } AppEvent::ForkCurrentSession => { self.session_telemetry.counter( "codex.thread.fork", diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index 6bc873b27e..78a2525350 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -124,6 +124,9 @@ pub(crate) enum AppEvent { /// Open the resume picker inside the running TUI session. OpenResumePicker, + /// Resume a thread by UUID or thread name inside the running TUI session. + ResumeSessionByIdOrName(String), + /// Fork the current session into a new thread. ForkCurrentSession, diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index fd87c58f69..27450ed5f9 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -5452,6 +5452,17 @@ impl ChatWidget { })); self.bottom_pane.drain_pending_submission_state(); } + SlashCommand::Resume if !trimmed.is_empty() => { + let Some((prepared_args, _prepared_elements)) = self + .bottom_pane + .prepare_inline_args_submission(/*record_history*/ false) + else { + return; + }; + self.app_event_tx + .send(AppEvent::ResumeSessionByIdOrName(prepared_args)); + self.bottom_pane.drain_pending_submission_state(); + } SlashCommand::SandboxReadRoot if !trimmed.is_empty() => { let Some((prepared_args, _prepared_elements)) = self .bottom_pane diff --git a/codex-rs/tui/src/chatwidget/tests/slash_commands.rs b/codex-rs/tui/src/chatwidget/tests/slash_commands.rs index fdf7c5008b..e2fda41685 100644 --- a/codex-rs/tui/src/chatwidget/tests/slash_commands.rs +++ b/codex-rs/tui/src/chatwidget/tests/slash_commands.rs @@ -447,6 +447,24 @@ async fn slash_resume_opens_picker() { assert_matches!(rx.try_recv(), Ok(AppEvent::OpenResumePicker)); } +#[tokio::test] +async fn slash_resume_with_arg_requests_named_session() { + let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await; + + chat.bottom_pane.set_composer_text( + "/resume my-saved-thread".to_string(), + Vec::new(), + Vec::new(), + ); + chat.handle_key_event(KeyEvent::from(KeyCode::Enter)); + + assert_matches!( + rx.try_recv(), + Ok(AppEvent::ResumeSessionByIdOrName(id_or_name)) if id_or_name == "my-saved-thread" + ); + assert_matches!(op_rx.try_recv(), Err(TryRecvError::Empty)); +} + #[tokio::test] async fn slash_fork_requests_current_fork() { let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; diff --git a/codex-rs/tui/src/slash_command.rs b/codex-rs/tui/src/slash_command.rs index ec624d3fb9..b1a6e97ad1 100644 --- a/codex-rs/tui/src/slash_command.rs +++ b/codex-rs/tui/src/slash_command.rs @@ -132,6 +132,7 @@ impl SlashCommand { | SlashCommand::Rename | SlashCommand::Plan | SlashCommand::Fast + | SlashCommand::Resume | SlashCommand::SandboxReadRoot ) } From 9f6f2c84c1dc65a1d9cf8378657f27f4cfea002b Mon Sep 17 00:00:00 2001 From: jif-oai Date: Thu, 9 Apr 2026 15:17:06 +0100 Subject: [PATCH 02/82] feat: advanced announcements per OS and plans (#17226) Support things like ``` [[announcements]] content = "custom message" from_date = "2026-04-09" to_date = "2026-06-01" target_app = "cli" target_plan_types = ["pro"] target_oses = ["macos"] version_regex = "..." # add version of the patch ``` --- codex-rs/tui/src/tooltips.rs | 174 +++++++++++++++++++++++++++++++++-- 1 file changed, 165 insertions(+), 9 deletions(-) diff --git a/codex-rs/tui/src/tooltips.rs b/codex-rs/tui/src/tooltips.rs index d2843a8921..9565831b27 100644 --- a/codex-rs/tui/src/tooltips.rs +++ b/codex-rs/tui/src/tooltips.rs @@ -51,7 +51,7 @@ fn experimental_tooltips() -> Vec<&'static str> { pub(crate) fn get_tooltip(plan: Option, fast_mode_enabled: bool) -> Option { let mut rng = rand::rng(); - if let Some(announcement) = announcement::fetch_announcement_tip() { + if let Some(announcement) = announcement::fetch_announcement_tip(plan) { return Some(announcement); } @@ -124,6 +124,7 @@ pub(crate) mod announcement { use crate::version::CODEX_CLI_VERSION; use chrono::NaiveDate; use chrono::Utc; + use codex_protocol::account::PlanType; use regex_lite::Regex; use serde::Deserialize; use std::sync::OnceLock; @@ -131,6 +132,7 @@ pub(crate) mod announcement { use std::time::Duration; static ANNOUNCEMENT_TIP: OnceLock> = OnceLock::new(); + const CURRENT_OS: TargetOs = TargetOs::current(); /// Prewarm the cache of the announcement tip. pub(crate) fn prewarm() { @@ -138,12 +140,12 @@ pub(crate) mod announcement { } /// Fetch the announcement tip, return None if the prewarm is not done yet. - pub(crate) fn fetch_announcement_tip() -> Option { + pub(crate) fn fetch_announcement_tip(plan: Option) -> Option { ANNOUNCEMENT_TIP .get() .cloned() .flatten() - .and_then(|raw| parse_announcement_tip_toml(&raw)) + .and_then(|raw| parse_announcement_tip_toml(&raw, plan)) } #[derive(Debug, Deserialize)] @@ -153,6 +155,8 @@ pub(crate) mod announcement { to_date: Option, version_regex: Option, target_app: Option, + target_plan_types: Option>, + target_oses: Option>, } #[derive(Debug, Deserialize)] @@ -167,6 +171,31 @@ pub(crate) mod announcement { to_date: Option, version_regex: Option, target_app: String, + target_plan_types: Option>, + target_oses: Option>, + } + + #[derive(Debug, Deserialize, Copy, Clone, PartialEq, Eq)] + #[serde(rename_all = "lowercase")] + enum TargetOs { + Linux, + Macos, + Windows, + #[serde(other)] + Unknown, + } + + impl TargetOs { + const fn current() -> Self { + if cfg!(target_os = "macos") { + Self::Macos + } else if cfg!(target_os = "windows") { + Self::Windows + } else { + // Codex currently publishes CLI builds for macOS, Windows, and Linux. + Self::Linux + } + } } fn init_announcement_tip_in_thread() -> Option { @@ -190,7 +219,10 @@ pub(crate) mod announcement { response.error_for_status().ok()?.text().ok() } - pub(crate) fn parse_announcement_tip_toml(text: &str) -> Option { + pub(crate) fn parse_announcement_tip_toml( + text: &str, + plan: Option, + ) -> Option { let announcements = toml::from_str::(text) .map(|doc| doc.announcements) .or_else(|_| toml::from_str::>(text)) @@ -202,9 +234,19 @@ pub(crate) mod announcement { let Some(tip) = AnnouncementTip::from_raw(raw) else { continue; }; + let plan_matches = tip + .target_plan_types + .as_ref() + .is_none_or(|target_plans| plan.is_some_and(|plan| target_plans.contains(&plan))); + let os_matches = tip + .target_oses + .as_ref() + .is_none_or(|target_oses| target_oses.contains(&CURRENT_OS)); if tip.version_matches(CODEX_CLI_VERSION) && tip.date_matches(today) && tip.target_app == "cli" + && plan_matches + && os_matches { latest_match = Some(tip.content); } @@ -231,6 +273,20 @@ pub(crate) mod announcement { Some(pattern) => Some(Regex::new(&pattern).ok()?), None => None, }; + let target_plan_types = raw.target_plan_types; + if target_plan_types + .as_ref() + .is_some_and(|plans| plans.contains(&PlanType::Unknown)) + { + return None; + } + let target_oses = raw.target_oses; + if target_oses + .as_ref() + .is_some_and(|oses| oses.contains(&TargetOs::Unknown)) + { + return None; + } Some(Self { content: content.to_string(), @@ -238,6 +294,8 @@ pub(crate) mod announcement { to_date, version_regex, target_app: raw.target_app.unwrap_or("cli".to_string()).to_lowercase(), + target_plan_types, + target_oses, }) } @@ -333,7 +391,7 @@ to_date = "2000-01-01" assert_eq!( Some("latest match".to_string()), - parse_announcement_tip_toml(toml) + parse_announcement_tip_toml(toml, /*plan*/ None) ); let toml = r#" @@ -353,7 +411,7 @@ to_date = "2000-01-01" assert_eq!( Some("latest match".to_string()), - parse_announcement_tip_toml(toml) + parse_announcement_tip_toml(toml, /*plan*/ None) ); } @@ -374,7 +432,7 @@ content = "should not match either " target_app = "vsce" "#; - assert_eq!(None, parse_announcement_tip_toml(toml)); + assert_eq!(None, parse_announcement_tip_toml(toml, /*plan*/ None)); } #[test] @@ -385,7 +443,7 @@ content = 123 from_date = "2000-01-01" "#; - assert_eq!(None, parse_announcement_tip_toml(toml)); + assert_eq!(None, parse_announcement_tip_toml(toml, /*plan*/ None)); } #[test] @@ -396,6 +454,8 @@ from_date = "2000-01-01" # Dates are UTC, formatted as YYYY-MM-DD. The from_date is inclusive and the to_date is exclusive. # version_regex matches against the CLI version (env!("CARGO_PKG_VERSION")); omit to apply to all versions. # target_app specify which app should display the announcement (cli, vsce, ...). +# target_plan_types optionally restricts the announcement to plan types like ["plus", "pro"]. +# target_oses optionally restricts the announcement to operating systems like ["macos", "windows"]. [[announcements]] content = "Welcome to Codex! Check out the new onboarding flow." @@ -410,7 +470,103 @@ content = "This is a test announcement" assert_eq!( Some("This is a test announcement".to_string()), - parse_announcement_tip_toml(toml) + parse_announcement_tip_toml(toml, /*plan*/ None) + ); + } + + #[test] + fn announcement_tip_toml_matches_target_plan_type() { + let toml = r#" +[[announcements]] +content = "all plans" + +[[announcements]] +content = "pro announcement" +target_plan_types = ["pro", "enterprise"] + +[[announcements]] +content = "free announcement" +target_plan_types = ["free"] + "#; + + assert_eq!( + Some("pro announcement".to_string()), + parse_announcement_tip_toml(toml, Some(PlanType::Pro)) + ); + assert_eq!( + Some("free announcement".to_string()), + parse_announcement_tip_toml(toml, Some(PlanType::Free)) + ); + assert_eq!( + Some("all plans".to_string()), + parse_announcement_tip_toml(toml, Some(PlanType::Plus)) + ); + assert_eq!( + Some("all plans".to_string()), + parse_announcement_tip_toml(toml, /*plan*/ None) + ); + } + + #[test] + fn announcement_tip_toml_rejects_unknown_target_plan_type() { + let toml = r#" +[[announcements]] +content = "all plans" + +[[announcements]] +content = "typo announcement" +target_plan_types = ["prp"] + "#; + + assert_eq!( + Some("all plans".to_string()), + parse_announcement_tip_toml(toml, Some(PlanType::Unknown)) + ); + } + + #[test] + fn announcement_tip_toml_matches_target_os() { + let toml = r#" +[[announcements]] +content = "linux announcement" +target_oses = ["linux"] + +[[announcements]] +content = "macos announcement" +target_oses = ["macos"] + +[[announcements]] +content = "windows announcement" +target_oses = ["windows"] + "#; + + let expected = if cfg!(target_os = "macos") { + "macos announcement" + } else if cfg!(target_os = "windows") { + "windows announcement" + } else { + "linux announcement" + }; + assert_eq!( + Some(expected.to_string()), + parse_announcement_tip_toml(toml, /*plan*/ None) + ); + } + + #[test] + fn announcement_tip_toml_rejects_unknown_target_os() { + let toml = r#" +[[announcements]] +content = "all operating systems" + +[[announcements]] +content = "typo announcement" +target_oses = ["amiga"] + "#; + + assert_eq!( + Some("all operating systems".to_string()), + parse_announcement_tip_toml(toml, /*plan*/ None) ); } } From 598d6ff0561f6372c69227bac719e76f39928e87 Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Thu, 9 Apr 2026 07:52:07 -0700 Subject: [PATCH 03/82] Render statusline context as a meter (#17170) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Problem: The statusline reported context as an “X% left” value, which could be mistaken for quota, and context usage was included in the default footer. Solution: Render configured context status items as a filling context meter, preserve `context-used` as a legacy alias while hiding it from the setup menu, and remove context from the default statusline. It will still be available as an opt-in option for users who want to see it. image --- codex-rs/config/src/types.rs | 3 +- codex-rs/core/config.schema.json | 2 +- ..._snapshot_uses_runtime_preview_values.snap | 4 +- .../tui/src/bottom_pane/status_line_setup.rs | 61 +++++++++++++---- codex-rs/tui/src/chatwidget.rs | 3 +- ..._review_denied_renders_denied_request.snap | 6 +- ...artup_failure_renders_warning_history.snap | 10 +-- ...i__chatwidget__tests__chatwidget_tall.snap | 6 +- ...compact_queues_user_messages_snapshot.snap | 6 +- ...pproved_exec_renders_approved_request.snap | 6 +- ...ec_renders_warning_and_denied_request.snap | 6 +- ...allel_reviews_render_aggregate_status.snap | 6 +- ...et__tests__mcp_startup_header_booting.snap | 6 +- ..._tests__preamble_keeps_working_status.snap | 6 +- ..._review_queues_user_messages_snapshot.snap | 6 +- ...line_model_with_reasoning_fast_footer.snap | 6 +- ...atwidget__tests__status_widget_active.snap | 6 +- ...ed_exec_begin_restores_working_status.snap | 6 +- ...renders_command_in_single_details_row.snap | 6 +- .../tui/src/chatwidget/status_surfaces.rs | 65 +++++++++++++++++-- .../src/chatwidget/tests/status_and_layout.rs | 40 ++++++++++-- 21 files changed, 191 insertions(+), 75 deletions(-) diff --git a/codex-rs/config/src/types.rs b/codex-rs/config/src/types.rs index cee7271691..9d1626dbd2 100644 --- a/codex-rs/config/src/types.rs +++ b/codex-rs/config/src/types.rs @@ -549,8 +549,7 @@ pub struct Tui { /// Ordered list of status line item identifiers. /// /// When set, the TUI renders the selected items as the status line. - /// When unset, the TUI defaults to: `model-with-reasoning`, `context-remaining`, and - /// `current-dir`. + /// When unset, the TUI defaults to: `model-with-reasoning` and `current-dir`. #[serde(default)] pub status_line: Option>, diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index bcc5193b2c..c3c29aa557 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -1864,7 +1864,7 @@ }, "status_line": { "default": null, - "description": "Ordered list of status line item identifiers.\n\nWhen set, the TUI renders the selected items as the status line. When unset, the TUI defaults to: `model-with-reasoning`, `context-remaining`, and `current-dir`.", + "description": "Ordered list of status line item identifiers.\n\nWhen set, the TUI renders the selected items as the status line. When unset, the TUI defaults to: `model-with-reasoning` and `current-dir`.", "items": { "type": "string" }, diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__status_line_setup__tests__setup_view_snapshot_uses_runtime_preview_values.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__status_line_setup__tests__setup_view_snapshot_uses_runtime_preview_values.snap index 20aca1e334..94d9cd450c 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__status_line_setup__tests__setup_view_snapshot_uses_runtime_preview_values.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__status_line_setup__tests__setup_view_snapshot_uses_runtime_preview_values.snap @@ -13,9 +13,9 @@ expression: "render_lines(&view, 72)" [x] git-branch Current Git branch (omitted when unavaila… [ ] model-with-reasoning Current model name with reasoning level [ ] project-root Project root directory (omitted when unav… - [ ] context-remaining Percentage of context window remaining (o… - [ ] context-used Percentage of context window used (omitte… + [ ] context-usage Visual meter of context window usage (omi… [ ] five-hour-limit Remaining usage on 5-hour usage limit (om… + [ ] weekly-limit Remaining usage on weekly usage limit (om… gpt-5-codex · ~/codex-rs · jif/statusline-preview Use ↑↓ to navigate, ←→ to move, space to select, enter to confirm, esc diff --git a/codex-rs/tui/src/bottom_pane/status_line_setup.rs b/codex-rs/tui/src/bottom_pane/status_line_setup.rs index cb0229e770..cdda2d7ca4 100644 --- a/codex-rs/tui/src/bottom_pane/status_line_setup.rs +++ b/codex-rs/tui/src/bottom_pane/status_line_setup.rs @@ -12,7 +12,7 @@ //! - Model information (name, reasoning level) //! - Directory paths (current dir, project root) //! - Git information (branch name) -//! - Context usage (remaining %, used %, window size) +//! - Context usage (meter, window size) //! - Usage limits (5-hour, weekly) //! - Session info (ID, tokens used) //! - Application version @@ -22,7 +22,6 @@ use ratatui::layout::Rect; use ratatui::text::Line; use std::collections::BTreeMap; use std::collections::HashSet; -use strum::IntoEnumIterator; use strum_macros::Display; use strum_macros::EnumIter; use strum_macros::EnumString; @@ -63,11 +62,15 @@ pub(crate) enum StatusLineItem { /// Current git branch name (if in a repository). GitBranch, - /// Percentage of context window remaining. - ContextRemaining, - - /// Percentage of context window used. - ContextUsed, + /// Visual meter of context window usage. + /// + /// Also accepts legacy `context-remaining` and `context-used` config values. + #[strum( + to_string = "context-usage", + serialize = "context-remaining", + serialize = "context-used" + )] + ContextUsage, /// Remaining usage on the 5-hour rate limit. FiveHourLimit, @@ -106,11 +109,8 @@ impl StatusLineItem { StatusLineItem::CurrentDir => "Current working directory", StatusLineItem::ProjectRoot => "Project root directory (omitted when unavailable)", StatusLineItem::GitBranch => "Current Git branch (omitted when unavailable)", - StatusLineItem::ContextRemaining => { - "Percentage of context window remaining (omitted when unknown)" - } - StatusLineItem::ContextUsed => { - "Percentage of context window used (omitted when unknown)" + StatusLineItem::ContextUsage => { + "Visual meter of context window usage (omitted when unknown)" } StatusLineItem::FiveHourLimit => { "Remaining usage on 5-hour usage limit (omitted when unavailable)" @@ -133,6 +133,24 @@ impl StatusLineItem { } } +const SELECTABLE_STATUS_LINE_ITEMS: &[StatusLineItem] = &[ + StatusLineItem::ModelName, + StatusLineItem::ModelWithReasoning, + StatusLineItem::CurrentDir, + StatusLineItem::ProjectRoot, + StatusLineItem::GitBranch, + StatusLineItem::ContextUsage, + StatusLineItem::FiveHourLimit, + StatusLineItem::WeeklyLimit, + StatusLineItem::CodexVersion, + StatusLineItem::ContextWindowSize, + StatusLineItem::UsedTokens, + StatusLineItem::TotalInputTokens, + StatusLineItem::TotalOutputTokens, + StatusLineItem::SessionId, + StatusLineItem::FastMode, +]; + /// Runtime values used to preview the current status-line selection. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub(crate) struct StatusLinePreviewData { @@ -209,7 +227,7 @@ impl StatusLineSetupView { } } - for item in StatusLineItem::iter() { + for item in SELECTABLE_STATUS_LINE_ITEMS.iter().cloned() { let item_id = item.to_string(); if used_ids.contains(&item_id) { continue; @@ -293,6 +311,23 @@ mod tests { use crate::app_event::AppEvent; + #[test] + fn context_usage_is_canonical_and_accepts_legacy_ids() { + assert_eq!(StatusLineItem::ContextUsage.to_string(), "context-usage"); + assert_eq!( + "context-usage".parse::(), + Ok(StatusLineItem::ContextUsage) + ); + assert_eq!( + "context-remaining".parse::(), + Ok(StatusLineItem::ContextUsage) + ); + assert_eq!( + "context-used".parse::(), + Ok(StatusLineItem::ContextUsage) + ); + } + #[test] fn preview_uses_runtime_values() { let preview_data = StatusLinePreviewData::from_iter([ diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 27450ed5f9..c110660549 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -388,8 +388,7 @@ use unicode_segmentation::UnicodeSegmentation; const USER_SHELL_COMMAND_HELP_TITLE: &str = "Prefix a command with ! to run it locally"; const USER_SHELL_COMMAND_HELP_HINT: &str = "Example: !ls"; const DEFAULT_OPENAI_BASE_URL: &str = "https://api.openai.com/v1"; -const DEFAULT_STATUS_LINE_ITEMS: [&str; 3] = - ["model-with-reasoning", "context-remaining", "current-dir"]; +const DEFAULT_STATUS_LINE_ITEMS: [&str; 2] = ["model-with-reasoning", "current-dir"]; // Track information about an in-flight exec command. struct RunningCommand { command: Vec, diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__app_server_guardian_review_denied_renders_denied_request.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__app_server_guardian_review_denied_renders_denied_request.snap index ae9931efe7..f783bd4d6d 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__app_server_guardian_review_denied_renders_denied_request.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__app_server_guardian_review_denied_renders_denied_request.snap @@ -1,6 +1,6 @@ --- -source: tui/src/chatwidget/tests.rs -expression: term.backend().vt100().screen().contents() +source: tui/src/chatwidget/tests/guardian.rs +expression: normalize_snapshot_paths(term.backend().vt100().screen().contents()) --- ✗ Request denied for codex to run curl -sS -i -X POST --data-binary @core/src/c odex.rs https://example.com @@ -10,4 +10,4 @@ expression: term.backend().vt100().screen().contents() › Ask Codex to do anything - gpt-5.3-codex default · 100% left · /tmp/project + gpt-5.3-codex default · /tmp/project diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__app_server_mcp_startup_failure_renders_warning_history.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__app_server_mcp_startup_failure_renders_warning_history.snap index be819de548..fedd9d6bc2 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__app_server_mcp_startup_failure_renders_warning_history.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__app_server_mcp_startup_failure_renders_warning_history.snap @@ -1,15 +1,11 @@ --- -source: tui/src/chatwidget/tests.rs -assertion_line: 11761 -expression: term.backend().vt100().screen().contents() +source: tui/src/chatwidget/tests/mcp_startup.rs +expression: normalize_snapshot_paths(term.backend().vt100().screen().contents()) --- - - - ⚠ MCP client for `alpha` failed to start: handshake failed ⚠ MCP startup incomplete (failed: alpha) › Ask Codex to do anything - gpt-5.3-codex default · 100% left · /tmp/project + gpt-5.3-codex default · /tmp/project diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chatwidget_tall.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chatwidget_tall.snap index 2200aaa748..2698463526 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chatwidget_tall.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chatwidget_tall.snap @@ -1,6 +1,6 @@ --- -source: tui/src/chatwidget/tests.rs -expression: term.backend().vt100().screen().contents() +source: tui/src/chatwidget/tests/status_and_layout.rs +expression: normalize_snapshot_paths(term.backend().vt100().screen().contents()) --- • Working (0s • esc to interrupt) @@ -24,4 +24,4 @@ expression: term.backend().vt100().screen().contents() › Ask Codex to do anything - gpt-5.3-codex default · 100% left · /tmp/project + gpt-5.3-codex default · /tmp/project diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__compact_queues_user_messages_snapshot.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__compact_queues_user_messages_snapshot.snap index c79f795b2e..d39932f3a6 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__compact_queues_user_messages_snapshot.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__compact_queues_user_messages_snapshot.snap @@ -1,6 +1,6 @@ --- -source: tui/src/chatwidget/tests.rs -expression: term.backend().vt100().screen().contents() +source: tui/src/chatwidget/tests/slash_commands.rs +expression: normalize_snapshot_paths(term.backend().vt100().screen().contents()) --- • Working (0s • esc to interrupt) @@ -9,4 +9,4 @@ expression: term.backend().vt100().screen().contents() › Ask Codex to do anything - gpt-5.3-codex default · 100% left · /tmp/project + gpt-5.3-codex default · /tmp/project diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__guardian_approved_exec_renders_approved_request.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__guardian_approved_exec_renders_approved_request.snap index 6aeb8c3a4a..80592e0dd8 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__guardian_approved_exec_renders_approved_request.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__guardian_approved_exec_renders_approved_request.snap @@ -1,6 +1,6 @@ --- -source: tui/src/chatwidget/tests.rs -expression: term.backend().vt100().screen().contents() +source: tui/src/chatwidget/tests/guardian.rs +expression: normalize_snapshot_paths(term.backend().vt100().screen().contents()) --- ✔ Auto-reviewer approved codex to run rm -f /tmp/guardian-approved.sqlite this time @@ -8,4 +8,4 @@ expression: term.backend().vt100().screen().contents() › Ask Codex to do anything - gpt-5.3-codex default · 100% left · /tmp/project + gpt-5.3-codex default · /tmp/project diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__guardian_denied_exec_renders_warning_and_denied_request.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__guardian_denied_exec_renders_warning_and_denied_request.snap index 5cc6b31dac..d910d6d6f3 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__guardian_denied_exec_renders_warning_and_denied_request.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__guardian_denied_exec_renders_warning_and_denied_request.snap @@ -1,6 +1,6 @@ --- -source: tui/src/chatwidget/tests.rs -expression: term.backend().vt100().screen().contents() +source: tui/src/chatwidget/tests/guardian.rs +expression: normalize_snapshot_paths(term.backend().vt100().screen().contents()) --- ⚠ Automatic approval review denied (risk: high): The planned action would transmit the full contents of a workspace source file (`core/src/codex.rs`) to @@ -14,4 +14,4 @@ expression: term.backend().vt100().screen().contents() › Ask Codex to do anything - gpt-5.3-codex default · 100% left · /tmp/project + gpt-5.3-codex default · /tmp/project diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__guardian_parallel_reviews_render_aggregate_status.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__guardian_parallel_reviews_render_aggregate_status.snap index b5fba29047..821c8d1a6b 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__guardian_parallel_reviews_render_aggregate_status.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__guardian_parallel_reviews_render_aggregate_status.snap @@ -1,6 +1,6 @@ --- -source: tui/src/chatwidget/tests.rs -expression: rendered +source: tui/src/chatwidget/tests/guardian.rs +expression: normalize_snapshot_paths(rendered) --- • Reviewing 2 approval requests (0s • esc to interrupt) └ • rm -rf '/tmp/guardian target 1' @@ -9,4 +9,4 @@ expression: rendered › Ask Codex to do anything - gpt-5.3-codex default · 100% left · /tmp/project + gpt-5.3-codex default · /tmp/project diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__mcp_startup_header_booting.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__mcp_startup_header_booting.snap index 06e47fc82d..f3936540a1 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__mcp_startup_header_booting.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__mcp_startup_header_booting.snap @@ -1,6 +1,6 @@ --- -source: tui/src/chatwidget/tests.rs -expression: terminal.backend() +source: tui/src/chatwidget/tests/mcp_startup.rs +expression: normalized_backend_snapshot(terminal.backend()) --- " " "• Booting MCP server: alpha (0s • esc to interrupt) " @@ -8,4 +8,4 @@ expression: terminal.backend() " " "› Ask Codex to do anything " " " -" gpt-5.3-codex default · 100% left · /tmp/project " +" gpt-5.3-codex default · /tmp/project " diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__preamble_keeps_working_status.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__preamble_keeps_working_status.snap index 7b1381c964..ad7fa52531 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__preamble_keeps_working_status.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__preamble_keeps_working_status.snap @@ -1,6 +1,6 @@ --- -source: tui/src/chatwidget/tests.rs -expression: terminal.backend() +source: tui/src/chatwidget/tests/exec_flow.rs +expression: normalized_backend_snapshot(terminal.backend()) --- " " "• Working (0s • esc to interrupt) " @@ -8,4 +8,4 @@ expression: terminal.backend() " " "› Ask Codex to do anything " " " -" gpt-5.3-codex default · 100% left · /tmp/project " +" gpt-5.3-codex default · /tmp/project " diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__review_queues_user_messages_snapshot.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__review_queues_user_messages_snapshot.snap index c60607c075..bb4a8cefe7 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__review_queues_user_messages_snapshot.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__review_queues_user_messages_snapshot.snap @@ -1,6 +1,6 @@ --- -source: tui/src/chatwidget/tests.rs -expression: term.backend().vt100().screen().contents() +source: tui/src/chatwidget/tests/review_mode.rs +expression: normalize_snapshot_paths(term.backend().vt100().screen().contents()) --- • Working (0s • esc to interrupt) @@ -9,4 +9,4 @@ expression: term.backend().vt100().screen().contents() › Ask Codex to do anything - gpt-5.3-codex default · 100% left · /tmp/project + gpt-5.3-codex default · /tmp/project diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_line_model_with_reasoning_fast_footer.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_line_model_with_reasoning_fast_footer.snap index 6355decd68..c71a570606 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_line_model_with_reasoning_fast_footer.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_line_model_with_reasoning_fast_footer.snap @@ -1,9 +1,9 @@ --- -source: tui/src/chatwidget/tests.rs -expression: terminal.backend() +source: tui/src/chatwidget/tests/status_and_layout.rs +expression: normalized_backend_snapshot(terminal.backend()) --- " " " " "› Ask Codex to do anything " " " -" gpt-5.4 xhigh fast · 100% left · /tmp/project " +" gpt-5.4 xhigh fast · Context [ ] · /tmp/project " diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_widget_active.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_widget_active.snap index e4fea35445..fea8a4db0f 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_widget_active.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_widget_active.snap @@ -1,6 +1,6 @@ --- -source: tui/src/chatwidget/tests.rs -expression: terminal.backend() +source: tui/src/chatwidget/tests/status_and_layout.rs +expression: normalized_backend_snapshot(terminal.backend()) --- " " "• Analyzing (0s • esc to interrupt) " @@ -8,4 +8,4 @@ expression: terminal.backend() " " "› Ask Codex to do anything " " " -" gpt-5.3-codex default · 100% left · /tmp/project " +" gpt-5.3-codex default · /tmp/project " diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__unified_exec_begin_restores_working_status.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__unified_exec_begin_restores_working_status.snap index 9146406a66..7a2d0b4b9d 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__unified_exec_begin_restores_working_status.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__unified_exec_begin_restores_working_status.snap @@ -1,6 +1,6 @@ --- -source: tui/src/chatwidget/tests.rs -expression: terminal.backend() +source: tui/src/chatwidget/tests/exec_flow.rs +expression: normalized_backend_snapshot(terminal.backend()) --- " " "• Working (0s • esc to interrupt) · 1 background terminal running · /ps to view…" @@ -8,4 +8,4 @@ expression: terminal.backend() " " "› Ask Codex to do anything " " " -" gpt-5.3-codex default · 100% left · /tmp/project " +" gpt-5.3-codex default · /tmp/project " diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__unified_exec_wait_status_renders_command_in_single_details_row.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__unified_exec_wait_status_renders_command_in_single_details_row.snap index 3b7c1ecc4a..a5b839e00c 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__unified_exec_wait_status_renders_command_in_single_details_row.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__unified_exec_wait_status_renders_command_in_single_details_row.snap @@ -1,6 +1,6 @@ --- -source: tui/src/chatwidget/tests.rs -expression: rendered +source: tui/src/chatwidget/tests/exec_flow.rs +expression: normalize_snapshot_paths(rendered) --- • Waiting for background terminal (0s • esc to … └ cargo test -p codex-core -- --exact… @@ -8,4 +8,4 @@ expression: rendered › Ask Codex to do anything - gpt-5.3-codex default · 100% left · /tmp/proj… + gpt-5.3-codex default · /tmp/project diff --git a/codex-rs/tui/src/chatwidget/status_surfaces.rs b/codex-rs/tui/src/chatwidget/status_surfaces.rs index d80003cc51..bd58fd4e8f 100644 --- a/codex-rs/tui/src/chatwidget/status_surfaces.rs +++ b/codex-rs/tui/src/chatwidget/status_surfaces.rs @@ -450,12 +450,9 @@ impl ChatWidget { Some(format!("{} used", format_tokens_compact(total))) } } - StatusLineItem::ContextRemaining => self - .status_line_context_remaining_percent() - .map(|remaining| format!("{remaining}% left")), - StatusLineItem::ContextUsed => self + StatusLineItem::ContextUsage => self .status_line_context_used_percent() - .map(|used| format!("{used}% used")), + .map(format_context_used_meter), StatusLineItem::FiveHourLimit => { let window = self .rate_limit_snapshots_by_limit_id @@ -660,3 +657,61 @@ where } (items, invalid) } + +fn format_context_used_meter(used_percent: i64) -> String { + const METER_WIDTH: usize = 5; + const EIGHTHS_PER_CELL: i64 = 8; + const PARTIAL_BLOCKS: [&str; 8] = ["", "▏", "▎", "▍", "▌", "▋", "▊", "▉"]; + + let used_percent = used_percent.clamp(0, 100); + let total_eighths = (used_percent * METER_WIDTH as i64 * EIGHTHS_PER_CELL + 50) / 100; + let filled_cells = (total_eighths / EIGHTHS_PER_CELL) as usize; + let partial_eighths = (total_eighths % EIGHTHS_PER_CELL) as usize; + + let mut meter = String::with_capacity(METER_WIDTH); + meter.push_str(&"█".repeat(filled_cells)); + meter.push_str(PARTIAL_BLOCKS[partial_eighths]); + + let occupied_cells = filled_cells + usize::from(partial_eighths > 0); + meter.push_str(&" ".repeat(METER_WIDTH.saturating_sub(occupied_cells))); + + format!("Context [{meter}]") +} + +#[cfg(test)] +mod tests { + use super::format_context_used_meter; + use pretty_assertions::assert_eq; + + #[test] + fn context_meter_uses_five_cells_with_partial_blocks() { + assert_eq!( + format_context_used_meter(/*used_percent*/ 100), + "Context [█████]" + ); + assert_eq!( + format_context_used_meter(/*used_percent*/ 50), + "Context [██▌ ]" + ); + assert_eq!( + format_context_used_meter(/*used_percent*/ 10), + "Context [▌ ]" + ); + assert_eq!( + format_context_used_meter(/*used_percent*/ 0), + "Context [ ]" + ); + } + + #[test] + fn context_meter_clamps_out_of_range_values() { + assert_eq!( + format_context_used_meter(/*used_percent*/ 125), + "Context [█████]" + ); + assert_eq!( + format_context_used_meter(/*used_percent*/ -1), + "Context [ ]" + ); + } +} diff --git a/codex-rs/tui/src/chatwidget/tests/status_and_layout.rs b/codex-rs/tui/src/chatwidget/tests/status_and_layout.rs index c5545d59ee..b04ce74a14 100644 --- a/codex-rs/tui/src/chatwidget/tests/status_and_layout.rs +++ b/codex-rs/tui/src/chatwidget/tests/status_and_layout.rs @@ -866,6 +866,36 @@ async fn status_line_invalid_items_warn_once() { ); } +#[tokio::test] +async fn status_line_legacy_context_used_renders_context_meter() { + let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; + chat.thread_id = Some(ThreadId::new()); + chat.config.tui_status_line = Some(vec!["context-used".to_string()]); + + chat.refresh_status_line(); + + assert_eq!(status_line_text(&chat), Some("Context [ ]".to_string())); + assert!( + drain_insert_history(&mut rx).is_empty(), + "legacy context-used should remain a valid status line item" + ); +} + +#[tokio::test] +async fn status_line_legacy_context_remaining_renders_context_meter() { + let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; + chat.thread_id = Some(ThreadId::new()); + chat.config.tui_status_line = Some(vec!["context-remaining".to_string()]); + + chat.refresh_status_line(); + + assert_eq!(status_line_text(&chat), Some("Context [ ]".to_string())); + assert!( + drain_insert_history(&mut rx).is_empty(), + "legacy context-remaining should remain a valid status line item" + ); +} + #[tokio::test] async fn status_line_branch_state_resets_when_git_branch_disabled() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; @@ -965,7 +995,7 @@ async fn status_line_model_with_reasoning_includes_fast_for_fast_capable_models( chat.config.cwd = test_project_path().abs(); chat.config.tui_status_line = Some(vec![ "model-with-reasoning".to_string(), - "context-remaining".to_string(), + "context-usage".to_string(), "current-dir".to_string(), ]); chat.set_reasoning_effort(Some(ReasoningEffortConfig::XHigh)); @@ -978,7 +1008,7 @@ async fn status_line_model_with_reasoning_includes_fast_for_fast_capable_models( assert_eq!( status_line_text(&chat), - Some(format!("gpt-5.4 xhigh fast · 100% left · {test_cwd}")) + Some(format!("gpt-5.4 xhigh fast · Context [ ] · {test_cwd}")) ); chat.set_model("gpt-5.3-codex"); @@ -986,7 +1016,9 @@ async fn status_line_model_with_reasoning_includes_fast_for_fast_capable_models( assert_eq!( status_line_text(&chat), - Some(format!("gpt-5.3-codex xhigh · 100% left · {test_cwd}")) + Some(format!( + "gpt-5.3-codex xhigh · Context [ ] · {test_cwd}" + )) ); } @@ -1073,7 +1105,7 @@ async fn status_line_model_with_reasoning_fast_footer_snapshot() { chat.config.cwd = test_project_path().abs(); chat.config.tui_status_line = Some(vec![ "model-with-reasoning".to_string(), - "context-remaining".to_string(), + "context-usage".to_string(), "current-dir".to_string(), ]); chat.set_reasoning_effort(Some(ReasoningEffortConfig::XHigh)); From c0b5d8d24a16d937db2cd9064e24886e0e94960a Mon Sep 17 00:00:00 2001 From: jif-oai Date: Thu, 9 Apr 2026 17:30:18 +0100 Subject: [PATCH 04/82] Skip local shell snapshots for remote unified exec (#17217) ## Summary - detect remote exec-server sessions in the unified-exec runtime - bypass the local shell-snapshot bootstrap only for those remote sessions - preserve existing local snapshot wrapping, PowerShell UTF-8 prefixing, sandbox orchestration, and zsh-fork handling ## Why The shell snapshot file is currently captured and stored next to Core. If Core wraps a remote command with `. /path/to/local/snapshot`, the process starts on the executor and tries to source a path from the orchestrator filesystem. This keeps remote commands from receiving that known-local path until shell snapshots are captured/restored on the executor side. ## Validation - `just fmt` - `git diff --check` - `cargo test -p codex-core --lib tools::runtimes::tests` Co-authored-by: Codex --- .../core/src/tools/runtimes/unified_exec.rs | 23 +++++++++++++------ 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/codex-rs/core/src/tools/runtimes/unified_exec.rs b/codex-rs/core/src/tools/runtimes/unified_exec.rs index 86b6163b87..fd12607c1b 100644 --- a/codex-rs/core/src/tools/runtimes/unified_exec.rs +++ b/codex-rs/core/src/tools/runtimes/unified_exec.rs @@ -202,13 +202,22 @@ impl<'a> ToolRuntime for UnifiedExecRunt ) -> Result { let base_command = &req.command; let session_shell = ctx.session.user_shell(); - let command = maybe_wrap_shell_lc_with_snapshot( - base_command, - session_shell.as_ref(), - &req.cwd, - &req.explicit_env_overrides, - &req.env, - ); + let environment_is_remote = ctx + .turn + .environment + .as_ref() + .is_some_and(|environment| environment.is_remote()); + let command = if environment_is_remote { + base_command.to_vec() + } else { + maybe_wrap_shell_lc_with_snapshot( + base_command, + session_shell.as_ref(), + &req.cwd, + &req.explicit_env_overrides, + &req.env, + ) + }; let command = if matches!(session_shell.shell_type, ShellType::PowerShell) { prefix_powershell_script_with_utf8(&command) } else { From 12f0e0b0ebcfc745226dbb918d0c55e55f409f0c Mon Sep 17 00:00:00 2001 From: jif-oai Date: Thu, 9 Apr 2026 18:44:26 +0100 Subject: [PATCH 05/82] chore: merge name and title (#17116) Merge title and name concept to leverage the sqlite title column and have more efficient queries --------- Co-authored-by: Codex --- .../app-server/src/codex_message_processor.rs | 142 ++++++++++++++---- .../tests/suite/v2/thread_name_websocket.rs | 52 +++++++ codex-rs/core/src/codex.rs | 136 +++++++++-------- codex-rs/core/src/lib.rs | 2 +- codex-rs/core/src/rollout.rs | 7 +- .../core/tests/suite/rollout_list_find.rs | 7 +- codex-rs/exec/src/lib.rs | 27 +++- codex-rs/rollout/src/lib.rs | 3 +- codex-rs/rollout/src/policy.rs | 17 ++- codex-rs/rollout/src/recorder.rs | 38 ++++- codex-rs/rollout/src/session_index.rs | 13 +- codex-rs/rollout/src/session_index_tests.rs | 21 +-- codex-rs/state/src/extract.rs | 35 ++++- codex-rs/state/src/runtime/threads.rs | 73 +++++++++ codex-rs/tui/src/app.rs | 8 +- codex-rs/tui/src/lib.rs | 103 +++++++++++-- 16 files changed, 539 insertions(+), 145 deletions(-) diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index 4e3bc70cb3..aae240e3f9 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -199,6 +199,7 @@ use codex_core::SteerInputError; use codex_core::ThreadConfigSnapshot; use codex_core::ThreadManager; use codex_core::ThreadSortKey as CoreThreadSortKey; +use codex_core::append_thread_name; use codex_core::config::Config; use codex_core::config::ConfigOverrides; use codex_core::config::NetworkProxyAuditMetadata; @@ -288,11 +289,13 @@ use codex_protocol::protocol::ReviewTarget as CoreReviewTarget; use codex_protocol::protocol::RolloutItem; use codex_protocol::protocol::SessionConfiguredEvent; use codex_protocol::protocol::SessionMetaLine; +use codex_protocol::protocol::ThreadNameUpdatedEvent; use codex_protocol::protocol::USER_MESSAGE_BEGIN; use codex_protocol::protocol::W3cTraceContext; use codex_protocol::user_input::MAX_USER_INPUT_TEXT_CHARS; use codex_protocol::user_input::UserInput as CoreInputItem; use codex_rmcp_client::perform_oauth_login_return_url; +use codex_rollout::append_rollout_item_to_path; use codex_rollout::state_db::StateDbHandle; use codex_rollout::state_db::get_state_db; use codex_rollout::state_db::reconcile_rollout; @@ -2674,11 +2677,11 @@ impl CodexMessageProcessor { return; } - let thread_exists = + let rollout_path = match find_thread_path_by_id_str(&self.config.codex_home, &thread_id.to_string()).await { - Ok(Some(_)) => true, - Ok(None) => false, + Ok(Some(path)) => Some(path), + Ok(None) => None, Err(err) => { self.send_invalid_request_error( request_id, @@ -2689,19 +2692,39 @@ impl CodexMessageProcessor { } }; - if !thread_exists { + let Some(rollout_path) = rollout_path else { self.send_invalid_request_error(request_id, format!("thread not found: {thread_id}")) .await; return; - } + }; - if let Err(err) = - codex_core::append_thread_name(&self.config.codex_home, thread_id, &name).await - { + let msg = EventMsg::ThreadNameUpdated(ThreadNameUpdatedEvent { + thread_id, + thread_name: Some(name.clone()), + }); + let item = RolloutItem::EventMsg(msg); + if let Err(err) = append_rollout_item_to_path(rollout_path.as_path(), &item).await { self.send_internal_error(request_id, format!("failed to set thread name: {err}")) .await; return; } + if let Err(err) = append_thread_name(&self.config.codex_home, thread_id, &name).await { + self.send_internal_error(request_id, format!("failed to index thread name: {err}")) + .await; + return; + } + + let state_db_ctx = open_state_db_for_direct_thread_lookup(&self.config).await; + reconcile_rollout( + state_db_ctx.as_deref(), + rollout_path.as_path(), + self.config.model_provider_id.as_str(), + /*builder*/ None, + &[], + /*archived_only*/ None, + /*new_thread_memory_mode*/ None, + ) + .await; self.outgoing .send_response(request_id, ThreadSetNameResponse {}) @@ -3445,13 +3468,7 @@ impl CodexMessageProcessor { threads.push((conversation_id, thread)); } - let names = match find_thread_names_by_ids(&self.config.codex_home, &thread_ids).await { - Ok(names) => names, - Err(err) => { - warn!("Failed to read thread names: {err}"); - HashMap::new() - } - }; + let names = thread_titles_by_ids(&self.config, &thread_ids).await; let statuses = self .thread_watch_manager @@ -3461,7 +3478,9 @@ impl CodexMessageProcessor { let data = threads .into_iter() .map(|(conversation_id, mut thread)| { - thread.name = names.get(&conversation_id).cloned(); + if let Some(title) = names.get(&conversation_id).cloned() { + set_thread_name_from_title(&mut thread, title); + } if let Some(status) = statuses.get(&thread.id) { thread.status = status.clone(); } @@ -4265,13 +4284,8 @@ impl CodexMessageProcessor { } async fn attach_thread_name(&self, thread_id: ThreadId, thread: &mut Thread) { - match find_thread_name_by_id(&self.config.codex_home, &thread_id).await { - Ok(name) => { - thread.name = name; - } - Err(err) => { - warn!("Failed to read thread name for {thread_id}: {err}"); - } + if let Some(title) = title_from_state_db(&self.config, thread_id).await { + set_thread_name_from_title(thread, title); } } @@ -8029,7 +8043,7 @@ async fn handle_thread_listener_command( async fn handle_pending_thread_resume_request( conversation_id: ThreadId, conversation: &Arc, - codex_home: &Path, + _codex_home: &Path, thread_state_manager: &ThreadStateManager, thread_state: &Arc>, thread_watch_manager: &ThreadWatchManager, @@ -8087,11 +8101,6 @@ async fn handle_pending_thread_resume_request( has_live_in_progress_turn, ); - match find_thread_name_by_id(codex_home, &conversation_id).await { - Ok(thread_name) => thread.name = thread_name, - Err(err) => warn!("Failed to read thread name for {conversation_id}: {err}"), - } - let ThreadConfigSnapshot { model, model_provider_id, @@ -8653,7 +8662,7 @@ async fn read_summary_from_state_db_by_thread_id( config: &Config, thread_id: ThreadId, ) -> Option { - let state_db_ctx = get_state_db(config).await; + let state_db_ctx = open_state_db_for_direct_thread_lookup(config).await; read_summary_from_state_db_context_by_thread_id(state_db_ctx.as_ref(), thread_id).await } @@ -8670,6 +8679,71 @@ async fn read_summary_from_state_db_context_by_thread_id( Some(summary_from_thread_metadata(&metadata)) } +async fn title_from_state_db(config: &Config, thread_id: ThreadId) -> Option { + if let Some(state_db_ctx) = open_state_db_for_direct_thread_lookup(config).await + && let Some(metadata) = state_db_ctx.get_thread(thread_id).await.ok().flatten() + && let Some(title) = distinct_title(&metadata) + { + return Some(title); + } + find_thread_name_by_id(&config.codex_home, &thread_id) + .await + .ok() + .flatten() +} + +async fn thread_titles_by_ids( + config: &Config, + thread_ids: &HashSet, +) -> HashMap { + let mut names = HashMap::with_capacity(thread_ids.len()); + if let Some(state_db_ctx) = open_state_db_for_direct_thread_lookup(config).await { + for &thread_id in thread_ids { + let Ok(Some(metadata)) = state_db_ctx.get_thread(thread_id).await else { + continue; + }; + if let Some(title) = distinct_title(&metadata) { + names.insert(thread_id, title); + } + } + } + if names.len() < thread_ids.len() + && let Ok(legacy_names) = find_thread_names_by_ids(&config.codex_home, thread_ids).await + { + for (thread_id, title) in legacy_names { + names.entry(thread_id).or_insert(title); + } + } + names +} + +async fn open_state_db_for_direct_thread_lookup(config: &Config) -> Option { + StateRuntime::init(config.sqlite_home.clone(), config.model_provider_id.clone()) + .await + .ok() +} + +fn non_empty_title(metadata: &ThreadMetadata) -> Option { + let title = metadata.title.trim(); + (!title.is_empty()).then(|| title.to_string()) +} + +fn distinct_title(metadata: &ThreadMetadata) -> Option { + let title = non_empty_title(metadata)?; + if metadata.first_user_message.as_deref().map(str::trim) == Some(title.as_str()) { + None + } else { + Some(title) + } +} + +fn set_thread_name_from_title(thread: &mut Thread, title: String) { + if title.trim().is_empty() || thread.preview.trim() == title.trim() { + return; + } + thread.name = Some(title); +} + async fn summary_from_thread_list_item( it: codex_core::ThreadItem, fallback_provider: &str, @@ -8968,6 +9042,14 @@ async fn load_thread_summary_for_rollout( } else if let Some(summary) = read_summary_from_state_db_by_thread_id(config, thread_id).await { merge_mutable_thread_metadata(&mut thread, summary_to_thread(summary)); } + let title = if let Some(metadata) = persisted_metadata { + non_empty_title(metadata) + } else { + title_from_state_db(config, thread_id).await + }; + if let Some(title) = title { + set_thread_name_from_title(&mut thread, title); + } Ok(thread) } diff --git a/codex-rs/app-server/tests/suite/v2/thread_name_websocket.rs b/codex-rs/app-server/tests/suite/v2/thread_name_websocket.rs index 4ec7344d6c..b41e2f1d18 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_name_websocket.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_name_websocket.rs @@ -21,7 +21,14 @@ use codex_app_server_protocol::ThreadResumeParams; use codex_app_server_protocol::ThreadResumeResponse; use codex_app_server_protocol::ThreadSetNameParams; use codex_app_server_protocol::ThreadSetNameResponse; +use codex_core::find_thread_name_by_id; +use codex_core::find_thread_path_by_id_str; +use codex_protocol::ThreadId; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::RolloutItem; +use codex_protocol::protocol::RolloutLine; use pretty_assertions::assert_eq; +use std::path::Path; use tempfile::TempDir; use tokio::time::Duration; use tokio::time::timeout; @@ -77,6 +84,11 @@ async fn thread_name_updated_broadcasts_for_loaded_threads() -> Result<()> { let ws2_notification = read_notification_for_method(&mut ws2, "thread/name/updated").await?; assert_thread_name_updated(ws2_notification, &conversation_id, renamed)?; + assert_legacy_thread_name(codex_home.path(), &conversation_id, renamed).await?; + assert_eq!( + thread_name_update_rollout_count(codex_home.path(), &conversation_id).await?, + 1 + ); assert_no_message(&mut ws1, Duration::from_millis(250)).await?; assert_no_message(&mut ws2, Duration::from_millis(250)).await?; @@ -128,6 +140,11 @@ async fn thread_name_updated_broadcasts_for_not_loaded_threads() -> Result<()> { let ws2_notification = read_notification_for_method(&mut ws2, "thread/name/updated").await?; assert_thread_name_updated(ws2_notification, &conversation_id, renamed)?; + assert_legacy_thread_name(codex_home.path(), &conversation_id, renamed).await?; + assert_eq!( + thread_name_update_rollout_count(codex_home.path(), &conversation_id).await?, + 1 + ); assert_no_message(&mut ws1, Duration::from_millis(250)).await?; assert_no_message(&mut ws2, Duration::from_millis(250)).await?; @@ -174,3 +191,38 @@ fn assert_thread_name_updated( assert_eq!(notification.thread_name.as_deref(), Some(thread_name)); Ok(()) } + +async fn assert_legacy_thread_name( + codex_home: &Path, + conversation_id: &str, + expected_name: &str, +) -> Result<()> { + let thread_id = ThreadId::from_string(conversation_id)?; + assert_eq!( + find_thread_name_by_id(codex_home, &thread_id) + .await? + .as_deref(), + Some(expected_name) + ); + Ok(()) +} + +async fn thread_name_update_rollout_count( + codex_home: &Path, + conversation_id: &str, +) -> Result { + let rollout_path = find_thread_path_by_id_str(codex_home, conversation_id) + .await? + .context("rollout path")?; + let contents = tokio::fs::read_to_string(rollout_path).await?; + Ok(contents + .lines() + .filter_map(|line| serde_json::from_str::(line).ok()) + .filter(|line| { + matches!( + line.item, + RolloutItem::EventMsg(EventMsg::ThreadNameUpdated(_)) + ) + }) + .count()) +} diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 54b9d524b9..6375f2a83a 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -33,7 +33,7 @@ use crate::realtime_conversation::handle_close as handle_realtime_conversation_c use crate::realtime_conversation::handle_start as handle_realtime_conversation_start; use crate::realtime_conversation::handle_text as handle_realtime_conversation_text; use crate::render_skills_section; -use crate::rollout::session_index; +use crate::rollout::find_thread_name_by_id; use crate::session_prefix::format_subagent_notification_message; use crate::skills_load_input_from_config; use crate::stream_events_utils::HandleOutputCtx; @@ -1096,6 +1096,26 @@ fn local_time_context() -> (String, String) { } } +async fn thread_title_from_state_db( + state_db: Option<&state_db::StateDbHandle>, + codex_home: &Path, + conversation_id: ThreadId, +) -> Option { + if let Some(metadata) = state_db + && let Some(metadata) = metadata.get_thread(conversation_id).await.ok().flatten() + { + let title = metadata.title.trim(); + if !title.is_empty() && metadata.first_user_message.as_deref().map(str::trim) != Some(title) + { + return Some(title.to_string()); + } + } + find_thread_name_by_id(codex_home, &conversation_id) + .await + .ok() + .flatten() +} + #[derive(Clone)] pub(crate) struct SessionConfiguration { /// Provider identifier ("openai", "openrouter", ...). @@ -1882,19 +1902,12 @@ impl Session { tx }; let thread_name = - match session_index::find_thread_name_by_id(&config.codex_home, &conversation_id) + thread_title_from_state_db(state_db_ctx.as_ref(), &config.codex_home, conversation_id) .instrument(info_span!( "session_init.thread_name_lookup", otel.name = "session_init.thread_name_lookup", )) - .await - { - Ok(name) => name, - Err(err) => { - warn!("Failed to read session index for thread name: {err}"); - None - } - }; + .await; session_configuration.thread_name = thread_name.clone(); let state = SessionState::new(session_configuration.clone()); let managed_network_requirements_enabled = config.managed_network_requirements_enabled(); @@ -4848,7 +4861,6 @@ mod handlers { use crate::review_prompts::resolve_review_request; use crate::rollout::RolloutRecorder; - use crate::rollout::session_index; use crate::tasks::CompactTask; use crate::tasks::UndoTask; use crate::tasks::UserShellCommandMode; @@ -5528,13 +5540,25 @@ mod handlers { .await; } - /// Persists the thread name in the session index, updates in-memory state, and emits - /// a `ThreadNameUpdated` event on success. - /// - /// This appends the name to `CODEX_HOME/sessions_index.jsonl` via `session_index::append_thread_name` for the - /// current `thread_id`, then updates `SessionConfiguration::thread_name`. - /// - /// Returns an error event if the name is empty or session persistence is disabled. + async fn persist_thread_name_update( + sess: &Arc, + event: ThreadNameUpdatedEvent, + ) -> anyhow::Result { + let msg = EventMsg::ThreadNameUpdated(event); + let item = RolloutItem::EventMsg(msg.clone()); + let recorder = { + let guard = sess.services.rollout.lock().await; + guard.clone() + } + .ok_or_else(|| anyhow::anyhow!("Session persistence is disabled; cannot rename thread."))?; + recorder.persist().await?; + recorder.record_items(std::slice::from_ref(&item)).await?; + recorder.flush().await?; + Ok(msg) + } + + /// Persists the thread name in the rollout and state database, updates in-memory state, and + /// emits a `ThreadNameUpdated` event on success. pub async fn set_thread_name(sess: &Arc, sub_id: String, name: String) { let Some(name) = crate::util::normalize_thread_name(&name) else { let event = Event { @@ -5548,47 +5572,33 @@ mod handlers { return; }; - let persistence_enabled = { - let rollout = sess.services.rollout.lock().await; - rollout.is_some() - }; - if !persistence_enabled { - let event = Event { - id: sub_id, - msg: EventMsg::Error(ErrorEvent { - message: "Session persistence is disabled; cannot rename thread.".to_string(), - codex_error_info: Some(CodexErrorInfo::Other), - }), - }; - sess.send_event_raw(event).await; - return; + let updated = ThreadNameUpdatedEvent { + thread_id: sess.conversation_id, + thread_name: Some(name.clone()), }; - if let Err(e) = sess.try_ensure_rollout_materialized().await { - let event = Event { - id: sub_id, - msg: EventMsg::Error(ErrorEvent { - message: format!("Failed to set thread name: {e}"), - codex_error_info: Some(CodexErrorInfo::Other), - }), - }; - sess.send_event_raw(event).await; - return; - } + let msg = match persist_thread_name_update(sess, updated).await { + Ok(msg) => msg, + Err(err) => { + warn!("Failed to persist thread name update to rollout: {err}"); + let event = Event { + id: sub_id, + msg: EventMsg::Error(ErrorEvent { + message: err.to_string(), + codex_error_info: Some(CodexErrorInfo::Other), + }), + }; + sess.send_event_raw(event).await; + return; + } + }; - let codex_home = sess.codex_home().await; - if let Err(e) = - session_index::append_thread_name(&codex_home, sess.conversation_id, &name).await + if let Some(state_db) = sess.services.state_db.as_deref() + && let Err(err) = state_db + .update_thread_title(sess.conversation_id, &name) + .await { - let event = Event { - id: sub_id, - msg: EventMsg::Error(ErrorEvent { - message: format!("Failed to set thread name: {e}"), - codex_error_info: Some(CodexErrorInfo::Other), - }), - }; - sess.send_event_raw(event).await; - return; + warn!("Failed to update thread title in state db: {err}"); } { @@ -5596,14 +5606,14 @@ mod handlers { state.session_configuration.thread_name = Some(name.clone()); } - sess.send_event_raw(Event { - id: sub_id, - msg: EventMsg::ThreadNameUpdated(ThreadNameUpdatedEvent { - thread_id: sess.conversation_id, - thread_name: Some(name), - }), - }) - .await; + let codex_home = sess.codex_home().await; + if let Err(err) = + crate::rollout::append_thread_name(&codex_home, sess.conversation_id, &name).await + { + warn!("Failed to update legacy thread name index: {err}"); + } + + sess.deliver_event_raw(Event { id: sub_id, msg }).await; } pub async fn shutdown(sess: &Arc, sub_id: String) -> bool { diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index efae8ae918..db04a09851 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -165,10 +165,10 @@ pub use rollout::append_thread_name; pub use rollout::find_archived_thread_path_by_id_str; #[deprecated(note = "use find_thread_path_by_id_str")] pub use rollout::find_conversation_path_by_id_str; +pub use rollout::find_thread_meta_by_name_str; pub use rollout::find_thread_name_by_id; pub use rollout::find_thread_names_by_ids; pub use rollout::find_thread_path_by_id_str; -pub use rollout::find_thread_path_by_name_str; pub use rollout::parse_cursor; pub use rollout::read_head_for_summary; pub use rollout::read_session_meta_line; diff --git a/codex-rs/core/src/rollout.rs b/codex-rs/core/src/rollout.rs index 492b0bc058..26e3a84d5c 100644 --- a/codex-rs/core/src/rollout.rs +++ b/codex-rs/core/src/rollout.rs @@ -14,10 +14,10 @@ pub use codex_rollout::append_thread_name; pub use codex_rollout::find_archived_thread_path_by_id_str; #[deprecated(note = "use find_thread_path_by_id_str")] pub use codex_rollout::find_conversation_path_by_id_str; +pub use codex_rollout::find_thread_meta_by_name_str; pub use codex_rollout::find_thread_name_by_id; pub use codex_rollout::find_thread_names_by_ids; pub use codex_rollout::find_thread_path_by_id_str; -pub use codex_rollout::find_thread_path_by_name_str; pub use codex_rollout::parse_cursor; pub use codex_rollout::read_head_for_summary; pub use codex_rollout::read_session_meta_line; @@ -66,11 +66,6 @@ pub(crate) mod recorder { pub use codex_rollout::RolloutRecorder; } -pub(crate) mod session_index { - pub use codex_rollout::append_thread_name; - pub use codex_rollout::find_thread_name_by_id; -} - pub(crate) use crate::session_rollout_init_error::map_session_init_error; pub(crate) mod truncation { diff --git a/codex-rs/core/tests/suite/rollout_list_find.rs b/codex-rs/core/tests/suite/rollout_list_find.rs index 7445a4ba05..eef0d0f5f4 100644 --- a/codex-rs/core/tests/suite/rollout_list_find.rs +++ b/codex-rs/core/tests/suite/rollout_list_find.rs @@ -9,8 +9,8 @@ use codex_core::RolloutRecorder; use codex_core::RolloutRecorderParams; use codex_core::config::ConfigBuilder; use codex_core::find_archived_thread_path_by_id_str; +use codex_core::find_thread_meta_by_name_str; use codex_core::find_thread_path_by_id_str; -use codex_core::find_thread_path_by_name_str; use codex_protocol::ThreadId; use codex_protocol::models::BaseInstructions; use codex_protocol::protocol::SessionSource; @@ -197,9 +197,10 @@ async fn find_locates_rollout_file_written_by_recorder() -> std::io::Result<()> ), )?; - let found = find_thread_path_by_name_str(home.path(), thread_name).await?; + let found = find_thread_meta_by_name_str(home.path(), thread_name).await?; - let path = found.expect("expected rollout path to be found"); + let (path, session_meta) = found.expect("expected rollout path to be found"); + assert_eq!(session_meta.meta.id, thread_id); assert!(path.exists()); let contents = std::fs::read_to_string(&path)?; assert!(contents.contains(&thread_id.to_string())); diff --git a/codex-rs/exec/src/lib.rs b/codex-rs/exec/src/lib.rs index 76634e7784..10a5fa1da8 100644 --- a/codex-rs/exec/src/lib.rs +++ b/codex-rs/exec/src/lib.rs @@ -60,6 +60,7 @@ use codex_core::config::resolve_oss_provider; use codex_core::config_loader::ConfigLoadError; use codex_core::config_loader::LoaderOverrides; use codex_core::config_loader::format_config_error_with_source; +use codex_core::find_thread_meta_by_name_str; use codex_core::format_exec_policy_error_with_source; use codex_core::path_utils; use codex_feedback::CodexFeedback; @@ -1256,6 +1257,27 @@ async fn resolve_resume_thread_id( if Uuid::parse_str(session_id).is_ok() { return Ok(Some(session_id.to_string())); } + if let Some(state_db) = codex_core::get_state_db(config).await { + let cwd = (!args.all).then_some(config.cwd.as_path()); + let resolved = state_db + .find_thread_by_exact_title( + session_id, + &[], + /*model_providers*/ None, + /*archived_only*/ false, + cwd, + ) + .await?; + if let Some(thread) = resolved { + return Ok(Some(thread.id.to_string())); + } + if let Some((_, session_meta)) = + find_thread_meta_by_name_str(&config.codex_home, session_id).await? + && (args.all || cwds_match(config.cwd.as_path(), &session_meta.meta.cwd)) + { + return Ok(Some(session_meta.meta.id.to_string())); + } + } let mut cursor = None; loop { @@ -1271,10 +1293,7 @@ async fn resolve_resume_thread_id( source_kinds: Some(all_thread_source_kinds()), archived: Some(false), cwd: None, - // Thread names are attached separately from rollout titles, so name - // resolution must scan the filtered list client-side instead of relying - // on the backend `search_term` filter. - search_term: None, + search_term: Some(session_id.to_string()), }, }, "thread/list", diff --git a/codex-rs/rollout/src/lib.rs b/codex-rs/rollout/src/lib.rs index 6acf2c3be4..31fcf47240 100644 --- a/codex-rs/rollout/src/lib.rs +++ b/codex-rs/rollout/src/lib.rs @@ -54,10 +54,11 @@ pub use policy::EventPersistenceMode; pub use policy::should_persist_response_item_for_memories; pub use recorder::RolloutRecorder; pub use recorder::RolloutRecorderParams; +pub use recorder::append_rollout_item_to_path; pub use session_index::append_thread_name; +pub use session_index::find_thread_meta_by_name_str; pub use session_index::find_thread_name_by_id; pub use session_index::find_thread_names_by_ids; -pub use session_index::find_thread_path_by_name_str; pub use state_db::StateDbHandle; #[cfg(test)] diff --git a/codex-rs/rollout/src/policy.rs b/codex-rs/rollout/src/policy.rs index a4c8913a46..4b50781e76 100644 --- a/codex-rs/rollout/src/policy.rs +++ b/codex-rs/rollout/src/policy.rs @@ -97,6 +97,7 @@ fn event_msg_persistence_mode(ev: &EventMsg) -> Option { | EventMsg::AgentReasoning(_) | EventMsg::AgentReasoningRawContent(_) | EventMsg::TokenCount(_) + | EventMsg::ThreadNameUpdated(_) | EventMsg::ContextCompacted(_) | EventMsg::EnteredReviewMode(_) | EventMsg::ExitedReviewMode(_) @@ -142,7 +143,6 @@ fn event_msg_persistence_mode(ev: &EventMsg) -> Option { | EventMsg::AgentReasoningSectionBreak(_) | EventMsg::RawResponseItem(_) | EventMsg::SessionConfigured(_) - | EventMsg::ThreadNameUpdated(_) | EventMsg::McpToolCallBegin(_) | EventMsg::WebSearchBegin(_) | EventMsg::ExecCommandBegin(_) @@ -188,8 +188,10 @@ fn event_msg_persistence_mode(ev: &EventMsg) -> Option { mod tests { use super::EventPersistenceMode; use super::should_persist_event_msg; + use codex_protocol::ThreadId; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::ImageGenerationEndEvent; + use codex_protocol::protocol::ThreadNameUpdatedEvent; #[test] fn persists_image_generation_end_events_in_limited_mode() { @@ -206,4 +208,17 @@ mod tests { EventPersistenceMode::Limited )); } + + #[test] + fn persists_thread_name_updates_in_limited_mode() { + let event = EventMsg::ThreadNameUpdated(ThreadNameUpdatedEvent { + thread_id: ThreadId::new(), + thread_name: Some("saved-session".to_string()), + }); + + assert!(should_persist_event_msg( + &event, + EventPersistenceMode::Limited + )); + } } diff --git a/codex-rs/rollout/src/recorder.rs b/codex-rs/rollout/src/recorder.rs index 3554cb3797..6098b805ec 100644 --- a/codex-rs/rollout/src/recorder.rs +++ b/codex-rs/rollout/src/recorder.rs @@ -225,6 +225,26 @@ impl RolloutRecorder { search_term: Option<&str>, ) -> std::io::Result { let codex_home = config.codex_home(); + let state_db_ctx = state_db::get_state_db(config).await; + + if search_term.is_some() + && let Some(db_page) = state_db::list_threads_db( + state_db_ctx.as_deref(), + codex_home, + page_size, + cursor, + sort_key, + allowed_sources, + model_providers, + archived, + search_term, + ) + .await + && (!db_page.items.is_empty() || cursor.is_some()) + { + return Ok(db_page.into()); + } + // Filesystem-first listing intentionally overfetches so we can repair stale/missing // SQLite rollout paths before the final DB-backed page is returned. let fs_page_size = page_size.saturating_mul(2).max(page_size); @@ -256,7 +276,6 @@ impl RolloutRecorder { .await? }; - let state_db_ctx = state_db::get_state_db(config).await; if state_db_ctx.is_none() { // Keep legacy behavior when SQLite is unavailable: return filesystem results // at the requested page size. @@ -951,6 +970,23 @@ async fn sync_thread_state_after_write( .await; } +/// Append one already-filtered rollout item to an existing rollout JSONL file. +/// +/// This is for metadata updates to unloaded threads. Live sessions should use +/// `RolloutRecorder::record_items` so rollout and SQLite updates remain ordered +/// with the rest of the session stream. +pub async fn append_rollout_item_to_path( + rollout_path: &Path, + item: &RolloutItem, +) -> std::io::Result<()> { + let file = tokio::fs::OpenOptions::new() + .append(true) + .open(rollout_path) + .await?; + let mut writer = JsonlWriter { file }; + writer.write_rollout_item(item).await +} + struct JsonlWriter { file: tokio::fs::File, } diff --git a/codex-rs/rollout/src/session_index.rs b/codex-rs/rollout/src/session_index.rs index f1acdd8124..039ce27f24 100644 --- a/codex-rs/rollout/src/session_index.rs +++ b/codex-rs/rollout/src/session_index.rs @@ -8,6 +8,7 @@ use std::path::Path; use std::path::PathBuf; use codex_protocol::ThreadId; +use codex_protocol::protocol::SessionMetaLine; use serde::Deserialize; use serde::Serialize; use tokio::io::AsyncBufReadExt; @@ -111,12 +112,12 @@ pub async fn find_thread_names_by_ids( Ok(names) } -/// Locate a recorded thread rollout file by thread name using newest-first ordering. -/// Returns `Ok(Some(path))` if found, `Ok(None)` if not present. -pub async fn find_thread_path_by_name_str( +/// Locate a recorded thread rollout and read its session metadata by thread name. +/// Returns the newest indexed name that still has a readable rollout header. +pub async fn find_thread_meta_by_name_str( codex_home: &Path, name: &str, -) -> std::io::Result> { +) -> std::io::Result> { if name.trim().is_empty() { return Ok(None); } @@ -136,11 +137,11 @@ pub async fn find_thread_path_by_name_str( // rename cannot shadow an older persisted session with the same name. if let Some(path) = super::list::find_thread_path_by_id_str(codex_home, &thread_id.to_string()).await? - && super::list::read_session_meta_line(&path).await.is_ok() + && let Ok(session_meta) = super::list::read_session_meta_line(&path).await { drop(rx); scan.await.map_err(std::io::Error::other)??; - return Ok(Some(path)); + return Ok(Some((path, session_meta))); } } scan.await.map_err(std::io::Error::other)??; diff --git a/codex-rs/rollout/src/session_index_tests.rs b/codex-rs/rollout/src/session_index_tests.rs index 9deba70b56..c6a539fb28 100644 --- a/codex-rs/rollout/src/session_index_tests.rs +++ b/codex-rs/rollout/src/session_index_tests.rs @@ -73,7 +73,7 @@ fn find_thread_id_by_name_prefers_latest_entry() -> std::io::Result<()> { } #[tokio::test] -async fn find_thread_path_by_name_str_skips_newest_entry_without_rollout() -> std::io::Result<()> { +async fn find_thread_meta_by_name_str_skips_newest_entry_without_rollout() -> std::io::Result<()> { // A newer unsaved name entry should not shadow an older persisted rollout with the same name. let temp = TempDir::new()?; let path = session_index_path(temp.path()); @@ -99,14 +99,17 @@ async fn find_thread_path_by_name_str_skips_newest_entry_without_rollout() -> st ]; write_index(&path, &lines)?; - let found = find_thread_path_by_name_str(temp.path(), "same").await?; + let found = find_thread_meta_by_name_str(temp.path(), "same").await?; - assert_eq!(found, Some(saved_rollout_path)); + assert_eq!( + found.map(|(path, session_meta)| (path, session_meta.meta.id)), + Some((saved_rollout_path, saved_id)) + ); Ok(()) } #[tokio::test] -async fn find_thread_path_by_name_str_skips_partial_rollout() -> std::io::Result<()> { +async fn find_thread_meta_by_name_str_skips_partial_rollout() -> std::io::Result<()> { let temp = TempDir::new()?; let path = session_index_path(temp.path()); let saved_id = ThreadId::new(); @@ -133,14 +136,14 @@ async fn find_thread_path_by_name_str_skips_partial_rollout() -> std::io::Result ]; write_index(&path, &lines)?; - let found = find_thread_path_by_name_str(temp.path(), "same").await?; + let found = find_thread_meta_by_name_str(temp.path(), "same").await?; - assert_eq!(found, Some(saved_rollout_path)); + assert_eq!(found.map(|(path, _)| path), Some(saved_rollout_path)); Ok(()) } #[tokio::test] -async fn find_thread_path_by_name_str_ignores_historical_name_after_rename() -> std::io::Result<()> +async fn find_thread_meta_by_name_str_ignores_historical_name_after_rename() -> std::io::Result<()> { let temp = TempDir::new()?; let path = session_index_path(temp.path()); @@ -171,9 +174,9 @@ async fn find_thread_path_by_name_str_ignores_historical_name_after_rename() -> ]; write_index(&path, &lines)?; - let found = find_thread_path_by_name_str(temp.path(), "same").await?; + let found = find_thread_meta_by_name_str(temp.path(), "same").await?; - assert_eq!(found, Some(current_rollout_path)); + assert_eq!(found.map(|(path, _)| path), Some(current_rollout_path)); Ok(()) } diff --git a/codex-rs/state/src/extract.rs b/codex-rs/state/src/extract.rs index 8d35d393a8..91c6755ffe 100644 --- a/codex-rs/state/src/extract.rs +++ b/codex-rs/state/src/extract.rs @@ -33,7 +33,9 @@ pub fn apply_rollout_item( pub fn rollout_item_affects_thread_metadata(item: &RolloutItem) -> bool { match item { RolloutItem::SessionMeta(_) | RolloutItem::TurnContext(_) => true, - RolloutItem::EventMsg(EventMsg::TokenCount(_) | EventMsg::UserMessage(_)) => true, + RolloutItem::EventMsg( + EventMsg::TokenCount(_) | EventMsg::UserMessage(_) | EventMsg::ThreadNameUpdated(_), + ) => true, RolloutItem::EventMsg(_) | RolloutItem::ResponseItem(_) | RolloutItem::Compacted(_) => { false } @@ -95,13 +97,18 @@ fn apply_event_msg(metadata: &mut ThreadMetadata, event: &EventMsg) { } } } + EventMsg::ThreadNameUpdated(updated) => { + if let Some(title) = updated.thread_name.as_deref() + && !title.trim().is_empty() + { + metadata.title = title.trim().to_string(); + } + } _ => {} } } -fn apply_response_item(_metadata: &mut ThreadMetadata, _item: &ResponseItem) { - // Title and first_user_message are derived from EventMsg::UserMessage only. -} +fn apply_response_item(_metadata: &mut ThreadMetadata, _item: &ResponseItem) {} fn strip_user_message_prefix(text: &str) -> &str { match text.find(USER_MESSAGE_BEGIN) { @@ -152,6 +159,7 @@ mod tests { use codex_protocol::protocol::SessionMeta; use codex_protocol::protocol::SessionMetaLine; use codex_protocol::protocol::SessionSource; + use codex_protocol::protocol::ThreadNameUpdatedEvent; use codex_protocol::protocol::TurnContextItem; use codex_protocol::protocol::USER_MESSAGE_BEGIN; use codex_protocol::protocol::UserMessageEvent; @@ -198,6 +206,25 @@ mod tests { assert_eq!(metadata.title, "actual user request"); } + #[test] + fn thread_name_update_replaces_title_without_changing_first_user_message() { + let mut metadata = metadata_for_test(); + metadata.title = "actual user request".to_string(); + metadata.first_user_message = Some("actual user request".to_string()); + let item = RolloutItem::EventMsg(EventMsg::ThreadNameUpdated(ThreadNameUpdatedEvent { + thread_id: metadata.id, + thread_name: Some("saved-session".to_string()), + })); + + apply_rollout_item(&mut metadata, &item, "test-provider"); + + assert_eq!( + metadata.first_user_message.as_deref(), + Some("actual user request") + ); + assert_eq!(metadata.title, "saved-session"); + } + #[test] fn event_msg_image_only_user_message_sets_image_placeholder_preview() { let mut metadata = metadata_for_test(); diff --git a/codex-rs/state/src/runtime/threads.rs b/codex-rs/state/src/runtime/threads.rs index 09b23a4319..e56ca3f386 100644 --- a/codex-rs/state/src/runtime/threads.rs +++ b/codex-rs/state/src/runtime/threads.rs @@ -326,6 +326,66 @@ ON CONFLICT(child_thread_id) DO NOTHING .map(PathBuf::from)) } + /// Find the newest thread whose user-facing title exactly matches `title`. + #[allow(clippy::too_many_arguments)] + pub async fn find_thread_by_exact_title( + &self, + title: &str, + allowed_sources: &[String], + model_providers: Option<&[String]>, + archived_only: bool, + cwd: Option<&Path>, + ) -> anyhow::Result> { + let mut builder = QueryBuilder::::new( + r#" +SELECT + id, + rollout_path, + created_at, + updated_at, + source, + agent_nickname, + agent_role, + agent_path, + model_provider, + model, + reasoning_effort, + cwd, + cli_version, + title, + sandbox_policy, + approval_mode, + tokens_used, + first_user_message, + archived_at, + git_sha, + git_branch, + git_origin_url +FROM threads + "#, + ); + push_thread_filters( + &mut builder, + archived_only, + allowed_sources, + model_providers, + /*anchor*/ None, + crate::SortKey::UpdatedAt, + /*search_term*/ None, + ); + builder.push(" AND title = "); + builder.push_bind(title); + if let Some(cwd) = cwd { + builder.push(" AND cwd = "); + builder.push_bind(cwd.display().to_string()); + } + push_thread_order_and_limit(&mut builder, crate::SortKey::UpdatedAt, /*limit*/ 1); + + let row = builder.build().fetch_optional(self.pool.as_ref()).await?; + row.map(|row| ThreadRow::try_from_row(&row).and_then(crate::ThreadMetadata::try_from)) + .transpose() + } + /// List threads using the underlying database. #[allow(clippy::too_many_arguments)] pub async fn list_threads( @@ -521,6 +581,19 @@ ON CONFLICT(id) DO NOTHING Ok(result.rows_affected() > 0) } + pub async fn update_thread_title( + &self, + thread_id: ThreadId, + title: &str, + ) -> anyhow::Result { + let result = sqlx::query("UPDATE threads SET title = ? WHERE id = ?") + .bind(title) + .bind(thread_id.to_string()) + .execute(self.pool.as_ref()) + .await?; + Ok(result.rows_affected() > 0) + } + pub async fn touch_thread_updated_at( &self, thread_id: ThreadId, diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 6986b9e595..25c536b660 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -4219,7 +4219,13 @@ impl App { tui.frame_requester().schedule_frame(); } AppEvent::ResumeSessionByIdOrName(id_or_name) => { - match crate::lookup_session_target_with_app_server(app_server, &id_or_name).await? { + match crate::lookup_session_target_with_app_server( + app_server, + self.config.codex_home.as_path(), + &id_or_name, + ) + .await? + { Some(target_session) => { return self .resume_target_session(tui, app_server, target_session) diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index facae979f9..eb46ba2c97 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -33,6 +33,7 @@ use codex_core::config_loader::CloudRequirementsLoader; use codex_core::config_loader::ConfigLoadError; use codex_core::config_loader::LoaderOverrides; use codex_core::config_loader::format_config_error_with_source; +use codex_core::find_thread_meta_by_name_str; use codex_core::format_exec_policy_error_with_source; use codex_core::path_utils; use codex_core::read_session_meta_line; @@ -492,6 +493,7 @@ fn session_target_from_app_server_thread( async fn lookup_session_target_by_name_with_app_server( app_server: &mut AppServerSession, + codex_home: &Path, name: &str, ) -> color_eyre::Result> { let mut cursor = None; @@ -505,10 +507,7 @@ async fn lookup_session_target_by_name_with_app_server( source_kinds: Some(vec![ThreadSourceKind::Cli, ThreadSourceKind::VsCode]), archived: Some(false), cwd: None, - // Thread names are hydrated after `thread/list` resolves rollout metadata, so - // name-based resume must scan the filtered list client-side instead of relying on - // the backend search index. - search_term: None, + search_term: Some(name.to_string()), }) .await?; if let Some(thread) = response @@ -519,7 +518,15 @@ async fn lookup_session_target_by_name_with_app_server( return Ok(session_target_from_app_server_thread(thread)); } if response.next_cursor.is_none() { - return Ok(None); + if app_server.is_remote() { + return Ok(None); + } + return Ok(find_thread_meta_by_name_str(codex_home, name).await?.map( + |(path, session_meta)| resume_picker::SessionTarget { + path: Some(path), + thread_id: session_meta.meta.id, + }, + )); } cursor = response.next_cursor; } @@ -527,6 +534,7 @@ async fn lookup_session_target_by_name_with_app_server( async fn lookup_session_target_with_app_server( app_server: &mut AppServerSession, + codex_home: &Path, id_or_name: &str, ) -> color_eyre::Result> { if Uuid::parse_str(id_or_name).is_ok() { @@ -557,7 +565,7 @@ async fn lookup_session_target_with_app_server( }; } - lookup_session_target_by_name_with_app_server(app_server, id_or_name).await + lookup_session_target_by_name_with_app_server(app_server, codex_home, id_or_name).await } async fn lookup_latest_session_target_with_app_server( @@ -1163,7 +1171,13 @@ async fn run_ratatui_app( let Some(startup_app_server) = app_server.as_mut() else { unreachable!("app server should be initialized for --fork "); }; - match lookup_session_target_with_app_server(startup_app_server, id_str).await? { + match lookup_session_target_with_app_server( + startup_app_server, + config.codex_home.as_path(), + id_str, + ) + .await? + { Some(target_session) => resume_picker::SessionSelection::Fork(target_session), None => { shutdown_app_server_if_present(app_server.take()).await; @@ -1224,7 +1238,13 @@ async fn run_ratatui_app( let Some(startup_app_server) = app_server.as_mut() else { unreachable!("app server should be initialized for --resume "); }; - match lookup_session_target_with_app_server(startup_app_server, id_str).await? { + match lookup_session_target_with_app_server( + startup_app_server, + config.codex_home.as_path(), + id_str, + ) + .await? + { Some(target_session) => resume_picker::SessionSelection::Resume(target_session), None => { shutdown_app_server_if_present(app_server.take()).await; @@ -1997,8 +2017,7 @@ mod tests { } #[tokio::test] - async fn lookup_session_target_by_name_ignores_backend_search_term_mismatch() - -> color_eyre::Result<()> { + async fn lookup_session_target_by_name_uses_backend_title_search() -> color_eyre::Result<()> { let temp_dir = TempDir::new()?; let config = build_config(&temp_dir).await?; let thread_id = ThreadId::new(); @@ -2034,22 +2053,76 @@ mod tests { ); builder.cwd = session_cwd; let mut metadata = builder.build(config.model_provider_id.as_str()); - metadata.title = "Different rollout title".to_string(); + metadata.title = "saved-session".to_string(); metadata.first_user_message = Some("preview text".to_string()); state_runtime .upsert_thread(&metadata) .await .map_err(std::io::Error::other)?; - codex_core::append_thread_name(&config.codex_home, thread_id, "saved-session").await?; + let mut app_server = + AppServerSession::new(codex_app_server_client::AppServerClient::InProcess( + start_test_embedded_app_server(config).await?, + )); + let target = lookup_session_target_by_name_with_app_server( + &mut app_server, + temp_dir.path(), + "saved-session", + ) + .await?; + let target = target.expect("name lookup should find the saved thread"); + assert_eq!(target.path, Some(rollout_path)); + assert_eq!(target.thread_id, thread_id); + + app_server.shutdown().await?; + Ok(()) + } + + #[tokio::test] + async fn lookup_session_target_by_name_falls_back_to_legacy_index() -> color_eyre::Result<()> { + let temp_dir = TempDir::new()?; + let config = build_config(&temp_dir).await?; + let thread_id = ThreadId::new(); + let rollout_path = temp_dir + .path() + .join("sessions/2025/02/01") + .join(format!("rollout-2025-02-01T10-00-00-{thread_id}.jsonl")); + std::fs::create_dir_all(rollout_path.parent().expect("rollout parent"))?; + let session_meta = SessionMeta { + id: thread_id, + timestamp: "2025-02-01T10:00:00Z".to_string(), + model_provider: Some(config.model_provider_id.clone()), + ..SessionMeta::default() + }; + let line = RolloutLine { + timestamp: session_meta.timestamp.clone(), + item: RolloutItem::SessionMeta(SessionMetaLine { + meta: session_meta, + git: None, + }), + }; + std::fs::write( + &rollout_path, + format!("{}\n", serde_json::to_string(&line)?), + )?; + std::fs::write( + temp_dir.path().join("session_index.jsonl"), + format!( + "{{\"id\":\"{thread_id}\",\"thread_name\":\"hello\",\"updated_at\":\"2025-02-02T10:00:00Z\"}}\n" + ), + )?; let mut app_server = AppServerSession::new(codex_app_server_client::AppServerClient::InProcess( start_test_embedded_app_server(config).await?, )); - let target = - lookup_session_target_by_name_with_app_server(&mut app_server, "saved-session").await?; - let target = target.expect("name lookup should find the saved thread"); + let target = lookup_session_target_by_name_with_app_server( + &mut app_server, + temp_dir.path(), + "hello", + ) + .await?; + let target = target.expect("legacy name lookup should find the saved thread"); assert_eq!(target.path, Some(rollout_path)); assert_eq!(target.thread_id, thread_id); From 76de99ff25fcb927571e918dc13861b46cb63d4b Mon Sep 17 00:00:00 2001 From: Kevin Liu Date: Thu, 9 Apr 2026 10:45:02 -0700 Subject: [PATCH 06/82] [codex] add memory extensions (#16276) # External (non-OpenAI) Pull Request Requirements Before opening this Pull Request, please read the dedicated "Contributing" markdown file or your PR may be closed: https://github.com/openai/codex/blob/main/docs/contributing.md If your PR conforms to our contribution guidelines, replace this text with a detailed and high quality description of your changes. Include a link to a bug report or enhancement request. --- codex-rs/core/src/memories/mod.rs | 5 ++ codex-rs/core/src/memories/prompts.rs | 81 +++++++++++++++++-- codex-rs/core/src/memories/prompts_tests.rs | 48 ++++++++++- .../core/templates/memories/consolidation.md | 4 +- 4 files changed, 128 insertions(+), 10 deletions(-) diff --git a/codex-rs/core/src/memories/mod.rs b/codex-rs/core/src/memories/mod.rs index ac49c640ca..194c27c907 100644 --- a/codex-rs/core/src/memories/mod.rs +++ b/codex-rs/core/src/memories/mod.rs @@ -25,6 +25,7 @@ pub(crate) use control::clear_memory_root_contents; pub(crate) use start::start_memories_startup_task; mod artifacts { + pub(super) const EXTENSIONS_SUBDIR: &str = "memories_extensions"; pub(super) const ROLLOUT_SUMMARIES_SUBDIR: &str = "rollout_summaries"; pub(super) const RAW_MEMORIES_FILENAME: &str = "raw_memories.md"; } @@ -106,6 +107,10 @@ fn rollout_summaries_dir(root: &Path) -> PathBuf { root.join(artifacts::ROLLOUT_SUMMARIES_SUBDIR) } +fn memory_extensions_root(root: &Path) -> PathBuf { + root.with_file_name(artifacts::EXTENSIONS_SUBDIR) +} + fn raw_memories_file(root: &Path) -> PathBuf { root.join(artifacts::RAW_MEMORIES_FILENAME) } diff --git a/codex-rs/core/src/memories/prompts.rs b/codex-rs/core/src/memories/prompts.rs index 56cb2b7b60..079ccd5c6a 100644 --- a/codex-rs/core/src/memories/prompts.rs +++ b/codex-rs/core/src/memories/prompts.rs @@ -1,3 +1,4 @@ +use crate::memories::memory_extensions_root; use crate::memories::memory_root; use crate::memories::phase_one; use crate::memories::storage::rollout_summary_file_stem_from_parts; @@ -31,6 +32,18 @@ static MEMORY_TOOL_DEVELOPER_INSTRUCTIONS_TEMPLATE: LazyLock