Add ephemeral /btw side-question threads

Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
Charles Cunningham
2026-03-24 17:05:35 -07:00
co-authored by Codex
parent 4a210faf33
commit 2ea2b940df
27 changed files with 1432 additions and 230 deletions
+161 -38
View File
@@ -133,13 +133,21 @@ use toml::Value as TomlValue;
use uuid::Uuid;
mod agent_navigation;
mod btw;
mod pending_interactive_replay;
use self::agent_navigation::AgentNavigationDirection;
use self::agent_navigation::AgentNavigationState;
use self::btw::BtwThreadState;
use self::pending_interactive_replay::PendingInteractiveReplayState;
const EXTERNAL_EDITOR_HINT: &str = "Save and close external editor to continue.";
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum AgentPickerVisibility {
Hidden,
ShowInAgentPicker,
}
const THREAD_EVENT_CHANNEL_CAPACITY: usize = 32768;
enum ThreadInteractiveRequest {
@@ -941,7 +949,7 @@ pub(crate) struct App {
/// We set this when intentionally stopping the current thread before moving
/// to another one, then ignore exactly one `ShutdownComplete` so it is not
/// misclassified as an unexpected sub-agent death.
suppress_shutdown_complete: bool,
suppress_shutdown_complete_thread_id: Option<ThreadId>,
/// Tracks the thread we intentionally shut down while exiting the app.
///
/// When this matches the active thread, its `ShutdownComplete` should lead to
@@ -957,6 +965,7 @@ pub(crate) struct App {
thread_event_channels: HashMap<ThreadId, ThreadEventChannel>,
thread_event_listener_tasks: HashMap<ThreadId, JoinHandle<()>>,
agent_navigation: AgentNavigationState,
btw_threads: HashMap<ThreadId, BtwThreadState>,
active_thread_id: Option<ThreadId>,
active_thread_rx: Option<mpsc::Receiver<Event>>,
primary_thread_id: Option<ThreadId>,
@@ -1587,15 +1596,40 @@ impl App {
async fn shutdown_current_thread(&mut self) {
if let Some(thread_id) = self.chat_widget.thread_id() {
// Clear any in-flight rollback guard when switching threads.
self.backtrack.pending_rollback = None;
self.suppress_shutdown_complete = true;
self.chat_widget.submit_op(Op::Shutdown);
self.server.remove_thread(&thread_id).await;
self.abort_thread_event_listener(thread_id);
self.shutdown_and_remove_thread(thread_id).await;
}
}
async fn shutdown_attached_threads_except(&mut self, excluded_thread_id: ThreadId) {
let thread_ids: Vec<ThreadId> = self
.thread_event_channels
.keys()
.copied()
.filter(|thread_id| *thread_id != excluded_thread_id)
.collect();
for thread_id in thread_ids {
self.shutdown_and_remove_thread(thread_id).await;
}
}
async fn request_thread_shutdown(&mut self, thread_id: ThreadId) {
if self.chat_widget.thread_id() == Some(thread_id) {
self.backtrack.pending_rollback = None;
self.suppress_shutdown_complete_thread_id = Some(thread_id);
self.chat_widget.submit_op(Op::Shutdown);
} else if let Ok(thread) = self.server.get_thread(thread_id).await {
let _ = thread.submit(Op::Shutdown).await;
}
}
/// Requests shutdown for a loaded thread, removes it from the thread manager, and stops its
/// event listener task.
async fn shutdown_and_remove_thread(&mut self, thread_id: ThreadId) {
self.request_thread_shutdown(thread_id).await;
self.server.remove_thread(&thread_id).await;
self.abort_thread_event_listener(thread_id);
}
fn abort_thread_event_listener(&mut self, thread_id: ThreadId) {
if let Some(handle) = self.thread_event_listener_tasks.remove(&thread_id) {
handle.abort();
@@ -1731,7 +1765,7 @@ impl App {
self.active_thread_id.or(self.chat_widget.thread_id())
}
/// Mirrors the visible thread into the contextual footer row.
/// Mirrors the visible thread into the contextual footer row and BTW banner.
///
/// The footer sometimes shows ambient context instead of an instructional hint. In multi-agent
/// sessions, that contextual row includes the currently viewed agent label. The label is
@@ -1742,6 +1776,60 @@ impl App {
.agent_navigation
.active_agent_label(self.current_displayed_thread_id(), self.primary_thread_id);
self.chat_widget.set_active_agent_label(label);
self.sync_btw_thread_ui();
}
/// Registers an already-running thread with the TUI without replacing the current session.
///
/// Unlike `/fork` and `/resume`, which swap the active `ChatWidget`, this is for parallel live
/// threads such as BTW children and background agent threads. It seeds the thread's replay
/// channel with a `SessionConfigured` event, starts the event-listener task, and optionally
/// exposes the thread in agent navigation.
async fn attach_live_thread(
&mut self,
thread_id: ThreadId,
thread: Arc<codex_core::CodexThread>,
session_configured: SessionConfiguredEvent,
visibility: AgentPickerVisibility,
) -> Result<()> {
if self.thread_event_channels.contains_key(&thread_id) {
return Ok(());
}
let config_snapshot = thread.config_snapshot().await;
match visibility {
AgentPickerVisibility::Hidden => {}
AgentPickerVisibility::ShowInAgentPicker => {
self.upsert_agent_picker_thread(
thread_id,
config_snapshot.session_source.get_nickname(),
config_snapshot.session_source.get_agent_role(),
false,
);
}
}
let event = Event {
id: String::new(),
msg: EventMsg::SessionConfigured(session_configured),
};
let channel =
ThreadEventChannel::new_with_session_configured(THREAD_EVENT_CHANNEL_CAPACITY, event);
let app_event_tx = self.app_event_tx.clone();
self.thread_event_channels.insert(thread_id, channel);
let listener_handle = tokio::spawn(async move {
loop {
let event = match thread.next_event().await {
Ok(event) => event,
Err(err) => {
tracing::debug!("external thread {thread_id} listener stopped: {err}");
break;
}
};
app_event_tx.send(AppEvent::ThreadEvent { thread_id, event });
}
});
self.thread_event_listener_tasks
.insert(thread_id, listener_handle);
Ok(())
}
async fn thread_cwd(&self, thread_id: ThreadId) -> Option<PathBuf> {
@@ -1978,6 +2066,9 @@ impl App {
async fn open_agent_picker(&mut self) {
let thread_ids: Vec<ThreadId> = self.thread_event_channels.keys().cloned().collect();
for thread_id in thread_ids {
if self.btw_threads.contains_key(&thread_id) {
continue;
}
match self.server.get_thread(thread_id).await {
Ok(thread) => {
let session_source = thread.config_snapshot().await.session_source;
@@ -2080,6 +2171,7 @@ impl App {
if self.active_thread_id == Some(thread_id) {
return Ok(());
}
let btw_threads_to_discard = self.btw_threads_to_discard_after_switch(thread_id);
let live_thread = match self.server.get_thread(thread_id).await {
Ok(thread) => Some(thread),
@@ -2119,7 +2211,12 @@ impl App {
let (tx, _rx) = unbounded_channel();
tx
};
self.replace_chat_widget(ChatWidget::new_with_op_sender(init, codex_op_tx));
let next_btw_fork_banner_parent_label =
self.take_next_btw_fork_banner_parent_label(thread_id);
self.chat_widget = ChatWidget::new_with_op_sender(init, codex_op_tx);
self.chat_widget
.set_next_fork_banner_parent_label(next_btw_fork_banner_parent_label);
self.sync_active_agent_label();
self.reset_for_thread_switch(tui)?;
self.replay_thread_snapshot(snapshot, !is_replay_only);
@@ -2131,6 +2228,9 @@ impl App {
}
self.drain_active_thread_events(tui).await?;
self.refresh_pending_thread_approvals().await;
for btw_thread_id in btw_threads_to_discard {
self.discard_btw_thread(btw_thread_id).await;
}
Ok(())
}
@@ -2142,8 +2242,12 @@ impl App {
self.has_emitted_history_lines = false;
self.backtrack = BacktrackState::default();
self.backtrack_render_pending = false;
tui.terminal.clear_scrollback()?;
tui.terminal.clear()?;
if let Err(err) = tui.terminal.clear_scrollback() {
tracing::warn!(error = %err, "failed to clear terminal scrollback during thread switch");
}
if let Err(err) = tui.terminal.clear() {
tracing::warn!(error = %err, "failed to clear terminal during thread switch");
}
Ok(())
}
@@ -2151,6 +2255,7 @@ impl App {
self.abort_all_thread_event_listeners();
self.thread_event_channels.clear();
self.agent_navigation.clear();
self.btw_threads.clear();
self.active_thread_id = None;
self.active_thread_rx = None;
self.primary_thread_id = None;
@@ -2578,12 +2683,13 @@ impl App {
feedback: feedback.clone(),
feedback_audience,
pending_update_action: None,
suppress_shutdown_complete: false,
suppress_shutdown_complete_thread_id: None,
pending_shutdown_exit_thread_id: None,
windows_sandbox: WindowsSandboxState::default(),
thread_event_channels: HashMap::new(),
thread_event_listener_tasks: HashMap::new(),
agent_navigation: AgentNavigationState::default(),
btw_threads: HashMap::new(),
active_thread_id: None,
active_thread_rx: None,
primary_thread_id: None,
@@ -2862,7 +2968,8 @@ impl App {
.await
{
Ok(resumed) => {
self.shutdown_current_thread().await;
self.shutdown_attached_threads_except(resumed.thread_id)
.await;
self.config = resume_config;
tui.set_notification_method(self.config.tui_notification_method);
self.file_search.update_search_dir(self.config.cwd.clone());
@@ -2936,7 +3043,8 @@ impl App {
.await
{
Ok(forked) => {
self.shutdown_current_thread().await;
self.shutdown_attached_threads_except(forked.thread_id)
.await;
let init = self.chatwidget_init_for_forked_or_resumed_thread(
tui,
self.config.clone(),
@@ -4002,6 +4110,14 @@ impl App {
AppEvent::SelectAgentThread(thread_id) => {
self.select_agent_thread(tui, thread_id).await?;
}
AppEvent::StartBtw {
parent_thread_id,
user_message,
} => {
return self
.handle_start_btw(tui, parent_thread_id, user_message)
.await;
}
AppEvent::OpenSkillsList => {
self.chat_widget.open_skills_list();
}
@@ -4300,8 +4416,10 @@ impl App {
// This guard is only for intentional thread-switch shutdowns.
// App-exit shutdowns are tracked by `pending_shutdown_exit_thread_id`
// and resolved in `handle_active_thread_event`.
if self.suppress_shutdown_complete && matches!(event.msg, EventMsg::ShutdownComplete) {
self.suppress_shutdown_complete = false;
if matches!(event.msg, EventMsg::ShutdownComplete)
&& self.suppress_shutdown_complete_thread_id == self.current_displayed_thread_id()
{
self.suppress_shutdown_complete_thread_id = None;
return;
}
if let EventMsg::ListSkillsResponse(response) = &event.msg {
@@ -4412,25 +4530,16 @@ impl App {
rollout_path: thread.rollout_path(),
}),
};
let channel =
ThreadEventChannel::new_with_session_configured(THREAD_EVENT_CHANNEL_CAPACITY, event);
let app_event_tx = self.app_event_tx.clone();
self.thread_event_channels.insert(thread_id, channel);
let listener_handle = tokio::spawn(async move {
loop {
let event = match thread.next_event().await {
Ok(event) => event,
Err(err) => {
tracing::debug!("external thread {thread_id} listener stopped: {err}");
break;
}
};
app_event_tx.send(AppEvent::ThreadEvent { thread_id, event });
}
});
self.thread_event_listener_tasks
.insert(thread_id, listener_handle);
Ok(())
let EventMsg::SessionConfigured(session_configured) = event.msg else {
unreachable!("thread-created event must be session-configured");
};
self.attach_live_thread(
thread_id,
thread,
session_configured,
AgentPickerVisibility::ShowInAgentPicker,
)
.await
}
fn reasoning_label(reasoning_effort: Option<ReasoningEffortConfig>) -> &'static str {
@@ -4650,12 +4759,24 @@ impl App {
// with the composer focused and empty. In any other state, forward
// Esc so the active UI (e.g. status indicator, modals, popups)
// handles it.
KeyEvent {
code: KeyCode::Char('c'),
modifiers: crossterm::event::KeyModifiers::CONTROL,
kind: KeyEventKind::Press | KeyEventKind::Repeat,
..
} => {
if self.maybe_return_from_btw(tui).await {
} else {
self.chat_widget.handle_key_event(key_event);
}
}
KeyEvent {
code: KeyCode::Esc,
kind: KeyEventKind::Press | KeyEventKind::Repeat,
..
} => {
if self.chat_widget.is_normal_backtrack_mode()
if self.maybe_return_from_btw(tui).await {
} else if self.chat_widget.is_normal_backtrack_mode()
&& self.chat_widget.composer_is_empty()
{
self.handle_backtrack_esc_key(tui);
@@ -7026,12 +7147,13 @@ guardian_approval = true
feedback: codex_feedback::CodexFeedback::new(),
feedback_audience: FeedbackAudience::External,
pending_update_action: None,
suppress_shutdown_complete: false,
suppress_shutdown_complete_thread_id: None,
pending_shutdown_exit_thread_id: None,
windows_sandbox: WindowsSandboxState::default(),
thread_event_channels: HashMap::new(),
thread_event_listener_tasks: HashMap::new(),
agent_navigation: AgentNavigationState::default(),
btw_threads: HashMap::new(),
active_thread_id: None,
active_thread_rx: None,
primary_thread_id: None,
@@ -7090,12 +7212,13 @@ guardian_approval = true
feedback: codex_feedback::CodexFeedback::new(),
feedback_audience: FeedbackAudience::External,
pending_update_action: None,
suppress_shutdown_complete: false,
suppress_shutdown_complete_thread_id: None,
pending_shutdown_exit_thread_id: None,
windows_sandbox: WindowsSandboxState::default(),
thread_event_channels: HashMap::new(),
thread_event_listener_tasks: HashMap::new(),
agent_navigation: AgentNavigationState::default(),
btw_threads: HashMap::new(),
active_thread_id: None,
active_thread_rx: None,
primary_thread_id: None,
+263
View File
@@ -0,0 +1,263 @@
use super::*;
const BTW_RENAME_BLOCK_MESSAGE: &str = "BTW threads are ephemeral and cannot be renamed.";
#[derive(Clone, Debug)]
pub(super) struct BtwThreadState {
/// Thread to return to when the current BTW thread is dismissed.
pub(super) parent_thread_id: ThreadId,
/// Pretty parent label for the next synthetic fork banner, consumed on first attach.
pub(super) next_fork_banner_parent_label: Option<String>,
}
impl App {
/// Keeps BTW-specific UI state in sync with the currently displayed thread.
pub(super) fn sync_btw_thread_ui(&mut self) {
let clear_btw_ui = |chat_widget: &mut crate::chatwidget::ChatWidget| {
chat_widget.set_thread_footer_hint_override(/*items*/ None);
chat_widget.clear_thread_rename_block();
};
let Some(active_thread_id) = self.current_displayed_thread_id() else {
clear_btw_ui(&mut self.chat_widget);
return;
};
let Some(mut parent_thread_id) = self
.btw_threads
.get(&active_thread_id)
.map(|state| state.parent_thread_id)
else {
clear_btw_ui(&mut self.chat_widget);
return;
};
self.chat_widget
.set_thread_rename_block_message(BTW_RENAME_BLOCK_MESSAGE);
let mut depth = 1usize;
while let Some(next_parent_thread_id) = self
.btw_threads
.get(&parent_thread_id)
.map(|state| state.parent_thread_id)
{
depth += 1;
parent_thread_id = next_parent_thread_id;
}
let repeated_prefix = "BTW from ".repeat(depth.saturating_sub(1));
let label = if self.primary_thread_id == Some(parent_thread_id) {
format!("from {repeated_prefix}main thread · Esc to return")
} else {
let parent_label = self.thread_label(parent_thread_id);
format!("from {repeated_prefix}parent thread ({parent_label}) · Esc to return")
};
self.chat_widget
.set_thread_footer_hint_override(Some(vec![("BTW".to_string(), label)]));
}
pub(super) fn active_btw_parent_thread_id(&self) -> Option<ThreadId> {
self.current_displayed_thread_id()
.and_then(|thread_id| self.btw_threads.get(&thread_id))
.map(|state| state.parent_thread_id)
}
pub(super) async fn maybe_return_from_btw(&mut self, tui: &mut tui::Tui) -> bool {
if self.overlay.is_none()
&& self.chat_widget.no_modal_or_popup_active()
&& self.chat_widget.composer_is_empty()
&& let Some(parent_thread_id) = self.active_btw_parent_thread_id()
{
let _ = self.select_agent_thread(tui, parent_thread_id).await;
true
} else {
false
}
}
pub(super) fn btw_threads_to_discard_after_switch(
&self,
target_thread_id: ThreadId,
) -> Vec<ThreadId> {
let Some(mut btw_thread_id) = self.current_displayed_thread_id() else {
return Vec::new();
};
if !self.btw_threads.contains_key(&btw_thread_id)
|| self
.btw_threads
.get(&target_thread_id)
.map(|state| state.parent_thread_id)
== Some(btw_thread_id)
{
return Vec::new();
}
let mut btw_threads_to_discard = Vec::new();
// Selecting the immediate return thread should keep that ancestor reachable. Only discard
// the BTW suffix that becomes unreachable after the replacement thread is fully attached
// and replayed.
loop {
btw_threads_to_discard.push(btw_thread_id);
let Some(parent_thread_id) = self
.btw_threads
.get(&btw_thread_id)
.map(|state| state.parent_thread_id)
else {
break;
};
if parent_thread_id == target_thread_id
|| !self.btw_threads.contains_key(&parent_thread_id)
{
break;
}
btw_thread_id = parent_thread_id;
}
btw_threads_to_discard
}
pub(super) fn take_next_btw_fork_banner_parent_label(
&mut self,
thread_id: ThreadId,
) -> Option<String> {
self.btw_threads
.get_mut(&thread_id)
.and_then(|state| state.next_fork_banner_parent_label.take())
}
/// Shuts down and forgets one ephemeral BTW thread.
///
/// This removes the thread from the core thread manager, aborts its listener task, clears any
/// TUI bookkeeping for replay/navigation, and recomputes the footer state. Callers that are
/// leaving a nested BTW stack are responsible for discarding the whole hidden chain in the
/// correct order.
pub(super) async fn discard_btw_thread(&mut self, thread_id: ThreadId) {
self.shutdown_and_remove_thread(thread_id).await;
self.thread_event_channels.remove(&thread_id);
self.btw_threads.remove(&thread_id);
if self.active_thread_id == Some(thread_id) {
self.clear_active_thread().await;
} else {
self.refresh_pending_thread_approvals().await;
}
self.sync_active_agent_label();
}
async fn fork_banner_parent_label(&self, parent_thread_id: ThreadId) -> Option<String> {
if self.chat_widget.thread_id() == Some(parent_thread_id) {
return self
.chat_widget
.thread_name()
.filter(|name| !name.trim().is_empty());
}
let channel = self.thread_event_channels.get(&parent_thread_id)?;
let store = channel.store.lock().await;
match store.session_configured.as_ref().map(|event| &event.msg) {
Some(EventMsg::SessionConfigured(session)) => session
.thread_name
.clone()
.filter(|name| !name.trim().is_empty()),
_ => None,
}
}
pub(super) async fn handle_start_btw(
&mut self,
tui: &mut tui::Tui,
parent_thread_id: ThreadId,
user_message: crate::chatwidget::UserMessage,
) -> Result<AppRunControl> {
self.session_telemetry.counter(
"codex.thread.btw",
/*inc*/ 1,
&[("source", "slash_command")],
);
self.refresh_in_memory_config_from_disk_best_effort("starting a BTW subagent")
.await;
let parent_rollout_path = match self.server.get_thread(parent_thread_id).await {
Ok(thread) => thread.rollout_path(),
Err(err) => {
if self.current_displayed_thread_id() == Some(parent_thread_id) {
self.chat_widget.rollout_path()
} else {
self.chat_widget.add_error_message(format!(
"Failed to fork BTW thread from {parent_thread_id}: {err}"
));
return Ok(AppRunControl::Continue);
}
}
}
.filter(|path| path.exists());
let Some(parent_rollout_path) = parent_rollout_path else {
self.chat_widget.add_error_message(
"A thread must contain at least one turn before /btw can fork it.".to_string(),
);
return Ok(AppRunControl::Continue);
};
let fork_result = if self.chat_widget.agent_turn_running() {
self.server
.fork_thread(
ForkSnapshot::Interrupted,
self.config.clone(),
parent_rollout_path.clone(),
/*persist_extended_history*/ false,
/*parent_trace*/ None,
)
.await
} else {
self.server
.fork_thread(
/*nth_user_message*/ usize::MAX,
self.config.clone(),
parent_rollout_path.clone(),
/*persist_extended_history*/ false,
/*parent_trace*/ None,
)
.await
};
match fork_result {
Ok(forked) => {
let child_thread_id = forked.thread_id;
let next_fork_banner_parent_label =
self.fork_banner_parent_label(parent_thread_id).await;
self.attach_live_thread(
child_thread_id,
Arc::clone(&forked.thread),
forked.session_configured,
AgentPickerVisibility::Hidden,
)
.await?;
self.btw_threads.insert(
child_thread_id,
BtwThreadState {
parent_thread_id,
next_fork_banner_parent_label,
},
);
if let Err(err) = self.select_agent_thread(tui, child_thread_id).await {
self.discard_btw_thread(child_thread_id).await;
return Err(err);
}
if self.active_thread_id == Some(child_thread_id) {
if let Some(op) = self
.chat_widget
.submit_user_message_as_plain_user_turn(user_message)
{
self.note_active_thread_outbound_op(&op).await;
}
} else {
self.discard_btw_thread(child_thread_id).await;
self.chat_widget.add_error_message(format!(
"Failed to switch into BTW thread {child_thread_id}."
));
}
}
Err(err) => {
let path_display = parent_rollout_path.display();
self.chat_widget.add_error_message(format!(
"Failed to start BTW thread from {path_display}: {err}"
));
}
}
Ok(AppRunControl::Continue)
}
}
+6
View File
@@ -27,6 +27,7 @@ use codex_utils_approval_presets::ApprovalPreset;
use crate::bottom_pane::ApprovalRequest;
use crate::bottom_pane::StatusLineItem;
use crate::bottom_pane::TerminalTitleItem;
use crate::chatwidget::UserMessage;
use crate::history_cell::HistoryCell;
use codex_core::config::types::ApprovalsReviewer;
@@ -81,6 +82,11 @@ pub(crate) enum AppEvent {
OpenAgentPicker,
/// Switch the active thread to the selected agent.
SelectAgentThread(ThreadId),
/// Fork the current thread into a transient BTW child and submit a side-question there.
StartBtw {
parent_thread_id: ThreadId,
user_message: UserMessage,
},
/// Submit an op to the specified thread, regardless of current focus.
SubmitThreadOp {
+17 -3
View File
@@ -383,6 +383,7 @@ pub(crate) struct ChatComposer {
custom_prompts: Vec<CustomPrompt>,
footer_mode: FooterMode,
footer_hint_override: Option<Vec<(String, String)>>,
thread_footer_hint_override: Option<Vec<(String, String)>>,
remote_image_urls: Vec<String>,
/// Tracks keyboard selection for the remote-image rows so Up/Down + Delete/Backspace
/// can highlight and remove remote attachments from the composer UI.
@@ -510,6 +511,7 @@ impl ChatComposer {
custom_prompts: Vec::new(),
footer_mode: FooterMode::ComposerEmpty,
footer_hint_override: None,
thread_footer_hint_override: None,
remote_image_urls: Vec::new(),
selected_remote_image_index: None,
footer_flash: None,
@@ -957,6 +959,14 @@ impl ChatComposer {
self.footer_hint_override = items;
}
/// Override the footer hint with thread-scoped UI, such as ephemeral BTW navigation state.
///
/// This lives below general footer overrides so temporary flows like external editor launch
/// or realtime status can still take precedence.
pub(crate) fn set_thread_footer_hint_override(&mut self, items: Option<Vec<(String, String)>>) {
self.thread_footer_hint_override = items;
}
pub(crate) fn set_remote_image_urls(&mut self, urls: Vec<String>) {
self.remote_image_urls = urls;
self.selected_remote_image_index = None;
@@ -4290,12 +4300,16 @@ impl ChatComposer {
} else {
self.collaboration_mode_indicator
};
let active_footer_hint_override = self
.footer_hint_override
.as_ref()
.or(self.thread_footer_hint_override.as_ref());
let mut left_width = if self.footer_flash_visible() {
self.footer_flash
.as_ref()
.map(|flash| flash.line.width() as u16)
.unwrap_or(0)
} else if let Some(items) = self.footer_hint_override.as_ref() {
} else if let Some(items) = active_footer_hint_override {
footer_hint_items_width(items)
} else if status_line_active {
truncated_status_line
@@ -4344,7 +4358,7 @@ impl ChatComposer {
let can_show_left_and_context =
can_show_left_with_context(hint_rect, left_width, right_width);
let has_override =
self.footer_flash_visible() || self.footer_hint_override.is_some();
self.footer_flash_visible() || active_footer_hint_override.is_some();
let single_line_layout = if has_override || status_line_active {
None
} else {
@@ -4420,7 +4434,7 @@ impl ChatComposer {
if let Some(flash) = self.footer_flash.as_ref() {
flash.line.render(inset_footer_hint_area(hint_rect), buf);
}
} else if let Some(items) = self.footer_hint_override.as_ref() {
} else if let Some(items) = active_footer_hint_override {
render_footer_hint_items(hint_rect, buf, items);
} else if status_line_active {
if let Some(line) = truncated_status_line {
+11 -2
View File
@@ -710,9 +710,18 @@ pub(crate) fn footer_hint_items_width(items: &[(String, String)]) -> u16 {
fn footer_hint_items_line(items: &[(String, String)]) -> Line<'static> {
let mut spans = Vec::with_capacity(items.len() * 4);
for (idx, (key, label)) in items.iter().enumerate() {
let is_btw = key == "BTW";
spans.push(" ".into());
spans.push(key.clone().bold());
spans.push(format!(" {label}").into());
spans.push(if is_btw {
key.clone().magenta().bold()
} else {
key.clone().bold()
});
spans.push(if is_btw {
format!(" {label}").magenta().bold()
} else {
format!(" {label}").into()
});
if idx + 1 != items.len() {
spans.push(" ".into());
}
+5
View File
@@ -618,6 +618,11 @@ impl BottomPane {
self.request_redraw();
}
pub(crate) fn set_thread_footer_hint_override(&mut self, items: Option<Vec<(String, String)>>) {
self.composer.set_thread_footer_hint_override(items);
self.request_redraw();
}
pub(crate) fn set_remote_image_urls(&mut self, urls: Vec<String>) {
self.composer.set_remote_image_urls(urls);
self.request_redraw();
+137 -66
View File
@@ -68,7 +68,6 @@ use codex_core::config::types::ApprovalsReviewer;
use codex_core::config::types::Notifications;
use codex_core::config::types::WindowsSandboxModeToml;
use codex_core::config_loader::ConfigLayerStackOrdering;
use codex_core::find_thread_name_by_id;
use codex_core::mcp::McpManager;
use codex_core::models_manager::manager::ModelsManager;
use codex_core::plugins::PluginsManager;
@@ -554,6 +553,12 @@ enum RateLimitErrorKind {
Generic,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum ShellEscapePolicy {
Allow,
Disallow,
}
fn rate_limit_error_kind(info: &CodexErrorInfo) -> Option<RateLimitErrorKind> {
match info {
CodexErrorInfo::ServerOverloaded => Some(RateLimitErrorKind::ServerOverloaded),
@@ -766,7 +771,10 @@ pub(crate) struct ChatWidget {
suppress_queue_autosend: bool,
thread_id: Option<ThreadId>,
thread_name: Option<String>,
thread_rename_block_message: Option<String>,
forked_from: Option<ThreadId>,
/// Pretty parent label used only for the next fork banner inserted on session configure.
next_fork_banner_parent_label: Option<String>,
frame_requester: FrameRequester,
// Whether to include the initial welcome banner on session configured
show_welcome_banner: bool,
@@ -1493,48 +1501,28 @@ impl ChatWidget {
}
}
fn emit_forked_thread_event(&self, forked_from_id: ThreadId) {
let app_event_tx = self.app_event_tx.clone();
let codex_home = self.config.codex_home.clone();
tokio::spawn(async move {
let forked_from_id_text = forked_from_id.to_string();
let send_name_and_id = |name: String| {
let line: Line<'static> = vec![
"• ".dim(),
"Thread forked from ".into(),
name.cyan(),
" (".into(),
forked_from_id_text.clone().cyan(),
")".into(),
]
.into();
app_event_tx.send(AppEvent::InsertHistoryCell(Box::new(
PlainHistoryCell::new(vec![line]),
)));
};
let send_id_only = || {
let line: Line<'static> = vec![
"• ".dim(),
"Thread forked from ".into(),
forked_from_id_text.clone().cyan(),
]
.into();
app_event_tx.send(AppEvent::InsertHistoryCell(Box::new(
PlainHistoryCell::new(vec![line]),
)));
};
match find_thread_name_by_id(&codex_home, &forked_from_id).await {
Ok(Some(name)) if !name.trim().is_empty() => {
send_name_and_id(name);
}
Ok(_) => send_id_only(),
Err(err) => {
tracing::warn!("Failed to read forked thread name: {err}");
send_id_only();
}
}
});
fn emit_forked_thread_event(&mut self, forked_from_id: ThreadId) {
let line: Line<'static> = if let Some(label) = self.next_fork_banner_parent_label.take() {
vec![
"• ".dim(),
"Thread forked from ".into(),
label.cyan(),
" (".into(),
forked_from_id.to_string().cyan(),
")".into(),
]
.into()
} else {
vec![
"• ".dim(),
"Thread forked from ".into(),
forked_from_id.to_string().cyan(),
]
.into()
};
self.app_event_tx.send(AppEvent::InsertHistoryCell(Box::new(
PlainHistoryCell::new(vec![line]),
)));
}
fn on_thread_name_updated(&mut self, event: codex_protocol::protocol::ThreadNameUpdatedEvent) {
@@ -3779,7 +3767,9 @@ impl ChatWidget {
suppress_queue_autosend: false,
thread_id: None,
thread_name: None,
thread_rename_block_message: None,
forked_from: None,
next_fork_banner_parent_label: None,
queued_user_messages: VecDeque::new(),
rejected_steers_queue: VecDeque::new(),
pending_steers: VecDeque::new(),
@@ -3983,7 +3973,9 @@ impl ChatWidget {
suppress_queue_autosend: false,
thread_id: None,
thread_name: None,
thread_rename_block_message: None,
forked_from: None,
next_fork_banner_parent_label: None,
saw_plan_update_this_turn: false,
saw_plan_item_this_turn: false,
last_plan_progress: None,
@@ -4179,7 +4171,9 @@ impl ChatWidget {
suppress_queue_autosend: false,
thread_id: None,
thread_name: None,
thread_rename_block_message: None,
forked_from: None,
next_fork_banner_parent_label: None,
queued_user_messages: VecDeque::new(),
rejected_steers_queue: VecDeque::new(),
pending_steers: VecDeque::new(),
@@ -4473,6 +4467,22 @@ impl ChatWidget {
self.bottom_pane.set_footer_hint_override(items);
}
pub(crate) fn set_thread_footer_hint_override(&mut self, items: Option<Vec<(String, String)>>) {
self.bottom_pane.set_thread_footer_hint_override(items);
}
pub(crate) fn clear_thread_rename_block(&mut self) {
self.thread_rename_block_message = None;
}
pub(crate) fn set_thread_rename_block_message(&mut self, message: impl Into<String>) {
self.thread_rename_block_message = Some(message.into());
}
pub(crate) fn set_next_fork_banner_parent_label(&mut self, label: Option<String>) {
self.next_fork_banner_parent_label = label;
}
pub(crate) fn show_selection_view(&mut self, params: SelectionViewParams) {
self.bottom_pane.show_selection_view(params);
self.request_redraw();
@@ -4620,6 +4630,9 @@ impl ChatWidget {
}
self.open_collaboration_modes_popup();
}
SlashCommand::Btw => {
self.add_error_message("Usage: /btw <question>".to_string());
}
SlashCommand::Agent | SlashCommand::MultiAgents => {
self.app_event_tx.send(AppEvent::OpenAgentPicker);
}
@@ -4891,6 +4904,9 @@ impl ChatWidget {
}
}
SlashCommand::Rename if !trimmed.is_empty() => {
if !self.ensure_thread_rename_allowed() {
return;
}
self.session_telemetry
.counter("codex.thread.rename", /*inc*/ 1, &[]);
let Some((prepared_args, _prepared_elements)) = self
@@ -4915,23 +4931,9 @@ impl ChatWidget {
if self.active_mode_kind() != ModeKind::Plan {
return;
}
let Some((prepared_args, prepared_elements)) = self
.bottom_pane
.prepare_inline_args_submission(/*record_history*/ true)
else {
let Some(user_message) = self.prepare_inline_submission_user_message() else {
return;
};
let local_images = self
.bottom_pane
.take_recent_submission_images_with_placeholders();
let remote_image_urls = self.take_remote_image_urls();
let user_message = UserMessage {
text: prepared_args,
local_images,
remote_image_urls,
text_elements: prepared_elements,
mention_bindings: self.bottom_pane.take_recent_submission_mention_bindings(),
};
if self.is_session_configured() {
self.reasoning_buffer.clear();
self.full_reasoning_buffer.clear();
@@ -4941,6 +4943,21 @@ impl ChatWidget {
self.queue_user_message(user_message);
}
}
SlashCommand::Btw if !trimmed.is_empty() => {
let Some(parent_thread_id) = self.thread_id else {
self.add_error_message(
"BTW is unavailable before the session starts.".to_string(),
);
return;
};
let Some(user_message) = self.prepare_inline_submission_user_message() else {
return;
};
self.app_event_tx.send(AppEvent::StartBtw {
parent_thread_id,
user_message,
});
}
SlashCommand::Review if !trimmed.is_empty() => {
let Some((prepared_args, _prepared_elements)) = self
.bottom_pane
@@ -4976,6 +4993,9 @@ impl ChatWidget {
}
fn show_rename_prompt(&mut self) {
if !self.ensure_thread_rename_allowed() {
return;
}
let tx = self.app_event_tx.clone();
let has_name = self
.thread_name
@@ -5007,6 +5027,34 @@ impl ChatWidget {
self.bottom_pane.show_view(Box::new(view));
}
fn ensure_thread_rename_allowed(&mut self) -> bool {
match self.thread_rename_block_message.clone() {
Some(message) => {
self.add_error_message(message);
false
}
None => true,
}
}
fn prepare_inline_submission_user_message(&mut self) -> Option<UserMessage> {
let (text, text_elements) = self
.bottom_pane
.prepare_inline_args_submission(/*record_history*/ true)?;
let local_images = self
.bottom_pane
.take_recent_submission_images_with_placeholders();
let remote_image_urls = self.take_remote_image_urls();
let mention_bindings = self.bottom_pane.take_recent_submission_mention_bindings();
Some(UserMessage {
text,
local_images,
remote_image_urls,
text_elements,
mention_bindings,
})
}
pub(crate) fn handle_paste(&mut self, text: String) {
self.bottom_pane.handle_paste(text);
}
@@ -5067,11 +5115,27 @@ impl ChatWidget {
}
fn submit_user_message(&mut self, user_message: UserMessage) {
let _ = self
.submit_user_message_with_shell_escape_policy(user_message, ShellEscapePolicy::Allow);
}
pub(crate) fn submit_user_message_as_plain_user_turn(
&mut self,
user_message: UserMessage,
) -> Option<Op> {
self.submit_user_message_with_shell_escape_policy(user_message, ShellEscapePolicy::Disallow)
}
fn submit_user_message_with_shell_escape_policy(
&mut self,
user_message: UserMessage,
shell_escape_policy: ShellEscapePolicy,
) -> Option<Op> {
if !self.is_session_configured() {
tracing::warn!("cannot submit user message before session is configured; queueing");
self.queued_user_messages.push_front(user_message);
self.refresh_pending_input_preview();
return;
return None;
}
let UserMessage {
text,
@@ -5081,7 +5145,7 @@ impl ChatWidget {
mention_bindings,
} = user_message;
if text.is_empty() && local_images.is_empty() && remote_image_urls.is_empty() {
return;
return None;
}
if (!local_images.is_empty() || !remote_image_urls.is_empty())
&& !self.current_model_supports_images()
@@ -5093,14 +5157,16 @@ impl ChatWidget {
mention_bindings,
remote_image_urls,
);
return;
return None;
}
let render_in_history = !self.agent_turn_running;
let mut items: Vec<UserInput> = Vec::new();
// Special-case: "!cmd" executes a local shell command instead of sending to the model.
if let Some(stripped) = text.strip_prefix('!') {
if shell_escape_policy == ShellEscapePolicy::Allow
&& let Some(stripped) = text.strip_prefix('!')
{
let cmd = stripped.trim();
if cmd.is_empty() {
self.app_event_tx.send(AppEvent::InsertHistoryCell(Box::new(
@@ -5109,12 +5175,12 @@ impl ChatWidget {
Some(USER_SHELL_COMMAND_HELP_HINT.to_string()),
),
)));
return;
return None;
}
self.submit_op(Op::RunUserShellCommand {
command: cmd.to_string(),
});
return;
return None;
}
for image_url in &remote_image_urls {
@@ -5281,8 +5347,8 @@ impl ChatWidget {
personality,
};
if !self.submit_op(op) {
return;
if !self.submit_op(op.clone()) {
return None;
}
// Persist the text to cross-session message history.
@@ -5344,6 +5410,7 @@ impl ChatWidget {
}
self.needs_final_message_separator = false;
Some(op)
}
/// Restore the blocked submission draft without losing mention resolution state.
@@ -9321,6 +9388,10 @@ impl ChatWidget {
self.thread_id
}
pub(crate) fn agent_turn_running(&self) -> bool {
self.agent_turn_running
}
pub(crate) fn thread_name(&self) -> Option<String> {
self.thread_name.clone()
}
@@ -0,0 +1,9 @@
---
source: tui/src/chatwidget/tests.rs
expression: terminal.backend()
---
" "
" "
"› Ask Codex to do anything "
" "
" BTW from main thread · Esc to return 100% context left "
@@ -0,0 +1,9 @@
---
source: tui/src/chatwidget/tests.rs
expression: terminal.backend()
---
" "
" "
"› Ask Codex to do anything "
" "
" Save and close external editor to continue. 100% context left "
@@ -2,4 +2,4 @@
source: tui/src/chatwidget/tests.rs
expression: combined
---
• Thread forked from named-thread (e9f18a88-8081-4e51-9d4e-8af5cde2d8dd)
• Thread forked from named parent (e9f18a88-8081-4e51-9d4e-8af5cde2d8dd)
+152 -15
View File
@@ -577,20 +577,12 @@ async fn replayed_user_message_with_only_local_images_does_not_render_history_ce
}
#[tokio::test]
async fn forked_thread_history_line_includes_name_and_id_snapshot() {
let (chat, mut rx, _op_rx) = make_chatwidget_manual(None).await;
let mut chat = chat;
let temp = tempdir().expect("tempdir");
chat.config.codex_home = temp.path().to_path_buf();
async fn forked_thread_history_line_snapshot() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None).await;
chat.set_next_fork_banner_parent_label(Some("named parent".to_string()));
let forked_from_id =
ThreadId::from_string("e9f18a88-8081-4e51-9d4e-8af5cde2d8dd").expect("forked id");
let session_index_entry = format!(
"{{\"id\":\"{forked_from_id}\",\"thread_name\":\"named-thread\",\"updated_at\":\"2024-01-02T00:00:00Z\"}}\n"
);
std::fs::write(temp.path().join("session_index.jsonl"), session_index_entry)
.expect("write session index");
chat.emit_forked_thread_event(forked_from_id);
let history_cell = tokio::time::timeout(std::time::Duration::from_secs(2), async {
@@ -615,10 +607,7 @@ async fn forked_thread_history_line_includes_name_and_id_snapshot() {
#[tokio::test]
async fn forked_thread_history_line_without_name_shows_id_once_snapshot() {
let (chat, mut rx, _op_rx) = make_chatwidget_manual(None).await;
let mut chat = chat;
let temp = tempdir().expect("tempdir");
chat.config.codex_home = temp.path().to_path_buf();
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None).await;
let forked_from_id =
ThreadId::from_string("019c2d47-4935-7423-a190-05691f566092").expect("forked id");
@@ -2052,7 +2041,9 @@ async fn make_chatwidget_manual(
suppress_queue_autosend: false,
thread_id: None,
thread_name: None,
thread_rename_block_message: None,
forked_from: None,
next_fork_banner_parent_label: None,
frame_requester: FrameRequester::test_dummy(),
show_welcome_banner: true,
startup_tooltip_override: None,
@@ -2679,6 +2670,25 @@ async fn submit_user_message_with_mode_sets_coding_collaboration_mode() {
}
}
#[tokio::test]
async fn submit_user_message_as_plain_user_turn_does_not_run_shell_commands() {
let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(Some("gpt-5")).await;
chat.thread_id = Some(ThreadId::new());
chat.submit_user_message_as_plain_user_turn("!echo hello".into());
match next_submit_op(&mut op_rx) {
Op::UserTurn { items, .. } => assert_eq!(
items,
vec![UserInput::Text {
text: "!echo hello".to_string(),
text_elements: Vec::new(),
}]
),
other => panic!("expected Op::UserTurn for BTW shell-like input, got {other:?}"),
}
}
#[tokio::test]
async fn reasoning_selection_in_plan_mode_opens_scope_prompt_event() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.1-codex-max")).await;
@@ -6545,6 +6555,83 @@ async fn slash_fork_requests_current_fork() {
assert_matches!(rx.try_recv(), Ok(AppEvent::ForkCurrentSession));
}
fn assert_btw_rename_rejected(
rx: &mut tokio::sync::mpsc::UnboundedReceiver<AppEvent>,
op_rx: &mut tokio::sync::mpsc::UnboundedReceiver<Op>,
) {
let event = rx.try_recv().expect("expected BTW rename error");
match event {
AppEvent::InsertHistoryCell(cell) => {
let rendered = lines_to_single_string(&cell.display_lines(80));
assert!(
rendered.contains("BTW threads are ephemeral and cannot be renamed."),
"expected BTW rename error, got {rendered:?}"
);
}
other => panic!("expected InsertHistoryCell error, got {other:?}"),
}
assert!(rx.try_recv().is_err(), "expected no follow-up events");
assert!(op_rx.try_recv().is_err(), "expected no rename op");
}
#[tokio::test]
async fn slash_rename_is_rejected_for_btw_threads() {
let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(None).await;
chat.set_thread_rename_block_message(
"BTW threads are ephemeral and cannot be renamed.".to_string(),
);
chat.dispatch_command(SlashCommand::Rename);
assert_btw_rename_rejected(&mut rx, &mut op_rx);
}
#[tokio::test]
async fn slash_rename_with_args_is_rejected_for_btw_threads() {
let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(None).await;
chat.set_thread_rename_block_message(
"BTW threads are ephemeral and cannot be renamed.".to_string(),
);
chat.dispatch_command_with_args(SlashCommand::Rename, "investigate".to_string(), Vec::new());
assert_btw_rename_rejected(&mut rx, &mut op_rx);
}
#[tokio::test]
async fn slash_btw_requests_forked_side_question_while_task_running() {
let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(None).await;
let parent_thread_id = ThreadId::new();
chat.thread_id = Some(parent_thread_id);
chat.on_task_started();
chat.bottom_pane.set_composer_text(
"/btw explore the codebase".to_string(),
Vec::new(),
Vec::new(),
);
chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
assert_matches!(
rx.try_recv(),
Ok(AppEvent::StartBtw {
parent_thread_id: emitted_parent_thread_id,
user_message,
}) if emitted_parent_thread_id == parent_thread_id
&& user_message
== UserMessage {
text: "explore the codebase".to_string(),
local_images: Vec::new(),
remote_image_urls: Vec::new(),
text_elements: Vec::new(),
mention_bindings: Vec::new(),
}
);
assert!(
op_rx.try_recv().is_err(),
"expected no op on the parent thread"
);
assert_eq!(chat.bottom_pane.composer_text(), "");
}
#[tokio::test]
async fn slash_rollout_displays_current_path() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None).await;
@@ -11782,6 +11869,56 @@ async fn status_line_fast_mode_footer_snapshot() {
assert_snapshot!("status_line_fast_mode_footer", terminal.backend());
}
#[tokio::test]
async fn btw_footer_override_snapshot() {
use ratatui::Terminal;
use ratatui::backend::TestBackend;
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await;
chat.show_welcome_banner = false;
chat.set_thread_footer_hint_override(Some(vec![(
"BTW".to_string(),
"from main thread · Esc to return".to_string(),
)]));
let width = 80;
let height = chat.desired_height(width);
let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("create terminal");
terminal
.draw(|f| chat.render(f.area(), f.buffer_mut()))
.expect("draw BTW footer");
assert_snapshot!("btw_footer_override", terminal.backend());
}
#[tokio::test]
async fn clearing_thread_footer_override_preserves_general_footer_hint_snapshot() {
use ratatui::Terminal;
use ratatui::backend::TestBackend;
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await;
chat.show_welcome_banner = false;
chat.set_footer_hint_override(Some(vec![(
"Save and close external editor to continue.".to_string(),
String::new(),
)]));
chat.set_thread_footer_hint_override(Some(vec![(
"BTW".to_string(),
"from main thread · Esc to return".to_string(),
)]));
chat.set_thread_footer_hint_override(/*items*/ None);
let width = 80;
let height = chat.desired_height(width);
let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("create terminal");
terminal
.draw(|f| chat.render(f.area(), f.buffer_mut()))
.expect("draw preserved footer hint");
assert_snapshot!(
"clearing_thread_footer_override_preserves_general_footer_hint",
terminal.backend()
);
}
#[tokio::test]
async fn status_line_model_with_reasoning_includes_fast_for_gpt54_only() {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.4")).await;
+5 -1
View File
@@ -32,6 +32,7 @@ pub enum SlashCommand {
Plan,
Collab,
Agent,
Btw,
// Undo,
Diff,
Copy,
@@ -102,6 +103,7 @@ impl SlashCommand {
SlashCommand::Plan => "switch to Plan mode",
SlashCommand::Collab => "change collaboration mode (experimental)",
SlashCommand::Agent | SlashCommand::MultiAgents => "switch the active agent thread",
SlashCommand::Btw => "ask a side question in a forked subagent",
SlashCommand::Approvals => "choose what Codex is allowed to do",
SlashCommand::Permissions => "choose what Codex is allowed to do",
SlashCommand::ElevateSandbox => "set up elevated agent sandbox",
@@ -132,6 +134,7 @@ impl SlashCommand {
| SlashCommand::Rename
| SlashCommand::Plan
| SlashCommand::Fast
| SlashCommand::Btw
| SlashCommand::SandboxReadRoot
)
}
@@ -173,7 +176,8 @@ impl SlashCommand {
| SlashCommand::Plugins
| SlashCommand::Feedback
| SlashCommand::Quit
| SlashCommand::Exit => true,
| SlashCommand::Exit
| SlashCommand::Btw => true,
SlashCommand::Rollout => true,
SlashCommand::TestApproval => true,
SlashCommand::Realtime => true,
+21 -9
View File
@@ -258,17 +258,14 @@ pub struct Tui {
}
impl Tui {
pub fn new(terminal: Terminal) -> Self {
fn from_terminal(
terminal: Terminal,
enhanced_keys_supported: bool,
notification_backend: Option<DesktopNotificationBackend>,
) -> Self {
let (draw_tx, _) = broadcast::channel(1);
let frame_requester = FrameRequester::new(draw_tx.clone());
// Detect keyboard enhancement support before any EventStream is created so the
// crossterm poller can acquire its lock without contention.
let enhanced_keys_supported = supports_keyboard_enhancement().unwrap_or(false);
// Cache this to avoid contention with the event reader.
supports_color::on_cached(supports_color::Stream::Stdout);
let _ = crate::terminal_palette::default_colors();
Self {
frame_requester,
draw_tx,
@@ -281,11 +278,26 @@ impl Tui {
alt_screen_active: Arc::new(AtomicBool::new(false)),
terminal_focused: Arc::new(AtomicBool::new(true)),
enhanced_keys_supported,
notification_backend: Some(detect_backend(NotificationMethod::default())),
notification_backend,
alt_screen_enabled: true,
}
}
pub fn new(terminal: Terminal) -> Self {
// Detect keyboard enhancement support before any EventStream is created so the
// crossterm poller can acquire its lock without contention.
let enhanced_keys_supported = supports_keyboard_enhancement().unwrap_or(false);
// Cache this to avoid contention with the event reader.
supports_color::on_cached(supports_color::Stream::Stdout);
let _ = crate::terminal_palette::default_colors();
Self::from_terminal(
terminal,
enhanced_keys_supported,
Some(detect_backend(NotificationMethod::default())),
)
}
/// Set whether alternate screen is enabled. When false, enter_alt_screen() becomes a no-op.
pub fn set_alt_screen_enabled(&mut self, enabled: bool) {
self.alt_screen_enabled = enabled;
+1
View File
@@ -8,6 +8,7 @@ Use /skills to list available skills or ask Codex to use one.
Use /status to see the current model, approvals, and token usage.
Use /statusline to configure which items appear in the status line.
Use /fork to branch the current chat into a new thread.
Use /btw to ask a side question in a temporary fork without polluting the main thread.
Use /init to create an AGENTS.md with project-specific guidance.
Use /mcp to list configured MCP tools.
Run `codex app` to open Codex Desktop (it installs on macOS if needed).
+48 -5
View File
@@ -141,11 +141,13 @@ use uuid::Uuid;
mod agent_navigation;
mod app_server_adapter;
mod app_server_requests;
mod btw;
mod pending_interactive_replay;
use self::agent_navigation::AgentNavigationDirection;
use self::agent_navigation::AgentNavigationState;
use self::app_server_requests::PendingAppServerRequests;
use self::btw::BtwThreadState;
use self::pending_interactive_replay::PendingInteractiveReplayState;
const EXTERNAL_EDITOR_HINT: &str = "Save and close external editor to continue.";
@@ -942,6 +944,7 @@ pub(crate) struct App {
thread_event_channels: HashMap<ThreadId, ThreadEventChannel>,
thread_event_listener_tasks: HashMap<ThreadId, JoinHandle<()>>,
agent_navigation: AgentNavigationState,
btw_threads: HashMap<ThreadId, BtwThreadState>,
active_thread_id: Option<ThreadId>,
active_thread_rx: Option<mpsc::Receiver<ThreadBufferedEvent>>,
primary_thread_id: Option<ThreadId>,
@@ -1615,6 +1618,7 @@ impl App {
.agent_navigation
.active_agent_label(self.current_displayed_thread_id(), self.primary_thread_id);
self.chat_widget.set_active_agent_label(label);
self.sync_btw_thread_ui();
}
async fn thread_cwd(&self, thread_id: ThreadId) -> Option<PathBuf> {
@@ -2500,6 +2504,9 @@ impl App {
async fn open_agent_picker(&mut self) {
let thread_ids: Vec<ThreadId> = self.thread_event_channels.keys().cloned().collect();
for thread_id in thread_ids {
if self.btw_threads.contains_key(&thread_id) {
continue;
}
if self.thread_event_listener_tasks.contains_key(&thread_id) {
if self.agent_navigation.get(&thread_id).is_none() {
self.upsert_agent_picker_thread(
@@ -2640,6 +2647,9 @@ impl App {
let init = self.chatwidget_init_for_forked_or_resumed_thread(tui, self.config.clone());
self.chat_widget = ChatWidget::new_with_app_event(init);
let next_fork_banner_parent_label = self.take_next_btw_fork_banner_parent_label(thread_id);
self.chat_widget
.set_next_fork_banner_parent_label(next_fork_banner_parent_label);
self.sync_active_agent_label();
self.reset_for_thread_switch(tui)?;
@@ -2672,6 +2682,7 @@ impl App {
self.abort_all_thread_event_listeners();
self.thread_event_channels.clear();
self.agent_navigation.clear();
self.btw_threads.clear();
self.active_thread_id = None;
self.active_thread_rx = None;
self.primary_thread_id = None;
@@ -3091,6 +3102,7 @@ impl App {
thread_event_channels: HashMap::new(),
thread_event_listener_tasks: HashMap::new(),
agent_navigation: AgentNavigationState::default(),
btw_threads: HashMap::new(),
active_thread_id: None,
active_thread_rx: None,
primary_thread_id: None,
@@ -4526,7 +4538,16 @@ impl App {
self.open_agent_picker().await;
}
AppEvent::SelectAgentThread(thread_id) => {
self.select_agent_thread(tui, app_server, thread_id).await?;
self.select_agent_thread_and_discard_btw_chain(tui, app_server, thread_id)
.await?;
}
AppEvent::StartBtw {
parent_thread_id,
user_message,
} => {
return self
.handle_start_btw(tui, app_server, parent_thread_id, user_message)
.await;
}
AppEvent::OpenSkillsList => {
self.chat_widget.open_skills_list();
@@ -4907,7 +4928,7 @@ impl App {
self.active_non_primary_shutdown_target(notification)
{
self.mark_agent_picker_thread_closed(closed_thread_id);
self.select_agent_thread(tui, app_server, primary_thread_id)
self.select_agent_thread_and_discard_btw_chain(tui, app_server, primary_thread_id)
.await?;
if self.active_thread_id == Some(primary_thread_id) {
self.chat_widget.add_info_message(
@@ -5089,7 +5110,9 @@ impl App {
self.current_displayed_thread_id(),
AgentNavigationDirection::Previous,
) {
let _ = self.select_agent_thread(tui, app_server, thread_id).await;
let _ = self
.select_agent_thread_and_discard_btw_chain(tui, app_server, thread_id)
.await;
}
return;
}
@@ -5104,7 +5127,9 @@ impl App {
self.current_displayed_thread_id(),
AgentNavigationDirection::Next,
) {
let _ = self.select_agent_thread(tui, app_server, thread_id).await;
let _ = self
.select_agent_thread_and_discard_btw_chain(tui, app_server, thread_id)
.await;
}
return;
}
@@ -5164,7 +5189,23 @@ impl App {
kind: KeyEventKind::Press | KeyEventKind::Repeat,
..
} => {
if self.chat_widget.is_normal_backtrack_mode()
if self.maybe_return_from_btw(tui, app_server).await {
} else if self.chat_widget.is_normal_backtrack_mode()
&& self.chat_widget.composer_is_empty()
{
self.handle_backtrack_esc_key(tui);
} else {
self.chat_widget.handle_key_event(key_event);
}
}
KeyEvent {
code: KeyCode::Char('c'),
modifiers: crossterm::event::KeyModifiers::CONTROL,
kind: KeyEventKind::Press | KeyEventKind::Repeat,
..
} => {
if self.maybe_return_from_btw(tui, app_server).await {
} else if self.chat_widget.is_normal_backtrack_mode()
&& self.chat_widget.composer_is_empty()
{
self.handle_backtrack_esc_key(tui);
@@ -7817,6 +7858,7 @@ guardian_approval = true
thread_event_channels: HashMap::new(),
thread_event_listener_tasks: HashMap::new(),
agent_navigation: AgentNavigationState::default(),
btw_threads: HashMap::new(),
active_thread_id: None,
active_thread_rx: None,
primary_thread_id: None,
@@ -7868,6 +7910,7 @@ guardian_approval = true
thread_event_channels: HashMap::new(),
thread_event_listener_tasks: HashMap::new(),
agent_navigation: AgentNavigationState::default(),
btw_threads: HashMap::new(),
active_thread_id: None,
active_thread_rx: None,
primary_thread_id: None,
+238
View File
@@ -0,0 +1,238 @@
use super::*;
const BTW_RENAME_BLOCK_MESSAGE: &str = "BTW threads are ephemeral and cannot be renamed.";
#[derive(Clone, Debug)]
pub(super) struct BtwThreadState {
/// Thread to return to when the current BTW thread is dismissed.
pub(super) parent_thread_id: ThreadId,
/// Pretty parent label for the next synthetic fork banner, consumed on first attach.
pub(super) next_fork_banner_parent_label: Option<String>,
}
impl App {
pub(super) fn sync_btw_thread_ui(&mut self) {
let clear_btw_ui = |chat_widget: &mut crate::chatwidget::ChatWidget| {
chat_widget.set_thread_footer_hint_override(/*items*/ None);
chat_widget.clear_thread_rename_block();
};
let Some(active_thread_id) = self.current_displayed_thread_id() else {
clear_btw_ui(&mut self.chat_widget);
return;
};
let Some(mut parent_thread_id) = self
.btw_threads
.get(&active_thread_id)
.map(|state| state.parent_thread_id)
else {
clear_btw_ui(&mut self.chat_widget);
return;
};
self.chat_widget
.set_thread_rename_block_message(BTW_RENAME_BLOCK_MESSAGE);
let mut depth = 1usize;
while let Some(next_parent_thread_id) = self
.btw_threads
.get(&parent_thread_id)
.map(|state| state.parent_thread_id)
{
depth += 1;
parent_thread_id = next_parent_thread_id;
}
let repeated_prefix = "BTW from ".repeat(depth.saturating_sub(1));
let label = if self.primary_thread_id == Some(parent_thread_id) {
format!("from {repeated_prefix}main thread · Esc to return")
} else {
let parent_label = self.thread_label(parent_thread_id);
format!("from {repeated_prefix}parent thread ({parent_label}) · Esc to return")
};
self.chat_widget
.set_thread_footer_hint_override(Some(vec![("BTW".to_string(), label)]));
}
pub(super) fn active_btw_parent_thread_id(&self) -> Option<ThreadId> {
self.current_displayed_thread_id()
.and_then(|thread_id| self.btw_threads.get(&thread_id))
.map(|state| state.parent_thread_id)
}
pub(super) async fn maybe_return_from_btw(
&mut self,
tui: &mut tui::Tui,
app_server: &mut AppServerSession,
) -> bool {
if self.overlay.is_none()
&& self.chat_widget.no_modal_or_popup_active()
&& self.chat_widget.composer_is_empty()
&& let Some(parent_thread_id) = self.active_btw_parent_thread_id()
{
let _ = self
.select_agent_thread_and_discard_btw_chain(tui, app_server, parent_thread_id)
.await;
true
} else {
false
}
}
pub(super) fn btw_threads_to_discard_after_switch(
&self,
target_thread_id: ThreadId,
) -> Vec<ThreadId> {
let Some(mut btw_thread_id) = self.current_displayed_thread_id() else {
return Vec::new();
};
if !self.btw_threads.contains_key(&btw_thread_id)
|| self
.btw_threads
.get(&target_thread_id)
.map(|state| state.parent_thread_id)
== Some(btw_thread_id)
{
return Vec::new();
}
let mut btw_threads_to_discard = Vec::new();
loop {
btw_threads_to_discard.push(btw_thread_id);
let Some(parent_thread_id) = self
.btw_threads
.get(&btw_thread_id)
.map(|state| state.parent_thread_id)
else {
break;
};
if parent_thread_id == target_thread_id
|| !self.btw_threads.contains_key(&parent_thread_id)
{
break;
}
btw_thread_id = parent_thread_id;
}
btw_threads_to_discard
}
pub(super) fn take_next_btw_fork_banner_parent_label(
&mut self,
thread_id: ThreadId,
) -> Option<String> {
self.btw_threads
.get_mut(&thread_id)
.and_then(|state| state.next_fork_banner_parent_label.take())
}
pub(super) async fn discard_btw_thread(
&mut self,
app_server: &mut AppServerSession,
thread_id: ThreadId,
) {
if let Err(err) = app_server.thread_unsubscribe(thread_id).await {
tracing::warn!("failed to unsubscribe BTW thread {thread_id}: {err}");
}
self.abort_thread_event_listener(thread_id);
self.thread_event_channels.remove(&thread_id);
self.btw_threads.remove(&thread_id);
if self.active_thread_id == Some(thread_id) {
self.clear_active_thread().await;
} else {
self.refresh_pending_thread_approvals().await;
}
self.sync_active_agent_label();
}
async fn fork_banner_parent_label(&self, parent_thread_id: ThreadId) -> Option<String> {
if self.chat_widget.thread_id() == Some(parent_thread_id) {
return self
.chat_widget
.thread_name()
.filter(|name| !name.trim().is_empty());
}
let channel = self.thread_event_channels.get(&parent_thread_id)?;
let store = channel.store.lock().await;
store
.session
.as_ref()
.and_then(|session| session.thread_name.clone())
.filter(|name| !name.trim().is_empty())
}
pub(super) async fn select_agent_thread_and_discard_btw_chain(
&mut self,
tui: &mut tui::Tui,
app_server: &mut AppServerSession,
thread_id: ThreadId,
) -> Result<()> {
let btw_threads_to_discard = self.btw_threads_to_discard_after_switch(thread_id);
self.select_agent_thread(tui, app_server, thread_id).await?;
if self.active_thread_id == Some(thread_id) {
for btw_thread_id in btw_threads_to_discard {
self.discard_btw_thread(app_server, btw_thread_id).await;
}
}
Ok(())
}
pub(super) async fn handle_start_btw(
&mut self,
tui: &mut tui::Tui,
app_server: &mut AppServerSession,
parent_thread_id: ThreadId,
user_message: crate::chatwidget::UserMessage,
) -> Result<AppRunControl> {
self.session_telemetry.counter(
"codex.thread.btw",
/*inc*/ 1,
&[("source", "slash_command")],
);
self.refresh_in_memory_config_from_disk_best_effort("starting a BTW subagent")
.await;
let mut fork_config = self.config.clone();
fork_config.ephemeral = true;
match app_server.fork_thread(fork_config, parent_thread_id).await {
Ok(forked) => {
let child_thread_id = forked.session.thread_id;
let next_fork_banner_parent_label =
self.fork_banner_parent_label(parent_thread_id).await;
let channel = self.ensure_thread_channel(child_thread_id);
{
let mut store = channel.store.lock().await;
store.set_session(forked.session, forked.turns);
}
self.btw_threads.insert(
child_thread_id,
BtwThreadState {
parent_thread_id,
next_fork_banner_parent_label,
},
);
if let Err(err) = self
.select_agent_thread_and_discard_btw_chain(tui, app_server, child_thread_id)
.await
{
self.discard_btw_thread(app_server, child_thread_id).await;
return Err(err);
}
if self.active_thread_id == Some(child_thread_id) {
let _ = self
.chat_widget
.submit_user_message_as_plain_user_turn(user_message);
} else {
self.discard_btw_thread(app_server, child_thread_id).await;
self.chat_widget.add_error_message(format!(
"Failed to switch into BTW thread {child_thread_id}."
));
}
}
Err(err) => {
self.chat_widget.add_error_message(format!(
"Failed to fork BTW thread from {parent_thread_id}: {err}"
));
}
}
Ok(AppRunControl::Continue)
}
}
+7
View File
@@ -28,6 +28,7 @@ use codex_utils_approval_presets::ApprovalPreset;
use crate::bottom_pane::ApprovalRequest;
use crate::bottom_pane::StatusLineItem;
use crate::chatwidget::UserMessage;
use crate::history_cell::HistoryCell;
use codex_core::config::types::ApprovalsReviewer;
@@ -82,6 +83,12 @@ pub(crate) enum AppEvent {
/// Switch the active thread to the selected agent.
SelectAgentThread(ThreadId),
/// Fork the current thread into a transient BTW child and submit a side-question there.
StartBtw {
parent_thread_id: ThreadId,
user_message: UserMessage,
},
/// Submit an op to the specified thread, regardless of current focus.
SubmitThreadOp {
thread_id: ThreadId,
@@ -383,6 +383,7 @@ pub(crate) struct ChatComposer {
custom_prompts: Vec<CustomPrompt>,
footer_mode: FooterMode,
footer_hint_override: Option<Vec<(String, String)>>,
thread_footer_hint_override: Option<Vec<(String, String)>>,
remote_image_urls: Vec<String>,
/// Tracks keyboard selection for the remote-image rows so Up/Down + Delete/Backspace
/// can highlight and remove remote attachments from the composer UI.
@@ -510,6 +511,7 @@ impl ChatComposer {
custom_prompts: Vec::new(),
footer_mode: FooterMode::ComposerEmpty,
footer_hint_override: None,
thread_footer_hint_override: None,
remote_image_urls: Vec::new(),
selected_remote_image_index: None,
footer_flash: None,
@@ -957,6 +959,14 @@ impl ChatComposer {
self.footer_hint_override = items;
}
/// Override the footer hint with thread-scoped UI, such as ephemeral BTW navigation state.
///
/// This lives below general footer overrides so temporary flows like external editor launch
/// or realtime status can still take precedence.
pub(crate) fn set_thread_footer_hint_override(&mut self, items: Option<Vec<(String, String)>>) {
self.thread_footer_hint_override = items;
}
pub(crate) fn set_remote_image_urls(&mut self, urls: Vec<String>) {
self.remote_image_urls = urls;
self.selected_remote_image_index = None;
@@ -4305,12 +4315,16 @@ impl ChatComposer {
} else {
self.collaboration_mode_indicator
};
let active_footer_hint_override = self
.footer_hint_override
.as_ref()
.or(self.thread_footer_hint_override.as_ref());
let mut left_width = if self.footer_flash_visible() {
self.footer_flash
.as_ref()
.map(|flash| flash.line.width() as u16)
.unwrap_or(0)
} else if let Some(items) = self.footer_hint_override.as_ref() {
} else if let Some(items) = active_footer_hint_override {
footer_hint_items_width(items)
} else if status_line_active {
truncated_status_line
@@ -4359,7 +4373,7 @@ impl ChatComposer {
let can_show_left_and_context =
can_show_left_with_context(hint_rect, left_width, right_width);
let has_override =
self.footer_flash_visible() || self.footer_hint_override.is_some();
self.footer_flash_visible() || active_footer_hint_override.is_some();
let single_line_layout = if has_override || status_line_active {
None
} else {
@@ -4435,7 +4449,7 @@ impl ChatComposer {
if let Some(flash) = self.footer_flash.as_ref() {
flash.line.render(inset_footer_hint_area(hint_rect), buf);
}
} else if let Some(items) = self.footer_hint_override.as_ref() {
} else if let Some(items) = active_footer_hint_override {
render_footer_hint_items(hint_rect, buf, items);
} else if status_line_active {
if let Some(line) = truncated_status_line {
@@ -710,9 +710,18 @@ pub(crate) fn footer_hint_items_width(items: &[(String, String)]) -> u16 {
fn footer_hint_items_line(items: &[(String, String)]) -> Line<'static> {
let mut spans = Vec::with_capacity(items.len() * 4);
for (idx, (key, label)) in items.iter().enumerate() {
let is_btw = key == "BTW";
spans.push(" ".into());
spans.push(key.clone().bold());
spans.push(format!(" {label}").into());
spans.push(if is_btw {
key.clone().magenta().bold()
} else {
key.clone().bold()
});
spans.push(if is_btw {
format!(" {label}").magenta().bold()
} else {
format!(" {label}").into()
});
if idx + 1 != items.len() {
spans.push(" ".into());
}
@@ -614,6 +614,11 @@ impl BottomPane {
self.request_redraw();
}
pub(crate) fn set_thread_footer_hint_override(&mut self, items: Option<Vec<(String, String)>>) {
self.composer.set_thread_footer_hint_override(items);
self.request_redraw();
}
pub(crate) fn set_remote_image_urls(&mut self, urls: Vec<String>) {
self.composer.set_remote_image_urls(urls);
self.request_redraw();
+133 -69
View File
@@ -88,7 +88,6 @@ use codex_core::config::types::ApprovalsReviewer;
use codex_core::config::types::Notifications;
use codex_core::config::types::WindowsSandboxModeToml;
use codex_core::config_loader::ConfigLayerStackOrdering;
use codex_core::find_thread_name_by_id;
use codex_core::plugins::PluginsManager;
use codex_core::project_doc::DEFAULT_PROJECT_DOC_FILENAME;
use codex_core::skills::model::SkillMetadata;
@@ -804,7 +803,10 @@ pub(crate) struct ChatWidget {
suppress_queue_autosend: bool,
thread_id: Option<ThreadId>,
thread_name: Option<String>,
thread_rename_block_message: Option<String>,
forked_from: Option<ThreadId>,
/// Pretty parent label used only for the next fork banner inserted on session configure.
next_fork_banner_parent_label: Option<String>,
frame_requester: FrameRequester,
// Whether to include the initial welcome banner on session configured
show_welcome_banner: bool,
@@ -947,6 +949,12 @@ pub(crate) struct UserMessage {
mention_bindings: Vec<MentionBinding>,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum ShellEscapePolicy {
Allow,
Disallow,
}
#[derive(Debug, Clone, PartialEq, Default)]
struct ThreadComposerState {
text: String,
@@ -1873,48 +1881,28 @@ impl ChatWidget {
self.on_session_configured(thread_session_state_to_legacy_event(session));
}
fn emit_forked_thread_event(&self, forked_from_id: ThreadId) {
let app_event_tx = self.app_event_tx.clone();
let codex_home = self.config.codex_home.clone();
tokio::spawn(async move {
let forked_from_id_text = forked_from_id.to_string();
let send_name_and_id = |name: String| {
let line: Line<'static> = vec![
"• ".dim(),
"Thread forked from ".into(),
name.cyan(),
" (".into(),
forked_from_id_text.clone().cyan(),
")".into(),
]
.into();
app_event_tx.send(AppEvent::InsertHistoryCell(Box::new(
PlainHistoryCell::new(vec![line]),
)));
};
let send_id_only = || {
let line: Line<'static> = vec![
"• ".dim(),
"Thread forked from ".into(),
forked_from_id_text.clone().cyan(),
]
.into();
app_event_tx.send(AppEvent::InsertHistoryCell(Box::new(
PlainHistoryCell::new(vec![line]),
)));
};
match find_thread_name_by_id(&codex_home, &forked_from_id).await {
Ok(Some(name)) if !name.trim().is_empty() => {
send_name_and_id(name);
}
Ok(_) => send_id_only(),
Err(err) => {
tracing::warn!("Failed to read forked thread name: {err}");
send_id_only();
}
}
});
fn emit_forked_thread_event(&mut self, forked_from_id: ThreadId) {
let line: Line<'static> = if let Some(label) = self.next_fork_banner_parent_label.take() {
vec![
"• ".dim(),
"Thread forked from ".into(),
label.cyan(),
" (".into(),
forked_from_id.to_string().cyan(),
")".into(),
]
.into()
} else {
vec![
"• ".dim(),
"Thread forked from ".into(),
forked_from_id.to_string().cyan(),
]
.into()
};
self.app_event_tx.send(AppEvent::InsertHistoryCell(Box::new(
PlainHistoryCell::new(vec![line]),
)));
}
fn on_thread_name_updated(&mut self, event: codex_protocol::protocol::ThreadNameUpdatedEvent) {
@@ -4340,7 +4328,9 @@ impl ChatWidget {
suppress_queue_autosend: false,
thread_id: None,
thread_name: None,
thread_rename_block_message: None,
forked_from: None,
next_fork_banner_parent_label: None,
queued_user_messages: VecDeque::new(),
rejected_steers_queue: VecDeque::new(),
pending_steers: VecDeque::new(),
@@ -4776,6 +4766,9 @@ impl ChatWidget {
}
self.open_collaboration_modes_popup();
}
SlashCommand::Btw => {
self.add_error_message("Usage: /btw <question>".to_string());
}
SlashCommand::Agent | SlashCommand::MultiAgents => {
self.app_event_tx.send(AppEvent::OpenAgentPicker);
}
@@ -5037,6 +5030,9 @@ impl ChatWidget {
}
}
SlashCommand::Rename if !trimmed.is_empty() => {
if !self.ensure_thread_rename_allowed() {
return;
}
self.session_telemetry
.counter("codex.thread.rename", /*inc*/ 1, &[]);
let Some((prepared_args, _prepared_elements)) = self
@@ -5060,23 +5056,9 @@ impl ChatWidget {
if self.active_mode_kind() != ModeKind::Plan {
return;
}
let Some((prepared_args, prepared_elements)) = self
.bottom_pane
.prepare_inline_args_submission(/*record_history*/ true)
else {
let Some(user_message) = self.prepare_inline_submission_user_message() else {
return;
};
let local_images = self
.bottom_pane
.take_recent_submission_images_with_placeholders();
let remote_image_urls = self.take_remote_image_urls();
let user_message = UserMessage {
text: prepared_args,
local_images,
remote_image_urls,
text_elements: prepared_elements,
mention_bindings: self.bottom_pane.take_recent_submission_mention_bindings(),
};
if self.is_session_configured() {
self.reasoning_buffer.clear();
self.full_reasoning_buffer.clear();
@@ -5086,6 +5068,21 @@ impl ChatWidget {
self.queue_user_message(user_message);
}
}
SlashCommand::Btw if !trimmed.is_empty() => {
let Some(parent_thread_id) = self.thread_id else {
self.add_error_message(
"BTW is unavailable before the session starts.".to_string(),
);
return;
};
let Some(user_message) = self.prepare_inline_submission_user_message() else {
return;
};
self.app_event_tx.send(AppEvent::StartBtw {
parent_thread_id,
user_message,
});
}
SlashCommand::Review if !trimmed.is_empty() => {
let Some((prepared_args, _prepared_elements)) = self
.bottom_pane
@@ -5119,6 +5116,9 @@ impl ChatWidget {
}
fn show_rename_prompt(&mut self) {
if !self.ensure_thread_rename_allowed() {
return;
}
let tx = self.app_event_tx.clone();
let has_name = self
.thread_name
@@ -5150,6 +5150,34 @@ impl ChatWidget {
self.bottom_pane.show_view(Box::new(view));
}
fn ensure_thread_rename_allowed(&mut self) -> bool {
match self.thread_rename_block_message.clone() {
Some(message) => {
self.add_error_message(message);
false
}
None => true,
}
}
fn prepare_inline_submission_user_message(&mut self) -> Option<UserMessage> {
let (text, text_elements) = self
.bottom_pane
.prepare_inline_args_submission(/*record_history*/ true)?;
let local_images = self
.bottom_pane
.take_recent_submission_images_with_placeholders();
let remote_image_urls = self.take_remote_image_urls();
let mention_bindings = self.bottom_pane.take_recent_submission_mention_bindings();
Some(UserMessage {
text,
local_images,
remote_image_urls,
text_elements,
mention_bindings,
})
}
pub(crate) fn handle_paste(&mut self, text: String) {
self.bottom_pane.handle_paste(text);
}
@@ -5210,11 +5238,27 @@ impl ChatWidget {
}
fn submit_user_message(&mut self, user_message: UserMessage) {
let _ = self
.submit_user_message_with_shell_escape_policy(user_message, ShellEscapePolicy::Allow);
}
pub(crate) fn submit_user_message_as_plain_user_turn(
&mut self,
user_message: UserMessage,
) -> Option<AppCommand> {
self.submit_user_message_with_shell_escape_policy(user_message, ShellEscapePolicy::Disallow)
}
fn submit_user_message_with_shell_escape_policy(
&mut self,
user_message: UserMessage,
shell_escape_policy: ShellEscapePolicy,
) -> Option<AppCommand> {
if !self.is_session_configured() {
tracing::warn!("cannot submit user message before session is configured; queueing");
self.queued_user_messages.push_front(user_message);
self.refresh_pending_input_preview();
return;
return None;
}
let UserMessage {
text,
@@ -5224,7 +5268,7 @@ impl ChatWidget {
mention_bindings,
} = user_message;
if text.is_empty() && local_images.is_empty() && remote_image_urls.is_empty() {
return;
return None;
}
if (!local_images.is_empty() || !remote_image_urls.is_empty())
&& !self.current_model_supports_images()
@@ -5236,14 +5280,16 @@ impl ChatWidget {
mention_bindings,
remote_image_urls,
);
return;
return None;
}
let render_in_history = !self.agent_turn_running;
let mut items: Vec<UserInput> = Vec::new();
// Special-case: "!cmd" executes a local shell command instead of sending to the model.
if let Some(stripped) = text.strip_prefix('!') {
if shell_escape_policy == ShellEscapePolicy::Allow
&& let Some(stripped) = text.strip_prefix('!')
{
let cmd = stripped.trim();
if cmd.is_empty() {
self.app_event_tx.send(AppEvent::InsertHistoryCell(Box::new(
@@ -5252,10 +5298,11 @@ impl ChatWidget {
Some(USER_SHELL_COMMAND_HELP_HINT.to_string()),
),
)));
return;
return None;
}
self.submit_op(AppCommand::run_user_shell_command(cmd.to_string()));
return;
let app_command = AppCommand::run_user_shell_command(cmd.to_string());
self.submit_op(app_command.clone());
return Some(app_command);
}
for image_url in &remote_image_urls {
@@ -5388,7 +5435,7 @@ impl ChatWidget {
self.add_error_message(
"Thread model is unavailable. Wait for the thread to finish syncing or choose a model before sending input.".to_string(),
);
return;
return None;
}
let collaboration_mode = if self.collaboration_modes_enabled() {
self.active_collaboration_mask
@@ -5427,8 +5474,8 @@ impl ChatWidget {
personality,
);
if !self.submit_op(op) {
return;
if !self.submit_op(op.clone()) {
return None;
}
// Persist the text to cross-session message history. Mentions are
@@ -5488,6 +5535,7 @@ impl ChatWidget {
}
self.needs_final_message_separator = false;
Some(op)
}
/// Restore the blocked submission draft without losing mention resolution state.
@@ -6169,10 +6217,10 @@ impl ChatWidget {
| ServerNotification::McpServerStatusUpdated(_)
| ServerNotification::McpServerOauthLoginCompleted(_)
| ServerNotification::AppListUpdated(_)
| ServerNotification::FsChanged(_)
| ServerNotification::ContextCompacted(_)
| ServerNotification::FuzzyFileSearchSessionUpdated(_)
| ServerNotification::FuzzyFileSearchSessionCompleted(_)
| ServerNotification::FsChanged(_)
| ServerNotification::ThreadRealtimeTranscriptUpdated(_)
| ServerNotification::WindowsWorldWritableWarning(_)
| ServerNotification::WindowsSandboxSetupCompleted(_)
@@ -6920,6 +6968,22 @@ impl ChatWidget {
self.bottom_pane.set_pending_thread_approvals(threads);
}
pub(crate) fn set_thread_footer_hint_override(&mut self, items: Option<Vec<(String, String)>>) {
self.bottom_pane.set_thread_footer_hint_override(items);
}
pub(crate) fn clear_thread_rename_block(&mut self) {
self.thread_rename_block_message = None;
}
pub(crate) fn set_thread_rename_block_message(&mut self, message: impl Into<String>) {
self.thread_rename_block_message = Some(message.into());
}
pub(crate) fn set_next_fork_banner_parent_label(&mut self, label: Option<String>) {
self.next_fork_banner_parent_label = label;
}
pub(crate) fn add_diff_in_progress(&mut self) {
self.request_redraw();
}
@@ -0,0 +1,9 @@
---
source: tui_app_server/src/chatwidget/tests.rs
expression: terminal.backend()
---
" "
" "
"› Ask Codex to do anything "
" "
" BTW from main thread · Esc to return 100% context left "
@@ -0,0 +1,9 @@
---
source: tui_app_server/src/chatwidget/tests.rs
expression: terminal.backend()
---
" "
" "
"› Ask Codex to do anything "
" "
" Save and close external editor to continue. 100% context left "
@@ -2,4 +2,4 @@
source: tui_app_server/src/chatwidget/tests.rs
expression: combined
---
• Thread forked from named-thread (e9f18a88-8081-4e51-9d4e-8af5cde2d8dd)
• Thread forked from named parent (e9f18a88-8081-4e51-9d4e-8af5cde2d8dd)
+150 -14
View File
@@ -602,19 +602,11 @@ async fn replayed_user_message_with_only_local_images_does_not_render_history_ce
#[tokio::test]
async fn forked_thread_history_line_includes_name_and_id_snapshot() {
let (chat, mut rx, _op_rx) = make_chatwidget_manual(None).await;
let mut chat = chat;
let temp = tempdir().expect("tempdir");
chat.config.codex_home = temp.path().to_path_buf();
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None).await;
chat.set_next_fork_banner_parent_label(Some("named parent".to_string()));
let forked_from_id =
ThreadId::from_string("e9f18a88-8081-4e51-9d4e-8af5cde2d8dd").expect("forked id");
let session_index_entry = format!(
"{{\"id\":\"{forked_from_id}\",\"thread_name\":\"named-thread\",\"updated_at\":\"2024-01-02T00:00:00Z\"}}\n"
);
std::fs::write(temp.path().join("session_index.jsonl"), session_index_entry)
.expect("write session index");
chat.emit_forked_thread_event(forked_from_id);
let history_cell = tokio::time::timeout(std::time::Duration::from_secs(2), async {
@@ -639,10 +631,7 @@ async fn forked_thread_history_line_includes_name_and_id_snapshot() {
#[tokio::test]
async fn forked_thread_history_line_without_name_shows_id_once_snapshot() {
let (chat, mut rx, _op_rx) = make_chatwidget_manual(None).await;
let mut chat = chat;
let temp = tempdir().expect("tempdir");
chat.config.codex_home = temp.path().to_path_buf();
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None).await;
let forked_from_id =
ThreadId::from_string("019c2d47-4935-7423-a190-05691f566092").expect("forked id");
@@ -2071,7 +2060,9 @@ async fn make_chatwidget_manual(
suppress_queue_autosend: false,
thread_id: None,
thread_name: None,
thread_rename_block_message: None,
forked_from: None,
next_fork_banner_parent_label: None,
frame_requester: FrameRequester::test_dummy(),
show_welcome_banner: true,
startup_tooltip_override: None,
@@ -7186,6 +7177,101 @@ async fn slash_fork_requests_current_fork() {
assert_matches!(rx.try_recv(), Ok(AppEvent::ForkCurrentSession));
}
fn assert_btw_rename_rejected(
rx: &mut tokio::sync::mpsc::UnboundedReceiver<AppEvent>,
op_rx: &mut tokio::sync::mpsc::UnboundedReceiver<Op>,
) {
let event = rx.try_recv().expect("expected BTW rename error");
match event {
AppEvent::InsertHistoryCell(cell) => {
let rendered = lines_to_single_string(&cell.display_lines(80));
assert!(
rendered.contains("BTW threads are ephemeral and cannot be renamed."),
"expected BTW rename error, got {rendered:?}"
);
}
other => panic!("expected InsertHistoryCell error, got {other:?}"),
}
assert!(rx.try_recv().is_err(), "expected no follow-up events");
assert!(op_rx.try_recv().is_err(), "expected no rename op");
}
#[tokio::test]
async fn slash_rename_is_rejected_for_btw_threads() {
let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(None).await;
chat.set_thread_rename_block_message(
"BTW threads are ephemeral and cannot be renamed.".to_string(),
);
chat.dispatch_command(SlashCommand::Rename);
assert_btw_rename_rejected(&mut rx, &mut op_rx);
}
#[tokio::test]
async fn slash_rename_with_args_is_rejected_for_btw_threads() {
let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(None).await;
chat.set_thread_rename_block_message(
"BTW threads are ephemeral and cannot be renamed.".to_string(),
);
chat.dispatch_command_with_args(SlashCommand::Rename, "investigate".to_string(), Vec::new());
assert_btw_rename_rejected(&mut rx, &mut op_rx);
}
#[tokio::test]
async fn submit_user_message_as_plain_user_turn_does_not_run_shell_commands() {
let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(None).await;
chat.thread_id = Some(ThreadId::new());
chat.submit_user_message_as_plain_user_turn("!echo hello".into());
match next_submit_op(&mut op_rx) {
Op::UserTurn { items, .. } => assert_eq!(
items,
vec![UserInput::Text {
text: "!echo hello".to_string(),
text_elements: Vec::new(),
}]
),
other => panic!("expected Op::UserTurn for BTW shell-like input, got {other:?}"),
}
}
#[tokio::test]
async fn slash_btw_requests_forked_side_question_while_task_running() {
let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(None).await;
let parent_thread_id = ThreadId::new();
chat.thread_id = Some(parent_thread_id);
chat.on_task_started();
chat.bottom_pane.set_composer_text(
"/btw explore the codebase".to_string(),
Vec::new(),
Vec::new(),
);
chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
assert_matches!(
rx.try_recv(),
Ok(AppEvent::StartBtw {
parent_thread_id: emitted_parent_thread_id,
user_message,
}) if emitted_parent_thread_id == parent_thread_id
&& user_message
== UserMessage {
text: "explore the codebase".to_string(),
local_images: Vec::new(),
remote_image_urls: Vec::new(),
text_elements: Vec::new(),
mention_bindings: Vec::new(),
}
);
assert!(
op_rx.try_recv().is_err(),
"expected no op on the parent thread"
);
}
#[tokio::test]
async fn slash_rollout_displays_current_path() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None).await;
@@ -12195,6 +12281,56 @@ async fn status_line_fast_mode_footer_snapshot() {
assert_snapshot!("status_line_fast_mode_footer", terminal.backend());
}
#[tokio::test]
async fn btw_footer_override_snapshot() {
use ratatui::Terminal;
use ratatui::backend::TestBackend;
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await;
chat.show_welcome_banner = false;
chat.set_thread_footer_hint_override(Some(vec![(
"BTW".to_string(),
"from main thread · Esc to return".to_string(),
)]));
let width = 80;
let height = chat.desired_height(width);
let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("create terminal");
terminal
.draw(|f| chat.render(f.area(), f.buffer_mut()))
.expect("draw BTW footer");
assert_snapshot!("btw_footer_override", terminal.backend());
}
#[tokio::test]
async fn clearing_thread_footer_override_preserves_general_footer_hint_snapshot() {
use ratatui::Terminal;
use ratatui::backend::TestBackend;
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await;
chat.show_welcome_banner = false;
chat.set_footer_hint_override(Some(vec![(
"Save and close external editor to continue.".to_string(),
String::new(),
)]));
chat.set_thread_footer_hint_override(Some(vec![(
"BTW".to_string(),
"from main thread · Esc to return".to_string(),
)]));
chat.set_thread_footer_hint_override(/*items*/ None);
let width = 80;
let height = chat.desired_height(width);
let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("create terminal");
terminal
.draw(|f| chat.render(f.area(), f.buffer_mut()))
.expect("draw preserved footer hint");
assert_snapshot!(
"clearing_thread_footer_override_preserves_general_footer_hint",
terminal.backend()
);
}
#[tokio::test]
async fn status_line_model_with_reasoning_includes_fast_for_gpt54_only() {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.4")).await;
+5 -1
View File
@@ -32,6 +32,7 @@ pub enum SlashCommand {
Plan,
Collab,
Agent,
Btw,
// Undo,
Diff,
Copy,
@@ -100,6 +101,7 @@ impl SlashCommand {
SlashCommand::Plan => "switch to Plan mode",
SlashCommand::Collab => "change collaboration mode (experimental)",
SlashCommand::Agent | SlashCommand::MultiAgents => "switch the active agent thread",
SlashCommand::Btw => "ask a side question in a forked subagent",
SlashCommand::Approvals => "choose what Codex is allowed to do",
SlashCommand::Permissions => "choose what Codex is allowed to do",
SlashCommand::ElevateSandbox => "set up elevated agent sandbox",
@@ -130,6 +132,7 @@ impl SlashCommand {
| SlashCommand::Rename
| SlashCommand::Plan
| SlashCommand::Fast
| SlashCommand::Btw
| SlashCommand::SandboxReadRoot
)
}
@@ -171,7 +174,8 @@ impl SlashCommand {
| SlashCommand::Plugins
| SlashCommand::Feedback
| SlashCommand::Quit
| SlashCommand::Exit => true,
| SlashCommand::Exit
| SlashCommand::Btw => true,
SlashCommand::Rollout => true,
SlashCommand::TestApproval => true,
SlashCommand::Realtime => true,
+1
View File
@@ -8,6 +8,7 @@ Use /skills to list available skills or ask Codex to use one.
Use /status to see the current model, approvals, and token usage.
Use /statusline to configure which items appear in the status line.
Use /fork to branch the current chat into a new thread.
Use /btw to ask a side question in a temporary fork without polluting the main thread.
Use /init to create an AGENTS.md with project-specific guidance.
Use /mcp to list configured MCP tools.
Run `codex app` to open Codex Desktop (it installs on macOS if needed).