mirror of
https://github.com/pchuan98/codex.git
synced 2026-07-01 00:31:56 +08:00
feat(app-server): persist remote-control desired state (#27445)
## Why
Remote-control runtime enablement and persisted enrollment preference
were represented by separate flags. That made startup rehydration, RPC
persistence, and new-enrollment seeding race with one another, and it
did not cleanly distinguish runtime-only CLI or daemon starts from
durable app-server RPC changes.
## What Changed
- Replace the parallel enablement, seed, and rehydration flags with one
transport-owned `RemoteControlDesiredState`.
- Add nullable enrollment-scoped persistence and preserve existing
preferences during enrollment upserts.
- Rehydrate plain startup only after auth and client scope resolve,
without overwriting a concurrent RPC transition.
- Make ordinary `remoteControl/enable` and `remoteControl/disable`
durable while retaining `ephemeral: true` for runtime-only callers.
- Have the daemon explicitly request ephemeral enablement and regenerate
the app-server schemas.
## Verification
- Covered migration and `NULL`/`0`/`1` persistence round trips.
- Covered plain-start rehydration and runtime-only versus durable
enrollment seeding.
- Covered durable enable, durable disable, and ephemeral enable through
app-server RPC.
- Covered the daemon's exact `{ "ephemeral": true }` request payload.
Related issue: N/A (internal remote-control persistence architecture
change).
This commit is contained in:
@@ -210,8 +210,8 @@ Example with notification opt-out:
|
||||
- `plugin/skill/read` — read remote plugin skill markdown on demand by `remoteMarketplaceName`, `remotePluginId`, and `skillName`. This lets clients preview uninstalled remote plugin skills without downloading the plugin bundle.
|
||||
- `skills/changed` — notification emitted when watched local skill files change.
|
||||
- `app/list` — list available apps.
|
||||
- `remoteControl/enable` — experimental; enable remote control for the current app-server process and return the current remote-control status snapshot. The caller is responsible for persisting the desired setting outside app-server.
|
||||
- `remoteControl/disable` — experimental; disable remote control for the current app-server process and return the current remote-control status snapshot. This does not revoke already enrolled controller devices.
|
||||
- `remoteControl/enable` — experimental; enable remote control for the current app-server process and return the current remote-control status snapshot. By default, any missing enrollment is completed before the response and the preference is persisted for the current app-server client scope. Pass `ephemeral: true` to enable remote control only for the current process without changing the persisted preference.
|
||||
- `remoteControl/disable` — experimental; disable remote control for the current app-server process and return the current remote-control status snapshot. By default, the disabled preference is persisted for the current app-server client scope. Pass `ephemeral: true` to disable only for the current process without changing the persisted preference. This does not revoke already enrolled controller devices.
|
||||
- `remoteControl/status/read` — experimental; read the current remote-control status snapshot. `status` is one of `disabled`, `connecting`, `connected`, or `errored`; `serverName` is the local machine name used by this app-server process; `environmentId` is a string when the app-server has a current enrollment and `null` when that enrollment is cleared, invalidated, or remote control is disabled.
|
||||
- `remoteControl/pairing/start` — experimental; start a short-lived remote-control pairing artifact for the current app-server process. Pass `manualCode: true` to also request a manual pairing code. Returns `pairingCode`, `manualPairingCode`, `environmentId`, and Unix-seconds `expiresAt`; app-server intentionally does not expose the backend `serverId`.
|
||||
- `remoteControl/pairing/status` — experimental; poll whether a remote-control `pairingCode` or `manualPairingCode` has been claimed. Pass exactly one of the two fields. Returns `claimed`.
|
||||
|
||||
@@ -110,10 +110,12 @@ mod transport;
|
||||
pub use crate::error_code::INPUT_TOO_LARGE_ERROR_CODE;
|
||||
pub use crate::error_code::INVALID_PARAMS_ERROR_CODE;
|
||||
pub use crate::transport::AppServerTransport;
|
||||
pub use crate::transport::RemoteControlStartupMode;
|
||||
pub use crate::transport::app_server_control_socket_path;
|
||||
pub use crate::transport::auth::AppServerWebsocketAuthArgs;
|
||||
pub use crate::transport::auth::AppServerWebsocketAuthSettings;
|
||||
pub use crate::transport::auth::WebsocketAuthCliMode;
|
||||
pub use crate::transport::take_remote_control_disabled_env;
|
||||
|
||||
const LOG_FORMAT_ENV_VAR: &str = "LOG_FORMAT";
|
||||
const OTEL_SERVICE_NAME: &str = "codex-app-server";
|
||||
@@ -408,7 +410,7 @@ pub enum PluginStartupTasks {
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct AppServerRuntimeOptions {
|
||||
pub plugin_startup_tasks: PluginStartupTasks,
|
||||
pub remote_control_enabled: bool,
|
||||
pub remote_control_startup_mode: RemoteControlStartupMode,
|
||||
pub install_shutdown_signal_handler: bool,
|
||||
}
|
||||
|
||||
@@ -416,7 +418,7 @@ impl Default for AppServerRuntimeOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
plugin_startup_tasks: PluginStartupTasks::Start,
|
||||
remote_control_enabled: false,
|
||||
remote_control_startup_mode: RemoteControlStartupMode::ResolvePersisted,
|
||||
install_shutdown_signal_handler: true,
|
||||
}
|
||||
}
|
||||
@@ -717,15 +719,21 @@ pub async fn run_main_with_transport_options(
|
||||
let auth_manager =
|
||||
AuthManager::shared_from_config(&config, /*enable_codex_api_key_env*/ false).await;
|
||||
|
||||
let remote_control_requested = runtime_options.remote_control_enabled;
|
||||
let remote_control_enabled = remote_control_requested && state_db.is_some();
|
||||
if remote_control_requested && state_db.is_none() {
|
||||
let remote_control_startup_mode = runtime_options.remote_control_startup_mode;
|
||||
let remote_control_explicitly_requested =
|
||||
remote_control_startup_mode == RemoteControlStartupMode::EnabledEphemeral;
|
||||
let remote_control_enabled = remote_control_explicitly_requested && state_db.is_some();
|
||||
if remote_control_explicitly_requested && state_db.is_none() {
|
||||
error!("remote control disabled because sqlite state db is unavailable");
|
||||
}
|
||||
if transport_accept_handles.is_empty() && !remote_control_enabled {
|
||||
let no_local_transport = transport_accept_handles.is_empty();
|
||||
if no_local_transport
|
||||
&& remote_control_startup_mode != RemoteControlStartupMode::ResolvePersisted
|
||||
&& !remote_control_enabled
|
||||
{
|
||||
return Err(std::io::Error::new(
|
||||
ErrorKind::InvalidInput,
|
||||
if remote_control_requested && state_db.is_none() {
|
||||
if remote_control_explicitly_requested && state_db.is_none() {
|
||||
"no transport configured; remote control disabled because sqlite state db is unavailable"
|
||||
} else {
|
||||
"no transport configured; use --listen or enable remote control"
|
||||
@@ -743,9 +751,31 @@ pub async fn run_main_with_transport_options(
|
||||
transport_event_tx.clone(),
|
||||
transport_shutdown_token.clone(),
|
||||
app_server_client_name_rx,
|
||||
remote_control_enabled,
|
||||
remote_control_startup_mode,
|
||||
)
|
||||
.await?;
|
||||
if no_local_transport
|
||||
&& remote_control_startup_mode == RemoteControlStartupMode::ResolvePersisted
|
||||
{
|
||||
let persisted_enabled = match remote_control_handle
|
||||
.resolve_persisted_preference(/*app_server_client_name*/ None)
|
||||
.await
|
||||
{
|
||||
Ok(persisted_enabled) => persisted_enabled,
|
||||
Err(err) => {
|
||||
warn!("failed to resolve persisted remote control preference: {err}");
|
||||
false
|
||||
}
|
||||
};
|
||||
if !persisted_enabled {
|
||||
transport_shutdown_token.cancel();
|
||||
let _ = remote_control_accept_handle.await;
|
||||
return Err(std::io::Error::new(
|
||||
ErrorKind::InvalidInput,
|
||||
"no transport configured; use --listen or enable remote control",
|
||||
));
|
||||
}
|
||||
}
|
||||
transport_accept_handles.push(remote_control_accept_handle);
|
||||
|
||||
let outbound_handle = tokio::spawn(async move {
|
||||
|
||||
@@ -53,13 +53,14 @@ struct AppServerArgs {
|
||||
#[arg(long = "disable-plugin-startup-tasks-for-tests", hide = true)]
|
||||
disable_plugin_startup_tasks_for_tests: bool,
|
||||
|
||||
/// Enable remote control for this app-server process.
|
||||
/// Enable remote control for this app-server process without changing persistence.
|
||||
#[arg(long = "remote-control", hide = true)]
|
||||
remote_control: bool,
|
||||
}
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
arg0_dispatch_or_else(|arg0_paths: Arg0DispatchPaths| async move {
|
||||
let remote_control_disabled = codex_app_server::take_remote_control_disabled_env();
|
||||
arg0_dispatch_or_else(move |arg0_paths: Arg0DispatchPaths| async move {
|
||||
let AppServerArgs {
|
||||
config_overrides,
|
||||
listen,
|
||||
@@ -84,7 +85,12 @@ fn main() -> anyhow::Result<()> {
|
||||
if disable_plugin_startup_tasks_for_tests {
|
||||
runtime_options.plugin_startup_tasks = PluginStartupTasks::Skip;
|
||||
}
|
||||
runtime_options.remote_control_enabled = remote_control;
|
||||
runtime_options.remote_control_startup_mode =
|
||||
match (remote_control, remote_control_disabled) {
|
||||
(true, _) => codex_app_server::RemoteControlStartupMode::EnabledEphemeral,
|
||||
(false, true) => codex_app_server::RemoteControlStartupMode::DisabledEphemeral,
|
||||
(false, false) => codex_app_server::RemoteControlStartupMode::ResolvePersisted,
|
||||
};
|
||||
|
||||
run_main_with_transport_options(
|
||||
arg0_paths,
|
||||
|
||||
@@ -951,13 +951,21 @@ impl MessageProcessor {
|
||||
.experimental_feature_enablement_set(request_id.clone(), params)
|
||||
.await
|
||||
}
|
||||
ClientRequest::RemoteControlEnable { .. } => self
|
||||
ClientRequest::RemoteControlEnable { params, .. } => self
|
||||
.remote_control_processor
|
||||
.enable()
|
||||
.enable(
|
||||
params.is_some_and(|params| params.ephemeral),
|
||||
app_server_client_name.as_deref(),
|
||||
)
|
||||
.await
|
||||
.map(|response| Some(response.into())),
|
||||
ClientRequest::RemoteControlDisable { .. } => self
|
||||
ClientRequest::RemoteControlDisable { params, .. } => self
|
||||
.remote_control_processor
|
||||
.disable()
|
||||
.disable(
|
||||
params.is_some_and(|params| params.ephemeral),
|
||||
app_server_client_name.as_deref(),
|
||||
)
|
||||
.await
|
||||
.map(|response| Some(response.into())),
|
||||
ClientRequest::RemoteControlStatusRead { .. } => self
|
||||
.remote_control_processor
|
||||
|
||||
@@ -28,17 +28,38 @@ impl RemoteControlRequestProcessor {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn enable(&self) -> Result<RemoteControlEnableResponse, JSONRPCErrorError> {
|
||||
pub(crate) async fn enable(
|
||||
&self,
|
||||
ephemeral: bool,
|
||||
app_server_client_name: Option<&str>,
|
||||
) -> Result<RemoteControlEnableResponse, JSONRPCErrorError> {
|
||||
let handle = self.handle()?;
|
||||
handle
|
||||
.enable()
|
||||
.map(RemoteControlEnableResponse::from)
|
||||
.map_err(map_unavailable)
|
||||
let status = if ephemeral {
|
||||
handle.enable_ephemeral().map_err(map_unavailable)?
|
||||
} else {
|
||||
handle
|
||||
.enable(app_server_client_name)
|
||||
.await
|
||||
.map_err(map_update_error)?
|
||||
};
|
||||
Ok(RemoteControlEnableResponse::from(status))
|
||||
}
|
||||
|
||||
pub(crate) fn disable(&self) -> Result<RemoteControlDisableResponse, JSONRPCErrorError> {
|
||||
pub(crate) async fn disable(
|
||||
&self,
|
||||
ephemeral: bool,
|
||||
app_server_client_name: Option<&str>,
|
||||
) -> Result<RemoteControlDisableResponse, JSONRPCErrorError> {
|
||||
let handle = self.handle()?;
|
||||
Ok(RemoteControlDisableResponse::from(handle.disable()))
|
||||
let status = if ephemeral {
|
||||
handle.disable_ephemeral().await
|
||||
} else {
|
||||
handle
|
||||
.disable(app_server_client_name)
|
||||
.await
|
||||
.map_err(map_update_error)?
|
||||
};
|
||||
Ok(RemoteControlDisableResponse::from(status))
|
||||
}
|
||||
|
||||
pub(crate) fn status_read(&self) -> Result<RemoteControlStatusReadResponse, JSONRPCErrorError> {
|
||||
@@ -104,6 +125,14 @@ fn map_unavailable(err: RemoteControlUnavailable) -> JSONRPCErrorError {
|
||||
invalid_request(err.to_string())
|
||||
}
|
||||
|
||||
fn map_update_error(err: io::Error) -> JSONRPCErrorError {
|
||||
if err.kind() == io::ErrorKind::NotFound {
|
||||
invalid_request(err.to_string())
|
||||
} else {
|
||||
internal_error(err.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
fn map_pairing_start_error(err: io::Error) -> JSONRPCErrorError {
|
||||
if err.kind() == io::ErrorKind::InvalidInput {
|
||||
invalid_request(err.to_string())
|
||||
|
||||
@@ -20,6 +20,7 @@ pub(crate) use codex_app_server_transport::OutgoingMessage;
|
||||
pub(crate) use codex_app_server_transport::QueuedOutgoingMessage;
|
||||
pub(crate) use codex_app_server_transport::RemoteControlHandle;
|
||||
pub(crate) use codex_app_server_transport::RemoteControlStartConfig;
|
||||
pub use codex_app_server_transport::RemoteControlStartupMode;
|
||||
pub(crate) use codex_app_server_transport::RemoteControlUnavailable;
|
||||
pub(crate) use codex_app_server_transport::TransportEvent;
|
||||
pub(crate) use codex_app_server_transport::acquire_app_server_startup_lock;
|
||||
@@ -31,6 +32,7 @@ pub(crate) use codex_app_server_transport::start_control_socket_acceptor;
|
||||
pub(crate) use codex_app_server_transport::start_remote_control;
|
||||
pub(crate) use codex_app_server_transport::start_stdio_connection;
|
||||
pub(crate) use codex_app_server_transport::start_websocket_acceptor;
|
||||
pub use codex_app_server_transport::take_remote_control_disabled_env;
|
||||
|
||||
pub(crate) struct ConnectionState {
|
||||
pub(crate) outbound_initialized: Arc<AtomicBool>,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::path::Path;
|
||||
use std::process::ExitStatus;
|
||||
use std::process::Stdio;
|
||||
use std::sync::atomic::AtomicI64;
|
||||
use std::sync::atomic::Ordering;
|
||||
@@ -128,6 +129,10 @@ pub const DISABLE_PLUGIN_STARTUP_TASKS_ARG: &str = "--disable-plugin-startup-tas
|
||||
const DISABLE_MANAGED_CONFIG_ENV_VAR: &str = "CODEX_APP_SERVER_DISABLE_MANAGED_CONFIG";
|
||||
|
||||
impl TestAppServer {
|
||||
pub async fn wait_for_exit(&mut self) -> std::io::Result<ExitStatus> {
|
||||
self.process.wait().await
|
||||
}
|
||||
|
||||
pub async fn new(codex_home: &Path) -> anyhow::Result<Self> {
|
||||
Self::new_with_env_and_args(codex_home, &[], &[DISABLE_PLUGIN_STARTUP_TASKS_ARG]).await
|
||||
}
|
||||
@@ -645,12 +650,30 @@ impl TestAppServer {
|
||||
.await
|
||||
}
|
||||
|
||||
/// Send a runtime-only `remoteControl/enable` JSON-RPC request.
|
||||
pub async fn send_remote_control_ephemeral_enable_request(&mut self) -> anyhow::Result<i64> {
|
||||
self.send_request(
|
||||
"remoteControl/enable",
|
||||
Some(serde_json::json!({ "ephemeral": true })),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Send a `remoteControl/disable` JSON-RPC request.
|
||||
pub async fn send_remote_control_disable_request(&mut self) -> anyhow::Result<i64> {
|
||||
self.send_request("remoteControl/disable", /*params*/ None)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Send a runtime-only `remoteControl/disable` JSON-RPC request.
|
||||
pub async fn send_remote_control_ephemeral_disable_request(&mut self) -> anyhow::Result<i64> {
|
||||
self.send_request(
|
||||
"remoteControl/disable",
|
||||
Some(serde_json::json!({ "ephemeral": true })),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Send a `remoteControl/status/read` JSON-RPC request.
|
||||
pub async fn send_remote_control_status_read_request(&mut self) -> anyhow::Result<i64> {
|
||||
self.send_request("remoteControl/status/read", /*params*/ None)
|
||||
|
||||
@@ -3,6 +3,7 @@ use std::time::Duration;
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use app_test_support::ChatGptAuthFixture;
|
||||
use app_test_support::DEFAULT_CLIENT_NAME;
|
||||
use app_test_support::TestAppServer;
|
||||
use app_test_support::to_response;
|
||||
use app_test_support::write_chatgpt_auth;
|
||||
@@ -24,6 +25,8 @@ use codex_app_server_protocol::RemoteControlPairingStatusResponse;
|
||||
use codex_app_server_protocol::RemoteControlStatusReadResponse;
|
||||
use codex_app_server_protocol::RequestId;
|
||||
use codex_config::types::AuthCredentialsStoreMode;
|
||||
use codex_state::RemoteControlEnrollmentRecord;
|
||||
use codex_state::StateRuntime;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
@@ -37,10 +40,92 @@ use tokio::task::JoinHandle;
|
||||
use tokio::time::timeout;
|
||||
|
||||
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
const STARTUP_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
async fn remote_control_preference(
|
||||
state_db: &StateRuntime,
|
||||
websocket_url: &str,
|
||||
) -> Result<Option<bool>> {
|
||||
Ok(state_db
|
||||
.get_remote_control_enrollment(websocket_url, "account_id", Some(DEFAULT_CLIENT_NAME))
|
||||
.await?
|
||||
.context("enrollment should exist")?
|
||||
.remote_control_enabled)
|
||||
}
|
||||
|
||||
async fn wait_for_response(mcp: &mut TestAppServer, request_id: i64) -> Result<JSONRPCResponse> {
|
||||
timeout(
|
||||
DEFAULT_TIMEOUT,
|
||||
mcp.read_stream_until_response_message(RequestId::Integer(request_id)),
|
||||
)
|
||||
.await?
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn listen_off_honors_persisted_remote_control_enable() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let listener = configured_remote_control_listener(codex_home.path()).await?;
|
||||
let websocket_url = format!(
|
||||
"ws://{}/backend-api/wham/remote/control/server",
|
||||
listener.local_addr()?
|
||||
);
|
||||
let state_db =
|
||||
StateRuntime::init(codex_home.path().to_path_buf(), "test-provider".to_string()).await?;
|
||||
state_db
|
||||
.upsert_remote_control_enrollment(&RemoteControlEnrollmentRecord {
|
||||
websocket_url,
|
||||
account_id: "account_id".to_string(),
|
||||
app_server_client_name: None,
|
||||
server_id: "server-id".to_string(),
|
||||
environment_id: "environment-id".to_string(),
|
||||
server_name: "server-name".to_string(),
|
||||
remote_control_enabled: Some(true),
|
||||
})
|
||||
.await?;
|
||||
|
||||
let _app_server = TestAppServer::new_with_args(codex_home.path(), &["--listen", "off"]).await?;
|
||||
timeout(STARTUP_TIMEOUT, listener.accept()).await??;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn listen_off_exits_without_persisted_remote_control_enable() -> Result<()> {
|
||||
for persisted_preference in [None, Some(false)] {
|
||||
let codex_home = TempDir::new()?;
|
||||
let listener = configured_remote_control_listener(codex_home.path()).await?;
|
||||
if let Some(remote_control_enabled) = persisted_preference {
|
||||
let websocket_url = format!(
|
||||
"ws://{}/backend-api/wham/remote/control/server",
|
||||
listener.local_addr()?
|
||||
);
|
||||
let state_db =
|
||||
StateRuntime::init(codex_home.path().to_path_buf(), "test-provider".to_string())
|
||||
.await?;
|
||||
state_db
|
||||
.upsert_remote_control_enrollment(&RemoteControlEnrollmentRecord {
|
||||
websocket_url,
|
||||
account_id: "account_id".to_string(),
|
||||
app_server_client_name: None,
|
||||
server_id: "server-id".to_string(),
|
||||
environment_id: "environment-id".to_string(),
|
||||
server_name: "server-name".to_string(),
|
||||
remote_control_enabled: Some(remote_control_enabled),
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
|
||||
let mut app_server =
|
||||
TestAppServer::new_with_args(codex_home.path(), &["--listen", "off"]).await?;
|
||||
let status = timeout(STARTUP_TIMEOUT, app_server.wait_for_exit()).await??;
|
||||
assert!(!status.success());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_control_disable_returns_disabled_status() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let _listener = configured_remote_control_listener(codex_home.path()).await?;
|
||||
let mut mcp = TestAppServer::new(codex_home.path()).await?;
|
||||
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
|
||||
|
||||
@@ -83,11 +168,22 @@ async fn remote_control_status_read_returns_disabled_status() -> Result<()> {
|
||||
#[tokio::test]
|
||||
async fn remote_control_enable_returns_connecting_status() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let _backend = BlockingRemoteControlBackend::start(codex_home.path()).await?;
|
||||
let mut backend = BlockingRemoteControlBackend::start(codex_home.path()).await?;
|
||||
let mut mcp = TestAppServer::new(codex_home.path()).await?;
|
||||
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
|
||||
|
||||
let request_id = mcp.send_remote_control_enable_request().await?;
|
||||
assert_eq!(
|
||||
timeout(DEFAULT_TIMEOUT, backend.wait_for_enroll_request()).await??,
|
||||
"POST /backend-api/wham/remote/control/server/enroll HTTP/1.1"
|
||||
);
|
||||
timeout(
|
||||
Duration::from_millis(100),
|
||||
mcp.read_stream_until_response_message(RequestId::Integer(request_id)),
|
||||
)
|
||||
.await
|
||||
.expect_err("enable response should wait for enrollment");
|
||||
backend.complete_enrollment()?;
|
||||
let response: JSONRPCResponse = timeout(
|
||||
DEFAULT_TIMEOUT,
|
||||
mcp.read_stream_until_response_message(RequestId::Integer(request_id)),
|
||||
@@ -97,11 +193,103 @@ async fn remote_control_enable_returns_connecting_status() -> Result<()> {
|
||||
|
||||
assert_eq!(received.status, RemoteControlConnectionStatus::Connecting);
|
||||
assert!(!received.server_name.is_empty());
|
||||
assert_eq!(received.environment_id, None);
|
||||
assert_eq!(received.environment_id.as_deref(), Some("environment-id"));
|
||||
assert!(!received.installation_id.is_empty());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disable_waits_for_in_flight_durable_enable() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let mut backend = BlockingRemoteControlBackend::start(codex_home.path()).await?;
|
||||
let websocket_url = backend.websocket_url().to_string();
|
||||
let state_db =
|
||||
StateRuntime::init(codex_home.path().to_path_buf(), "test-provider".to_string()).await?;
|
||||
let mut mcp = TestAppServer::new(codex_home.path()).await?;
|
||||
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
|
||||
|
||||
mcp.send_remote_control_enable_request().await?;
|
||||
timeout(DEFAULT_TIMEOUT, backend.wait_for_enroll_request()).await??;
|
||||
let disable_request_id = mcp.send_remote_control_disable_request().await?;
|
||||
timeout(
|
||||
Duration::from_millis(100),
|
||||
mcp.read_stream_until_response_message(RequestId::Integer(disable_request_id)),
|
||||
)
|
||||
.await
|
||||
.expect_err("disable response should wait for the in-flight enable");
|
||||
|
||||
backend.complete_enrollment()?;
|
||||
let response = wait_for_response(&mut mcp, disable_request_id).await?;
|
||||
let received: RemoteControlDisableResponse = to_response(response)?;
|
||||
assert_eq!(received.status, RemoteControlConnectionStatus::Disabled);
|
||||
assert_eq!(
|
||||
remote_control_preference(&state_db, &websocket_url).await?,
|
||||
Some(false)
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rpc_updates_durable_preference_but_ephemeral_does_not() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let mut backend = BlockingRemoteControlBackend::start(codex_home.path()).await?;
|
||||
let websocket_url = backend.websocket_url().to_string();
|
||||
let state_db =
|
||||
StateRuntime::init(codex_home.path().to_path_buf(), "test-provider".to_string()).await?;
|
||||
|
||||
let mut mcp = TestAppServer::new(codex_home.path()).await?;
|
||||
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
|
||||
|
||||
let request_id = mcp.send_remote_control_enable_request().await?;
|
||||
assert_eq!(
|
||||
timeout(DEFAULT_TIMEOUT, backend.wait_for_enroll_request()).await??,
|
||||
"POST /backend-api/wham/remote/control/server/enroll HTTP/1.1"
|
||||
);
|
||||
backend.complete_enrollment()?;
|
||||
wait_for_response(&mut mcp, request_id).await?;
|
||||
assert_eq!(
|
||||
remote_control_preference(&state_db, &websocket_url).await?,
|
||||
Some(true)
|
||||
);
|
||||
|
||||
let request_id = mcp.send_remote_control_ephemeral_disable_request().await?;
|
||||
wait_for_response(&mut mcp, request_id).await?;
|
||||
assert_eq!(
|
||||
remote_control_preference(&state_db, &websocket_url).await?,
|
||||
Some(true)
|
||||
);
|
||||
|
||||
let request_id = mcp.send_remote_control_disable_request().await?;
|
||||
wait_for_response(&mut mcp, request_id).await?;
|
||||
assert_eq!(
|
||||
remote_control_preference(&state_db, &websocket_url).await?,
|
||||
Some(false)
|
||||
);
|
||||
|
||||
let request_id = mcp.send_remote_control_enable_request().await?;
|
||||
wait_for_response(&mut mcp, request_id).await?;
|
||||
assert_eq!(
|
||||
remote_control_preference(&state_db, &websocket_url).await?,
|
||||
Some(true)
|
||||
);
|
||||
|
||||
let request_id = mcp.send_remote_control_disable_request().await?;
|
||||
wait_for_response(&mut mcp, request_id).await?;
|
||||
assert_eq!(
|
||||
remote_control_preference(&state_db, &websocket_url).await?,
|
||||
Some(false)
|
||||
);
|
||||
|
||||
let request_id = mcp.send_remote_control_ephemeral_enable_request().await?;
|
||||
wait_for_response(&mut mcp, request_id).await?;
|
||||
assert_eq!(
|
||||
remote_control_preference(&state_db, &websocket_url).await?,
|
||||
Some(false)
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_control_status_read_returns_connecting_status_after_enable() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
@@ -110,17 +298,17 @@ async fn remote_control_status_read_returns_connecting_status_after_enable() ->
|
||||
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
|
||||
|
||||
let request_id = mcp.send_remote_control_enable_request().await?;
|
||||
let _: JSONRPCResponse = timeout(
|
||||
DEFAULT_TIMEOUT,
|
||||
mcp.read_stream_until_response_message(RequestId::Integer(request_id)),
|
||||
)
|
||||
.await??;
|
||||
|
||||
let enroll_request = timeout(DEFAULT_TIMEOUT, backend.wait_for_enroll_request()).await??;
|
||||
assert_eq!(
|
||||
enroll_request,
|
||||
"POST /backend-api/wham/remote/control/server/enroll HTTP/1.1"
|
||||
);
|
||||
backend.complete_enrollment()?;
|
||||
let _: JSONRPCResponse = timeout(
|
||||
DEFAULT_TIMEOUT,
|
||||
mcp.read_stream_until_response_message(RequestId::Integer(request_id)),
|
||||
)
|
||||
.await??;
|
||||
|
||||
let request_id = mcp.send_remote_control_status_read_request().await?;
|
||||
let response: JSONRPCResponse = timeout(
|
||||
@@ -132,7 +320,7 @@ async fn remote_control_status_read_returns_connecting_status_after_enable() ->
|
||||
|
||||
assert_eq!(received.status, RemoteControlConnectionStatus::Connecting);
|
||||
assert!(!received.server_name.is_empty());
|
||||
assert_eq!(received.environment_id, None);
|
||||
assert_eq!(received.environment_id.as_deref(), Some("environment-id"));
|
||||
assert!(!received.installation_id.is_empty());
|
||||
Ok(())
|
||||
}
|
||||
@@ -235,11 +423,13 @@ async fn remote_control_pairing_start_returns_pairing_artifacts() -> Result<()>
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_control_pairing_start_returns_pairing_artifacts_while_disabled() -> Result<()> {
|
||||
async fn pairing_start_works_after_ephemeral_enable() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let mut backend = PairingRemoteControlBackend::start(codex_home.path()).await?;
|
||||
let mut mcp = TestAppServer::new(codex_home.path()).await?;
|
||||
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
|
||||
let request_id = mcp.send_remote_control_ephemeral_enable_request().await?;
|
||||
wait_for_response(&mut mcp, request_id).await?;
|
||||
|
||||
let request_id = mcp
|
||||
.send_remote_control_pairing_start_request(RemoteControlPairingStartParams {
|
||||
@@ -333,6 +523,8 @@ async fn remote_control_client_management_works_while_disabled() -> Result<()> {
|
||||
|
||||
struct BlockingRemoteControlBackend {
|
||||
enroll_request_rx: Option<oneshot::Receiver<Result<String>>>,
|
||||
enroll_response_tx: Option<oneshot::Sender<()>>,
|
||||
websocket_url: String,
|
||||
server_task: JoinHandle<()>,
|
||||
}
|
||||
|
||||
@@ -397,12 +589,37 @@ impl ClientManagementRemoteControlBackend {
|
||||
impl BlockingRemoteControlBackend {
|
||||
async fn start(codex_home: &std::path::Path) -> Result<Self> {
|
||||
let listener = configured_remote_control_listener(codex_home).await?;
|
||||
let websocket_url = format!(
|
||||
"ws://{}/backend-api/wham/remote/control/server",
|
||||
listener.local_addr()?
|
||||
);
|
||||
|
||||
let (enroll_request_tx, enroll_request_rx) = oneshot::channel();
|
||||
let (enroll_response_tx, enroll_response_rx) = oneshot::channel();
|
||||
let server_task = tokio::spawn(async move {
|
||||
match read_enroll_request(listener).await {
|
||||
Ok((request_line, _reader)) => {
|
||||
match read_enroll_request(&listener).await {
|
||||
Ok((request_line, reader)) => {
|
||||
let _ = enroll_request_tx.send(Ok(request_line));
|
||||
if enroll_response_rx.await.is_err() {
|
||||
return;
|
||||
}
|
||||
if respond_with_json(
|
||||
reader.into_inner(),
|
||||
serde_json::json!({
|
||||
"server_id": "server-id",
|
||||
"environment_id": "environment-id",
|
||||
"remote_control_token": "remote-control-token",
|
||||
"expires_at": "3026-05-22T12:34:56Z",
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
return;
|
||||
}
|
||||
let Ok(_websocket) = listener.accept().await else {
|
||||
return;
|
||||
};
|
||||
std::future::pending::<()>().await;
|
||||
}
|
||||
Err(err) => {
|
||||
@@ -413,6 +630,8 @@ impl BlockingRemoteControlBackend {
|
||||
|
||||
Ok(Self {
|
||||
enroll_request_rx: Some(enroll_request_rx),
|
||||
enroll_response_tx: Some(enroll_response_tx),
|
||||
websocket_url,
|
||||
server_task,
|
||||
})
|
||||
}
|
||||
@@ -424,6 +643,18 @@ impl BlockingRemoteControlBackend {
|
||||
.context("enroll request should only be awaited once")?;
|
||||
rx.await?
|
||||
}
|
||||
|
||||
fn complete_enrollment(&mut self) -> Result<()> {
|
||||
self.enroll_response_tx
|
||||
.take()
|
||||
.context("enrollment should only complete once")?
|
||||
.send(())
|
||||
.map_err(|()| anyhow::anyhow!("enrollment response receiver dropped"))
|
||||
}
|
||||
|
||||
fn websocket_url(&self) -> &str {
|
||||
&self.websocket_url
|
||||
}
|
||||
}
|
||||
|
||||
struct PairingRemoteControlBackend {
|
||||
@@ -558,8 +789,8 @@ async fn configured_remote_control_listener(codex_home: &std::path::Path) -> Res
|
||||
Ok(listener)
|
||||
}
|
||||
|
||||
async fn read_enroll_request(listener: TcpListener) -> Result<(String, BufReader<TcpStream>)> {
|
||||
let request = read_http_request(&listener).await?;
|
||||
async fn read_enroll_request(listener: &TcpListener) -> Result<(String, BufReader<TcpStream>)> {
|
||||
let request = read_http_request(listener).await?;
|
||||
Ok((request.request_line, request.reader))
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user