Refactor exec to use the shared app-server client (#61706)

## What changed

- Use `AppServerClient` throughout exec and extract turn completion into `finish_turn`, including handling for server and thread-stream disconnections.
- Move remote address parsing and auth-token resolution into `codex-app-server-client`, with re-exports from the TUI.
- Allow human-readable exec output to be initialized without a local `Config`.

## Testing

Move remote address and auth-token tests into `codex-app-server-client`, retaining coverage for WebSocket and Unix socket addresses, invalid addresses, and missing, empty, or whitespace-padded tokens.

GitOrigin-RevId: 465b17a1c03392a7d4e7700d83ce67c2cf5ef021
This commit is contained in:
Eric Traut
2026-11-15 23:50:49 +00:00
committed by copyberry
parent a394ff9cf6
commit 598df2d015
10 changed files with 325 additions and 273 deletions
+3 -3
View File
@@ -1,7 +1,7 @@
//! Resolve the cyber treatment for an exec turn from the connected server's catalog.
use crate::RequestIdSequencer;
use codex_app_server_client::InProcessAppServerClient;
use codex_app_server_client::AppServerClient;
use codex_app_server_protocol::Account;
use codex_app_server_protocol::ClientRequest;
use codex_app_server_protocol::CyberAccessProgram;
@@ -16,7 +16,7 @@ use codex_protocol::openai_models::ModelAccessPrograms;
pub(crate) async fn program_for_turn(
features: &Features,
client: &InProcessAppServerClient,
client: &AppServerClient,
request_ids: &mut RequestIdSequencer,
model: &str,
provider_id: &str,
@@ -94,7 +94,7 @@ pub(crate) async fn program_for_turn(
}
async fn read_account(
client: &InProcessAppServerClient,
client: &AppServerClient,
request_ids: &mut RequestIdSequencer,
) -> anyhow::Result<Option<Account>> {
let account = client
@@ -44,7 +44,7 @@ pub(crate) struct EventProcessorWithHumanOutput {
impl EventProcessorWithHumanOutput {
pub(crate) fn create_with_ansi(
with_ansi: bool,
config: &Config,
config: Option<&Config>,
last_message_path: Option<PathBuf>,
) -> Self {
let style = |styled: Style, plain: Style| if with_ansi { styled } else { plain };
@@ -57,8 +57,8 @@ impl EventProcessorWithHumanOutput {
magenta: style(Style::new().magenta(), Style::new()),
red: style(Style::new().red(), Style::new()),
yellow: style(Style::new().yellow(), Style::new()),
show_agent_reasoning: !config.hide_agent_reasoning,
show_raw_agent_reasoning: config.show_raw_agent_reasoning,
show_agent_reasoning: config.is_none_or(|config| !config.hide_agent_reasoning),
show_raw_agent_reasoning: config.is_some_and(|config| config.show_raw_agent_reasoning),
last_message_path,
final_message: None,
final_message_rendered: false,
+68 -21
View File
@@ -16,12 +16,13 @@ mod worktree;
pub use cli::Cli;
pub use cli::Command;
pub use cli::ReviewArgs;
use codex_app_server_client::AppServerClient;
use codex_app_server_client::AppServerEvent;
use codex_app_server_client::DEFAULT_IN_PROCESS_CHANNEL_CAPACITY;
use codex_app_server_client::EnvironmentManager;
use codex_app_server_client::ExecServerRuntimeOptions;
use codex_app_server_client::InProcessAppServerClient;
use codex_app_server_client::InProcessClientStartArgs;
use codex_app_server_client::InProcessServerEvent;
use codex_app_server_client::TypedRequestError;
use codex_app_server_protocol::ClientRequest;
use codex_app_server_protocol::ConfigWarningNotification;
@@ -957,7 +958,7 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
true => Box::new(EventProcessorWithJsonOutput::new(last_message_file.clone())),
_ => Box::new(EventProcessorWithHumanOutput::create_with_ansi(
stderr_with_ansi,
&config,
Some(&config),
last_message_file.clone(),
)),
};
@@ -1094,11 +1095,13 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
.transpose()?;
let mut request_ids = RequestIdSequencer::new();
let mut client = InProcessAppServerClient::start(in_process_start_args)
.await
.map_err(|err| {
anyhow::anyhow!("failed to initialize in-process app-server client: {err}")
})?;
let client = AppServerClient::InProcess(
InProcessAppServerClient::start(in_process_start_args)
.await
.map_err(|err| {
anyhow::anyhow!("failed to initialize in-process app-server client: {err}")
})?,
);
let mut daybreak_enabled = config.daybreak_enabled;
// Resolve resume and fork through existing app-server thread lifecycle APIs.
@@ -1263,7 +1266,7 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
info!("Codex initialized with event: {session_configured:?}");
let (interrupt_tx, mut interrupt_rx) = mpsc::unbounded_channel::<()>();
let (interrupt_tx, interrupt_rx) = mpsc::unbounded_channel::<()>();
tokio::spawn(async move {
if tokio::signal::ctrl_c().await.is_ok() {
tracing::debug!("Keyboard interrupt");
@@ -1376,12 +1379,49 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
};
exec_span.record("turn.id", task_id.as_str());
finish_turn(
client,
request_ids,
ExecTurn {
thread_id: primary_thread_id.to_string(),
turn_id: task_id,
ephemeral: config.ephemeral,
history_mode,
},
event_processor,
bound_output,
interrupt_rx,
)
.await
}
struct ExecTurn {
thread_id: String,
turn_id: String,
ephemeral: bool,
history_mode: ThreadHistoryMode,
}
async fn finish_turn(
mut client: AppServerClient,
mut request_ids: RequestIdSequencer,
turn: ExecTurn,
mut event_processor: Box<dyn EventProcessor>,
bound_output: Option<codex_exec_server::BoundOutput>,
mut interrupt_rx: mpsc::UnboundedReceiver<()>,
) -> anyhow::Result<()> {
let ExecTurn {
thread_id,
turn_id: task_id,
ephemeral: thread_ephemeral,
history_mode,
} = turn;
// Run the loop until the task is complete.
// Track whether a fatal error was reported by the server so we can
// exit with a non-zero status for automation-friendly signaling.
let mut error_seen = false;
let mut interrupt_channel_open = true;
let primary_thread_id_for_requests = primary_thread_id.to_string();
let primary_thread_id_for_requests = thread_id;
loop {
let server_event = tokio::select! {
maybe_interrupt = interrupt_rx.recv(), if interrupt_channel_open => {
@@ -1414,10 +1454,10 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
};
match server_event {
InProcessServerEvent::ServerRequest(request) => {
AppServerEvent::ServerRequest(request) => {
handle_server_request(&client, *request, &mut error_seen).await;
}
InProcessServerEvent::ServerNotification(notification) => {
AppServerEvent::ServerNotification(notification) => {
let mut notification = *notification;
if let ServerNotification::Error(payload) = &notification {
if payload.thread_id == primary_thread_id_for_requests
@@ -1444,7 +1484,7 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
&task_id,
) {
maybe_backfill_turn_completed_items(
config.ephemeral,
thread_ephemeral,
history_mode,
&client,
&mut request_ids,
@@ -1469,7 +1509,14 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
}
}
}
InProcessServerEvent::Lagged { skipped } => {
AppServerEvent::Disconnected { message } => {
anyhow::bail!("app-server disconnected: {message}")
}
AppServerEvent::ThreadStreamDisconnected(error) => {
anyhow::bail!("app-server stream disconnected: {}", error.error.message)
}
AppServerEvent::ThreadStreamReconnected(_) => {}
AppServerEvent::Lagged { skipped } => {
let message = lagged_event_warning_message(skipped);
warn!("{message}");
event_processor.process_warning(message);
@@ -1489,7 +1536,7 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
}
async fn start_thread(
client: &InProcessAppServerClient,
client: &AppServerClient,
request_ids: &mut RequestIdSequencer,
config: &Config,
thread_source: &ThreadSource,
@@ -1616,7 +1663,7 @@ fn sandbox_mode_from_permission_profile(
}
async fn send_request_with_response<T>(
client: &InProcessAppServerClient,
client: &AppServerClient,
request: ClientRequest,
method: &str,
) -> Result<T, String>
@@ -1816,7 +1863,7 @@ fn should_process_notification(
async fn maybe_backfill_turn_completed_items(
thread_ephemeral: bool,
history_mode: ThreadHistoryMode,
client: &InProcessAppServerClient,
client: &AppServerClient,
request_ids: &mut RequestIdSequencer,
notification: &mut ServerNotification,
) {
@@ -1991,7 +2038,7 @@ fn cwds_match(current_cwd: &Path, session_cwd: &Path) -> bool {
}
async fn resolve_resume_thread_id(
client: &InProcessAppServerClient,
client: &AppServerClient,
config: &Config,
state_db: Option<&StateDbHandle>,
args: &crate::cli::ResumeArgs,
@@ -2169,7 +2216,7 @@ fn canceled_mcp_server_elicitation_response(
}
async fn request_shutdown(
client: &InProcessAppServerClient,
client: &AppServerClient,
request_ids: &mut RequestIdSequencer,
thread_id: &str,
) -> Result<(), String> {
@@ -2185,7 +2232,7 @@ async fn request_shutdown(
}
async fn resolve_server_request(
client: &InProcessAppServerClient,
client: &AppServerClient,
request_id: RequestId,
value: serde_json::Value,
method: &str,
@@ -2197,7 +2244,7 @@ async fn resolve_server_request(
}
async fn reject_server_request(
client: &InProcessAppServerClient,
client: &AppServerClient,
request_id: RequestId,
method: &str,
reason: String,
@@ -2228,7 +2275,7 @@ fn server_request_method_name(request: &ServerRequest) -> String {
}
async fn handle_server_request(
client: &InProcessAppServerClient,
client: &AppServerClient,
request: ServerRequest,
error_seen: &mut bool,
) {
+1
View File
@@ -54,6 +54,7 @@ pub(super) async fn fork_source(
channel_capacity: DEFAULT_IN_PROCESS_CHANNEL_CAPACITY,
})
.await?;
let client = AppServerClient::InProcess(client);
let result = async {
let lookup = crate::cli::ResumeArgs {
session_id: Some(args.session_id.clone()),