diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 30dd137241..eea1030474 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -248,6 +248,7 @@ mod misalignment_policy; mod model_defaults; mod new_session; mod quick_dials; +pub(crate) mod remote_control; mod turn_tips; pub(crate) use new_session::has_launch_setting; mod archived_thread; @@ -649,6 +650,7 @@ pub(crate) struct App { pub(crate) pending_update_action: Option, /// Retained through all loop exits so shutdown cannot interrupt stop followed by start. daemon_restart: Option>>, + remote_control_pending: bool, /// Tracks the thread we intentionally shut down while exiting the app. /// diff --git a/codex-rs/tui/src/app/event_dispatch.rs b/codex-rs/tui/src/app/event_dispatch.rs index b976c63d59..3a8433243e 100644 --- a/codex-rs/tui/src/app/event_dispatch.rs +++ b/codex-rs/tui/src/app/event_dispatch.rs @@ -229,6 +229,7 @@ impl App { }; match event { AppEvent::OpenDaemonMenu => self.open_daemon_menu(), + AppEvent::RemoteControl(_) | AppEvent::RemoteControlForBackend { .. } | AppEvent::RemoteControlFinished { .. } => {} AppEvent::ConfirmDaemonRestart => self.confirm_daemon_restart(), AppEvent::RunDaemonRestart => { if self.chat_widget.remote_connection.as_ref().is_some_and(|connection| connection.is_managed_daemon) diff --git a/codex-rs/tui/src/app/remote_control.rs b/codex-rs/tui/src/app/remote_control.rs new file mode 100644 index 0000000000..cf39e3778b --- /dev/null +++ b/codex-rs/tui/src/app/remote_control.rs @@ -0,0 +1,375 @@ +//! Remote control configures the entire local daemon. Device pairing is a separate action, +//! and pairing codes are redacted from event diagnostics. + +use super::App; +use super::backend_sessions::BackendSessions; +use crate::app_event::AppEvent; +use crate::app_server_session::AppServerSession; +use crate::backend_id::BackendId; +use crate::bottom_pane::SelectionItem; +use crate::bottom_pane::SelectionViewParams; +use codex_app_server_protocol::ClientRequest; +use codex_app_server_protocol::RemoteControlConnectionStatus; +use codex_app_server_protocol::RemoteControlPairingStartParams; +use codex_app_server_protocol::RemoteControlPairingStartResponse; +use std::time::Duration; + +const OPERATION_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 30); + +#[derive(Debug, Clone, Copy)] +pub(crate) enum Action { + Menu, + Enable, + Disable, + AddDevice, +} + +pub(crate) enum Outcome { + Menu(RemoteControlConnectionStatus, Option), + Unavailable(String), + Pairing(String), + Info(String), + Error(String), +} + +impl std::fmt::Debug for Outcome { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Menu(status, saved) => f.debug_tuple("Menu").field(status).field(saved).finish(), + Self::Unavailable(reason) => f.debug_tuple("Unavailable").field(reason).finish(), + Self::Pairing(_) => f.write_str("Pairing([redacted])"), + Self::Info(_) => f.write_str("Info([redacted])"), + Self::Error(_) => f.write_str("Error([redacted])"), + } + } +} + +fn pairing(code: String) -> SelectionViewParams { + SelectionViewParams { + title: Some("Add device".into()), + subtitle: Some(format!( + "Enter this pairing code on your other device: {code}. If it expires, select Add device again." + )), + allow_input_when_disconnected: true, + items: vec![SelectionItem { + name: "Done".into(), + dismiss_on_select: true, + ..Default::default() + }], + ..SelectionViewParams::picker() + } +} + +fn menu( + connection: Option<(BackendId, RemoteControlConnectionStatus, Option)>, + unavailable: &str, +) -> SelectionViewParams { + let status = connection.map(|(_, status, _)| status); + let enabled = status.is_some_and(|status| status != RemoteControlConnectionStatus::Disabled); + let retry_disable = !enabled && connection.is_some_and(|(_, _, saved)| saved != Some(false)); + let (name, action) = if enabled || retry_disable { + ("Disable", Action::Disable) + } else if status.is_none() { + ("Enable (disabled)", Action::Enable) + } else { + ("Enable", Action::Enable) + }; + SelectionViewParams { + title: Some("Remote control".into()), + allow_input_when_disconnected: true, + subtitle: Some(match status { + None => unavailable.into(), + Some(_) if retry_disable => "Remote control is off now, but may return after restart. Choose Disable to save the preference.".into(), + Some(_) => "Applies to local sessions; cloud sessions are unaffected.".into(), + }), + items: [ + (name, action, None), + ( + "Add device", + Action::AddDevice, + (!enabled).then(|| "Enable remote control first".into()), + ), + ] + .into_iter() + .take(if status.is_some() { 2 } else { 1 }) + .map(|(name, action, disabled_reason)| SelectionItem { + name: name.into(), + disabled_reason, + is_disabled: status.is_none(), + actions: vec![Box::new(move |tx| { + if let Some((backend_id, _, _)) = connection { + tx.send(AppEvent::RemoteControlForBackend { backend_id, action }); + } + })], + dismiss_on_select: true, + ..Default::default() + }) + .collect(), + ..SelectionViewParams::picker() + } +} + +fn local_daemon<'a>( + app: &App, + backends: &'a BackendSessions, +) -> Option<(&'a AppServerSession, std::path::PathBuf)> { + let (owner, target) = match &app.app_server_target { + target @ crate::AppServerTarget::LocalDaemon { .. } => (backends.displayed_owner(), target), + crate::AppServerTarget::Cloud => { + backends.settings.iter().find_map(|(&owner, settings)| { + matches!(settings.target, crate::AppServerTarget::LocalDaemon { .. }) + .then_some((owner, &settings.target)) + })? + } + _ => return None, + }; + let crate::AppServerTarget::LocalDaemon { + endpoint: crate::RemoteAppServerEndpoint::UnixSocket { socket_path }, + .. + } = target + else { + return None; + }; + backends + .session(owner) + .map(|session| (session, socket_path.to_path_buf())) +} + +pub(super) fn handle(app: &mut App, backends: &BackendSessions, event: AppEvent) { + let daemon = local_daemon(app, backends); + let (action, requested_owner) = match event { + AppEvent::RemoteControl(action) => (action, None), + AppEvent::RemoteControlForBackend { backend_id, action } => (action, Some(backend_id)), + AppEvent::RemoteControlFinished { backend_id, result } => { + app.remote_control_pending = false; + if daemon + .as_ref() + .is_some_and(|(session, _)| session.backend_id() == backend_id) + { + match result { + Outcome::Menu(status, saved) => app + .chat_widget + .show_selection_view(menu(Some((backend_id, status, saved)), "")), + Outcome::Unavailable(reason) => { + app.chat_widget + .show_selection_view(menu(/*connection*/ None, &reason)) + } + Outcome::Pairing(code) => app.chat_widget.show_selection_view(pairing(code)), + Outcome::Info(message) => { + app.chat_widget.add_info_message(message, /*hint*/ None) + } + Outcome::Error(message) => app.chat_widget.add_error_message(message), + } + } + return; + } + _ => return, + }; + let Some((daemon, endpoint)) = daemon + .filter(|(session, _)| requested_owner.is_none_or(|owner| session.backend_id() == owner)) + else { + if matches!(action, Action::Menu) { + app.chat_widget.show_selection_view(menu( + /*connection*/ None, + "Remote control requires the local background server", + )); + } else { + app.chat_widget + .add_error_message("Remote control requires the local background server.".into()); + } + return; + }; + if app.remote_control_pending { + app.chat_widget.add_error_message( + "A remote control operation is already in progress. Try again when it finishes.".into(), + ); + return; + } + app.remote_control_pending = true; + let backend_id = daemon.backend_id(); + let tx = app.app_event_tx.app_event_tx.clone(); + tokio::spawn(async move { + let operation = async { + match verified_daemon_session(endpoint.as_path(), backend_id).await { + Ok((session, settings_file)) => { + let mut result = run(session, action).await; + let expected = match (&action, &result) { + (Action::Enable, Outcome::Menu(..)) => Some(true), + (Action::Disable, Outcome::Info(_)) => Some(false), + _ => None, + }; + if expected.is_some() || matches!(result, Outcome::Menu(..)) { + let saved = match tokio::fs::read(&settings_file).await { + Ok(bytes) => serde_json::from_slice::(&bytes) + .ok() + .and_then(|value| { + value + .get("remoteControlEnabled") + .map_or(Some(false), serde_json::Value::as_bool) + }), + Err(err) if err.kind() == std::io::ErrorKind::NotFound => Some(false), + Err(_) => None, + }; + if let Outcome::Menu(_, preference) = &mut result { + *preference = saved; + } + if let Some(expected) = expected + && saved != Some(expected) + { + return Outcome::Error("Remote control changed for the running daemon, but the preference could not be saved. It may revert after restart.".into()); + } + } + result + } + Err(reason) if matches!(action, Action::Menu) => Outcome::Unavailable(reason), + Err(reason) => Outcome::Error(reason), + } + }; + let result = bounded(action, operation).await; + let _ = tx.send(AppEvent::RemoteControlFinished { backend_id, result }); + }); +} + +async fn bounded(action: Action, operation: impl std::future::Future) -> Outcome { + tokio::time::timeout(OPERATION_TIMEOUT, operation) + .await + .unwrap_or_else(|_| match action { + Action::Menu => Outcome::Error("Remote control status timed out. Try again.".into()), + Action::Enable | Action::Disable | Action::AddDevice => Outcome::Error( + "The remote control operation timed out. Its outcome is unknown; reopen /rc to check the state.".into(), + ), + }) +} + +async fn verified_daemon_session( + endpoint: &std::path::Path, + backend_id: BackendId, +) -> Result<(AppServerSession, std::path::PathBuf), String> { + let status = codex_app_server_daemon::run(codex_app_server_daemon::LifecycleCommand::Version) + .await + .map_err(|_| { + "Codex could not verify that it manages the local background server.".to_string() + })?; + let Some(protected) = + codex_app_server_client::verified_local_daemon_socket(&status.socket_path) + .ok() + .flatten() + else { + return Err("Codex could not verify that it manages the local background server.".into()); + }; + if status.backend.is_none() || endpoint != status.socket_path && endpoint != protected.as_path() + { + return Err("Codex could not verify that it manages the local background server.".into()); + } + let target = crate::AppServerTarget::LocalDaemon { + endpoint: crate::RemoteAppServerEndpoint::UnixSocket { + socket_path: protected, + }, + allow_embedded_fallback: false, + }; + let client = crate::app_server_connection::connect(&target) + .await + .map_err(|err| { + format!("Could not connect to the verified local background server: {err}") + })?; + let session = AppServerSession::new( + backend_id, + client, + crate::app_server_session::ThreadParamsMode::Embedded, + ); + let supported = session + .server_version() + .and_then(|v| semver::Version::parse(v).ok()) + .is_some_and(|v| { + v == semver::Version::new(0, 0, 0) + || semver::Version::parse("0.163.0-alpha.2").is_ok_and(|minimum| v >= minimum) + }); + if !supported { + return Err( + "Update the background server with /daemon to use persistent remote control.".into(), + ); + } + let home = status + .socket_path + .parent() + .and_then(std::path::Path::parent) + .ok_or_else(|| "Could not locate background server settings.".to_string())?; + Ok((session, home.join("app-server-daemon/settings.json"))) +} + +async fn run(mut session: AppServerSession, action: Action) -> Outcome { + let request_id = session.next_request_id(); + let request = match action { + Action::Menu => ClientRequest::RemoteControlStatusRead { + request_id, + params: None, + }, + Action::Enable => ClientRequest::RemoteControlEnable { + request_id, + params: None, + }, + Action::Disable => ClientRequest::RemoteControlDisable { + request_id, + params: None, + }, + Action::AddDevice => ClientRequest::RemoteControlPairingStart { + request_id, + params: RemoteControlPairingStartParams { manual_code: true }, + }, + }; + let handle = session.request_handle(); + if matches!(action, Action::AddDevice) { + return match handle + .request_typed::(request) + .await + { + Ok(response) => response.manual_pairing_code.map_or_else( + || Outcome::Error("No manual pairing code was returned.".into()), + Outcome::Pairing, + ), + Err(_) => Outcome::Error("Could not add device. Try again.".into()), + }; + } + #[derive(serde::Deserialize)] + struct Status { + status: RemoteControlConnectionStatus, + } + let status = handle.request_typed::(request).await; + match (action, status) { + (Action::Menu | Action::Enable, Ok(response)) => Outcome::Menu(response.status, None), + (Action::Disable, Ok(_)) => Outcome::Info( + "Remote control is disabled for local sessions. Cloud sessions are unaffected.".into(), + ), + (Action::Menu, Err(codex_app_server_client::TypedRequestError::Server { source, .. })) + if source.message == "remote control is disabled by managed requirements" => + { + Outcome::Unavailable("Remote control is disabled by managed requirements.".into()) + } + (Action::Menu, Err(_)) => Outcome::Error("Could not read remote control status.".into()), + (Action::Enable, Err(err)) => Outcome::Error(mutation_error("enabling", err)), + (Action::Disable, Err(err)) => Outcome::Error(mutation_error("disabling", err)), + (Action::AddDevice, _) => unreachable!(), + } +} + +fn mutation_error(operation: &str, err: codex_app_server_client::TypedRequestError) -> String { + if let codex_app_server_client::TypedRequestError::Server { source, .. } = err { + match source.message.as_str() { + "remote control requires ChatGPT authentication" + | "remote control requires ChatGPT authentication; API key auth is not supported" => { + return "Sign in with ChatGPT to manage remote control.".into(); + } + "remote control is disabled by managed requirements" => { + return "Remote control is disabled by managed requirements.".into(); + } + _ => {} + } + } + format!( + "Could not complete {operation} remote control. The running daemon may already have changed; reopen /rc to check its state." + ) +} + +#[cfg(test)] +#[path = "remote_control_tests.rs"] +mod tests; diff --git a/codex-rs/tui/src/app/remote_control_tests.rs b/codex-rs/tui/src/app/remote_control_tests.rs new file mode 100644 index 0000000000..785f4adf08 --- /dev/null +++ b/codex-rs/tui/src/app/remote_control_tests.rs @@ -0,0 +1,124 @@ +#![cfg(test)] + +use super::*; +use crate::app_server_session::ThreadParamsMode; +use crate::chatwidget::tests::helpers::render_bottom_popup; +use crate::chatwidget::tests::make_chatwidget_manual_with_sender; +use codex_app_server_client::AppServerClient; +use codex_app_server_client::CloudClient; +use codex_app_server_client::CloudOperation; +use pretty_assertions::assert_eq; + +#[tokio::test] +async fn rc_requests_durable_changes_and_manual_pairing() { + let (client, mut commands, _events) = CloudClient::channel(/*capacity*/ 3); + let session = AppServerSession::new( + BackendId::new(), + AppServerClient::Cloud(client), + ThreadParamsMode::Cloud, + ); + for action in [Action::Enable, Action::Disable, Action::AddDevice] { + let request = run(session.request_view(), action); + let check = async { + let command = commands.recv().await.unwrap(); + let CloudOperation::Request(request) = command.operation else { + panic!("expected request") + }; + assert!(matches!( + (action, *request), + ( + Action::Enable, + ClientRequest::RemoteControlEnable { params: None, .. } + ) | ( + Action::Disable, + ClientRequest::RemoteControlDisable { params: None, .. } + ) | ( + Action::AddDevice, + ClientRequest::RemoteControlPairingStart { + params: RemoteControlPairingStartParams { manual_code: true }, + .. + } + ) + )); + drop(command.response); + }; + tokio::join!(request, check); + } +} + +#[tokio::test] +async fn rc_menu_snapshot() { + let (mut chat, _, _, _) = make_chatwidget_manual_with_sender().await; + let mut views = Vec::new(); + for state in [ + None, + Some((RemoteControlConnectionStatus::Disabled, Some(false))), + Some((RemoteControlConnectionStatus::Connected, Some(true))), + Some((RemoteControlConnectionStatus::Disabled, Some(true))), + ] { + chat.show_selection_view(menu( + state.map(|(status, saved)| (crate::backend_id::BackendId::new(), status, saved)), + "Remote control requires the local background server", + )); + views.push(render_bottom_popup(&chat, /*width*/ 80)); + } + assert_eq!( + format!("{:?}", Outcome::Pairing("ABCD-EFGH".into())), + "Pairing([redacted])" + ); + chat.show_selection_view(pairing("ABCD-EFGH".into())); + views.push(render_bottom_popup(&chat, /*width*/ 80)); + insta::assert_snapshot!("rc_menu", views.join("\n\n")); +} + +#[tokio::test] +async fn rc_from_cloud_uses_only_the_parked_local_daemon() { + use super::super::backend_sessions::BackendSessions; + use super::super::test_support::make_test_app; + use crate::AppServerTarget; + let mut app = make_test_app().await; + let (cloud, _cloud_commands, _cloud_events) = CloudClient::channel(/*capacity*/ 2); + let cloud_session = AppServerSession::new( + BackendId::new(), + AppServerClient::Cloud(cloud), + ThreadParamsMode::Cloud, + ); + let (local, _local_commands, local_events) = CloudClient::channel(/*capacity*/ 2); + let local_id = BackendId::new(); + let local_session = AppServerSession::new( + local_id, + AppServerClient::Cloud(local), + ThreadParamsMode::Embedded, + ); + let mut backends = BackendSessions::from_initial(cloud_session, vec![local_session]); + let mut settings = app.backend_settings(); + settings.target = AppServerTarget::LocalDaemon { + endpoint: crate::RemoteAppServerEndpoint::UnixSocket { + socket_path: codex_utils_absolute_path::AbsolutePathBuf::relative_to_current_dir( + "codex.sock", + ) + .unwrap(), + }, + allow_embedded_fallback: false, + }; + backends.settings.insert(local_id, settings); + app.app_server_target = AppServerTarget::Embedded; + assert!(local_daemon(&app, &backends).is_none()); + app.app_server_target = AppServerTarget::Cloud; + drop(local_events); + assert_eq!( + backends.next_event(/*paused_backend*/ None).await.0, + local_id + ); + assert!(!backends.is_listening(local_id)); + assert_eq!( + local_daemon(&app, &backends).map(|(session, _)| session.backend_id()), + Some(local_id) + ); +} + +#[tokio::test(start_paused = true)] +async fn stalled_mutation_reports_unknown_outcome() { + let result = bounded(Action::Disable, std::future::pending()).await; + assert_matches::assert_matches!(result, Outcome::Error(message) if message.contains("outcome is unknown")); +} diff --git a/codex-rs/tui/src/app/snapshots/codex_tui__app__remote_control__tests__rc_menu.snap b/codex-rs/tui/src/app/snapshots/codex_tui__app__remote_control__tests__rc_menu.snap new file mode 100644 index 0000000000..147bef15c0 --- /dev/null +++ b/codex-rs/tui/src/app/snapshots/codex_tui__app__remote_control__tests__rc_menu.snap @@ -0,0 +1,48 @@ +--- +source: tui/src/app/remote_control_tests.rs +expression: "views.join(\"\\n\\n\")" +--- + Remote control + Remote control requires the local background server + + +› Enable (disabled) + + enter select · esc back + + Remote control + Applies to local sessions; cloud sessions are unaffected. + + +› 1. Enable + Add device (disabled) Enable remote control first + + enter select · esc back + + Remote control + Applies to local sessions; cloud sessions are unaffected. + + +› 1. Disable + 2. Add device + + enter select · esc back + + Remote control + Remote control is off now, but may return after restart. Choose Disable to + save the preference. + + +› 1. Disable + Add device (disabled) Enable remote control first + + enter select · esc back + + Add device + Enter this pairing code on your other device: ABCD-EFGH. If it expires, + select Add device again. + + +› 1. Done + + enter select · esc back diff --git a/codex-rs/tui/src/app/startup.rs b/codex-rs/tui/src/app/startup.rs index c06a93aed5..9e51c9be30 100644 --- a/codex-rs/tui/src/app/startup.rs +++ b/codex-rs/tui/src/app/startup.rs @@ -1057,6 +1057,7 @@ See the Codex keymap documentation for supported actions and examples." daemon_cli_executable, pending_update_action: None, daemon_restart: None, + remote_control_pending: false, pending_shutdown_exit_thread_id: None, windows_sandbox: WindowsSandboxState { prompt_after_trust: should_prompt_windows_sandbox_nux_at_startup @@ -1561,6 +1562,15 @@ See the Codex keymap documentation for supported actions and examples." { backends.parked_inputs_mut(slot).remove(thread_id); } + if matches!(&event, AppEvent::RemoteControl(_) | AppEvent::RemoteControlForBackend { .. } | AppEvent::RemoteControlFinished { .. }) { + super::remote_control::handle(&mut app, &backends, event); + if app.chat_widget.has_active_modal() + && let Err(err) = app.render_startup_frame(tui, &app_event_rx) + { + break Err(err); + } + continue; + } let switch_backend = match &event { AppEvent::ChooseCloudEnvironment => { if let Some(source) = cloud_draft diff --git a/codex-rs/tui/src/app/test_support.rs b/codex-rs/tui/src/app/test_support.rs index 41b883e22f..d380068553 100644 --- a/codex-rs/tui/src/app/test_support.rs +++ b/codex-rs/tui/src/app/test_support.rs @@ -117,6 +117,7 @@ pub(crate) async fn make_test_app() -> Box { daemon_cli_executable: None, pending_update_action: None, daemon_restart: None, + remote_control_pending: false, pending_shutdown_exit_thread_id: None, windows_sandbox: WindowsSandboxState::default(), thread_event_channels: HashMap::new(), diff --git a/codex-rs/tui/src/app/tests.rs b/codex-rs/tui/src/app/tests.rs index e11fdf958c..89f8d690d1 100644 --- a/codex-rs/tui/src/app/tests.rs +++ b/codex-rs/tui/src/app/tests.rs @@ -9248,6 +9248,7 @@ async fn make_test_app() -> Box { daemon_cli_executable: None, pending_update_action: None, daemon_restart: None, + remote_control_pending: false, pending_shutdown_exit_thread_id: None, windows_sandbox: WindowsSandboxState::default(), thread_event_channels: HashMap::new(), @@ -9394,6 +9395,7 @@ pub(super) async fn make_test_app_with_channels() -> ( daemon_cli_executable: None, pending_update_action: None, daemon_restart: None, + remote_control_pending: false, pending_shutdown_exit_thread_id: None, windows_sandbox: WindowsSandboxState::default(), thread_event_channels: HashMap::new(), diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index 8c5a2693be..ebc48ef459 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -367,6 +367,15 @@ pub(crate) enum AppEvent { notice: crate::security_setup::Notice, }, OpenDaemonMenu, + RemoteControl(crate::app::remote_control::Action), + RemoteControlForBackend { + backend_id: crate::backend_id::BackendId, + action: crate::app::remote_control::Action, + }, + RemoteControlFinished { + backend_id: crate::backend_id::BackendId, + result: crate::app::remote_control::Outcome, + }, ConfirmDaemonRestart, RunDaemonRestart, ConfirmDaemonUpdate(crate::update_action::DaemonUpdateSource), diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index a13422fe2b..ca9a235f0b 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -191,7 +191,8 @@ //! //! During reconnection, `handle_restricted_key` edits the draft directly without popup dispatch, //! composer shortcuts, or submission; `?` becomes literal input. Enter and Tab leave the draft -//! intact until reconnection succeeds, except for `/warnings`, `/config`, `/quit`, and `/exit`. +//! intact until reconnection succeeds, except for `/warnings`, `/config`, `/rc` (alias `/remote`, +//! including `stop`), `/quit`, and `/exit`. //! When connected but the thread is unavailable, configured //! submit keys may dispatch explicitly allowed recovery and local commands; other drafts stay put. //! Empty-prompt agents navigation remains available with its usual editor and draft guards. @@ -526,7 +527,7 @@ pub enum InputResult { fn parent_owned_command_is_allowed(command: SlashCommand, args: &str) -> bool { if matches!( command, - SlashCommand::Export | SlashCommand::Title | SlashCommand::Statusline + SlashCommand::Export | SlashCommand::Title | SlashCommand::Statusline | SlashCommand::Rc ) { return true; } @@ -3489,7 +3490,7 @@ impl ChatComposer { matches!( self.slash_input().command(name), Some(SlashCommandItem::Builtin(command)) - if name == command.command() + if (name == command.command() || command == SlashCommand::Rc && name == "remote") && parent_owned_command_is_allowed(command, args) ) }); diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/agents_navigation_tests.rs b/codex-rs/tui/src/bottom_pane/chat_composer/agents_navigation_tests.rs index 87079389a6..bbc151deb8 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer/agents_navigation_tests.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer/agents_navigation_tests.rs @@ -14,6 +14,8 @@ fn parent_owned_thread_allows_local_commands() { ("/btw", SlashCommand::Btw), ("/diff ", SlashCommand::Diff), ("/daemon", SlashCommand::Daemon), + ("/rc", SlashCommand::Rc), + ("/remote", SlashCommand::Rc), ("/warnings", SlashCommand::Warnings), ] { let (mut composer, _rx) = new_test_composer(); @@ -29,6 +31,7 @@ fn parent_owned_thread_allows_local_commands() { for (command, args) in [ (SlashCommand::Title, "model"), (SlashCommand::Statusline, "model --no-colors"), + (SlashCommand::Rc, "invalid"), ] { let (mut composer, _rx) = new_test_composer(); composer.set_parent_owned_thread(); diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/reconnect.rs b/codex-rs/tui/src/bottom_pane/chat_composer/reconnect.rs index 3a99ad388c..e18fce2458 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer/reconnect.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer/reconnect.rs @@ -199,7 +199,7 @@ impl ChatComposer { .or_else(|| input.inline_command(text).map(|command| command.command)) .filter(|_| text.trim().lines().count() == 1); if matches!(command, Some(SlashCommandItem::Builtin(command)) - if matches!(command, SlashCommand::Warnings | SlashCommand::Config | SlashCommand::Quit | SlashCommand::Exit) + if matches!(command, SlashCommand::Warnings | SlashCommand::Config | SlashCommand::Rc | SlashCommand::Quit | SlashCommand::Exit) || mode == RestrictedInputMode::UnavailableThread && command.available_when_thread_unavailable()) { let result = self diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/reconnect_tests.rs b/codex-rs/tui/src/bottom_pane/chat_composer/reconnect_tests.rs index d7bda8b860..89cec6bb24 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer/reconnect_tests.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer/reconnect_tests.rs @@ -324,6 +324,11 @@ fn disconnected_input_dispatches_local_config_command() { InputResult::Command(SlashCommand::Config), ); assert_eq!(composer.current_text(), ""); + composer.set_text_content("/rc".into(), Vec::new(), Vec::new()); + assert_eq!( + composer.handle_restricted_key(KeyCode::Enter.into(), RestrictedInputMode::Disconnected), + InputResult::Command(SlashCommand::Rc), + ); } #[test] diff --git a/codex-rs/tui/src/bottom_pane/slash_commands.rs b/codex-rs/tui/src/bottom_pane/slash_commands.rs index b3d3b5e7c4..9cd8018e29 100644 --- a/codex-rs/tui/src/bottom_pane/slash_commands.rs +++ b/codex-rs/tui/src/bottom_pane/slash_commands.rs @@ -348,6 +348,7 @@ mod tests { SlashCommand::Mention, SlashCommand::Status, SlashCommand::Daemon, + SlashCommand::Rc, SlashCommand::Warnings, SlashCommand::Pwd, SlashCommand::Usage, diff --git a/codex-rs/tui/src/chatwidget/slash_dispatch.rs b/codex-rs/tui/src/chatwidget/slash_dispatch.rs index 4523395a3b..f985b03356 100644 --- a/codex-rs/tui/src/chatwidget/slash_dispatch.rs +++ b/codex-rs/tui/src/chatwidget/slash_dispatch.rs @@ -538,6 +538,9 @@ impl ChatWidget { self.add_hooks_output(); } SlashCommand::Daemon => self.app_event_tx.send(AppEvent::OpenDaemonMenu), + SlashCommand::Rc => self.app_event_tx.send(AppEvent::RemoteControl( + crate::app::remote_control::Action::Menu, + )), SlashCommand::Warnings => self.app_event_tx.send(AppEvent::OpenWarnings), SlashCommand::Status => { if self.should_prefetch_rate_limits() { @@ -803,6 +806,9 @@ impl ChatWidget { return; } match cmd { + SlashCommand::Rc => self.add_error_message( + "Open /rc and choose Disable to turn off remote control.".into(), + ), SlashCommand::Model if !trimmed.is_empty() => { self.handle_model_command_args(trimmed); self.app_event_tx.send(AppEvent::SettingsSelectionClosed); @@ -1324,6 +1330,7 @@ impl ChatWidget { SlashCommand::Ide | SlashCommand::Status | SlashCommand::Daemon + | SlashCommand::Rc | SlashCommand::Pwd | SlashCommand::Usage | SlashCommand::DebugConfig diff --git a/codex-rs/tui/src/chatwidget/tests/slash_commands.rs b/codex-rs/tui/src/chatwidget/tests/slash_commands.rs index f7959d50cd..0ac63dd273 100644 --- a/codex-rs/tui/src/chatwidget/tests/slash_commands.rs +++ b/codex-rs/tui/src/chatwidget/tests/slash_commands.rs @@ -2557,6 +2557,17 @@ async fn slash_keymap_debug_can_inspect_app_shortcuts() { assert!(op_rx.try_recv().is_err(), "expected no core op to be sent"); } +#[tokio::test] +async fn slash_rc_arguments_direct_user_to_menu() { + let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await; + + submit_composer_text(&mut chat, "/rc stop"); + + let [cell]: [_; 1] = drain_insert_history(&mut rx).try_into().expect("one cell"); + insta::assert_snapshot!(lines_to_single_string(&cell), @"■ Open /rc and choose Disable to turn off remote control."); + assert!(op_rx.try_recv().is_err(), "expected no agent turn"); +} + #[tokio::test] async fn slash_keymap_invalid_args_show_usage() { let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await; diff --git a/codex-rs/tui/src/slash_command.rs b/codex-rs/tui/src/slash_command.rs index 368d61a92f..443f26d8eb 100644 --- a/codex-rs/tui/src/slash_command.rs +++ b/codex-rs/tui/src/slash_command.rs @@ -55,6 +55,8 @@ pub enum SlashCommand { Mention, Status, Daemon, + #[strum(to_string = "rc", serialize = "remote")] + Rc, Warnings, Cd, #[strum(to_string = "pwd", serialize = "cwd")] @@ -118,6 +120,7 @@ impl SlashCommand { SlashCommand::Import => "import setup, this project, and recent chats from Claude Code", SlashCommand::Hooks => "view and manage lifecycle hooks", SlashCommand::Daemon => "Manage the local background server", + SlashCommand::Rc => "manage remote control for the local background server", SlashCommand::Warnings => "view retained warnings and diagnostic details", SlashCommand::Status => "show current session configuration and token usage", SlashCommand::Cd => "change the current working directory", @@ -196,6 +199,7 @@ impl SlashCommand { | SlashCommand::Side | SlashCommand::Btw | SlashCommand::Resume + | SlashCommand::Rc ) } @@ -211,6 +215,7 @@ impl SlashCommand { | SlashCommand::Mention | SlashCommand::Status | SlashCommand::Daemon + | SlashCommand::Rc | SlashCommand::Warnings | SlashCommand::Pwd | SlashCommand::Usage @@ -237,6 +242,7 @@ impl SlashCommand { | SlashCommand::Quit | SlashCommand::Exit | SlashCommand::Status + | SlashCommand::Rc | SlashCommand::Warnings | SlashCommand::DebugConfig | SlashCommand::Pwd @@ -286,6 +292,7 @@ impl SlashCommand { | SlashCommand::Hooks | SlashCommand::Status | SlashCommand::Daemon + | SlashCommand::Rc | SlashCommand::Warnings | SlashCommand::Pwd | SlashCommand::Usage