Lightweight coding agent that runs in your terminal
Rust
Use app-server metadata for TUI session restoration (#43360)
Eric Traut694b6319d3ad
diff --git a/codex-rs/tui/src/app/agents_overview.rs b/codex-rs/tui/src/app/agents_overview.rsindex 9962185b9c..79668e61eb 100644--- a/codex-rs/tui/src/app/agents_overview.rs+++ b/codex-rs/tui/src/app/agents_overview.rs@@ -369,6 +369,7 @@ impl App {let target_session = SessionTarget {path: target_thread.path.clone(),thread_id: root_thread_id,+ cwd: Some(target_thread.cwd.to_path_buf()),history_mode: Some(target_thread.history_mode),};match selfdiff --git a/codex-rs/tui/src/app/agents_overview_tests.rs b/codex-rs/tui/src/app/agents_overview_tests.rsindex 76a0e221ad..e14458c455 100644--- a/codex-rs/tui/src/app/agents_overview_tests.rs+++ b/codex-rs/tui/src/app/agents_overview_tests.rs@@ -1849,6 +1849,7 @@ async fn resuming_active_session_closes_command_center() -> Result<()> {SessionSelection::Resume(SessionTarget {path: None,thread_id,+ cwd: None,history_mode: None,}))@@ -1907,6 +1908,7 @@ async fn resume_picker_round_trip_preserves_each_threads_input() -> Result<()> {&id,)),thread_id: ThreadId::from_string(&id)?,+ cwd: None,history_mode: None,});}@@ -2006,6 +2008,7 @@ async fn command_center_handles_resume_failure_and_success() -> Result<()> {SessionSelection::Resume(SessionTarget {path: None,thread_id: ThreadId::new(),+ cwd: None,history_mode: None,}))@@ -2029,6 +2032,7 @@ async fn command_center_handles_resume_failure_and_success() -> Result<()> {SessionSelection::Resume(SessionTarget {path: Some(path),thread_id,+ cwd: None,history_mode: None,}))diff --git a/codex-rs/tui/src/app/input.rs b/codex-rs/tui/src/app/input.rsindex 3d1a6794ef..fbf1d98032 100644--- a/codex-rs/tui/src/app/input.rs+++ b/codex-rs/tui/src/app/input.rs@@ -264,6 +264,7 @@ impl App {.as_ref().and_then(|session| session.rollout_path.clone()),thread_id,+ cwd: None,history_mode: None,};let _ = self.resume_target_session(tui, app_server, target).await;diff --git a/codex-rs/tui/src/app/resume_config.rs b/codex-rs/tui/src/app/resume_config.rsindex f5e0b2bdd2..746fc7d05a 100644--- a/codex-rs/tui/src/app/resume_config.rs+++ b/codex-rs/tui/src/app/resume_config.rs@@ -9,7 +9,7 @@ impl App {pub(super) async fn resume_config_for_target(&mut self,tui: &mut tui::Tui,- app_server: &AppServerSession,+ app_server: &mut AppServerSession,target_session: &SessionTarget,) -> std::result::Result<(Config, crate::local_settings::LocalSettings), AppRunControl> {self.refresh_in_memory_config_from_disk_best_effort("resuming a thread")@@ -18,7 +18,9 @@ impl App {.runtime_working_directory_override.as_deref().or(self.harness_overrides.cwd.as_deref())- .or_else(|| app_server.remote_cwd_override());+ .or_else(|| app_server.remote_cwd_override())+ .map(Path::to_path_buf);+ let cwd_override = cwd_override.as_deref();let resume_cwd_mode = crate::session_resume::effective_resume_cwd_mode(self.local_settings.tui.resume_cwd,cwd_override,@@ -47,11 +49,17 @@ impl App {let resume_cwd = if self.app_server_target.uses_remote_workspace() {current_cwd.clone()} else {+ let history_cwd = if matches!(resume_cwd_mode, Some(ResumeCwdMode::Current)) {+ None+ } else {+ crate::session_resume::read_session_cwd(app_server, target_session.thread_id)+ .await+ .or_else(|| target_session.cwd.clone())+ };let outcome = crate::session_resume::resolve_cwd_for_resume_or_fork(tui,&self.config,- self.state_db.as_deref(),- target_session,+ history_cwd,CwdPromptAction::Resume,crate::session_resume::ResumeCwdContext {current_cwd: ¤t_cwd,diff --git a/codex-rs/tui/src/app/tests.rs b/codex-rs/tui/src/app/tests.rsindex 97994076b1..266f957280 100644--- a/codex-rs/tui/src/app/tests.rs+++ b/codex-rs/tui/src/app/tests.rs@@ -4354,18 +4354,6 @@ async fn inactive_thread_started_notification_initializes_replay_session() -> Re);let rollout_path = temp_dir.path().join("agent-rollout.jsonl");- let rollout = serde_json::json!({- "timestamp": "t0",- "type": "turn_context",- "payload": {- "cwd": test_path_buf("/tmp/agent"),- "model": "gpt-agent",- },- });- std::fs::write(- &rollout_path,- format!("{}\n", serde_json::to_string(&rollout)?),- )?;app.enqueue_thread_notification(agent_thread_id,ServerNotification::ThreadStarted(ThreadStartedNotification {@@ -4385,7 +4373,7 @@ async fn inactive_thread_started_notification_initializes_replay_session() -> Redaybreak_enabled: None,history_mode: Default::default(),model_provider: "agent-provider".to_string(),- model: None,+ model: Some("gpt-agent".to_string()),reasoning_effort: None,created_at: 1,updated_at: 2,@@ -4560,7 +4548,7 @@ async fn thread_read_session_state_does_not_reuse_primary_permission_profile() {daybreak_enabled: None,history_mode: Default::default(),model_provider: "read-provider".to_string(),- model: None,+ model: Some("server-reported-model".to_string()),reasoning_effort: None,created_at: 1,updated_at: 2,@@ -4584,6 +4572,7 @@ async fn thread_read_session_state_does_not_reuse_primary_permission_profile() {.await;assert_eq!(session.thread_id, read_thread_id);+ assert_eq!(session.model, "server-reported-model");assert_eq!(session.cwd.as_path(), test_path_buf("/tmp/read").as_path());assert_eq!(session.runtime_workspace_roots,@@ -4600,6 +4589,17 @@ async fn thread_read_session_state_does_not_reuse_primary_permission_profile() {"thread/read does not return fresh server permissions; the fallback profile must use the \active widget permissions rather than reusing the cached primary session profile");++ app.enqueue_primary_thread_session(session, Vec::new())+ .await+ .expect("switch to read thread");+ let header =+ lines_to_single_string(&app.clear_ui_header_lines_with_version(/*width*/ 80, "<VERSION>"));+ let model_line = header+ .lines()+ .find(|line| line.contains("model:"))+ .expect("rendered model line");+ assert_app_snapshot!("thread_read_model_after_switch", model_line);}#[test]@@ -7263,6 +7263,7 @@ async fn remote_resume_current_cwd_rejection_snapshot() -> Result<()> {crate::resume_picker::SessionTarget {path: None,thread_id: ThreadId::new(),+ cwd: None,history_mode: None,},)@@ -7306,6 +7307,7 @@ async fn remote_exec_resume_current_cwd_is_rejected() -> Result<()> {crate::resume_picker::SessionTarget {path: None,thread_id: ThreadId::new(),+ cwd: None,history_mode: None,},)@@ -7344,6 +7346,7 @@ async fn in_app_resume_session_cwd_without_metadata_is_non_fatal() -> Result<()>crate::resume_picker::SessionTarget {path: None,thread_id: ThreadId::new(),+ cwd: None,history_mode: None,},)@@ -7425,6 +7428,7 @@ async fn remote_resume_keeps_server_only_cwd_out_of_local_config() -> Result<()>crate::resume_picker::SessionTarget {path: Some(rollout_path),thread_id: ThreadId::from_string(&thread_id)?,+ cwd: None,history_mode: None,},)@@ -7566,6 +7570,7 @@ async fn in_app_resume_uses_configured_or_explicit_cwd() -> Result<()> {crate::resume_picker::SessionTarget {path: Some(rollout_path),thread_id,+ cwd: None,history_mode: None,},)@@ -7671,6 +7676,7 @@ async fn remembered_current_cwd_stays_at_launch_across_in_app_resumes() -> Resultargets.push(crate::resume_picker::SessionTarget {path: Some(rollout_path),thread_id: ThreadId::from_string(&thread_id)?,+ cwd: None,history_mode: None,});}diff --git a/codex-rs/tui/src/app/tests/session_lifecycle_requests.rs b/codex-rs/tui/src/app/tests/session_lifecycle_requests.rsindex a9ad47d45a..ac9fb674e5 100644--- a/codex-rs/tui/src/app/tests/session_lifecycle_requests.rs+++ b/codex-rs/tui/src/app/tests/session_lifecycle_requests.rs@@ -120,6 +120,7 @@ async fn same_thread_retry_keeps_subscription_and_restores_draft() -> Result<()>crate::resume_picker::SessionTarget {path,thread_id,+ cwd: None,history_mode: None,},)@@ -3844,6 +3845,7 @@ fn session_lifecycle_avoids_redundant_subagent_metadata_reads() -> Result<()> {crate::resume_picker::SessionTarget {path: Some(root_rollout_path),thread_id: root_thread_id,+ cwd: None,history_mode: None,},)diff --git a/codex-rs/tui/src/app/tests/startup.rs b/codex-rs/tui/src/app/tests/startup.rsindex da39ffa0ac..02b3be4e6b 100644--- a/codex-rs/tui/src/app/tests/startup.rs+++ b/codex-rs/tui/src/app/tests/startup.rs@@ -148,6 +148,7 @@ fn startup_waiting_gate_is_only_for_fresh_or_exit_session_selection() {crate::resume_picker::SessionTarget {path: Some(PathBuf::from("/tmp/restore")),thread_id: ThreadId::new(),+ cwd: None,history_mode: None,})),@@ -158,6 +159,7 @@ fn startup_waiting_gate_is_only_for_fresh_or_exit_session_selection() {crate::resume_picker::SessionTarget {path: Some(PathBuf::from("/tmp/fork")),thread_id: ThreadId::new(),+ cwd: None,history_mode: None,})),@@ -170,11 +172,13 @@ fn startup_paused_goal_prompt_gate_is_only_for_quiet_resume() {let resume = SessionSelection::Resume(crate::resume_picker::SessionTarget {path: Some(PathBuf::from("/tmp/restore")),thread_id: ThreadId::new(),+ cwd: None,history_mode: None,});let fork = SessionSelection::Fork(crate::resume_picker::SessionTarget {path: Some(PathBuf::from("/tmp/fork")),thread_id: ThreadId::new(),+ cwd: None,history_mode: None,});let no_images: Vec<PathBuf> = Vec::new();@@ -244,6 +248,7 @@ fn startup_waiting_gate_not_applied_for_resume_or_fork_session_selection() {crate::resume_picker::SessionTarget {path: Some(PathBuf::from("/tmp/restore")),thread_id: ThreadId::new(),+ cwd: None,history_mode: None,},));@@ -258,6 +263,7 @@ fn startup_waiting_gate_not_applied_for_resume_or_fork_session_selection() {crate::resume_picker::SessionTarget {path: Some(PathBuf::from("/tmp/fork")),thread_id: ThreadId::new(),+ cwd: None,history_mode: None,},));@@ -1335,6 +1341,7 @@ async fn ignore_same_thread_resume_reports_noop_for_current_thread() {let ignored = app.ignore_same_thread_resume(&crate::resume_picker::SessionTarget {path: Some(test_path_buf("/tmp/project")),thread_id,+ cwd: None,history_mode: None,});@@ -1360,6 +1367,7 @@ async fn ignore_same_thread_resume_allows_reattaching_displayed_inactive_thread(let ignored = app.ignore_same_thread_resume(&crate::resume_picker::SessionTarget {path: Some(test_path_buf("/tmp/project")),thread_id,+ cwd: None,history_mode: None,});@@ -1386,6 +1394,7 @@ async fn ignore_same_thread_resume_allows_retrying_read_only_view() -> Result<()!app.ignore_same_thread_resume(&crate::resume_picker::SessionTarget {path: Some(test_path_buf("/tmp/project")),thread_id,+ cwd: None,history_mode: None,}));diff --git a/codex-rs/tui/src/app/thread_routing.rs b/codex-rs/tui/src/app/thread_routing.rsindex d8174e755b..e688317558 100644--- a/codex-rs/tui/src/app/thread_routing.rs+++ b/codex-rs/tui/src/app/thread_routing.rs@@ -8,7 +8,6 @@ use super::session_lifecycle::ThreadAttachPresentation;use super::*;use crate::app_event::ThreadTitleDestination;use crate::chatwidget::ThreadInputStateRestoreMode;-use crate::session_resume::read_session_model;use codex_app_server_protocol::ThreadStartedNotification;use codex_app_server_protocol::TurnInterruptParams;use codex_app_server_protocol::TurnInterruptResponse;@@ -1252,10 +1251,8 @@ impl App {session.set_cwd_retargeting_implicit_runtime_workspace_root(notification.thread.cwd.clone());let rollout_path = notification.thread.path.clone();- if let Some(model) =- read_session_model(self.state_db.as_deref(), thread_id, rollout_path.as_deref()).await- {- session.model = model;+ if let Some(model) = ¬ification.thread.model {+ session.model = model.clone();} else if rollout_path.is_some() {session.model.clear();}diff --git a/codex-rs/tui/src/app/thread_session_state.rs b/codex-rs/tui/src/app/thread_session_state.rsindex a7bec92334..8ec8f85727 100644--- a/codex-rs/tui/src/app/thread_session_state.rs+++ b/codex-rs/tui/src/app/thread_session_state.rs@@ -1,5 +1,4 @@use super::App;-use crate::session_resume::read_session_model;use crate::session_state::ThreadSessionState;use codex_app_server_protocol::AskForApproval;use codex_app_server_protocol::Thread;@@ -80,7 +79,7 @@ impl App {let active_permission_profile = self.current_active_permission_profile();let mut session = if let Some(mut session) = self.primary_session_configured.clone() {if session.thread_id != thread_id {- // `thread/read` does not include thread settings, so do not carry+ // `thread/read` does not include all thread settings, so do not carry// thread-scoped state from the currently active session.session.collaboration_mode = None;session.personality = None;@@ -120,10 +119,8 @@ impl App {session.active_permission_profile = active_permission_profile;session.instruction_source_paths = Vec::new();session.rollout_path = thread.path.clone();- if let Some(model) =- read_session_model(self.state_db.as_deref(), thread_id, thread.path.as_deref()).await- {- session.model = model;+ if let Some(model) = &thread.model {+ session.model = model.clone();} else if thread.path.is_some() {session.model.clear();}diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rsindex b512fd4323..5791eee586 100644--- a/codex-rs/tui/src/lib.rs+++ b/codex-rs/tui/src/lib.rs@@ -16,6 +16,7 @@ use crate::legacy_core::config::resolve_profile_v2_config_path;use crate::session_resume::ResolveCwdOutcome;use crate::session_resume::ResumeCwdContext;use crate::session_resume::effective_resume_cwd_mode;+use crate::session_resume::read_session_cwd;use crate::session_resume::resolve_cwd_for_resume_or_fork;pub use crate::startup_error::LocalStateDbStartupError;use additional_dirs::add_dir_warning_message;@@ -659,6 +660,7 @@ fn session_target_from_app_server_thread(Ok(thread_id) => Some(resume_picker::SessionTarget {path: thread.path,thread_id,+ cwd: Some(thread.cwd.to_path_buf()),history_mode: Some(thread.history_mode),}),Err(err) => {@@ -842,7 +844,7 @@ fn uses_remote_workspace_or_environment(async fn resolve_startup_resume_or_fork_cwd(tui: &mut Tui,config: &Config,- state_db: Option<&codex_state::StateRuntime>,+ app_server: Option<&mut AppServerSession>,session_selection: &resume_picker::SessionSelection,cwd_override: Option<&Path>,uses_remote_workspace: bool,@@ -873,11 +875,19 @@ async fn resolve_startup_resume_or_fork_cwd(return Ok(ResolveCwdOutcome::Continue(Some(config.cwd.to_path_buf())));}+ let history_cwd = if matches!(resume_cwd_mode, Some(ResumeCwdMode::Current)) {+ None+ } else if let Some(cwd) = &target_session.cwd {+ Some(cwd.clone())+ } else if let Some(app_server) = app_server {+ read_session_cwd(app_server, target_session.thread_id).await+ } else {+ None+ };resolve_cwd_for_resume_or_fork(tui,config,- state_db,- target_session,+ history_cwd,action,ResumeCwdContext {current_cwd: config.cwd.as_path(),@@ -1562,7 +1572,7 @@ async fn run_ratatui_app(let fallback_cwd = match resolve_startup_resume_or_fork_cwd(&mut tui,&config,- state_db.as_deref(),+ app_server.as_mut(),&session_selection,cli.cwd.as_deref(),uses_remote_workspace,@@ -2468,6 +2478,7 @@ requires_openai_auth = {requires_openai_auth}let target_session = resume_picker::SessionTarget {path: Some(rollout_path),thread_id,+ cwd: Some(session_cwd.clone()),history_mode: None,};let session_selection = match action {@@ -2479,7 +2490,7 @@ requires_openai_auth = {requires_openai_auth}let fallback_cwd = match resolve_startup_resume_or_fork_cwd(&mut tui,&config,- state_db.as_deref(),+ /*app_server*/ None,&session_selection,cwd_override,/*uses_remote_workspace*/ false,@@ -2564,10 +2575,11 @@ requires_openai_auth = {requires_openai_auth}let error = resolve_startup_resume_or_fork_cwd(&mut tui,&config,- /*state_db*/ None,+ /*app_server*/ None,&resume_picker::SessionSelection::Resume(resume_picker::SessionTarget {path: None,thread_id: ThreadId::new(),+ cwd: None,history_mode: None,}),/*cwd_override*/ None,@@ -2584,10 +2596,11 @@ requires_openai_auth = {requires_openai_auth}let explicit = resolve_startup_resume_or_fork_cwd(&mut tui,&config,- /*state_db*/ None,+ /*app_server*/ None,&resume_picker::SessionSelection::Resume(resume_picker::SessionTarget {path: None,thread_id: ThreadId::new(),+ cwd: None,history_mode: None,}),Some(Path::new("/remote-only/project")),@@ -2618,10 +2631,11 @@ requires_openai_auth = {requires_openai_auth}let error = resolve_startup_resume_or_fork_cwd(&mut tui,&config,- /*state_db*/ None,+ /*app_server*/ None,&resume_picker::SessionSelection::Resume(resume_picker::SessionTarget {path: None,thread_id: ThreadId::new(),+ cwd: None,history_mode: None,}),/*cwd_override*/ None,@@ -2664,6 +2678,7 @@ requires_openai_auth = {requires_openai_auth}let target = crate::resume_picker::SessionTarget {path: None,thread_id,+ cwd: None,history_mode: None,};diff --git a/codex-rs/tui/src/resume_picker.rs b/codex-rs/tui/src/resume_picker.rsindex 1ea7d49b9e..ef4dd6df72 100644--- a/codex-rs/tui/src/resume_picker.rs+++ b/codex-rs/tui/src/resume_picker.rs@@ -19,7 +19,6 @@ use crate::legacy_core::config::Config;use crate::legacy_core::config::edit::ConfigEditsBuilder;use crate::markdown_render::render_streaming_markdown_lines_with_width_and_cwd as render_assistant;use crate::pager_overlay::Overlay;-use crate::session_resume::resolve_session_thread_id;use crate::status::format_directory_display;use crate::style::footer_hint_key_style;use crate::style::footer_hint_label_style;@@ -107,6 +106,8 @@ const PICKER_LIST_HORIZONTAL_INSET: u16 = 4;pub struct SessionTarget {pub path: Option<PathBuf>,pub thread_id: ThreadId,+ /// Working directory reported by `thread/list` or `thread/read` at selection time.+ pub cwd: Option<PathBuf>,/// History mode observed during selection, if the server provided one.pub history_mode: Option<ThreadHistoryMode>,}@@ -780,6 +781,7 @@ fn spawn_app_server_page_loader(.map(|response| SessionTarget {path: response.thread.path,thread_id,+ cwd: Some(response.thread.cwd.to_path_buf()),history_mode: Some(response.thread.history_mode),}).map_err(std::io::Error::other);@@ -1280,17 +1282,7 @@ impl PickerState {_ if self.list_keymap.accept.is_pressed(key) => {if let Some(row) = self.filtered_rows.get(self.selected) {let path = row.path.clone();- let thread_id = match row.thread_id {- Some(thread_id) => Some(thread_id),- None => match path.as_ref() {- Some(path) => {- resolve_session_thread_id(path.as_path(), /*id_str_if_uuid*/ None)- .await- }- None => None,- },- };- if let Some(thread_id) = thread_id {+ if let Some(thread_id) = row.thread_id {if self.status == SessionStatus::Archived {self.request_unarchive(thread_id);return Ok(None);@@ -1298,6 +1290,7 @@ impl PickerState {return Ok(Some(self.action.selection(SessionTarget {path,thread_id,+ cwd: row.cwd.clone(),history_mode: self.thread_history_modes.get(&thread_id).copied(),})));}@@ -4033,6 +4026,7 @@ mod tests {"indexed metadata",);row.thread_id = Some(thread_id);+ row.cwd = Some(PathBuf::from("/tmp/saved-cwd"));let mut listed_page = ok_page(vec![row], /*next_cursor*/ None).expect("indexed thread page should be available");listed_page@@ -4048,9 +4042,10 @@ mod tests {selection,Some(SessionSelection::Resume(SessionTarget {thread_id: selected_thread_id,+ cwd: Some(cwd),history_mode: Some(ThreadHistoryMode::Legacy),..- })) if selected_thread_id == thread_id+ })) if selected_thread_id == thread_id && cwd == Path::new("/tmp/saved-cwd")));}@@ -6520,6 +6515,7 @@ session_picker_view = "dense"Some(SessionSelection::Resume(SessionTarget {path: None,thread_id: selected_thread_id,+ cwd: None,history_mode: None,})) => assert_eq!(selected_thread_id, thread_id),other => panic!("unexpected selection: {other:?}"),diff --git a/codex-rs/tui/src/resume_picker/archive_tests.rs b/codex-rs/tui/src/resume_picker/archive_tests.rsindex b453ee1a22..f4d232feb1 100644--- a/codex-rs/tui/src/resume_picker/archive_tests.rs+++ b/codex-rs/tui/src/resume_picker/archive_tests.rs@@ -258,6 +258,7 @@ async fn archived_session_restore_resumes_after_completion() {Ok(SessionTarget {path: None,thread_id,+ cwd: None,history_mode: None,}),);@@ -267,6 +268,7 @@ async fn archived_session_restore_resumes_after_completion() {Some(SessionSelection::Resume(SessionTarget {path: None,thread_id: resumed_thread_id,+ cwd: None,history_mode: None,})) if resumed_thread_id == thread_id));diff --git a/codex-rs/tui/src/session_resume.rs b/codex-rs/tui/src/session_resume.rsindex efbbaf3f8d..0c1b839683 100644--- a/codex-rs/tui/src/session_resume.rs+++ b/codex-rs/tui/src/session_resume.rs@@ -1,52 +1,20 @@//! Resolve saved-session state needed before resuming or forking a thread.//!-//! The app-server API owns normal thread lifecycle data. This module coordinates-//! the TUI-specific cwd prompt and falls back to local rollout metadata only-//! before the app server has resumed the selected thread.+//! The app-server API owns thread metadata. This module coordinates the TUI-specific+//! cwd prompt using the cwd reported by the selected thread.-use std::io;use std::path::Path;use std::path::PathBuf;+use crate::app_server_session::AppServerSession;use crate::cwd_prompt;use crate::cwd_prompt::CwdPromptAction;use crate::cwd_prompt::CwdPromptOutcome;use crate::legacy_core::config::Config;-use crate::resume_picker::SessionTarget;use crate::tui::Tui;use codex_config::types::ResumeCwdMode;use codex_protocol::ThreadId;-use codex_rollout::open_rollout_line_reader;-use codex_state::StateRuntime;use codex_utils_path as path_utils;-use serde::Deserialize;-use serde_json::Value;--#[derive(Default)]-struct RolloutResumeState {- thread_id: Option<ThreadId>,- cwd: Option<PathBuf>,- model: Option<String>,-}--#[derive(Deserialize)]-struct SessionMetadata {- id: ThreadId,- cwd: PathBuf,-}--#[derive(Deserialize)]-struct TurnContextResumeState {- cwd: PathBuf,- model: String,-}--#[derive(Deserialize)]-struct RawRecord {- #[serde(rename = "type")]- item_type: String,- payload: Option<Value>,-}#[derive(Debug, PartialEq, Eq)]pub(crate) enum ResolveCwdOutcome {@@ -74,43 +42,26 @@ pub(crate) fn effective_resume_cwd_mode(}}-pub(crate) async fn resolve_session_thread_id(- path: &Path,- id_str_if_uuid: Option<&str>,-) -> Option<ThreadId> {- match id_str_if_uuid {- Some(id_str) => ThreadId::from_string(id_str).ok(),- None => read_rollout_resume_state(path)- .await- .ok()- .and_then(|state| state.thread_id),- }-}--pub(crate) async fn read_session_model(- state_db_ctx: Option<&StateRuntime>,+pub(crate) async fn read_session_cwd(+ app_server: &mut AppServerSession,thread_id: ThreadId,- path: Option<&Path>,-) -> Option<String> {- if let Some(state_db_ctx) = state_db_ctx- && let Ok(Some(metadata)) = state_db_ctx.get_thread(thread_id).await- && let Some(model) = metadata.model+) -> Option<PathBuf> {+ match app_server+ .thread_read(thread_id, /*include_turns*/ false)+ .await{- return Some(model);+ Ok(thread) => Some(thread.cwd.to_path_buf()),+ Err(err) => {+ tracing::warn!(%thread_id, %err, "Failed to read session cwd from app server");+ None+ }}-- let path = path?;- read_rollout_resume_state(path)- .await- .ok()- .and_then(|state| state.model)}pub(crate) async fn resolve_cwd_for_resume_or_fork(tui: &mut Tui,config: &Config,- state_db_ctx: Option<&StateRuntime>,- target_session: &SessionTarget,+ history_cwd: Option<PathBuf>,action: CwdPromptAction,cwd_context: ResumeCwdContext<'_>,) -> color_eyre::Result<ResolveCwdOutcome> {@@ -119,13 +70,7 @@ pub(crate) async fn resolve_cwd_for_resume_or_fork(cwd_context.remembered_current_cwd.to_path_buf(),)));}- let Some(history_cwd) = read_session_cwd(- state_db_ctx,- target_session.thread_id,- target_session.path.as_deref(),- )- .await- else {+ let Some(history_cwd) = history_cwd else {if matches!(cwd_context.mode, Some(ResumeCwdMode::Session)) {color_eyre::eyre::bail!("failed to determine the working directory recorded for the selected session"@@ -166,346 +111,35 @@ pub(crate) async fn resolve_cwd_for_resume_or_fork(Ok(ResolveCwdOutcome::Continue(Some(history_cwd)))}-async fn read_session_cwd(- state_db_ctx: Option<&StateRuntime>,- thread_id: ThreadId,- path: Option<&Path>,-) -> Option<PathBuf> {- if let Some(state_db_ctx) = state_db_ctx- && let Ok(Some(metadata)) = state_db_ctx.get_thread(thread_id).await- {- return Some(metadata.cwd);- }-- let path = path?;- match read_rollout_resume_state(path).await {- Ok(state) => state.cwd,- Err(err) => {- let rollout_path = path.display().to_string();- tracing::warn!(- %rollout_path,- %err,- "Failed to read session metadata from rollout"- );- None- }- }-}-pub(crate) fn cwds_differ(current_cwd: &Path, session_cwd: &Path) -> bool {!path_utils::paths_match_after_normalization(current_cwd, session_cwd)}-async fn read_rollout_resume_state(path: &Path) -> io::Result<RolloutResumeState> {- let mut reader = open_rollout_line_reader(path).await?;- let mut state = RolloutResumeState::default();- let mut saw_record = false;-- while let Some(line) = reader.next_line().await? {- let trimmed = line.trim();- if trimmed.is_empty() {- continue;- }- let Ok(record) = serde_json::from_str::<RawRecord>(trimmed) else {- continue;- };- saw_record = true;- let Some(payload) = record.payload else {- continue;- };-- match record.item_type.as_str() {- "session_meta" if state.thread_id.is_none() => {- if let Ok(metadata) = serde_json::from_value::<SessionMetadata>(payload) {- state.thread_id = Some(metadata.id);- state.cwd.get_or_insert(metadata.cwd);- }- }- "turn_context" => {- if let Ok(turn_context) = serde_json::from_value::<TurnContextResumeState>(payload)- {- state.cwd = Some(turn_context.cwd);- state.model = Some(turn_context.model);- }- }- _ => {}- }- }-- if saw_record {- Ok(state)- } else {- Err(io::Error::other(format!(- "rollout at {} is empty",- path.display()- )))- }-}-#[cfg(test)]mod tests {use super::*;- use codex_utils_absolute_path::test_support::PathExt;use pretty_assertions::assert_eq;use tempfile::TempDir;- fn rollout_line(- timestamp: &str,- item_type: &str,- payload: serde_json::Value,- ) -> serde_json::Value {- serde_json::json!({- "timestamp": timestamp,- "type": item_type,- "payload": payload,- })- }-- fn write_rollout_lines(path: &Path, lines: &[serde_json::Value]) -> std::io::Result<()> {- let mut text = String::new();- for line in lines {- text.push_str(&serde_json::to_string(line).expect("serialize rollout"));- text.push('\n');- }- std::fs::write(path, text)- }-- #[tokio::test]- async fn rollout_resume_state_prefers_latest_turn_context() -> std::io::Result<()> {- let temp_dir = TempDir::new()?;- let thread_id = ThreadId::new();- let original = temp_dir.path().join("original");- let latest = temp_dir.path().join("latest");- let rollout_path = temp_dir.path().join("rollout.jsonl");- write_rollout_lines(- &rollout_path,- &[- rollout_line(- "t0",- "session_meta",- serde_json::json!({- "id": thread_id,- "cwd": original,- "originator": "test",- "cli_version": "test",- }),- ),- rollout_line(- "t1",- "turn_context",- serde_json::json!({ "cwd": temp_dir.path().join("middle"), "model": "middle" }),- ),- rollout_line(- "t2",- "turn_context",- serde_json::json!({ "cwd": latest.clone(), "model": "latest" }),- ),- ],- )?;-- let state = read_rollout_resume_state(&rollout_path).await?;-- assert_eq!(state.thread_id, Some(thread_id));- assert_eq!(state.cwd, Some(latest));- assert_eq!(state.model, Some("latest".to_string()));- Ok(())- }-- #[tokio::test]- async fn rollout_resume_state_falls_back_to_session_meta() -> std::io::Result<()> {- let temp_dir = TempDir::new()?;- let thread_id = ThreadId::new();- let cwd = temp_dir.path().join("session");- let rollout_path = temp_dir.path().join("rollout.jsonl");- write_rollout_lines(- &rollout_path,- &[rollout_line(- "t0",- "session_meta",- serde_json::json!({- "id": thread_id,- "cwd": cwd.clone(),- "originator": "test",- "cli_version": "test",- }),- )],- )?;-- let state = read_rollout_resume_state(&rollout_path).await?;-- assert_eq!(state.thread_id, Some(thread_id));- assert_eq!(state.cwd, Some(cwd));- assert_eq!(state.model, None);- Ok(())- }-- #[tokio::test]- async fn rollout_resume_state_skips_malformed_lines() -> std::io::Result<()> {- let temp_dir = TempDir::new()?;- let thread_id = ThreadId::new();- let cwd = temp_dir.path().join("session");- let rollout_path = temp_dir.path().join("rollout.jsonl");- let valid_line = serde_json::to_string(&rollout_line(- "t0",- "session_meta",- serde_json::json!({- "id": thread_id,- "cwd": cwd.clone(),- "originator": "test",- "cli_version": "test",- }),- ))- .expect("serialize rollout line");- std::fs::write(&rollout_path, format!("{valid_line}\n{{"))?;-- let state = read_rollout_resume_state(&rollout_path).await?;-- assert_eq!(state.thread_id, Some(thread_id));- assert_eq!(state.cwd, Some(cwd));- Ok(())- }-- #[tokio::test]- async fn rollout_resume_state_preserves_legacy_fork_child_context() -> std::io::Result<()> {- let temp_dir = TempDir::new()?;- let thread_id = ThreadId::from_string("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa")- .expect("legacy thread id");- let parent_thread_id = ThreadId::from_string("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb")- .expect("legacy parent id");- let child_cwd = temp_dir.path().join("child");- let rollout_path = temp_dir.path().join("rollout.jsonl");- write_rollout_lines(- &rollout_path,- &[- rollout_line(- "t0",- "session_meta",- serde_json::json!({- "id": thread_id,- "forked_from_id": parent_thread_id,- "cwd": temp_dir.path().join("initial"),- "originator": "test",- "cli_version": "test",- }),- ),- rollout_line(- "t1",- "event_msg",- serde_json::json!({ "type": "task_started", "turn_id": "legacy-child-turn" }),- ),- rollout_line(- "t2",- "turn_context",- serde_json::json!({ "cwd": child_cwd.clone(), "model": "child-model" }),- ),- ],- )?;-- let state = read_rollout_resume_state(&rollout_path).await?;-- assert_eq!(state.thread_id, Some(thread_id));- assert_eq!(state.cwd, Some(child_cwd));- assert_eq!(state.model.as_deref(), Some("child-model"));- Ok(())- }-- #[tokio::test]- async fn session_cwd_prefers_state_metadata_over_rollout_context() -> std::io::Result<()> {- let temp_dir = TempDir::new()?;- let thread_id = ThreadId::new();- let session_cwd = temp_dir.path().join("child");- let rollout_path = temp_dir.path().join("rollout.jsonl");- write_rollout_lines(- &rollout_path,- &[- rollout_line(- "t0",- "session_meta",- serde_json::json!({- "id": thread_id,- "cwd": session_cwd,- "originator": "test",- "cli_version": "test",- }),- ),- rollout_line(- "t1",- "turn_context",- serde_json::json!({- "cwd": temp_dir.path().join("copied-parent"),- "model": "parent-model",- }),- ),- ],- )?;- let state_runtime = StateRuntime::init(- codex_state::SqliteConfig::new_for_testing(temp_dir.path().abs()),- "test-provider".to_string(),- )- .await- .map_err(std::io::Error::other)?;- let created_at = chrono::DateTime::parse_from_rfc3339("2025-01-05T12:00:00Z")- .expect("timestamp should parse")- .with_timezone(&chrono::Utc);- let mut builder = codex_state::ThreadMetadataBuilder::new(- thread_id,- rollout_path.clone(),- created_at,- serde_json::from_value(serde_json::json!("cli"))- .expect("cli session source should deserialize"),- );- builder.cwd = session_cwd.clone();- state_runtime- .upsert_thread(&builder.build("test-provider"))- .await- .map_err(std::io::Error::other)?;-- let cwd =- read_session_cwd(Some(state_runtime.as_ref()), thread_id, Some(&rollout_path)).await;-- assert_eq!(cwd, Some(session_cwd));- Ok(())- }-#[tokio::test]async fn configured_resume_cwd_skips_prompt() -> color_eyre::Result<()> {let temp_dir = TempDir::new()?;- let thread_id = ThreadId::new();let session_cwd = temp_dir.path().join("session");- let rollout_path = temp_dir.path().join("rollout.jsonl");let config = crate::legacy_core::config::ConfigBuilder::default().codex_home(temp_dir.path().to_path_buf()).build().await?;let current_cwd = config.cwd.to_path_buf();- write_rollout_lines(- &rollout_path,- &[rollout_line(- "t0",- "session_meta",- serde_json::json!({- "id": thread_id,- "cwd": session_cwd.clone(),- "originator": "test",- "cli_version": "test",- }),- )],- )?;let mut tui = crate::tui::test_support::make_test_tui()?;for (cwd_mode, expected_cwd) in [(ResumeCwdMode::Current, current_cwd.clone()),- (ResumeCwdMode::Session, session_cwd),+ (ResumeCwdMode::Session, session_cwd.clone()),] {let outcome = resolve_cwd_for_resume_or_fork(&mut tui,&config,- /*state_db_ctx*/ None,- &SessionTarget {- path: Some(rollout_path.clone()),- thread_id,- history_mode: None,- },+ Some(session_cwd.clone()),CwdPromptAction::Fork,ResumeCwdContext {current_cwd: ¤t_cwd,@@ -524,37 +158,17 @@ mod tests {#[tokio::test]async fn matching_resume_cwd_skips_prompt_without_configured_mode() -> color_eyre::Result<()> {let temp_dir = TempDir::new()?;- let thread_id = ThreadId::new();- let rollout_path = temp_dir.path().join("rollout.jsonl");let config = crate::legacy_core::config::ConfigBuilder::default().codex_home(temp_dir.path().to_path_buf()).build().await?;let current_cwd = config.cwd.to_path_buf();- write_rollout_lines(- &rollout_path,- &[rollout_line(- "t0",- "session_meta",- serde_json::json!({- "id": thread_id,- "cwd": current_cwd,- "originator": "test",- "cli_version": "test",- }),- )],- )?;let mut tui = crate::tui::test_support::make_test_tui()?;let outcome = resolve_cwd_for_resume_or_fork(&mut tui,&config,- /*state_db_ctx*/ None,- &SessionTarget {- path: Some(rollout_path),- thread_id,- history_mode: None,- },+ Some(current_cwd.clone()),CwdPromptAction::Resume,ResumeCwdContext {current_cwd: ¤t_cwd,@@ -582,12 +196,7 @@ mod tests {let error = resolve_cwd_for_resume_or_fork(&mut tui,&config,- /*state_db_ctx*/ None,- &SessionTarget {- path: None,- thread_id: ThreadId::new(),- history_mode: None,- },+ /*history_cwd*/ None,CwdPromptAction::Resume,ResumeCwdContext {current_cwd: ¤t_cwd,diff --git a/codex-rs/tui/src/session_start_tests.rs b/codex-rs/tui/src/session_start_tests.rsindex e101904d78..888d0bf237 100644--- a/codex-rs/tui/src/session_start_tests.rs+++ b/codex-rs/tui/src/session_start_tests.rs@@ -49,6 +49,7 @@ async fn archived_session_requires_confirmation_before_resume_or_fork() -> Resullet target = SessionTarget {path: Some(archived_path.clone()),thread_id: ThreadId::from_string(&id)?,+ cwd: None,history_mode: None,};let mut app_server = crate::start_embedded_app_server_for_picker(&config).await?;@@ -105,6 +106,7 @@ async fn archived_session_requires_confirmation_before_resume_or_fork() -> Resullet missing = SessionTarget {path: None,thread_id: ThreadId::new(),+ cwd: None,history_mode: None,};let error = start_session(&mut app_server, &config, &missing, action, async || {@@ -131,6 +133,7 @@ fn session_start_error_surfaces_archived_guidance_without_rollout_path() {"/Users/me/.codex/archived_sessions/rollout.jsonl",)),thread_id,+ cwd: None,history_mode: None,};let expected = format!(diff --git a/codex-rs/tui/src/snapshots/codex_tui__app__tests__thread_read_model_after_switch.snap b/codex-rs/tui/src/snapshots/codex_tui__app__tests__thread_read_model_after_switch.snapnew file mode 100644index 0000000000..2a2d06db87--- /dev/null+++ b/codex-rs/tui/src/snapshots/codex_tui__app__tests__thread_read_model_after_switch.snap@@ -0,0 +1,5 @@+---+source: tui/src/app/tests.rs+expression: model_line+---+│ model: server-reported-model /model to change │