Add a Cloud environment picker for new TUI conversations (#61974)

## What changed

- Open a searchable picker with `Ctrl+X E` to choose a saved personal or workspace environment, or use Default with the current GitHub project when available.
- Show the selected environment above the composer and expose `tui.keymap.global.choose_cloud_environment` for custom bindings.
- Preserve the composer draft and staged model, reasoning effort, and service tier when changing environments. Remember the saved environment when cycling through a local host and back to the same Cloud backend.

## Testing

Add coverage for picker search and selection, dismissal without losing the draft, keyboard routing, environment label truncation, staged settings on the first turn, and saved-environment reuse after host switching.

GitOrigin-RevId: ac9036fd46b252286852df4d792418a3330bae73
This commit is contained in:
Benjamin Carlsson
2026-11-17 05:52:43 +00:00
committed by copyberry
parent c826ca1286
commit 9a5a78925d
29 changed files with 747 additions and 81 deletions
+2
View File
@@ -137,6 +137,8 @@ pub struct TuiGlobalKeymap {
pub leader: Option<KeybindingsSpec>,
/// Change where a new conversation runs.
pub change_host: Option<KeybindingsSpec>,
/// Choose a saved environment for a new Cloud conversation.
pub choose_cloud_environment: Option<KeybindingsSpec>,
/// Focus the main conversation composer.
pub focus_main_composer: Option<KeybindingsSpec>,
/// Focus the side conversation, or hide it when already focused.
+10
View File
@@ -5556,6 +5556,7 @@
},
"global": {
"change_host": null,
"choose_cloud_environment": null,
"clear_terminal": null,
"close_sidebar_tab": null,
"copy": null,
@@ -6406,6 +6407,14 @@
],
"description": "Change where a new conversation runs."
},
"choose_cloud_environment": {
"allOf": [
{
"$ref": "#/definitions/KeybindingsSpec"
}
],
"description": "Choose a saved environment for a new Cloud conversation."
},
"clear_terminal": {
"allOf": [
{
@@ -6777,6 +6786,7 @@
],
"default": {
"change_host": null,
"choose_cloud_environment": null,
"clear_terminal": null,
"close_sidebar_tab": null,
"copy": null,
+1
View File
@@ -222,6 +222,7 @@ mod backend_registry;
pub(crate) mod backend_selection;
pub(crate) mod backend_sessions;
mod background_requests;
mod cloud_environments;
mod cloud_switch_wait;
#[cfg(test)]
pub(crate) use cloud_switch_wait::wait_for_cloud_switch;
+3
View File
@@ -86,6 +86,9 @@ pub(super) struct AgentsOverviewState {
pub(super) requested_permission_profiles: HashMap<ThreadId, PermissionProfileSelection>,
/// Keep new tasks subscribed and reusable until a first turn makes them resumable.
pub(super) blank_sessions: HashMap<ThreadId, crate::app_server_session::AppServerStartedThread>,
/// A host switch carries this choice with the draft, but only its original backend can use it.
pub(super) draft_cloud_environments:
HashMap<ThreadId, (BackendId, codex_app_server_client::SavedEnvironment)>,
pub(super) input_states: HashMap<ThreadId, ThreadInputState>,
pub(super) new_session_draft: Option<Box<StartupDraftPump>>,
pub(super) dispatched_requests: HashMap<ThreadId, Vec<BufferedServerRequest>>,
@@ -112,6 +112,9 @@ impl App {
| ServerNotification::ThreadDeleted(_)
) {
self.agents_overview.blank_sessions.remove(&thread_id);
self.agents_overview
.draft_cloud_environments
.remove(&thread_id);
}
self.track_agents_overview_activity(thread_id, notification);
let thread = self
+75 -24
View File
@@ -15,6 +15,7 @@ use futures::TryFutureExt;
pub(super) enum NewBackendSession {
Fresh { name: Option<String> },
CarryDraft,
ChangeCloudEnvironment(Option<codex_app_server_client::SavedEnvironment>),
}
/// Host inputs for the new-thread preference. A cloud thread's cwd and credentials
@@ -171,16 +172,21 @@ impl App {
}
let displayed_thread = self.current_displayed_thread_id();
let outgoing_slot = backends.displayed;
let switching_backend = owner != backends.displayed_owner();
if let Some(thread_id) = displayed_thread
&& self.active_turn_id_for_thread(thread_id).await.is_some()
{
return Err("Wait for the current turn to finish before switching.".into());
}
let mut settings = backends
.settings
.get(&owner)
.cloned()
.ok_or("Connection settings are unavailable.")?;
let mut settings = if !switching_backend {
self.backend_settings()
} else {
backends
.settings
.get(&owner)
.cloned()
.ok_or("Connection settings are unavailable.")?
};
if settings.target == AppServerTarget::Cloud && self.chat_widget.thread_id().is_some() {
self.remember_attached_host_project(backends.session_at(outgoing_slot));
}
@@ -196,19 +202,28 @@ impl App {
};
let user_config_path = self.local_settings.user_config_path.clone();
let responsive_cloud_switch = settings.target == AppServerTarget::Cloud
&& matches!(session, NewBackendSession::CarryDraft);
let (name, mut draft) = match session {
&& !matches!(session, NewBackendSession::Fresh { .. });
let replacing_cloud_draft = matches!(session, NewBackendSession::ChangeCloudEnvironment(_));
let (name, mut draft, saved_environment) = match session {
NewBackendSession::Fresh { name } => {
*fresh_draft = Some(StartupDraftPump::for_new_session(
tui,
&settings.local_settings,
settings.config.cwd.as_path(),
));
(name, None)
(name, None, None)
}
NewBackendSession::CarryDraft => (
self.chat_widget.thread_name(),
(!responsive_cloud_switch).then(|| self.chat_widget.composer_draft_snapshot()),
displayed_thread
.and_then(|id| self.agents_overview.draft_cloud_environments.get(&id))
.cloned(),
),
NewBackendSession::ChangeCloudEnvironment(environment) => (
self.chat_widget.thread_name(),
None,
environment.map(|env| (owner, env)),
),
};
let destination = backends.session_at_mut(slot);
@@ -294,14 +309,20 @@ impl App {
draft.apply_settings(&local_settings, config.cwd.as_path());
}
let host_project_cwd = self.backend_preference_context.local_cwd.clone();
let cloud_start = match &saved_environment {
Some((backend, env)) if *backend == owner => {
crate::app_server_session::CloudThreadStart::Saved(env.id.clone())
}
_ => crate::app_server_session::CloudThreadStart::Project(host_project_cwd.as_deref()),
};
let start = destination
.start_thread_with_session_start_source(
.start_thread_with_environment(
&local_settings,
&config,
/*session_start_source*/ None,
/*remote_cwd_override*/ None,
/*selected_profile*/ None,
host_project_cwd.as_deref(),
cloud_start,
)
.map_err(|error| format!("Failed to start the new conversation: {error}"));
let Some(started) = if responsive_cloud_switch {
@@ -325,8 +346,8 @@ impl App {
if responsive_cloud_switch {
draft = Some(self.chat_widget.composer_draft_snapshot());
}
// Clear before switching so a terminal error leaves the outgoing conversation usable.
if let Err(error) = tui.clear_for_thread_switch() {
// A same-backend Cloud start already replaced the attachment. Clear on its first draw.
if switching_backend && let Err(error) = tui.clear_for_thread_switch() {
if responsive_cloud_switch {
let events = tui.event_stream();
if finish_failed_cloud_switch(self, tui, events)
@@ -340,15 +361,17 @@ impl App {
}
let destination_thread = started.session.thread_id;
let outgoing_has_queue = self.chat_widget.has_queued_follow_up_messages();
self.switch_backend_context(
backends,
slot,
started.session.thread_id,
settings.target,
config.cwd.to_path_buf(),
bootstrap,
)
.await;
if switching_backend {
self.switch_backend_context(
backends,
slot,
started.session.thread_id,
settings.target,
config.cwd.to_path_buf(),
bootstrap,
)
.await;
}
let destination = backends.session_at_mut(slot);
self.adopt_fresh_session(
tui,
@@ -358,12 +381,32 @@ impl App {
config,
local_settings,
},
ThreadAttachPresentation::FreshAfterClear,
if switching_backend {
ThreadAttachPresentation::FreshAfterClear
} else {
ThreadAttachPresentation::FreshWithDraft
},
/*initial_user_message*/ None,
name,
)
.await;
backends.switch_displayed(slot, &mut self.agents_overview.input_states);
if replacing_cloud_draft
&& let Some(source) = displayed_thread
&& self.current_displayed_thread_id() == Some(destination_thread)
{
destination.move_staged_cloud_settings(source, destination_thread);
self.chat_widget.sync_service_tier_commands();
}
if let Some(environment) = saved_environment
&& self.current_displayed_thread_id() == Some(destination_thread)
{
self.agents_overview
.draft_cloud_environments
.insert(destination_thread, environment);
}
if switching_backend {
backends.switch_displayed(slot, &mut self.agents_overview.input_states);
}
if !backends.session_at_mut(slot).uses_remote_workspace()
&& self.current_displayed_thread_id() == Some(destination_thread)
{
@@ -381,7 +424,10 @@ impl App {
} else {
self.chat_widget.restore_startup_draft(draft);
}
// Another Cloud client may have started a turn on the source while we
// opened this environment. Keep that thread and its local input accessible.
if let Some(thread_id) = displayed_thread
&& !replacing_cloud_draft
&& !outgoing_has_queue
&& self.current_displayed_thread_id() == Some(destination_thread)
&& self
@@ -390,7 +436,12 @@ impl App {
.remove(&thread_id)
.is_some()
{
backends.parked_inputs_mut(outgoing_slot).remove(&thread_id);
let input_states = if switching_backend {
backends.parked_inputs_mut(outgoing_slot)
} else {
&mut self.agents_overview.input_states
};
input_states.remove(&thread_id);
self.remove_agents_overview_thread(thread_id);
if let Err(error) = backends
.session_at_mut(outgoing_slot)
@@ -0,0 +1,74 @@
//! Shows saved Cloud environments before starting a conversation on the Cloud backend.
use crate::app_event::AppEvent;
use crate::bottom_pane::SelectionItem;
use crate::bottom_pane::SelectionViewParams;
use codex_app_server_client::SavedEnvironment;
use codex_protocol::ThreadId;
pub(super) const LOADING_VIEW_ID: &str = "cloud_environment_loading";
pub(super) fn loading_view() -> SelectionViewParams {
SelectionViewParams {
view_id: Some(LOADING_VIEW_ID),
title: Some("Cloud environment".into()),
subtitle: Some("Loading saved environments…".into()),
..SelectionViewParams::picker()
}
}
pub(super) fn cloud_environment_picker(
result: Result<Vec<SavedEnvironment>, String>,
source: ThreadId,
) -> SelectionViewParams {
let (environments, subtitle) = match result {
Ok(environments) => (environments, None),
Err(error) => (
Vec::new(),
Some(format!("{error}. You can still use Default.")),
),
};
let choices = std::iter::once((
"Default".to_string(),
"Use the default environment with the current GitHub project, if available",
None,
))
.chain(environments.into_iter().map(|environment| {
(
environment.name.clone(),
if environment.workspace_shared {
"Workspace environment"
} else {
"Personal environment"
},
Some(environment),
)
}));
let items = choices
.map(|(name, description, saved_environment)| SelectionItem {
search_value: Some(name.clone()),
name,
description: Some(description.to_string()),
actions: vec![Box::new(move |tx| {
tx.send(AppEvent::StartCloudConversation {
source,
saved_environment: saved_environment.clone(),
});
})],
dismiss_on_select: true,
..Default::default()
})
.collect();
SelectionViewParams {
title: Some("Cloud environment".into()),
subtitle,
items,
is_searchable: true,
search_placeholder: Some("Search environments".to_string()),
..SelectionViewParams::picker()
}
}
#[cfg(test)]
#[path = "cloud_environments_tests.rs"]
mod tests;
@@ -0,0 +1,61 @@
#![cfg(test)]
use super::*;
use crate::app::tests::make_test_app_with_channels;
use crate::chatwidget::tests::render_bottom_popup;
use crossterm::event::KeyCode;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn cloud_environment_picker_shows_default_and_saved_choice() {
let (mut app, mut events, _) = make_test_app_with_channels().await;
let source = ThreadId::new();
let saved = SavedEnvironment {
id: "ws~asenvcfg_saved".into(),
name: "Team Rust".into(),
workspace_shared: true,
};
app.chat_widget
.show_selection_view(cloud_environment_picker(Ok(vec![saved.clone()]), source));
let rendered = render_bottom_popup(&app.chat_widget, /*width*/ 110);
let rows = ["Cloud environment", "Default", "Team Rust"].map(|label| {
let line = rendered.lines().find(|line| line.contains(label)).unwrap();
line[line.find(label).unwrap()..]
.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
});
insta::assert_snapshot!(rows.join("\n"), @"
Cloud environment
Default Use the default environment with the current GitHub project, if available
Team Rust Workspace environment
");
for key in "rust".chars().map(KeyCode::Char) {
app.chat_widget.handle_key_event(key.into());
}
app.chat_widget.handle_key_event(KeyCode::Enter.into());
let selection = std::iter::from_fn(|| events.try_recv().ok()).find_map(|event| match event {
AppEvent::StartCloudConversation {
source,
saved_environment,
} => Some((source, saved_environment)),
_ => None,
});
assert_eq!(selection, Some((source, Some(saved))));
}
#[tokio::test]
async fn dismissing_cloud_environment_loading_keeps_the_draft() {
let (mut app, _, _) = make_test_app_with_channels().await;
app.chat_widget.apply_external_edit("draft".into());
app.chat_widget.show_selection_view(loading_view());
app.chat_widget.handle_key_event(KeyCode::Esc.into());
let view = cloud_environment_picker(Ok(Vec::new()), ThreadId::new());
assert!(
!app.chat_widget
.replace_selection_view_if_present(LOADING_VIEW_ID, view)
);
assert_eq!(app.chat_widget.composer_text_with_pending(), "draft");
}
+4 -1
View File
@@ -655,7 +655,10 @@ impl App {
Err(err) => return Err(err),
}
}
AppEvent::ResumeBackendSession(_) | AppEvent::CycleNewConversationBackend => {
AppEvent::ResumeBackendSession(_)
| AppEvent::CycleNewConversationBackend
| AppEvent::ChooseCloudEnvironment
| AppEvent::StartCloudConversation { .. } => {
unreachable!("backend selection is handled by the session manager")
}
AppEvent::ArchiveCurrentThread => {
@@ -1046,6 +1046,12 @@ impl App {
});
self.thread_event_channels
.retain(|id, _| Some(*id) == voice_owner || self.side_threads.contains_key(id));
let displayed = self.current_displayed_thread_id();
self.agents_overview
.draft_cloud_environments
.retain(|id, _| {
displayed == Some(*id) || self.agents_overview.blank_sessions.contains_key(id)
});
// A retained side can still display its parent even after the parent channel is detached.
self.side_companions.retain(|id, _| {
self.side_threads.contains_key(id)
+3
View File
@@ -602,6 +602,9 @@ impl App {
});
self.abort_thread_event_listener(thread_id);
self.thread_event_channels.remove(&thread_id);
self.agents_overview
.draft_cloud_environments
.remove(&thread_id);
self.pending_server_profiles.remove(&thread_id);
self.agents_overview.activity.remove(&thread_id);
self.sidebars.remove(&Some(thread_id));
+48 -1
View File
@@ -1308,6 +1308,9 @@ See the Codex keymap documentation for supported actions and examples."
let mut settled_size_tags = crate::terminal_size_telemetry::tags(last_screen_size);
let mut pending_resize: Option<(ratatui::layout::Size, Instant)> = None;
let mut reconnect = None;
let mut cloud_environment_picker: Option<
futures::future::LocalBoxFuture<'static, crate::bottom_pane::SelectionViewParams>,
> = None;
let mut waiting_for_initial_session_configured = wait_for_initial_session_configured;
let mut waiting_for_initial_session_header = true;
@@ -1368,7 +1371,25 @@ See the Codex keymap documentation for supported actions and examples."
.flatten();
let current_label =
next_backend.and_then(|_| backends.displayed_name(&app.app_server_target));
app.chat_widget.set_new_backend_control(current_label);
let cloud_draft = draft.filter(|_| {
app.app_server_target == AppServerTarget::Cloud
&& backends.is_listening(displayed_owner)
});
let environment_name = cloud_draft.map(|id| {
app.agents_overview
.draft_cloud_environments
.get(&id)
.filter(|(owner, _)| *owner == displayed_owner)
.map(|(_, env)| {
crate::terminal_title::sanitize_terminal_title(
&env.name,
crate::terminal_title::TitleEncoding::Unicode,
)
})
.unwrap_or_else(|| "Default".into())
});
app.chat_widget
.set_new_backend_control(current_label, environment_name);
if !backends.is_listening(displayed_owner)
&& !app.pending_startup_thread_start
&& !app.reconnect.offline
@@ -1523,6 +1544,13 @@ See the Codex keymap documentation for supported actions and examples."
}
AppRunControl::Continue
}
Some(view) = futures::future::OptionFuture::from(cloud_environment_picker.as_mut()) => {
cloud_environment_picker = None;
app.chat_widget.replace_selection_view_if_present(
super::cloud_environments::LOADING_VIEW_ID, view,
);
AppRunControl::Continue
}
Some(event) = app.saved_openings.next_event(&mut app_event_rx) => {
if let AppEvent::ArchiveFinished { backend_id, thread_id, result: Ok(()) } = &event
&& *backend_id != displayed_owner
@@ -1531,6 +1559,25 @@ See the Codex keymap documentation for supported actions and examples."
backends.parked_inputs_mut(slot).remove(thread_id);
}
let switch_backend = match &event {
AppEvent::ChooseCloudEnvironment => {
if let Some(source) = cloud_draft
&& app.chat_widget.no_modal_or_popup_active()
&& let AppServerRequestHandle::Cloud(handle) = backends.session_at(displayed_session).request_handle()
{
app.chat_widget.show_selection_view(super::cloud_environments::loading_view());
cloud_environment_picker = Some(Box::pin(async move {
let environments = handle.list_saved_environments().await.map_err(|error| error.to_string());
super::cloud_environments::cloud_environment_picker(environments, source)
}));
}
continue;
}
AppEvent::StartCloudConversation { source, saved_environment }
if cloud_draft == Some(*source) =>
{
Some((displayed_owner, NewBackendSession::ChangeCloudEnvironment(saved_environment.clone())))
}
AppEvent::StartCloudConversation { .. } => continue,
AppEvent::ChooseNewSessionCheckout { name } | AppEvent::NewSession { name }
if multi_backend => app.other_new_session_backend(&backends).await
.map(|owner| (owner, NewBackendSession::Fresh { name: name.clone() })),
+31 -4
View File
@@ -79,10 +79,37 @@ async fn empty_thread_backend_chord_preserves_draft_until_first_submission() ->
let mut tui = crate::tui::test_support::make_test_tui()?;
app.chat_widget
.apply_external_edit("first draft".to_string());
app.chat_widget
.set_new_backend_control(Some("Cloud".to_string()));
let screen = render_bottom_popup(&app.chat_widget, /*width*/ 80);
insta::assert_snapshot!(screen.lines().find(|line| line.trim_start().starts_with("Cloud")).unwrap().trim(), @"Cloud ⌃x b to cycle");
let host_lines = [
("Default", 80),
("Team Rust", 80),
("Team Rust — shared development environment", 45),
]
.map(|(environment, width)| {
app.chat_widget
.set_new_backend_control(Some("Cloud".into()), Some(environment.into()));
render_bottom_popup(&app.chat_widget, width)
.lines()
.map(str::trim)
.find(|line| line.starts_with("Cloud"))
.unwrap()
.to_owned()
});
insta::assert_snapshot!(host_lines.join("\n"), @"
Cloud ⌃x b cycle - Default ⌃x e change
Cloud ⌃x b cycle - Team Rust ⌃x e change
Cloud ⌃x b cycle - Team Rust… ⌃x e change
");
assert_eq!(app.route_key_chord_event(&mut tui, ctrl('x')), None);
let key = app
.route_key_chord_event(&mut tui, KeyCode::Char('e').into())
.expect("environment chord dispatch");
app.chat_widget.handle_key_event(key);
assert!(
std::iter::from_fn(|| events.try_recv().ok())
.any(|event| matches!(event, AppEvent::ChooseCloudEnvironment))
);
assert_eq!(app.chat_widget.composer_text_with_pending(), "first draft");
// Cursor movement remains available while the backend selector is visible.
let key = app.route_key_chord_event(&mut tui, ctrl('b')).unwrap();
@@ -745,3 +745,242 @@ async fn model_default_saves_report_server_outcomes_and_target_server_profile()
}
Ok(())
}
#[tokio::test]
async fn changing_cloud_environment_carries_staged_settings_to_first_turn() -> Result<()> {
use crate::app::backend_selection::NewBackendSession;
use crate::app::backend_sessions::BackendSessions;
use codex_app_server_protocol::ClientRequest;
let (mut app, mut events, mut ops) = make_test_app_with_channels().await;
let mut tui = crate::tui::test_support::make_test_tui()?;
tui.pause_events();
let mut embedded = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?;
let blank = embedded.start_thread(&app.config).await?;
let source = blank.session.thread_id;
let (client, mut commands, _server_events) =
codex_app_server_client::CloudClient::channel(/*capacity*/ 8);
let owner = crate::backend_id::BackendId::new();
let mut cloud = AppServerSession::new(
owner,
AppServerClient::Cloud(client),
crate::ThreadParamsMode::Cloud,
);
app.app_server_target = crate::AppServerTarget::Cloud;
app.bind_backend_workspace(&cloud, app.config.cwd.to_path_buf());
app.agents_overview
.blank_sessions
.insert(source, blank.clone());
app.enqueue_primary_thread_session(blank.session, blank.turns)
.await?;
app.chat_widget
.apply_external_edit("keep this draft".into());
let mut model = app.model_catalog.models[0].clone();
model.model = "model-selected-before-switch".into();
cloud
.stage_cloud_model_selection(source, &model, Some(ReasoningEffortConfig::High))
.expect("stage model");
cloud
.toggle_cloud_service_tier(source, /*current*/ None, "fast".into())
.expect("stage speed");
// Use the embedded server for ordinary bootstrap requests. Observe the native admission
// after the environment start to verify that pending choices moved to the new thread ID.
let proxy = embedded.request_handle();
let worker = tokio::spawn(async move {
let mut starts = Vec::new();
while let Some(command) = commands.recv().await {
let request = match command.operation {
CloudOperation::Request(request) => {
if matches!(&*request, ClientRequest::ThreadStart { .. }) {
starts.push(None);
}
*request
}
CloudOperation::StartThreadWithEnvironment {
request_id,
params,
environment: codex_app_server_client::EnvironmentSelection::Saved(id),
} => {
starts.push(Some(id));
ClientRequest::ThreadStart {
request_id,
params: *params,
}
}
CloudOperation::SubmitUserMessage(params) => {
let turn = test_turn("first-turn", TurnStatus::InProgress, Vec::new());
let receipt =
serde_json::to_value(CloudUserMessageReceipt::Started(turn)).unwrap();
command.response.send(Ok(Ok(receipt))).unwrap();
return (starts, params);
}
_ => panic!("unexpected native operation before the first turn"),
};
let _ = command.response.send(proxy.request(request).await);
}
panic!("no native submission");
});
let mut backends = BackendSessions::from_initial(cloud, vec![]);
// Start Default without a project so the caller's Git checkout cannot affect routing.
app.backend_preference_context.local_cwd = None;
let default_switch = Box::pin(app.start_new_session_on_other_backend(
&mut tui,
&mut backends,
owner,
NewBackendSession::ChangeCloudEnvironment(None),
));
tokio::time::timeout(std::time::Duration::from_secs(30), default_switch)
.await?
.expect("switch to Default");
let saved = codex_app_server_client::SavedEnvironment {
id: "asenvcfg_saved".into(),
name: "Saved".into(),
workspace_shared: false,
};
let switch = Box::pin(app.start_new_session_on_other_backend(
&mut tui,
&mut backends,
owner,
NewBackendSession::ChangeCloudEnvironment(Some(saved)),
));
tokio::time::timeout(std::time::Duration::from_secs(30), switch)
.await?
.expect("switch environment");
let destination = app.chat_widget.thread_id().expect("new Cloud draft");
assert_ne!(source, destination);
assert!(!app.agents_overview.removed_threads.contains(&source));
assert_eq!(
app.chat_widget.composer_text_with_pending(),
"keep this draft"
);
app.chat_widget.handle_key_event(KeyCode::Enter.into());
let op = std::iter::from_fn(|| events.try_recv().ok())
.find_map(|event| match event {
AppEvent::CodexOp(op @ Op::UserTurn { .. })
| AppEvent::SubmitThreadOp {
op: op @ Op::UserTurn { .. },
..
} => Some(op),
_ => None,
})
.unwrap_or_else(|| next_user_turn_op(&mut ops));
let submit = Box::pin(super::super::user_turn_submission::try_submit_user_turn(
&mut app,
backends.session_at_mut(backends.displayed),
destination,
&op,
));
assert!(tokio::time::timeout(std::time::Duration::from_secs(5), submit).await??);
let (starts, params) =
tokio::time::timeout(std::time::Duration::from_secs(5), worker).await??;
assert_eq!(starts, vec![None, Some("asenvcfg_saved".to_string())]);
assert_eq!(
(
params.thread_id,
params.model,
params.effort,
params.service_tier
),
(
destination.to_string(),
Some(model.model),
Some(ReasoningEffortConfig::High),
Some(Some("fast".into()))
)
);
embedded.shutdown().await?;
Ok(())
}
#[tokio::test]
async fn cycling_cloud_draft_through_local_reuses_its_saved_environment() -> Result<()> {
use crate::app::backend_selection::NewBackendSession;
use crate::app::backend_sessions::BackendSessions;
use codex_app_server_client::EnvironmentSelection;
use codex_app_server_protocol::ClientRequest;
let (mut app, _events, _ops) = make_test_app_with_channels().await;
let mut tui = crate::tui::test_support::make_test_tui()?;
tui.pause_events();
let mut local = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?;
let local_owner = local.backend_id();
let local_settings = app.backend_settings();
let blank = local.start_thread(&app.config).await?;
let proxy = local.request_handle();
let (client, mut commands, _server_events) =
codex_app_server_client::CloudClient::channel(/*capacity*/ 8);
let cloud_owner = crate::backend_id::BackendId::new();
let cloud = AppServerSession::new(
cloud_owner,
AppServerClient::Cloud(client),
crate::ThreadParamsMode::Cloud,
);
app.app_server_target = crate::AppServerTarget::Cloud;
app.bind_backend_workspace(&cloud, app.config.cwd.to_path_buf());
app.enqueue_primary_thread_session(blank.session, blank.turns)
.await?;
app.chat_widget.apply_external_edit("carry me".into());
let mut backends = BackendSessions::from_initial(cloud, vec![local]);
backends.settings.insert(local_owner, local_settings);
let saved = codex_app_server_client::SavedEnvironment {
id: "asenvcfg_rust".into(),
name: "Rust".into(),
workspace_shared: false,
};
let (started_tx, mut started_rx) = tokio::sync::mpsc::unbounded_channel();
let worker = tokio::spawn(async move {
while let Some(command) = commands.recv().await {
let request = match command.operation {
CloudOperation::Request(request) => {
if matches!(&*request, ClientRequest::ThreadStart { .. }) {
started_tx.send(None).unwrap();
}
*request
}
CloudOperation::StartThreadWithEnvironment {
request_id,
environment: EnvironmentSelection::Saved(id),
params,
} => {
started_tx.send(Some(id)).unwrap();
ClientRequest::ThreadStart {
request_id,
params: *params,
}
}
CloudOperation::Shutdown => {
command
.response
.send(Ok(Ok(serde_json::Value::Null)))
.unwrap();
return;
}
_ => panic!("unexpected Cloud operation for this draft"),
};
let _ = command.response.send(proxy.request(request).await);
}
});
for (owner, selection) in [
(
cloud_owner,
NewBackendSession::ChangeCloudEnvironment(Some(saved.clone())),
),
(local_owner, NewBackendSession::CarryDraft),
(cloud_owner, NewBackendSession::CarryDraft),
] {
Box::pin(app.start_new_session_on_other_backend(&mut tui, &mut backends, owner, selection))
.await
.expect("carry draft");
assert_eq!(app.chat_widget.composer_text_with_pending(), "carry me");
if owner == cloud_owner {
assert_eq!(started_rx.try_recv()?, Some(saved.id.clone()));
}
}
backends.shutdown().await?;
worker.await?;
Ok(())
}
@@ -1184,6 +1184,19 @@ async fn check_retained_draft_handoff(
if retained_blank {
app.agents_overview.blank_sessions.insert(thread_id, blank);
}
if !saved_history {
app.agents_overview.draft_cloud_environments.insert(
thread_id,
(
destination_id,
codex_app_server_client::SavedEnvironment {
id: "asenvcfg_rust".into(),
name: "Saved Rust".into(),
workspace_shared: false,
},
),
);
}
app.chat_widget
.restore_user_message_to_composer("draft for the retained task".into());
let parked_policy = (!saved_history && history_capabilities == HistoryCapabilities::Current)
@@ -1304,6 +1317,16 @@ async fn check_retained_draft_handoff(
.contains(&destination_id)
);
assert_eq!(app.chat_widget.thread_id(), Some(thread_id));
if !saved_history {
let draft = app.backend_draft().expect("restored blank draft");
assert_eq!(
app.agents_overview
.draft_cloud_environments
.get(&draft)
.map(|(_, env)| env.name.as_str()),
Some("Saved Rust"),
);
}
if saved_history || parked_policy.is_some() {
assert_eq!(
app.chat_widget.effective_collaboration_mode(),
@@ -1637,7 +1660,7 @@ async fn cloud_switch_wait_keeps_draft_editable_without_submitting_to_local() ->
let session = test_thread_session(ThreadId::new(), app.config.cwd.to_path_buf());
app.chat_widget.handle_thread_session(session);
app.chat_widget
.set_new_backend_control(Some("Cloud".into()));
.set_new_backend_control(Some("Cloud".into()), /*cloud_environment_name*/ None);
app.chat_widget
.apply_external_edit("/review first draft".into());
app.keymap
@@ -1903,7 +1926,7 @@ async fn cloud_switch_wait_displays_pending_submission_hint() -> Result<()> {
let session = test_thread_session(ThreadId::new(), app.config.cwd.to_path_buf());
app.chat_widget.handle_thread_session(session);
app.chat_widget
.set_new_backend_control(Some("Cloud".into()));
.set_new_backend_control(Some("Cloud".into()), /*cloud_environment_name*/ None);
let mut tui = crate::tui::test_support::make_test_tui()?;
{
let wait = wait_for_cloud_switch(
@@ -327,6 +327,7 @@ async fn cloud_resume_picker_reconciles_admitted_steers() -> Result<()> {
use codex_protocol::models::MessagePhase;
let (mut app, mut events, mut ops) = make_test_app_with_channels().await;
app.local_settings.tui.show_tooltips = false;
let [original, other, failed] = std::array::from_fn(|_| ThreadId::new());
app.app_server_target = AppServerTarget::Cloud;
app.enqueue_primary_thread_session(
+1
View File
@@ -63,6 +63,7 @@ impl App {
(1, "Pane right")
}
"hide_pane" | "focus_pane_left" | "focus_pane_right" => continue,
"choose_cloud_environment" => (2, "Choose environment"),
"open_presets" => (2, "Presets ›"),
"find_transcript" => (2, "Find text"),
"select_transcript" => (2, "Select transcript"),
+9
View File
@@ -701,6 +701,15 @@ pub(crate) enum AppEvent {
/// Move an empty conversation to the next connected backend.
CycleNewConversationBackend,
/// Show the saved environments for the empty Cloud draft.
ChooseCloudEnvironment,
/// Move the empty Cloud draft to the selected environment.
StartCloudConversation {
source: ThreadId,
saved_environment: Option<codex_app_server_client::SavedEnvironment>,
},
/// Continue a provider-locked conversation in a fresh chat using its saved history.
ContinueProviderChat {
thread_id: ThreadId,
-4
View File
@@ -614,10 +614,6 @@ pub(crate) struct UnsupportedLegacyPermissionProfile;
/// The environment choice for a new Cloud thread.
pub(crate) enum CloudThreadStart<'a> {
Project(Option<&'a std::path::Path>),
#[cfg_attr(
not(test),
expect(dead_code, reason = "saved starts are wired by the Cloud picker")
)]
Saved(String),
}
@@ -135,6 +135,13 @@ impl AppServerSession {
.then(|| self.cloud_turn_settings.clone())
}
pub(crate) fn move_staged_cloud_settings(&self, from: ThreadId, to: ThreadId) {
let mut pending = self.cloud_turn_settings.lock();
if let Some(settings) = pending.remove(&from) {
pending.insert(to, settings);
}
}
fn cloud_model_catalog_is_current(&self) -> bool {
matches!(&self.request_handle,
AppServerRequestHandle::Cloud(handle) if handle.model_catalog_is_current()
+1
View File
@@ -722,6 +722,7 @@ pub(crate) struct ChatWidget {
/// Main chat-surface bindings resolved from `tui.keymap.chat`.
chat_keymap: ChatKeymap,
new_backend_label: Option<String>,
cloud_environment_name: Option<String>,
/// Whether the preset submenu owns the next key.
quick_dial_menu: bool,
/// Ignore a held key after it dismisses the preset submenu.
@@ -268,6 +268,7 @@ impl ChatWidget {
pending_notification: None,
quit_shortcut_expires_at: None,
new_backend_label: None,
cloud_environment_name: None,
quick_dial_menu: false,
quick_dial_menu_key_guard: None,
quit_shortcut_key: None,
+35 -17
View File
@@ -83,12 +83,16 @@ impl ChatWidget {
}
pub(crate) fn keymap_contexts(&self) -> crate::keymap::KeymapContextSet {
let contexts = self.bottom_pane.keymap_contexts();
if self.visible_new_backend_control().is_some() {
contexts.with_backend_cycling()
} else {
contexts
let mut contexts = self.bottom_pane.keymap_contexts();
if let Some((cycle, choose_environment)) = self.visible_new_backend_control() {
if cycle.is_some() {
contexts = contexts.with_backend_cycling();
}
if choose_environment.is_some() {
contexts = contexts.with_cloud_environment_selection();
}
}
contexts
}
pub(crate) fn take_key_chord_reset(&mut self) -> bool {
@@ -122,9 +126,15 @@ 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 {
pub(crate) fn set_new_backend_control(
&mut self,
label: Option<String>,
cloud_environment_name: Option<String>,
) {
if self.new_backend_label != label || self.cloud_environment_name != cloud_environment_name
{
self.new_backend_label = label;
self.cloud_environment_name = cloud_environment_name;
self.request_redraw();
}
}
@@ -138,9 +148,11 @@ impl ChatWidget {
&& 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()
pub(super) fn visible_new_backend_control(&self) -> Option<(Option<&str>, Option<&str>)> {
let cycle = self.new_backend_label.as_deref();
let environment = self.cloud_environment_name.as_deref();
((cycle.is_some() || environment.is_some())
&& self.can_choose_new_backend()
&& self.bottom_pane.no_modal_or_popup_active()
&& !self.fork_in_progress
&& !self.shortcut_overlay_visible()
@@ -148,7 +160,7 @@ impl ChatWidget {
&& self.safety_recourse.is_none()
&& !self.has_provider_error()
&& matches!(self.external_editor_state, ExternalEditorState::Closed))
.then_some(label)
.then_some((cycle, environment))
}
pub(crate) fn handle_key_event_with_activation_key(
@@ -194,12 +206,18 @@ impl ChatWidget {
}
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 let Some((cycle, choose_environment)) = self.visible_new_backend_control() {
if cycle.is_some() && keymap.app.change_host.is_pressed(key_event) {
self.app_event_tx
.send(AppEvent::CycleNewConversationBackend);
return KeyEventAction::None;
}
if choose_environment.is_some()
&& keymap.app.choose_cloud_environment.is_pressed(key_event)
{
self.app_event_tx.send(AppEvent::ChooseCloudEnvironment);
return KeyEventAction::None;
}
}
if self.shortcut_overlay_visible() && key_hint::plain(KeyCode::Esc).is_press(key_event) {
+40 -5
View File
@@ -5,6 +5,8 @@ use super::transcript::ActiveCellLayoutCache;
use super::transcript::ActiveCellLayoutCacheKey;
use super::*;
use crate::keymap::KeymapContext;
use crate::line_truncation::span_width;
use crate::line_truncation::truncate_line_with_ellipsis_if_overflow;
use crate::render::RectExt;
use crate::terminal_hyperlinks::HyperlinkParagraph;
use crate::wrapping::RtOptions;
@@ -14,6 +16,27 @@ use ratatui::text::Span;
use ratatui::widgets::Block;
use std::cell::Cell;
struct NewBackendControl<'a>(Line<'a>, Option<(usize, String)>);
impl Renderable for NewBackendControl<'_> {
fn render(&self, area: Rect, buf: &mut Buffer) {
let mut line = self.0.clone();
if let Some((index, environment)) = &self.1 {
let reserved: usize = line.iter().map(span_width).sum();
let environment = truncate_line_with_ellipsis_if_overflow(
Line::from(environment.clone()),
usize::from(area.width).saturating_sub(reserved),
);
line.spans.splice(*index..*index, environment.spans);
}
Widget::render(line, area, buf);
}
fn desired_height(&self, _width: u16) -> u16 {
1
}
}
struct ReadOnlyThreadNotice {
reason: ReadOnlyThread,
agents_navigation_key_available: bool,
@@ -298,13 +321,25 @@ impl ChatWidget {
let bottom_pane = self.bottom_pane.backdrop_with_options(options);
let above_composer = if self.quick_dial_menu && !options.floating_shortcuts {
RenderableItem::Owned(Box::new(self.quick_dial_hud()))
} else if let Some(backend) = self.visible_new_backend_control() {
let mut spans = vec![" ".into(), backend.into()];
} else if let Some((cycle, environment)) = self.visible_new_backend_control() {
let mut spans = vec![" ".into(), cycle.unwrap_or("Cloud").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()]);
if cycle.is_some()
&& let Some(key) = keymap.primary_hint(KeymapContext::Global, "change_host")
{
spans.extend([" ".into(), key.into(), " cycle".dim()]);
}
RenderableItem::Owned(Box::new(Paragraph::new(Line::from(spans))))
let environment = environment.map(|name| {
spans.push(" - ".dim());
let index = spans.len();
if let Some(key) =
keymap.primary_hint(KeymapContext::Global, "choose_cloud_environment")
{
spans.extend([" ".into(), key.into(), " change".dim()]);
}
(index, name.to_owned())
});
RenderableItem::Owned(Box::new(NewBackendControl(Line::from(spans), environment)))
} else {
return bottom_pane;
};
+19
View File
@@ -105,6 +105,7 @@ pub(crate) struct RuntimeKeymap {
pub(crate) struct AppKeymap {
/// Change where a new conversation runs.
pub(crate) change_host: Vec<KeyBinding>,
pub(crate) choose_cloud_environment: Vec<KeyBinding>,
pub(crate) focus_main_composer: Vec<KeyBinding>,
pub(crate) focus_sidebar_content: Vec<KeyBinding>,
pub(crate) focus_sidebar_tabs: Vec<KeyBinding>,
@@ -775,6 +776,11 @@ impl RuntimeKeymap {
&defaults.app.change_host,
"tui.keymap.global.change_host",
)?,
choose_cloud_environment: resolve_bindings(
keymap.global.choose_cloud_environment.as_ref(),
&defaults.app.choose_cloud_environment,
"tui.keymap.global.choose_cloud_environment",
)?,
focus_main_composer: resolve_bindings(
keymap.global.focus_main_composer.as_ref(),
&[],
@@ -1882,6 +1888,7 @@ impl RuntimeKeymap {
Self {
app: AppKeymap {
change_host: Vec::new(),
choose_cloud_environment: Vec::new(),
focus_main_composer: Vec::new(),
focus_sidebar_content: Vec::new(),
focus_sidebar_tabs: Vec::new(),
@@ -2228,6 +2235,10 @@ impl RuntimeKeymap {
fn validate_conflicts(&self) -> Result<(), String> {
for (action, bindings) in [
("global.change_host", &self.app.change_host),
(
"global.choose_cloud_environment",
&self.app.choose_cloud_environment,
),
("chat.open_presets", &self.chat.open_presets),
("chat.toggle_voice", &self.chat.toggle_voice),
("composer.undo", &self.composer.undo),
@@ -2257,6 +2268,10 @@ impl RuntimeKeymap {
#[cfg(unix)]
for (action, bindings) in [
("global.change_host", &self.app.change_host),
(
"global.choose_cloud_environment",
&self.app.choose_cloud_environment,
),
("global.open_agents", &self.app.open_agents),
("global.focus_main_composer", &self.app.focus_main_composer),
(
@@ -2310,6 +2325,10 @@ impl RuntimeKeymap {
let divider_right = self.app.move_divider_right.as_slice();
let main_bindings = [
("change_host", self.app.change_host.as_slice()),
(
"choose_cloud_environment",
self.app.choose_cloud_environment.as_slice(),
),
(
"focus_main_composer",
self.app.focus_main_composer.as_slice(),
+1
View File
@@ -321,6 +321,7 @@ macro_rules! define_runtime_action_bindings {
define_runtime_action_bindings! {
"global" => Global, app, global [
change_host,
choose_cloud_environment,
open_agents,
open_transcript,
find_transcript,
+32 -23
View File
@@ -45,28 +45,29 @@ const LIST_RESERVED_BINDINGS: &[(&str, KeyBinding)] = &[
/// Compact set of keymap contexts that share one active input path.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub(crate) struct KeymapContextSet(u32);
pub(crate) struct KeymapContextSet(u64);
const ACTIVITY_FOCUS: u32 = 1 << 13;
const TRANSCRIPT_CLOSE: u32 = 1 << 15;
const WARNINGS_FOCUS: u32 = 1 << 16;
const VOICE_TOGGLE: u32 = 1 << 17;
const RAW_KEY_CAPTURE: u32 = 1 << 18;
const VOICE_TOGGLE_BLOCKED: u32 = 1 << 19;
const TRANSCRIPT_ACTIONS: u32 = 1 << 20;
const BACKEND_CYCLING: u32 = 1 << 21;
const SIDE_PANE: u32 = 1 << 22;
const MAIN_COMPOSER_FOCUS: u32 = 1 << 23;
const PANE_DIRECTION: u32 = 1 << 24;
const OPEN_PANE: u32 = 1 << 25;
const FOCUSED_SIDE_PANE: u32 = 1 << 26;
const SIDEBAR_CHOOSER: u32 = 1 << 27;
const SIDEBAR_RESIZE: u32 = 1 << 28;
const FOCUSED_SIDEBAR: u32 = 1 << 29;
const TRANSCRIPT_SELECT: u32 = 1 << 30;
const COMPOSER_EDIT_ONLY: u32 = 1 << 31;
const ACTIVITY_FOCUS: u64 = 1 << 13;
const TRANSCRIPT_CLOSE: u64 = 1 << 15;
const WARNINGS_FOCUS: u64 = 1 << 16;
const VOICE_TOGGLE: u64 = 1 << 17;
const RAW_KEY_CAPTURE: u64 = 1 << 18;
const VOICE_TOGGLE_BLOCKED: u64 = 1 << 19;
const TRANSCRIPT_ACTIONS: u64 = 1 << 20;
const BACKEND_CYCLING: u64 = 1 << 21;
const SIDE_PANE: u64 = 1 << 22;
const MAIN_COMPOSER_FOCUS: u64 = 1 << 23;
const PANE_DIRECTION: u64 = 1 << 24;
const OPEN_PANE: u64 = 1 << 25;
const FOCUSED_SIDE_PANE: u64 = 1 << 26;
const SIDEBAR_CHOOSER: u64 = 1 << 27;
const SIDEBAR_RESIZE: u64 = 1 << 28;
const FOCUSED_SIDEBAR: u64 = 1 << 29;
const TRANSCRIPT_SELECT: u64 = 1 << 30;
const COMPOSER_EDIT_ONLY: u64 = 1 << 31;
const CLOUD_ENVIRONMENT_SELECTION: u64 = 1 << 32;
const TRANSCRIPT_BROWSING: u32 = 1 << 14;
const TRANSCRIPT_BROWSING: u64 = 1 << 14;
impl KeymapContextSet {
pub(crate) const fn composer_edit_only() -> Self {
@@ -92,6 +93,10 @@ impl KeymapContextSet {
Self(self.0 | BACKEND_CYCLING)
}
pub(crate) const fn with_cloud_environment_selection(self) -> Self {
Self(self.0 | CLOUD_ENVIRONMENT_SELECTION)
}
/// Add only the detail-close action to an owned composer path.
pub(crate) const fn with_transcript_close(self) -> Self {
Self(self.0 | context_bit(KeymapContext::Pager) | TRANSCRIPT_CLOSE)
@@ -230,8 +235,12 @@ impl KeymapContextSet {
if action.context == KeymapContext::Pager && action.action == "mark_markdown" {
return self.0 & TRANSCRIPT_SELECT != 0;
}
if action.context == KeymapContext::Global && action.action == "change_host" {
return self.0 & BACKEND_CYCLING != 0;
if action.context == KeymapContext::Global {
match action.action {
"change_host" => return self.0 & BACKEND_CYCLING != 0,
"choose_cloud_environment" => return self.0 & CLOUD_ENVIRONMENT_SELECTION != 0,
_ => {}
}
}
if action.is_side_pane() {
let required = match action.action {
@@ -291,7 +300,7 @@ impl KeymapContextSet {
}
}
const fn context_bit(context: KeymapContext) -> u32 {
const fn context_bit(context: KeymapContext) -> u64 {
1 << match context {
KeymapContext::Global => 0,
KeymapContext::Chat => 1,
@@ -57,6 +57,7 @@ pub(in crate::keymap) fn register(
(Global, "sidebar_down", KeyCode::Down, "down"),
(Global, "sidebar_down", Char('j'), "j"),
(Pager, "mark_markdown", Char('v'), "v"),
(Global, "choose_cloud_environment", Char('e'), "e"),
] {
if remaining == 0 {
break;
+14
View File
@@ -636,6 +636,20 @@ fn warning_context_keeps_local_chords_ahead_of_copy_and_hides_unreachable_hints(
assert!(!runtime.app.copy.is_pressed(event));
}
#[test]
fn cloud_picker_preserves_composer_undo_and_stays_hidden_in_edit_only_popups() {
let picker = keymap_action_id("global", "choose_cloud_environment").unwrap();
let undo = keymap_action_id("composer", "undo").unwrap();
let editor = KeymapContextSet::new(KeymapContext::Editor).with(KeymapContext::Composer);
assert!(
editor
.with_cloud_environment_selection()
.contains_action(undo)
);
assert!(!KeymapContextSet::composer_edit_only().contains_action(picker));
}
#[test]
fn composer_undo_defaults_yield_without_shadowing_vim_redo() {
let mut config = TuiKeymap::default();