mirror of
https://github.com/openai/codex.git
synced 2026-12-01 00:20:48 +00:00
TUI: track user turns locally and drop context overrides
This commit is contained in:
+40
-15
@@ -1,4 +1,5 @@
|
||||
use crate::app_backtrack::BacktrackState;
|
||||
use crate::app_backtrack::UserTurnRecord;
|
||||
use crate::app_event::AppEvent;
|
||||
use crate::app_event::ExitMode;
|
||||
#[cfg(target_os = "windows")]
|
||||
@@ -519,6 +520,7 @@ pub(crate) struct App {
|
||||
pub(crate) file_search: FileSearchManager,
|
||||
|
||||
pub(crate) transcript_cells: Vec<Arc<dyn HistoryCell>>,
|
||||
pub(crate) user_turns: Vec<UserTurnRecord>,
|
||||
|
||||
// Pager overlay state (Transcript or Static like Diff)
|
||||
pub(crate) overlay: Option<Overlay>,
|
||||
@@ -845,6 +847,7 @@ impl App {
|
||||
fn reset_for_thread_switch(&mut self, tui: &mut tui::Tui) -> Result<()> {
|
||||
self.overlay = None;
|
||||
self.transcript_cells.clear();
|
||||
self.user_turns.clear();
|
||||
self.deferred_history_lines.clear();
|
||||
self.has_emitted_history_lines = false;
|
||||
self.backtrack = BacktrackState::default();
|
||||
@@ -1067,6 +1070,7 @@ impl App {
|
||||
file_search,
|
||||
enhanced_keys_supported,
|
||||
transcript_cells: Vec::new(),
|
||||
user_turns: Vec::new(),
|
||||
overlay: None,
|
||||
deferred_history_lines: Vec::new(),
|
||||
has_emitted_history_lines: false,
|
||||
@@ -1268,6 +1272,7 @@ impl App {
|
||||
};
|
||||
self.chat_widget = ChatWidget::new(init, self.server.clone());
|
||||
self.reset_thread_event_state();
|
||||
self.user_turns.clear();
|
||||
if let Some(summary) = summary {
|
||||
let mut lines: Vec<Line<'static>> = vec![summary.usage_line.clone().into()];
|
||||
if let Some(command) = summary.resume_command {
|
||||
@@ -1449,6 +1454,13 @@ impl App {
|
||||
}
|
||||
}
|
||||
}
|
||||
AppEvent::RecordUserTurn { items } => {
|
||||
let transcript_cut_index = self.transcript_cells.len();
|
||||
self.user_turns.push(UserTurnRecord {
|
||||
items,
|
||||
transcript_cut_index,
|
||||
});
|
||||
}
|
||||
AppEvent::StartCommitAnimation => {
|
||||
if self
|
||||
.commit_anim_running
|
||||
@@ -1696,18 +1708,6 @@ impl App {
|
||||
},
|
||||
);
|
||||
} else {
|
||||
self.app_event_tx.send(AppEvent::CodexOp(
|
||||
Op::OverrideTurnContext {
|
||||
cwd: None,
|
||||
approval_policy: Some(preset.approval),
|
||||
sandbox_policy: Some(preset.sandbox.clone()),
|
||||
model: None,
|
||||
effort: None,
|
||||
summary: None,
|
||||
collaboration_mode: None,
|
||||
personality: None,
|
||||
},
|
||||
));
|
||||
self.app_event_tx
|
||||
.send(AppEvent::UpdateAskForApprovalPolicy(preset.approval));
|
||||
self.app_event_tx
|
||||
@@ -2387,7 +2387,7 @@ impl App {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::app_backtrack::BacktrackState;
|
||||
use crate::app_backtrack::user_count;
|
||||
use crate::app_backtrack::UserTurnRecord;
|
||||
use crate::chatwidget::tests::make_chatwidget_manual_with_sender;
|
||||
use crate::file_search::FileSearchManager;
|
||||
use crate::history_cell::AgentMessageCell;
|
||||
@@ -2409,6 +2409,7 @@ mod tests {
|
||||
use codex_otel::OtelManager;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::user_input::TextElement;
|
||||
use codex_protocol::user_input::UserInput;
|
||||
use insta::assert_snapshot;
|
||||
use pretty_assertions::assert_eq;
|
||||
use ratatui::prelude::Line;
|
||||
@@ -2505,6 +2506,7 @@ mod tests {
|
||||
runtime_sandbox_policy_override: None,
|
||||
file_search,
|
||||
transcript_cells: Vec::new(),
|
||||
user_turns: Vec::new(),
|
||||
overlay: None,
|
||||
deferred_history_lines: Vec::new(),
|
||||
has_emitted_history_lines: false,
|
||||
@@ -2557,6 +2559,7 @@ mod tests {
|
||||
runtime_sandbox_policy_override: None,
|
||||
file_search,
|
||||
transcript_cells: Vec::new(),
|
||||
user_turns: Vec::new(),
|
||||
overlay: None,
|
||||
deferred_history_lines: Vec::new(),
|
||||
has_emitted_history_lines: false,
|
||||
@@ -2843,7 +2846,29 @@ mod tests {
|
||||
agent_cell("answer edited"),
|
||||
];
|
||||
|
||||
assert_eq!(user_count(&app.transcript_cells), 2);
|
||||
app.user_turns = vec![
|
||||
UserTurnRecord {
|
||||
items: vec![UserInput::Text {
|
||||
text: "first question".to_string(),
|
||||
text_elements: Vec::new(),
|
||||
}],
|
||||
transcript_cut_index: 6,
|
||||
},
|
||||
UserTurnRecord {
|
||||
items: vec![
|
||||
UserInput::LocalImage {
|
||||
path: edited_local_image_paths[0].clone(),
|
||||
},
|
||||
UserInput::Text {
|
||||
text: edited_text.clone(),
|
||||
text_elements: edited_text_elements.clone(),
|
||||
},
|
||||
],
|
||||
transcript_cut_index: 8,
|
||||
},
|
||||
];
|
||||
|
||||
assert_eq!(app.user_turns.len(), 2);
|
||||
|
||||
let base_id = ThreadId::new();
|
||||
app.chat_widget.handle_codex_event(Event {
|
||||
@@ -2866,7 +2891,7 @@ mod tests {
|
||||
|
||||
app.backtrack.base_id = Some(base_id);
|
||||
app.backtrack.primed = true;
|
||||
app.backtrack.nth_user_message = user_count(&app.transcript_cells).saturating_sub(1);
|
||||
app.backtrack.nth_user_message = app.user_turns.len().saturating_sub(1);
|
||||
|
||||
let selection = app
|
||||
.confirm_backtrack_from_main()
|
||||
|
||||
@@ -23,13 +23,10 @@
|
||||
//! `TranscriptOverlay::sync_live_tail`. This preserves the invariant that the overlay reflects
|
||||
//! both committed history and in-flight activity without changing flush or coalescing behavior.
|
||||
|
||||
use std::any::TypeId;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::app::App;
|
||||
use crate::history_cell::SessionInfoCell;
|
||||
use crate::history_cell::UserHistoryCell;
|
||||
use crate::pager_overlay::Overlay;
|
||||
use crate::tui;
|
||||
use crate::tui::TuiEvent;
|
||||
@@ -39,6 +36,7 @@ use codex_core::protocol::EventMsg;
|
||||
use codex_core::protocol::Op;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::user_input::TextElement;
|
||||
use codex_protocol::user_input::UserInput;
|
||||
use color_eyre::eyre::Result;
|
||||
use crossterm::event::KeyCode;
|
||||
use crossterm::event::KeyEvent;
|
||||
@@ -96,6 +94,17 @@ pub(crate) struct PendingBacktrackRollback {
|
||||
pub(crate) thread_id: Option<ThreadId>,
|
||||
}
|
||||
|
||||
/// Local record of a submitted user turn.
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct UserTurnRecord {
|
||||
/// Items sent to core for this turn.
|
||||
pub(crate) items: Vec<UserInput>,
|
||||
/// Transcript length at the moment this turn started.
|
||||
///
|
||||
/// When rolling back to this turn, we truncate the transcript to this index.
|
||||
pub(crate) transcript_cut_index: usize,
|
||||
}
|
||||
|
||||
impl App {
|
||||
/// Route overlay events while the transcript overlay is active.
|
||||
///
|
||||
@@ -186,7 +195,7 @@ impl App {
|
||||
/// The composer prefill is applied immediately as a UX convenience; it does not imply that
|
||||
/// core has accepted the rollback.
|
||||
pub(crate) fn apply_backtrack_rollback(&mut self, selection: BacktrackSelection) {
|
||||
let user_total = user_count(&self.transcript_cells);
|
||||
let user_total = self.user_turns.len();
|
||||
if user_total == 0 {
|
||||
return;
|
||||
}
|
||||
@@ -273,7 +282,7 @@ impl App {
|
||||
self.backtrack.primed = true;
|
||||
self.backtrack.base_id = self.chat_widget.thread_id();
|
||||
self.backtrack.overlay_preview_active = true;
|
||||
let count = user_count(&self.transcript_cells);
|
||||
let count = self.user_turns.len();
|
||||
if let Some(last) = count.checked_sub(1) {
|
||||
self.apply_backtrack_selection_internal(last);
|
||||
}
|
||||
@@ -282,7 +291,7 @@ impl App {
|
||||
|
||||
/// Step selection to the next older user message and update overlay.
|
||||
fn step_backtrack_and_highlight(&mut self, tui: &mut tui::Tui) {
|
||||
let count = user_count(&self.transcript_cells);
|
||||
let count = self.user_turns.len();
|
||||
if count == 0 {
|
||||
return;
|
||||
}
|
||||
@@ -305,7 +314,7 @@ impl App {
|
||||
|
||||
/// Step selection to the next newer user message and update overlay.
|
||||
fn step_forward_backtrack_and_highlight(&mut self, tui: &mut tui::Tui) {
|
||||
let count = user_count(&self.transcript_cells);
|
||||
let count = self.user_turns.len();
|
||||
if count == 0 {
|
||||
return;
|
||||
}
|
||||
@@ -326,16 +335,19 @@ impl App {
|
||||
|
||||
/// Apply a computed backtrack selection to the overlay and internal counter.
|
||||
fn apply_backtrack_selection_internal(&mut self, nth_user_message: usize) {
|
||||
if let Some(cell_idx) = nth_user_position(&self.transcript_cells, nth_user_message) {
|
||||
self.backtrack.nth_user_message = nth_user_message;
|
||||
if let Some(Overlay::Transcript(t)) = &mut self.overlay {
|
||||
t.set_highlight_cell(Some(cell_idx));
|
||||
}
|
||||
} else {
|
||||
let Some(record) = self.user_turns.get(nth_user_message) else {
|
||||
self.backtrack.nth_user_message = usize::MAX;
|
||||
if let Some(Overlay::Transcript(t)) = &mut self.overlay {
|
||||
t.set_highlight_cell(None);
|
||||
}
|
||||
return;
|
||||
};
|
||||
|
||||
let cell_idx = (record.transcript_cut_index < self.transcript_cells.len())
|
||||
.then_some(record.transcript_cut_index);
|
||||
self.backtrack.nth_user_message = nth_user_message;
|
||||
if let Some(Overlay::Transcript(t)) = &mut self.overlay {
|
||||
t.set_highlight_cell(cell_idx);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -487,18 +499,8 @@ impl App {
|
||||
return None;
|
||||
}
|
||||
|
||||
let (prefill, text_elements, local_image_paths) =
|
||||
nth_user_position(&self.transcript_cells, nth_user_message)
|
||||
.and_then(|idx| self.transcript_cells.get(idx))
|
||||
.and_then(|cell| cell.as_any().downcast_ref::<UserHistoryCell>())
|
||||
.map(|cell| {
|
||||
(
|
||||
cell.message.clone(),
|
||||
cell.text_elements.clone(),
|
||||
cell.local_image_paths.clone(),
|
||||
)
|
||||
})
|
||||
.unwrap_or_else(|| (String::new(), Vec::new(), Vec::new()));
|
||||
let record = self.user_turns.get(nth_user_message)?;
|
||||
let (prefill, text_elements, local_image_paths) = prefill_from_items(&record.items);
|
||||
|
||||
Some(BacktrackSelection {
|
||||
nth_user_message,
|
||||
@@ -510,53 +512,48 @@ impl App {
|
||||
|
||||
/// Trim `transcript_cells` to preserve only content before the selected user message.
|
||||
fn trim_transcript_for_backtrack(&mut self, nth_user_message: usize) {
|
||||
trim_transcript_cells_to_nth_user(&mut self.transcript_cells, nth_user_message);
|
||||
if nth_user_message == usize::MAX {
|
||||
return;
|
||||
}
|
||||
let Some(record) = self.user_turns.get(nth_user_message) else {
|
||||
return;
|
||||
};
|
||||
trim_transcript_cells_to_cut_index(&mut self.transcript_cells, record.transcript_cut_index);
|
||||
self.user_turns.truncate(nth_user_message);
|
||||
}
|
||||
}
|
||||
|
||||
fn trim_transcript_cells_to_nth_user(
|
||||
fn trim_transcript_cells_to_cut_index(
|
||||
transcript_cells: &mut Vec<Arc<dyn crate::history_cell::HistoryCell>>,
|
||||
nth_user_message: usize,
|
||||
cut_index: usize,
|
||||
) {
|
||||
if nth_user_message == usize::MAX {
|
||||
return;
|
||||
let cut_index = cut_index.min(transcript_cells.len());
|
||||
transcript_cells.truncate(cut_index);
|
||||
}
|
||||
|
||||
fn prefill_from_items(items: &[UserInput]) -> (String, Vec<TextElement>, Vec<PathBuf>) {
|
||||
let mut prefill = String::new();
|
||||
let mut text_elements = Vec::new();
|
||||
let mut local_image_paths = Vec::new();
|
||||
|
||||
for item in items {
|
||||
match item {
|
||||
UserInput::Text {
|
||||
text,
|
||||
text_elements: elements,
|
||||
} => {
|
||||
if prefill.is_empty() {
|
||||
prefill = text.clone();
|
||||
text_elements = elements.clone();
|
||||
}
|
||||
}
|
||||
UserInput::LocalImage { path } => local_image_paths.push(path.clone()),
|
||||
UserInput::Image { .. } | UserInput::Skill { .. } => {}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(cut_idx) = nth_user_position(transcript_cells, nth_user_message) {
|
||||
transcript_cells.truncate(cut_idx);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn user_count(cells: &[Arc<dyn crate::history_cell::HistoryCell>]) -> usize {
|
||||
user_positions_iter(cells).count()
|
||||
}
|
||||
|
||||
fn nth_user_position(
|
||||
cells: &[Arc<dyn crate::history_cell::HistoryCell>],
|
||||
nth: usize,
|
||||
) -> Option<usize> {
|
||||
user_positions_iter(cells)
|
||||
.enumerate()
|
||||
.find_map(|(i, idx)| (i == nth).then_some(idx))
|
||||
}
|
||||
|
||||
fn user_positions_iter(
|
||||
cells: &[Arc<dyn crate::history_cell::HistoryCell>],
|
||||
) -> impl Iterator<Item = usize> + '_ {
|
||||
let session_start_type = TypeId::of::<SessionInfoCell>();
|
||||
let user_type = TypeId::of::<UserHistoryCell>();
|
||||
let type_of = |cell: &Arc<dyn crate::history_cell::HistoryCell>| cell.as_any().type_id();
|
||||
|
||||
let start = cells
|
||||
.iter()
|
||||
.rposition(|cell| type_of(cell) == session_start_type)
|
||||
.map_or(0, |idx| idx + 1);
|
||||
|
||||
cells
|
||||
.iter()
|
||||
.enumerate()
|
||||
.skip(start)
|
||||
.filter_map(move |(idx, cell)| (type_of(cell) == user_type).then_some(idx))
|
||||
(prefill, text_elements, local_image_paths)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -564,39 +561,32 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::history_cell::AgentMessageCell;
|
||||
use crate::history_cell::HistoryCell;
|
||||
use pretty_assertions::assert_eq;
|
||||
use ratatui::prelude::Line;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[test]
|
||||
fn trim_transcript_for_first_user_drops_user_and_newer_cells() {
|
||||
let mut cells: Vec<Arc<dyn HistoryCell>> = vec![
|
||||
Arc::new(UserHistoryCell {
|
||||
message: "first user".to_string(),
|
||||
text_elements: Vec::new(),
|
||||
local_image_paths: Vec::new(),
|
||||
}) as Arc<dyn HistoryCell>,
|
||||
Arc::new(AgentMessageCell::new(vec![Line::from("assistant")], true))
|
||||
as Arc<dyn HistoryCell>,
|
||||
];
|
||||
trim_transcript_cells_to_nth_user(&mut cells, 0);
|
||||
fn trim_transcript_to_zero_clears_all_cells() {
|
||||
let mut cells: Vec<Arc<dyn HistoryCell>> =
|
||||
vec![
|
||||
Arc::new(AgentMessageCell::new(vec![Line::from("assistant")], true))
|
||||
as Arc<dyn HistoryCell>,
|
||||
];
|
||||
trim_transcript_cells_to_cut_index(&mut cells, 0);
|
||||
|
||||
assert!(cells.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trim_transcript_preserves_cells_before_selected_user() {
|
||||
fn trim_transcript_preserves_cells_before_cut_index() {
|
||||
let mut cells: Vec<Arc<dyn HistoryCell>> = vec![
|
||||
Arc::new(AgentMessageCell::new(vec![Line::from("intro")], true))
|
||||
as Arc<dyn HistoryCell>,
|
||||
Arc::new(UserHistoryCell {
|
||||
message: "first".to_string(),
|
||||
text_elements: Vec::new(),
|
||||
local_image_paths: Vec::new(),
|
||||
}) as Arc<dyn HistoryCell>,
|
||||
Arc::new(AgentMessageCell::new(vec![Line::from("after")], false))
|
||||
as Arc<dyn HistoryCell>,
|
||||
];
|
||||
trim_transcript_cells_to_nth_user(&mut cells, 0);
|
||||
trim_transcript_cells_to_cut_index(&mut cells, 1);
|
||||
|
||||
assert_eq!(cells.len(), 1);
|
||||
let agent = cells[0]
|
||||
@@ -614,26 +604,16 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trim_transcript_for_later_user_keeps_prior_history() {
|
||||
fn trim_transcript_keeps_prior_history_up_to_cut_index() {
|
||||
let mut cells: Vec<Arc<dyn HistoryCell>> = vec![
|
||||
Arc::new(AgentMessageCell::new(vec![Line::from("intro")], true))
|
||||
as Arc<dyn HistoryCell>,
|
||||
Arc::new(UserHistoryCell {
|
||||
message: "first".to_string(),
|
||||
text_elements: Vec::new(),
|
||||
local_image_paths: Vec::new(),
|
||||
}) as Arc<dyn HistoryCell>,
|
||||
Arc::new(AgentMessageCell::new(vec![Line::from("between")], false))
|
||||
as Arc<dyn HistoryCell>,
|
||||
Arc::new(UserHistoryCell {
|
||||
message: "second".to_string(),
|
||||
text_elements: Vec::new(),
|
||||
local_image_paths: Vec::new(),
|
||||
}) as Arc<dyn HistoryCell>,
|
||||
Arc::new(AgentMessageCell::new(vec![Line::from("tail")], false))
|
||||
as Arc<dyn HistoryCell>,
|
||||
];
|
||||
trim_transcript_cells_to_nth_user(&mut cells, 1);
|
||||
trim_transcript_cells_to_cut_index(&mut cells, 3);
|
||||
|
||||
assert_eq!(cells.len(), 3);
|
||||
let agent_intro = cells[0]
|
||||
@@ -647,14 +627,7 @@ mod tests {
|
||||
.map(|span| span.content.as_ref())
|
||||
.collect();
|
||||
assert_eq!(intro_text, "• intro");
|
||||
|
||||
let user_first = cells[1]
|
||||
.as_any()
|
||||
.downcast_ref::<UserHistoryCell>()
|
||||
.expect("first user");
|
||||
assert_eq!(user_first.message, "first");
|
||||
|
||||
let agent_between = cells[2]
|
||||
let agent_between = cells[1]
|
||||
.as_any()
|
||||
.downcast_ref::<AgentMessageCell>()
|
||||
.expect("between agent");
|
||||
@@ -666,4 +639,16 @@ mod tests {
|
||||
.collect();
|
||||
assert_eq!(between_text, " between");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prefill_from_items_handles_image_only_turns() {
|
||||
let items = vec![UserInput::LocalImage {
|
||||
path: PathBuf::from("/tmp/image.png"),
|
||||
}];
|
||||
let (prefill, text_elements, local_image_paths) = prefill_from_items(&items);
|
||||
|
||||
assert_eq!(prefill, String::new());
|
||||
assert_eq!(text_elements, Vec::new());
|
||||
assert_eq!(local_image_paths, vec![PathBuf::from("/tmp/image.png")]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ use codex_core::protocol::SandboxPolicy;
|
||||
use codex_protocol::config_types::CollaborationModeMask;
|
||||
use codex_protocol::config_types::Personality;
|
||||
use codex_protocol::openai_models::ReasoningEffort;
|
||||
use codex_protocol::user_input::UserInput;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
|
||||
@@ -94,6 +95,11 @@ pub(crate) enum AppEvent {
|
||||
|
||||
InsertHistoryCell(Box<dyn HistoryCell>),
|
||||
|
||||
/// Record a submitted user turn for local backtrack state.
|
||||
RecordUserTurn {
|
||||
items: Vec<UserInput>,
|
||||
},
|
||||
|
||||
StartCommitAnimation,
|
||||
StopCommitAnimation,
|
||||
CommitTick,
|
||||
|
||||
@@ -2861,6 +2861,12 @@ impl ChatWidget {
|
||||
}
|
||||
}
|
||||
|
||||
if !items.is_empty() {
|
||||
self.app_event_tx.send(AppEvent::RecordUserTurn {
|
||||
items: items.clone(),
|
||||
});
|
||||
}
|
||||
|
||||
let effective_mode = self.effective_collaboration_mode();
|
||||
let collaboration_mode = if self.collaboration_modes_enabled() {
|
||||
self.active_collaboration_mask
|
||||
@@ -3133,11 +3139,32 @@ impl ChatWidget {
|
||||
}
|
||||
|
||||
fn on_user_message_event(&mut self, event: UserMessageEvent) {
|
||||
if !event.message.trim().is_empty() {
|
||||
let UserMessageEvent {
|
||||
message,
|
||||
images: _,
|
||||
local_images,
|
||||
text_elements,
|
||||
} = event;
|
||||
|
||||
let mut items = Vec::new();
|
||||
for path in &local_images {
|
||||
items.push(UserInput::LocalImage { path: path.clone() });
|
||||
}
|
||||
if !message.trim().is_empty() {
|
||||
items.push(UserInput::Text {
|
||||
text: message.clone(),
|
||||
text_elements: text_elements.clone(),
|
||||
});
|
||||
}
|
||||
if !items.is_empty() {
|
||||
self.app_event_tx.send(AppEvent::RecordUserTurn { items });
|
||||
}
|
||||
|
||||
if !message.trim().is_empty() {
|
||||
self.add_to_history(history_cell::new_user_prompt(
|
||||
event.message,
|
||||
event.text_elements,
|
||||
event.local_images,
|
||||
message,
|
||||
text_elements,
|
||||
local_images,
|
||||
));
|
||||
}
|
||||
|
||||
@@ -3336,16 +3363,6 @@ impl ChatWidget {
|
||||
let default_effort: ReasoningEffortConfig = preset.default_reasoning_effort;
|
||||
|
||||
let switch_actions: Vec<SelectionAction> = vec![Box::new(move |tx| {
|
||||
tx.send(AppEvent::CodexOp(Op::OverrideTurnContext {
|
||||
cwd: None,
|
||||
approval_policy: None,
|
||||
sandbox_policy: None,
|
||||
model: Some(switch_model.clone()),
|
||||
effort: Some(Some(default_effort)),
|
||||
summary: None,
|
||||
collaboration_mode: None,
|
||||
personality: None,
|
||||
}));
|
||||
tx.send(AppEvent::UpdateModel(switch_model.clone()));
|
||||
tx.send(AppEvent::UpdateReasoningEffort(Some(default_effort)));
|
||||
})];
|
||||
@@ -3454,16 +3471,6 @@ impl ChatWidget {
|
||||
let name = Self::personality_label(personality).to_string();
|
||||
let description = Some(Self::personality_description(personality).to_string());
|
||||
let actions: Vec<SelectionAction> = vec![Box::new(move |tx| {
|
||||
tx.send(AppEvent::CodexOp(Op::OverrideTurnContext {
|
||||
cwd: None,
|
||||
approval_policy: None,
|
||||
sandbox_policy: None,
|
||||
model: None,
|
||||
effort: None,
|
||||
summary: None,
|
||||
collaboration_mode: None,
|
||||
personality: Some(personality),
|
||||
}));
|
||||
tx.send(AppEvent::UpdatePersonality(personality));
|
||||
tx.send(AppEvent::PersistPersonalitySelection { personality });
|
||||
})];
|
||||
@@ -3727,16 +3734,6 @@ impl ChatWidget {
|
||||
let effort_label = effort_for_action
|
||||
.map(|effort| effort.to_string())
|
||||
.unwrap_or_else(|| "default".to_string());
|
||||
tx.send(AppEvent::CodexOp(Op::OverrideTurnContext {
|
||||
cwd: None,
|
||||
approval_policy: None,
|
||||
sandbox_policy: None,
|
||||
model: Some(model_for_action.clone()),
|
||||
effort: Some(effort_for_action),
|
||||
summary: None,
|
||||
collaboration_mode: None,
|
||||
personality: None,
|
||||
}));
|
||||
tx.send(AppEvent::UpdateModel(model_for_action.clone()));
|
||||
tx.send(AppEvent::UpdateReasoningEffort(effort_for_action));
|
||||
tx.send(AppEvent::PersistModelSelection {
|
||||
@@ -3899,17 +3896,6 @@ impl ChatWidget {
|
||||
}
|
||||
|
||||
fn apply_model_and_effort(&self, model: String, effort: Option<ReasoningEffortConfig>) {
|
||||
self.app_event_tx
|
||||
.send(AppEvent::CodexOp(Op::OverrideTurnContext {
|
||||
cwd: None,
|
||||
approval_policy: None,
|
||||
sandbox_policy: None,
|
||||
model: Some(model.clone()),
|
||||
effort: Some(effort),
|
||||
summary: None,
|
||||
collaboration_mode: None,
|
||||
personality: None,
|
||||
}));
|
||||
self.app_event_tx.send(AppEvent::UpdateModel(model.clone()));
|
||||
self.app_event_tx
|
||||
.send(AppEvent::UpdateReasoningEffort(effort));
|
||||
@@ -4084,16 +4070,6 @@ impl ChatWidget {
|
||||
) -> Vec<SelectionAction> {
|
||||
vec![Box::new(move |tx| {
|
||||
let sandbox_clone = sandbox.clone();
|
||||
tx.send(AppEvent::CodexOp(Op::OverrideTurnContext {
|
||||
cwd: None,
|
||||
approval_policy: Some(approval),
|
||||
sandbox_policy: Some(sandbox_clone.clone()),
|
||||
model: None,
|
||||
effort: None,
|
||||
summary: None,
|
||||
collaboration_mode: None,
|
||||
personality: None,
|
||||
}));
|
||||
tx.send(AppEvent::UpdateAskForApprovalPolicy(approval));
|
||||
tx.send(AppEvent::UpdateSandboxPolicy(sandbox_clone));
|
||||
})]
|
||||
|
||||
@@ -3444,22 +3444,14 @@ async fn approvals_popup_navigation_skips_disabled() {
|
||||
assert!(
|
||||
app_events.iter().any(|ev| matches!(
|
||||
ev,
|
||||
AppEvent::CodexOp(Op::OverrideTurnContext {
|
||||
approval_policy: Some(AskForApproval::OnRequest),
|
||||
personality: None,
|
||||
..
|
||||
})
|
||||
AppEvent::UpdateAskForApprovalPolicy(AskForApproval::OnRequest)
|
||||
)),
|
||||
"enter should select an enabled preset"
|
||||
);
|
||||
assert!(
|
||||
!app_events.iter().any(|ev| matches!(
|
||||
ev,
|
||||
AppEvent::CodexOp(Op::OverrideTurnContext {
|
||||
approval_policy: Some(AskForApproval::Never),
|
||||
personality: None,
|
||||
..
|
||||
})
|
||||
AppEvent::UpdateAskForApprovalPolicy(AskForApproval::Never)
|
||||
)),
|
||||
"disabled preset should not be selected"
|
||||
);
|
||||
|
||||
+61
-35
@@ -33,6 +33,10 @@ use codex_core::read_session_meta_line;
|
||||
use codex_core::terminal::Multiplexer;
|
||||
use codex_protocol::config_types::AltScreenMode;
|
||||
use codex_protocol::config_types::SandboxMode;
|
||||
use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use codex_protocol::protocol::ENVIRONMENT_CONTEXT_CLOSE_TAG;
|
||||
use codex_protocol::protocol::ENVIRONMENT_CONTEXT_OPEN_TAG;
|
||||
use codex_protocol::protocol::RolloutItem;
|
||||
use codex_protocol::protocol::RolloutLine;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
@@ -647,12 +651,12 @@ async fn run_ratatui_app(
|
||||
}
|
||||
|
||||
pub(crate) async fn read_session_cwd(path: &Path) -> Option<PathBuf> {
|
||||
// Prefer the latest TurnContext cwd so resume/fork reflects the most recent
|
||||
// session directory (for the changed-cwd prompt). The alternative would be
|
||||
// mutating the SessionMeta line when the session cwd changes, but the rollout
|
||||
// is an append-only JSONL log and rewriting the head would be error-prone.
|
||||
// When rollouts move to SQLite, we can drop this scan.
|
||||
if let Some(cwd) = parse_latest_turn_context_cwd(path).await {
|
||||
// Prefer the latest environment_context cwd so resume/fork reflects the most recent
|
||||
// session directory (for the changed-cwd prompt). The alternative would be mutating the
|
||||
// SessionMeta line when the session cwd changes, but the rollout is an append-only JSONL log
|
||||
// and rewriting the head would be error-prone. When rollouts move to SQLite, we can drop
|
||||
// this scan.
|
||||
if let Some(cwd) = parse_latest_environment_context_cwd(path).await {
|
||||
return Some(cwd);
|
||||
}
|
||||
match read_session_meta_line(path).await {
|
||||
@@ -669,7 +673,7 @@ pub(crate) async fn read_session_cwd(path: &Path) -> Option<PathBuf> {
|
||||
}
|
||||
}
|
||||
|
||||
async fn parse_latest_turn_context_cwd(path: &Path) -> Option<PathBuf> {
|
||||
async fn parse_latest_environment_context_cwd(path: &Path) -> Option<PathBuf> {
|
||||
let text = tokio::fs::read_to_string(path).await.ok()?;
|
||||
for line in text.lines().rev() {
|
||||
let trimmed = line.trim();
|
||||
@@ -679,13 +683,42 @@ async fn parse_latest_turn_context_cwd(path: &Path) -> Option<PathBuf> {
|
||||
let Ok(rollout_line) = serde_json::from_str::<RolloutLine>(trimmed) else {
|
||||
continue;
|
||||
};
|
||||
if let RolloutItem::TurnContext(item) = rollout_line.item {
|
||||
return Some(item.cwd);
|
||||
if let RolloutItem::ResponseItem(ResponseItem::Message { role, content, .. }) =
|
||||
rollout_line.item
|
||||
&& role == "user"
|
||||
{
|
||||
for content_item in content {
|
||||
if let ContentItem::InputText { text } = content_item
|
||||
&& let Some(cwd) = extract_environment_context_cwd(&text)
|
||||
{
|
||||
return Some(cwd);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn extract_environment_context_cwd(text: &str) -> Option<PathBuf> {
|
||||
let env_block = extract_between(
|
||||
text,
|
||||
ENVIRONMENT_CONTEXT_OPEN_TAG,
|
||||
ENVIRONMENT_CONTEXT_CLOSE_TAG,
|
||||
)?;
|
||||
let cwd_text = extract_between(env_block, "<cwd>", "</cwd>")?;
|
||||
let cwd_text = cwd_text.trim();
|
||||
if cwd_text.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(PathBuf::from(cwd_text))
|
||||
}
|
||||
|
||||
fn extract_between<'a>(text: &'a str, start: &str, end: &str) -> Option<&'a str> {
|
||||
let start_idx = text.find(start)? + start.len();
|
||||
let end_idx = text[start_idx..].find(end)? + start_idx;
|
||||
Some(&text[start_idx..end_idx])
|
||||
}
|
||||
|
||||
pub(crate) fn cwds_differ(current_cwd: &Path, session_cwd: &Path) -> bool {
|
||||
match (
|
||||
path_utils::normalize_for_path_comparison(current_cwd),
|
||||
@@ -857,11 +890,14 @@ mod tests {
|
||||
use codex_core::config::ConfigOverrides;
|
||||
use codex_core::config::ProjectConfig;
|
||||
use codex_core::protocol::AskForApproval;
|
||||
use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use codex_protocol::protocol::ENVIRONMENT_CONTEXT_CLOSE_TAG;
|
||||
use codex_protocol::protocol::ENVIRONMENT_CONTEXT_OPEN_TAG;
|
||||
use codex_protocol::protocol::RolloutItem;
|
||||
use codex_protocol::protocol::RolloutLine;
|
||||
use codex_protocol::protocol::SessionMeta;
|
||||
use codex_protocol::protocol::SessionMetaLine;
|
||||
use codex_protocol::protocol::TurnContextItem;
|
||||
use serial_test::serial;
|
||||
use tempfile::TempDir;
|
||||
|
||||
@@ -936,31 +972,22 @@ mod tests {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn build_turn_context(config: &Config, cwd: PathBuf) -> TurnContextItem {
|
||||
let model = config
|
||||
.model
|
||||
.clone()
|
||||
.unwrap_or_else(|| "gpt-5.1".to_string());
|
||||
TurnContextItem {
|
||||
cwd,
|
||||
approval_policy: config.approval_policy.value(),
|
||||
sandbox_policy: config.sandbox_policy.get().clone(),
|
||||
model,
|
||||
personality: None,
|
||||
collaboration_mode: None,
|
||||
effort: config.model_reasoning_effort,
|
||||
summary: config.model_reasoning_summary,
|
||||
user_instructions: None,
|
||||
developer_instructions: None,
|
||||
final_output_json_schema: None,
|
||||
truncation_policy: None,
|
||||
}
|
||||
fn build_environment_context_response(cwd: PathBuf) -> RolloutItem {
|
||||
let cwd_display = cwd.display();
|
||||
let text = format!(
|
||||
"{ENVIRONMENT_CONTEXT_OPEN_TAG}\n <cwd>{cwd_display}</cwd>\n <shell>bash</shell>\n{ENVIRONMENT_CONTEXT_CLOSE_TAG}"
|
||||
);
|
||||
RolloutItem::ResponseItem(ResponseItem::Message {
|
||||
id: None,
|
||||
role: "user".to_string(),
|
||||
content: vec![ContentItem::InputText { text }],
|
||||
end_turn: None,
|
||||
})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_session_cwd_prefers_latest_turn_context() -> std::io::Result<()> {
|
||||
async fn read_session_cwd_prefers_latest_environment_context() -> std::io::Result<()> {
|
||||
let temp_dir = TempDir::new()?;
|
||||
let config = build_config(&temp_dir).await?;
|
||||
let first = temp_dir.path().join("first");
|
||||
let second = temp_dir.path().join("second");
|
||||
std::fs::create_dir_all(&first)?;
|
||||
@@ -970,11 +997,11 @@ mod tests {
|
||||
let lines = vec![
|
||||
RolloutLine {
|
||||
timestamp: "t0".to_string(),
|
||||
item: RolloutItem::TurnContext(build_turn_context(&config, first)),
|
||||
item: build_environment_context_response(first),
|
||||
},
|
||||
RolloutLine {
|
||||
timestamp: "t1".to_string(),
|
||||
item: RolloutItem::TurnContext(build_turn_context(&config, second.clone())),
|
||||
item: build_environment_context_response(second.clone()),
|
||||
},
|
||||
];
|
||||
let mut text = String::new();
|
||||
@@ -993,7 +1020,6 @@ mod tests {
|
||||
async fn should_prompt_when_meta_matches_current_but_latest_turn_differs() -> std::io::Result<()>
|
||||
{
|
||||
let temp_dir = TempDir::new()?;
|
||||
let config = build_config(&temp_dir).await?;
|
||||
let current = temp_dir.path().join("current");
|
||||
let latest = temp_dir.path().join("latest");
|
||||
std::fs::create_dir_all(¤t)?;
|
||||
@@ -1014,7 +1040,7 @@ mod tests {
|
||||
},
|
||||
RolloutLine {
|
||||
timestamp: "t1".to_string(),
|
||||
item: RolloutItem::TurnContext(build_turn_context(&config, latest.clone())),
|
||||
item: build_environment_context_response(latest.clone()),
|
||||
},
|
||||
];
|
||||
let mut text = String::new();
|
||||
|
||||
Reference in New Issue
Block a user