Skip to content

armgit / codex

Public Imported from GitHub
0

Lightweight coding agent that runs in your terminal

Rust

Enable `/import` in remote and local daemon sessions (#47317)

Eric Traut7e6c4c20fded
diff --git a/codex-rs/tui/src/app/app_server_events.rs b/codex-rs/tui/src/app/app_server_events.rs
index fbea229338..9eaf570e02 100644
--- a/codex-rs/tui/src/app/app_server_events.rs
+++ b/codex-rs/tui/src/app/app_server_events.rs
@@ -337,9 +337,11 @@ impl App {
return;
}
ServerNotification::ExternalAgentConfigImportCompleted(notification) => {
- let should_report_completion =
- app_server_client.consume_external_agent_config_import_completion();
- if let Err(err) = self.refresh_in_memory_config_from_disk().await {
+ let should_report_completion = app_server_client
+ .consume_external_agent_config_import_completion(&notification.import_id);
+ if !app_server_client.uses_remote_workspace()
+ && let Err(err) = self.refresh_in_memory_config_from_disk().await
+ {
tracing::warn!(
error = %err,
"failed to refresh config after external agent config import"
diff --git a/codex-rs/tui/src/app/event_dispatch.rs b/codex-rs/tui/src/app/event_dispatch.rs
index 53310962fd..c85478cf85 100644
--- a/codex-rs/tui/src/app/event_dispatch.rs
+++ b/codex-rs/tui/src/app/event_dispatch.rs
@@ -392,10 +392,17 @@ impl App {
self.pending_open_resume_picker = true;
}
AppEvent::OpenExternalAgentConfigMigration => {
+ let cwd = if self.chat_widget.thread_id().is_some()
+ || !app_server.uses_remote_workspace()
+ {
+ Some(self.chat_widget.config_ref().cwd.to_path_buf())
+ } else {
+ app_server.remote_cwd_override().map(Path::to_path_buf)
+ };
match crate::external_agent_config_migration::flow::handle_external_agent_config_migration_prompt(
tui,
app_server,
- &self.config,
+ cwd.as_deref(),
)
.await
{
diff --git a/codex-rs/tui/src/app_server_session.rs b/codex-rs/tui/src/app_server_session.rs
index fcedffc35b..84df511e1a 100644
--- a/codex-rs/tui/src/app_server_session.rs
+++ b/codex-rs/tui/src/app_server_session.rs
@@ -3,6 +3,7 @@
//! This module owns the typed JSON-RPC calls needed by the TUI and keeps
//! request/response plumbing out of `App` and `ChatWidget`.
+mod external_agent_config;
mod fs;
mod history;
mod models;
@@ -45,11 +46,6 @@ use codex_app_server_protocol::ClientRequest;
use codex_app_server_protocol::ConfigBatchWriteParams;
use codex_app_server_protocol::ConfigRequirementsReadResponse;
use codex_app_server_protocol::ConfigWriteResponse;
-use codex_app_server_protocol::ExternalAgentConfigDetectParams;
-use codex_app_server_protocol::ExternalAgentConfigDetectResponse;
-use codex_app_server_protocol::ExternalAgentConfigImportParams;
-use codex_app_server_protocol::ExternalAgentConfigImportResponse;
-use codex_app_server_protocol::ExternalAgentConfigMigrationItem;
use codex_app_server_protocol::GetAccountParams;
use codex_app_server_protocol::GetAccountRateLimitsResponse;
use codex_app_server_protocol::GetAccountResponse;
@@ -154,9 +150,8 @@ use std::collections::HashMap;
use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::Arc;
-use std::sync::atomic::AtomicBool;
+use std::sync::Mutex;
use std::sync::atomic::AtomicU64;
-use std::sync::atomic::Ordering;
use std::time::Duration;
use std::time::Instant;
use uuid::Uuid;
@@ -328,7 +323,7 @@ pub(crate) struct AppServerSession {
default_model: Option<String>,
available_models: Vec<ModelPreset>,
managed_new_thread_defaults: Option<NewThreadModelDefaults>,
- external_agent_config_import_completion_pending: AtomicBool,
+ external_agent_config_import_id: Mutex<Option<String>>,
dynamic_tool_mcp: Option<Arc<DynamicToolMcpServer>>,
}
@@ -438,7 +433,7 @@ impl AppServerSession {
default_model: None,
available_models: Vec::new(),
managed_new_thread_defaults: None,
- external_agent_config_import_completion_pending: AtomicBool::new(false),
+ external_agent_config_import_id: Mutex::default(),
dynamic_tool_mcp: None,
}
}
@@ -740,64 +735,6 @@ impl AppServerSession {
.map_err(|err| bootstrap_request_error("account/read failed during TUI bootstrap", err))
}
- pub(crate) async fn external_agent_config_detect(
- &mut self,
- params: ExternalAgentConfigDetectParams,
- ) -> Result<ExternalAgentConfigDetectResponse> {
- let request_id = self.next_request_id();
- self.client
- .request_typed(ClientRequest::ExternalAgentConfigDetect { request_id, params })
- .await
- .wrap_err("externalAgentConfig/detect failed during external agent import")
- }
-
- pub(crate) async fn external_agent_config_import(
- &mut self,
- migration_items: Vec<ExternalAgentConfigMigrationItem>,
- migration_source: String,
- ) -> Result<()> {
- // Mark the import active before sending the request so a fast completion notification
- // cannot arrive before the TUI records it.
- if self
- .external_agent_config_import_completion_pending
- .swap(true, Ordering::Relaxed)
- {
- color_eyre::eyre::bail!(EXTERNAL_AGENT_CONFIG_IMPORT_IN_PROGRESS_MESSAGE);
- }
- let request_id = self.next_request_id();
- let response: Result<ExternalAgentConfigImportResponse> = self
- .client
- .request_typed(ClientRequest::ExternalAgentConfigImport {
- request_id,
- params: ExternalAgentConfigImportParams {
- migration_items,
- source: Some("cli".to_string()),
- provider_id: Some(migration_source.clone()),
- migration_source: Some(migration_source),
- },
- })
- .await
- .wrap_err("externalAgentConfig/import failed during external agent import");
- match response {
- Ok(_) => Ok(()),
- Err(err) => {
- self.external_agent_config_import_completion_pending
- .store(false, Ordering::Relaxed);
- Err(err)
- }
- }
- }
-
- pub(crate) fn external_agent_config_import_in_progress(&self) -> bool {
- self.external_agent_config_import_completion_pending
- .load(Ordering::Relaxed)
- }
-
- pub(crate) fn consume_external_agent_config_import_completion(&self) -> bool {
- self.external_agent_config_import_completion_pending
- .swap(false, Ordering::Relaxed)
- }
-
pub(crate) async fn next_event(&mut self) -> Option<AppServerEvent> {
self.client.next_event().await
}
diff --git a/codex-rs/tui/src/app_server_session/external_agent_config.rs b/codex-rs/tui/src/app_server_session/external_agent_config.rs
new file mode 100644
index 0000000000..424490ccda
--- /dev/null
+++ b/codex-rs/tui/src/app_server_session/external_agent_config.rs
@@ -0,0 +1,75 @@
+//! External setup migration uses the connected server's filesystem and tracks this client's import.
+
+use super::*;
+use codex_app_server_protocol::ExternalAgentConfigDetectParams;
+use codex_app_server_protocol::ExternalAgentConfigDetectResponse;
+use codex_app_server_protocol::ExternalAgentConfigImportParams;
+use codex_app_server_protocol::ExternalAgentConfigImportResponse;
+use codex_app_server_protocol::ExternalAgentConfigMigrationItem;
+
+impl AppServerSession {
+ pub(crate) async fn external_agent_config_detect(
+ &mut self,
+ params: ExternalAgentConfigDetectParams,
+ ) -> Result<ExternalAgentConfigDetectResponse> {
+ let request_id = self.next_request_id();
+ self.client
+ .request_typed(ClientRequest::ExternalAgentConfigDetect { request_id, params })
+ .await
+ .wrap_err("externalAgentConfig/detect failed during external agent import")
+ }
+
+ pub(crate) async fn external_agent_config_import(
+ &mut self,
+ migration_items: Vec<ExternalAgentConfigMigrationItem>,
+ migration_source: String,
+ ) -> Result<()> {
+ if self.external_agent_config_import_in_progress() {
+ color_eyre::eyre::bail!(EXTERNAL_AGENT_CONFIG_IMPORT_IN_PROGRESS_MESSAGE);
+ }
+ let request_id = self.next_request_id();
+ let response: ExternalAgentConfigImportResponse = self
+ .client
+ .request_typed(ClientRequest::ExternalAgentConfigImport {
+ request_id,
+ params: ExternalAgentConfigImportParams {
+ migration_items,
+ source: Some("cli".to_string()),
+ provider_id: Some(migration_source.clone()),
+ migration_source: Some(migration_source),
+ },
+ })
+ .await
+ .wrap_err("externalAgentConfig/import failed during external agent import")?;
+ // Notifications remain queued until the event loop regains this mutable session.
+ // Shared daemons also broadcast completions for imports started by other clients.
+ *self
+ .external_agent_config_import_id
+ .get_mut()
+ .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(response.import_id);
+ Ok(())
+ }
+
+ pub(crate) fn external_agent_config_import_in_progress(&self) -> bool {
+ self.external_agent_config_import_id
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .is_some()
+ }
+
+ pub(crate) fn consume_external_agent_config_import_completion(&self, import_id: &str) -> bool {
+ let mut pending = self
+ .external_agent_config_import_id
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ if pending.as_deref() != Some(import_id) {
+ return false;
+ }
+ *pending = None;
+ true
+ }
+}
+
+#[cfg(test)]
+#[path = "external_agent_config_tests.rs"]
+mod tests;
diff --git a/codex-rs/tui/src/app_server_session/external_agent_config_tests.rs b/codex-rs/tui/src/app_server_session/external_agent_config_tests.rs
new file mode 100644
index 0000000000..039c25ba66
--- /dev/null
+++ b/codex-rs/tui/src/app_server_session/external_agent_config_tests.rs
@@ -0,0 +1,147 @@
+//! Exercises migration over shared transports with interleaved import completions.
+
+use super::*;
+use crate::external_agent_config_migration::flow::ExternalAgentConfigMigrationFlowOutcome;
+use crate::external_agent_config_migration::flow::handle_external_agent_config_migration_prompt;
+use codex_app_server_protocol::JSONRPCMessage;
+use codex_app_server_protocol::ServerNotification;
+use futures::SinkExt;
+use futures::StreamExt;
+use pretty_assertions::assert_eq;
+use serde_json::json;
+use tokio::net::TcpListener;
+use tokio_tungstenite::tungstenite::Message;
+
+#[tokio::test]
+async fn external_agent_config_migration_over_shared_transport() -> Result<()> {
+ for mode in [ThreadParamsMode::Embedded, ThreadParamsMode::Remote] {
+ let listener = TcpListener::bind("127.0.0.1:0").await?;
+ let endpoint = crate::resolve_remote_addr(&format!("ws://{}", listener.local_addr()?))?;
+ let server = tokio::spawn(async move {
+ let (stream, _) = listener.accept().await?;
+ let mut socket = tokio_tungstenite::accept_async(stream).await?;
+ let mut requests = Vec::new();
+ let mut import_attempts = 0;
+ while let Some(Ok(Message::Text(text))) = socket.next().await {
+ let JSONRPCMessage::Request(request) = serde_json::from_str(&text)? else {
+ continue;
+ };
+ let mut reply = match request.method.as_str() {
+ "initialize" => json!({"result": {"userAgent": "import-test/1.0"}}),
+ "externalAgentConfig/detect" => {
+ requests.push((request.method, request.params.unwrap()));
+ json!({"result": {"items": [], "connectors": []}})
+ }
+ "externalAgentConfig/import" => {
+ requests.push((request.method, request.params.unwrap()));
+ import_attempts += 1;
+ if import_attempts == 1 {
+ json!({"error": {"code": -32603, "message": "retry import"}})
+ } else {
+ // A fast completion can already be queued when the RPC returns.
+ for import_id in ["other-client", "this-client"] {
+ let notification = json!({
+ "method": "externalAgentConfig/import/completed",
+ "params": {"importId": import_id, "itemTypeResults": []}
+ });
+ socket
+ .send(Message::Text(notification.to_string().into()))
+ .await?;
+ }
+ json!({"result": {"importId": "this-client"}})
+ }
+ }
+ method => panic!("unexpected request: {method}"),
+ };
+ reply["id"] = json!(request.id);
+ socket.send(Message::Text(reply.to_string().into())).await?;
+ }
+ Ok::<_, color_eyre::Report>(requests)
+ });
+ let mut session =
+ AppServerSession::new(crate::connect_remote_app_server(endpoint).await?, mode);
+ let workspace = tempfile::tempdir()?;
+ let cwd = workspace.path();
+ let mut tui = crate::tui::test_support::make_test_tui()?;
+ // Exercise the actual /import entry point, including remote home-only detection.
+ for cwd in [Some(cwd), None] {
+ assert!(matches!(
+ handle_external_agent_config_migration_prompt(&mut tui, &mut session, cwd)
+ .await
+ .map_err(|err| color_eyre::eyre::eyre!(err))?,
+ ExternalAgentConfigMigrationFlowOutcome::NoItems
+ ));
+ }
+ let items = json!([
+ {"itemType": "SKILLS", "description": "Skills", "cwd": null, "details": null},
+ {"itemType": "PLUGINS", "description": "Plugins", "cwd": null, "details": null},
+ {"itemType": "MCP_SERVER_CONFIG", "description": "MCP", "cwd": null, "details": null}
+ ]);
+ let source = "claude-code";
+ assert!(
+ session
+ .external_agent_config_import(serde_json::from_value(items.clone())?, source.into())
+ .await
+ .is_err()
+ );
+ assert!(!session.external_agent_config_import_in_progress());
+ session
+ .external_agent_config_import(serde_json::from_value(items.clone())?, source.into())
+ .await?;
+ assert!(session.external_agent_config_import_in_progress());
+ let err = session
+ .external_agent_config_import(serde_json::from_value(items.clone())?, source.into())
+ .await
+ .unwrap_err();
+ assert_eq!(
+ err.to_string(),
+ EXTERNAL_AGENT_CONFIG_IMPORT_IN_PROGRESS_MESSAGE
+ );
+ for (import_id, consumed) in [("other-client", false), ("this-client", true)] {
+ let event =
+ tokio::time::timeout(Duration::from_secs(/*secs*/ 5), session.next_event()).await?;
+ let Some(AppServerEvent::ServerNotification(notification)) = event else {
+ panic!("expected import completion");
+ };
+ let ServerNotification::ExternalAgentConfigImportCompleted(notification) =
+ *notification
+ else {
+ panic!("expected import completion");
+ };
+ assert_eq!(notification.import_id, import_id);
+ assert_eq!(
+ session.consume_external_agent_config_import_completion(import_id),
+ consumed
+ );
+ assert_eq!(
+ session.external_agent_config_import_in_progress(),
+ !consumed
+ );
+ }
+ assert!(!session.consume_external_agent_config_import_completion("this-client"));
+ session.shutdown().await?;
+ let mut expected = Vec::new();
+ for cwds in [json!([cwd]), json!(null)] {
+ for source in ["claude-code", "cursor"] {
+ expected.push((
+ "externalAgentConfig/detect".to_string(),
+ json!({
+ "includeHome": true, "cwds": cwds, "maxSessionAgeDays": null,
+ "maxSessions": null, "source": null, "migrationSource": source
+ }),
+ ));
+ }
+ }
+ for _ in 0..2 {
+ expected.push((
+ "externalAgentConfig/import".to_string(),
+ json!({
+ "migrationItems": items, "source": "cli", "providerId": source,
+ "migrationSource": source
+ }),
+ ));
+ }
+ assert_eq!(server.await??, expected);
+ }
+ Ok(())
+}
diff --git a/codex-rs/tui/src/external_agent_config_migration/flow.rs b/codex-rs/tui/src/external_agent_config_migration/flow.rs
index ebaf050519..612bb24555 100644
--- a/codex-rs/tui/src/external_agent_config_migration/flow.rs
+++ b/codex-rs/tui/src/external_agent_config_migration/flow.rs
@@ -1,6 +1,5 @@
use crate::app_server_session::AppServerSession;
use crate::app_server_session::EXTERNAL_AGENT_CONFIG_IMPORT_IN_PROGRESS_MESSAGE;
-use crate::legacy_core::config::Config;
use crate::tui;
use codex_app_server_protocol::ExternalAgentConfigDetectParams;
use codex_app_server_protocol::ExternalAgentConfigImportCompletedNotification;
@@ -8,6 +7,7 @@ use codex_app_server_protocol::ExternalAgentConfigMigrationItem;
use codex_app_server_protocol::ExternalAgentConfigMigrationItemType;
use ratatui::prelude::Stylize as _;
use ratatui::text::Line;
+use std::path::Path;
use super::ExternalAgentConfigMigrationOutcome;
use super::model::external_agent_config_migration_item_count;
@@ -18,8 +18,6 @@ use super::source::run_external_agent_config_source_prompt;
pub(crate) const EXTERNAL_AGENT_CONFIG_MIGRATION_NO_ITEMS_MESSAGE: &str =
"No compatible setup was found to import.";
-pub(crate) const EXTERNAL_AGENT_CONFIG_MIGRATION_REMOTE_UNAVAILABLE_MESSAGE: &str = "Import from other apps is unavailable in remote sessions. Start Codex locally and run /import.";
-pub(crate) const EXTERNAL_AGENT_CONFIG_MIGRATION_DAEMON_UNAVAILABLE_MESSAGE: &str = "Import from other apps is unavailable while Codex is connected to the local app-server daemon. Restart with `codex --no-daemon` and run /import.";
pub(crate) enum ExternalAgentConfigMigrationFlowOutcome {
Started(Vec<Line<'static>>),
@@ -257,25 +255,18 @@ fn remaining_items_handoff(remaining_item_count: usize) -> Option<String> {
pub(crate) async fn handle_external_agent_config_migration_prompt(
tui: &mut tui::Tui,
app_server: &mut AppServerSession,
- config: &Config,
+ cwd: Option<&Path>,
) -> Result<ExternalAgentConfigMigrationFlowOutcome, String> {
- if app_server.uses_remote_workspace() {
- return Err(EXTERNAL_AGENT_CONFIG_MIGRATION_REMOTE_UNAVAILABLE_MESSAGE.to_string());
- }
- if !app_server.uses_embedded_app_server() {
- return Err(EXTERNAL_AGENT_CONFIG_MIGRATION_DAEMON_UNAVAILABLE_MESSAGE.to_string());
- }
if app_server.external_agent_config_import_in_progress() {
return Err(EXTERNAL_AGENT_CONFIG_IMPORT_IN_PROGRESS_MESSAGE.to_string());
}
- let cwd = config.cwd.to_path_buf();
let mut detection = ExternalAgentConfigDetection::default();
for source in ExternalAgentConfigMigrationSource::ALL {
let response = match app_server
.external_agent_config_detect(ExternalAgentConfigDetectParams {
include_home: true,
- cwds: Some(vec![cwd.clone()]),
+ cwds: cwd.map(|cwd| vec![cwd.to_path_buf()]),
max_session_age_days: None,
max_sessions: None,
source: None,
@@ -287,7 +278,7 @@ pub(crate) async fn handle_external_agent_config_migration_prompt(
Err(err) => {
tracing::warn!(
error = %err,
- cwd = %cwd.display(),
+ cwd = ?cwd,
source = source.label(),
"failed to detect external agent config migrations"
);
@@ -362,7 +353,7 @@ pub(crate) async fn handle_external_agent_config_migration_prompt(
Err(err) => {
tracing::warn!(
error = %err,
- cwd = %cwd.display(),
+ cwd = ?cwd,
"failed to import external agent config migration items"
);
error = Some(format!("Import failed: {err}"));
diff --git a/codex-rs/tui/src/external_agent_config_migration/flow_tests.rs b/codex-rs/tui/src/external_agent_config_migration/flow_tests.rs
index bc5cc6d667..b9bd58c12f 100644
--- a/codex-rs/tui/src/external_agent_config_migration/flow_tests.rs
+++ b/codex-rs/tui/src/external_agent_config_migration/flow_tests.rs
@@ -188,8 +188,6 @@ fn external_agent_config_migration_messages_snapshot() {
))
.chain([
Line::from(EXTERNAL_AGENT_CONFIG_MIGRATION_NO_ITEMS_MESSAGE),
- Line::from(EXTERNAL_AGENT_CONFIG_MIGRATION_REMOTE_UNAVAILABLE_MESSAGE),
- Line::from(EXTERNAL_AGENT_CONFIG_MIGRATION_DAEMON_UNAVAILABLE_MESSAGE),
Line::from(EXTERNAL_AGENT_CONFIG_IMPORT_IN_PROGRESS_MESSAGE),
])
.map(|line| {
diff --git a/codex-rs/tui/src/external_agent_config_migration/snapshots/codex_tui__external_agent_config_migration__flow__tests__external_agent_config_migration_messages.snap b/codex-rs/tui/src/external_agent_config_migration/snapshots/codex_tui__external_agent_config_migration__flow__tests__external_agent_config_migration_messages.snap
index 04d7038b3c..2d07c0310c 100644
--- a/codex-rs/tui/src/external_agent_config_migration/snapshots/codex_tui__external_agent_config_migration__flow__tests__external_agent_config_migration_messages.snap
+++ b/codex-rs/tui/src/external_agent_config_migration/snapshots/codex_tui__external_agent_config_migration__flow__tests__external_agent_config_migration_messages.snap
@@ -38,6 +38,4 @@ expression: messages
Plugins: 1 imported, 1 failed
Run /import again to check for additional items.
No compatible setup was found to import.
-Import from other apps is unavailable in remote sessions. Start Codex locally and run /import.
-Import from other apps is unavailable while Codex is connected to the local app-server daemon. Restart with `codex --no-daemon` and run /import.
A previous external agent import is still running. Wait for it to finish before importing again.