Add host cycling and saved defaults for new TUI conversations (#59007)

## What changed

- With multi-backend support enabled, show the current host before the first submission and use `leader b` to cycle through available connections. Expose the shortcut as `tui.keymap.global.change_host`.
- Preserve the conversation name and composer draft, including cursor position, attachments, pending pastes, and literal versus shell-command interpretation of `!`.
- Save explicit host choices in user-only `tui.default_hosts`, scoped to the local project and user identity. Use the saved host for new conversations, falling back to the first available connection when it is unavailable.
- Prepare the destination and check directory trust before replacing the current conversation. Block switching during voice calls and active turns, and remove replaced blank conversations from the session overview.

## Testing

Add coverage for shortcut visibility and remapping, draft and name preservation, project/user preference isolation, unavailable-host fallback, destination trust and startup failures, and voice-call guards.

GitOrigin-RevId: def7b088951336bec8fe3962954fba9b861f91c6
This commit is contained in:
Benjamin Carlsson
2026-11-02 23:19:03 +00:00
committed by copyberry
parent 857415f7f2
commit 26f73fba8f
49 changed files with 1273 additions and 118 deletions
@@ -260,6 +260,7 @@ impl ChatWidget {
suppress_initial_user_message_submit: false,
pending_notification: None,
quit_shortcut_expires_at: None,
new_backend_label: None,
quick_dial_menu: false,
quick_dial_menu_key_guard: None,
quit_shortcut_key: None,
+34 -8
View File
@@ -7,6 +7,7 @@ use codex_protocol::models::local_image_label_text;
use crate::bottom_pane::ComposerDraftSnapshot;
use crate::bottom_pane::KillBufferSnapshot;
use crate::bottom_pane::MentionUsage;
use crate::bottom_pane::ShellPrefixHandling;
use super::user_messages::remap_colliding_paste_placeholders;
use super::*;
@@ -24,6 +25,15 @@ impl ChatWidget {
self.bottom_pane.restore_kill_buffer_snapshot(snapshot);
}
pub(crate) fn composer_draft_snapshot(&mut self) -> ComposerDraftSnapshot {
self.bottom_pane.flush_pending_composer_input();
let mut draft = self.bottom_pane.composer_draft_snapshot();
// This snapshot comes from an active host, where disabled shell commands
// also mean a leading bang was entered literally.
draft.shell_mode = Some(draft.shell_mode.unwrap_or(false));
draft
}
/// Restore the exact draft entered before the fully initialized composer became available.
pub(crate) fn restore_startup_draft(&mut self, draft: ComposerDraftSnapshot) {
self.bottom_pane
@@ -79,20 +89,23 @@ impl ChatWidget {
.saturating_sub(original_end)
});
pending_pastes.extend(startup_pending_pastes);
self.restore_composer_state(Self::composer_state_from_user_message(
merge_user_messages(vec![existing_message, startup_message]),
pending_pastes,
));
self.restore_composer_state_with_shell_mode(
Self::composer_state_from_user_message(
merge_user_messages(vec![existing_message, startup_message]),
pending_pastes,
),
existing_draft.shell_mode,
);
startup_offset
.saturating_add(draft.cursor)
.saturating_add(cursor_adjustment)
} else if existing_has_content || !startup_has_content {
existing_cursor
} else {
self.restore_composer_state(Self::composer_state_from_user_message(
startup_message,
draft.pending_pastes,
));
self.restore_composer_state_with_shell_mode(
Self::composer_state_from_user_message(startup_message, draft.pending_pastes),
draft.shell_mode,
);
draft.cursor
};
self.bottom_pane.set_composer_cursor(cursor);
@@ -564,6 +577,14 @@ impl ChatWidget {
}
pub(super) fn restore_composer_state(&mut self, composer: ThreadComposerState) {
self.restore_composer_state_with_shell_mode(composer, None);
}
fn restore_composer_state_with_shell_mode(
&mut self,
composer: ThreadComposerState,
shell_mode: Option<bool>,
) {
let ThreadComposerState {
text,
local_images,
@@ -579,6 +600,11 @@ impl ChatWidget {
text_elements,
local_image_paths,
mention_bindings,
if shell_mode == Some(false) {
ShellPrefixHandling::Literal
} else {
ShellPrefixHandling::Interpret
},
);
self.bottom_pane.set_composer_pending_pastes(pending_pastes);
}
+44 -1
View File
@@ -75,7 +75,12 @@ impl ChatWidget {
}
pub(crate) fn keymap_contexts(&self) -> crate::keymap::KeymapContextSet {
self.bottom_pane.keymap_contexts()
let contexts = self.bottom_pane.keymap_contexts();
if self.visible_new_backend_control().is_some() {
contexts.with_backend_cycling()
} else {
contexts
}
}
pub(crate) fn take_key_chord_reset(&mut self) -> bool {
@@ -92,6 +97,35 @@ impl ChatWidget {
self.handle_key_event_with_activation_key(key_event, /*activation_key*/ None)
}
pub(crate) fn set_new_backend_control(&mut self, label: Option<String>) {
if self.new_backend_label != label {
self.new_backend_label = label;
self.request_redraw();
}
}
pub(crate) fn can_choose_new_backend(&self) -> bool {
!self.blocks_direct_input
&& !self.is_user_turn_pending_or_running()
&& self.last_turn_id().is_none()
&& !self.input_queue.has_queued_follow_up_messages()
&& self.input_queue.startup_submission.is_none()
&& self.initial_user_message.is_none()
}
pub(super) fn visible_new_backend_control(&self) -> Option<&str> {
let label = self.new_backend_label.as_deref()?;
(self.can_choose_new_backend()
&& self.bottom_pane.no_modal_or_popup_active()
&& !self.fork_in_progress
&& !self.shortcut_overlay_visible()
&& !self.quick_dial_menu
&& self.safety_recourse.is_none()
&& !self.has_provider_error()
&& matches!(self.external_editor_state, ExternalEditorState::Closed))
.then_some(label)
}
pub(crate) fn handle_key_event_with_activation_key(
&mut self,
key_event: KeyEvent,
@@ -134,6 +168,15 @@ impl ChatWidget {
return KeyEventAction::None;
}
let keymap = self.bottom_pane.keymap();
if keymap.app.change_host.is_pressed(key_event)
&& self.visible_new_backend_control().is_some()
{
self.app_event_tx
.send(AppEvent::CycleNewConversationBackend);
return KeyEventAction::None;
}
if self.shortcut_overlay_visible() && key_hint::plain(KeyCode::Esc).is_press(key_event) {
self.bottom_pane
.handle_key_event_with_activation_key(key_event, activation_key);
@@ -12,6 +12,7 @@
//! appear to accept a remap while some handlers still respond to the old keys.
use codex_config::types::TuiKeymap;
use codex_features::Feature;
use super::ChatWidget;
use crate::app_event::KeymapCaptureMode;
@@ -154,6 +155,7 @@ impl ChatWidget {
fn keymap_action_filter(&self) -> keymap_setup::KeymapActionFilter {
keymap_setup::KeymapActionFilter {
fast_mode_enabled: self.fast_mode_enabled(),
multi_backend_enabled: self.config.features.enabled(Feature::TuiMultiBackend),
}
}
+8
View File
@@ -4,6 +4,7 @@ use super::provider_error::ProviderErrorNotice;
use super::transcript::ActiveCellLayoutCache;
use super::transcript::ActiveCellLayoutCacheKey;
use super::*;
use crate::keymap::KeymapContext;
use crate::render::RectExt;
use crate::terminal_hyperlinks::HyperlinkParagraph;
use crate::wrapping::RtOptions;
@@ -296,6 +297,13 @@ impl ChatWidget {
&& !self.bottom_pane.has_active_view()
{
RenderableItem::Borrowed(&pending.notice)
} else if let Some(backend) = self.visible_new_backend_control() {
let mut spans = vec![" ".into(), backend.into()];
let keymap = self.bottom_pane.keymap();
if let Some(key) = keymap.primary_hint(KeymapContext::Global, "change_host") {
spans.extend([" ".into(), key.into(), " to cycle".dim()]);
}
RenderableItem::Owned(Box::new(Paragraph::new(Line::from(spans))))
} else {
return bottom_pane;
};
@@ -996,6 +996,7 @@ async fn submission_prefers_selected_duplicate_skill_path() {
mention: "figma".to_string(),
path: user_skill_path.to_string_lossy().into_owned(),
}],
crate::bottom_pane::ShellPrefixHandling::Interpret,
);
chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
@@ -1174,6 +1175,42 @@ async fn blocked_image_restore_with_remote_images_keeps_local_placeholder_mappin
assert_eq!(chat.remote_image_urls(), remote_image_urls);
}
#[tokio::test]
async fn startup_draft_handoff_preserves_literal_and_shell_bang() {
for text in [
"!echo literal",
"!echo literal\nsecond line",
" !echo literal",
] {
let (mut source, _rx, _ops) = make_chatwidget_manual(/*model_override*/ None).await;
source.bottom_pane.insert_str(&format!("x{text}"));
source.bottom_pane.set_composer_cursor(0);
source.handle_key_event(KeyEvent::from(KeyCode::Delete));
let draft = source.composer_draft_snapshot();
assert_eq!(draft.text, text);
assert_eq!(draft.shell_mode, Some(false));
let (mut chat, _rx, mut ops) = make_chatwidget_manual(/*model_override*/ None).await;
chat.thread_id = Some(ThreadId::new());
chat.restore_startup_draft(draft.clone());
assert_eq!(chat.bottom_pane.composer_draft_snapshot(), draft);
chat.handle_key_event(KeyEvent::from(KeyCode::Enter));
assert_hidden_shell_payload_is_literal(ops.try_recv(), text.trim().to_string());
}
let (mut source, _rx, _ops) = make_chatwidget_manual(/*model_override*/ None).await;
source
.bottom_pane
.set_composer_text("!pwd".into(), Vec::new(), Vec::new());
let draft = source.composer_draft_snapshot();
assert_eq!(draft.shell_mode, Some(true));
let (mut chat, _rx, mut ops) = make_chatwidget_manual(/*model_override*/ None).await;
chat.thread_id = Some(ThreadId::new());
chat.restore_startup_draft(draft);
chat.handle_key_event(KeyEvent::from(KeyCode::Enter));
assert_matches!(ops.try_recv(), Ok(Op::RunUserShellCommand { command }) if command == "pwd");
}
#[tokio::test]
async fn startup_draft_handoff_preserves_cursor_and_large_paste() {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
@@ -2679,6 +2716,7 @@ async fn image_preparation_failure_restores_full_input_without_submitting() {
mention: "file".into(),
path: "/tmp/skills/file/SKILL.md".into(),
}],
crate::bottom_pane::ShellPrefixHandling::Interpret,
);
let draft = chat.bottom_pane.composer_draft_snapshot();
if oversized {
@@ -989,6 +989,7 @@ async fn manual_interrupt_restores_pending_steer_mention_bindings_to_composer()
)],
Vec::new(),
mention_bindings.clone(),
crate::bottom_pane::ShellPrefixHandling::Interpret,
);
chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
@@ -807,6 +807,7 @@ async fn goal_slash_command_uses_plain_text_for_mentions() {
mention: "figma".to_string(),
path: "app://figma".to_string(),
}],
crate::bottom_pane::ShellPrefixHandling::Interpret,
);
chat.handle_key_event(KeyEvent::new(KeyCode::End, KeyModifiers::NONE));
@@ -1251,6 +1252,7 @@ async fn interrupted_merged_message_history_encodes_mentions_once() {
mention: "figma".to_string(),
path: "app://figma".to_string(),
}],
crate::bottom_pane::ShellPrefixHandling::Interpret,
);
chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
@@ -2,6 +2,22 @@ use super::*;
use crate::app_event::HistoryLookupResponse;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn host_switch_snapshot_preserves_buffered_typing() {
for typed in ["x", "several keys"] {
let (mut chat, _events, _ops) = make_chatwidget_manual(/*model_override*/ None).await;
chat.bottom_pane.set_disable_paste_burst(/*disabled*/ false);
chat.insert_str("draft ");
for ch in typed.chars() {
chat.handle_key_event(KeyEvent::from(KeyCode::Char(ch)));
}
assert_eq!(
chat.composer_draft_snapshot().text,
format!("draft {typed}")
);
}
}
#[tokio::test]
async fn initial_prompt_recall_precedes_cross_session_history() {
for submit_follow_up in [false, true] {
@@ -36,12 +36,19 @@ async fn slash_new_and_fork_offer_checkout_choices_inside_local_git_repository()
assert!(popup.contains("Create new Git worktree"), "popup: {popup}");
assert_matches!(rx.try_recv(), Err(TryRecvError::Empty));
chat.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
chat.set_feature_enabled(Feature::TuiMultiBackend, /*enabled*/ true);
chat.bottom_pane
.set_composer_text("/new named".into(), Vec::new(), Vec::new());
chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
assert_matches!(rx.try_recv(), Ok(AppEvent::FollowTranscript));
let Ok(AppEvent::ChooseNewSessionCheckout { name }) = rx.try_recv() else {
panic!("/new must resolve its host before offering checkout choices");
};
assert!(!chat.has_active_modal());
assert_eq!(name.as_deref(), Some("named"));
chat.open_session_checkout_picker(crate::app_event::ManagedWorktreeMode::New, name);
chat.handle_key_event(KeyEvent::new(KeyCode::Char('1'), KeyModifiers::NONE));
assert_matches!(rx.try_recv(), Ok(AppEvent::NewSession { name: Some(name) }) if name == "named");
assert_matches!(rx.try_recv(), Ok(AppEvent::NewSessionInCurrentWorktree { name: Some(name) }) if name == "named");
chat.bottom_pane
.set_composer_text("/fork named".into(), Vec::new(), Vec::new());
chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
@@ -51,6 +58,7 @@ async fn slash_new_and_fork_offer_checkout_choices_inside_local_git_repository()
mode: crate::app_event::ManagedWorktreeMode::Fork,
name: Some(name),
}) if name == "named");
chat.set_feature_enabled(Feature::TuiMultiBackend, /*enabled*/ false);
chat.set_local_worktree_operations(/*enabled*/ false);
chat.dispatch_command(SlashCommand::New);
assert_matches!(rx.try_recv(), Ok(AppEvent::NewSession { name: None }));
+17 -2
View File
@@ -13,7 +13,7 @@ use crate::worktree_browser::Request;
const BROWSER_VIEW_ID: &str = "managed-worktrees";
impl ChatWidget {
pub(super) fn managed_worktree_available(&self) -> bool {
pub(crate) fn managed_worktree_available(&self) -> bool {
self.local_worktree_operations && get_git_repo_root(self.config.cwd.as_path()).is_some()
}
@@ -22,6 +22,13 @@ impl ChatWidget {
mode: ManagedWorktreeMode,
name: Option<String>,
) {
if mode == ManagedWorktreeMode::New
&& self.config.features.enabled(Feature::TuiMultiBackend)
{
self.app_event_tx
.send(AppEvent::ChooseNewSessionCheckout { name });
return;
}
if !self.managed_worktree_available() {
match mode {
ManagedWorktreeMode::New => {
@@ -35,6 +42,14 @@ impl ChatWidget {
return;
}
self.open_session_checkout_picker(mode, name);
}
pub(crate) fn open_session_checkout_picker(
&mut self,
mode: ManagedWorktreeMode,
name: Option<String>,
) {
let title = match mode {
ManagedWorktreeMode::New => "Where should the new conversation run?",
ManagedWorktreeMode::Fork => "Where should the forked conversation run?",
@@ -48,7 +63,7 @@ impl ChatWidget {
description: Some("Keep using the current working directory".to_string()),
actions: vec![Box::new(move |tx| match mode {
ManagedWorktreeMode::New => {
tx.send(AppEvent::NewSession {
tx.send(AppEvent::NewSessionInCurrentWorktree {
name: current_name.clone(),
});
}