Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
172 changes: 143 additions & 29 deletions src/acp/connection.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
use crate::acp::protocol::{ConfigOption, JsonRpcMessage, JsonRpcRequest, JsonRpcResponse, parse_config_options};
use crate::acp::protocol::{
parse_config_options, ConfigOption, JsonRpcMessage, JsonRpcRequest, JsonRpcResponse,
};
use anyhow::{anyhow, Result};
use serde_json::{json, Value};
use std::collections::HashMap;
use std::collections::VecDeque;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::process::{Child, ChildStdin};
use tokio::sync::{mpsc, oneshot, Mutex};
use tokio::task::JoinHandle;
use tracing::{debug, error, info};
use tracing::{debug, error, info, warn};

const STDERR_TAIL_CAPACITY: usize = 8;
const STDERR_DRAIN_TIMEOUT_MS: u64 = 250;

/// Pick the most permissive selectable permission option from ACP options.
fn pick_best_option(options: &[Value]) -> Option<String> {
Expand Down Expand Up @@ -83,6 +88,17 @@ fn expand_env(val: &str) -> String {
}
use tokio::time::Instant;

fn build_connection_closed_message(stderr_tail: &VecDeque<String>) -> String {
if stderr_tail.is_empty() {
"connection closed".into()
} else {
format!(
"connection closed; agent stderr: {}",
stderr_tail.iter().cloned().collect::<Vec<_>>().join(" | ")
)
}
}

/// A content block for the ACP prompt — either text or image.
#[derive(Debug, Clone)]
pub enum ContentBlock {
Expand Down Expand Up @@ -162,7 +178,7 @@ impl AcpConnection {
cmd.args(args)
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null())
.stderr(std::process::Stdio::piped())
.current_dir(working_dir);
// Create a new process group so we can kill the entire tree.
// SAFETY: setpgid is async-signal-safe (POSIX.1-2008) and called
Expand All @@ -187,20 +203,39 @@ impl AcpConnection {
// Preserve the real HOME so agents can find OAuth/auth files (~/.codex,
// ~/.claude, ~/.config/gh, etc.). working_dir is already set via
// current_dir() above and is not necessarily the user's home directory.
cmd.env("HOME", std::env::var("HOME").unwrap_or_else(|_| working_dir.into()));
cmd.env("PATH", std::env::var("PATH").unwrap_or_else(|_| "/usr/local/bin:/usr/bin:/bin".into()));
cmd.env(
"HOME",
std::env::var("HOME").unwrap_or_else(|_| working_dir.into()),
);
cmd.env(
"PATH",
std::env::var("PATH").unwrap_or_else(|_| "/usr/local/bin:/usr/bin:/bin".into()),
);
#[cfg(unix)]
{
cmd.env("USER", std::env::var("USER").unwrap_or_else(|_| "agent".into()));
cmd.env(
"USER",
std::env::var("USER").unwrap_or_else(|_| "agent".into()),
);
}
#[cfg(windows)]
{
// Windows requires SystemRoot for DLL loading and basic OS functionality.
// USERPROFILE is the Windows equivalent of HOME.
cmd.env("USERPROFILE", std::env::var("USERPROFILE").unwrap_or_else(|_| working_dir.into()));
cmd.env("USERNAME", std::env::var("USERNAME").unwrap_or_else(|_| "agent".into()));
if let Ok(v) = std::env::var("SystemRoot") { cmd.env("SystemRoot", v); }
if let Ok(v) = std::env::var("SystemDrive") { cmd.env("SystemDrive", v); }
cmd.env(
"USERPROFILE",
std::env::var("USERPROFILE").unwrap_or_else(|_| working_dir.into()),
);
cmd.env(
"USERNAME",
std::env::var("USERNAME").unwrap_or_else(|_| "agent".into()),
);
if let Ok(v) = std::env::var("SystemRoot") {
cmd.env("SystemRoot", v);
}
if let Ok(v) = std::env::var("SystemDrive") {
cmd.env("SystemDrive", v);
}
}
for (k, v) in env {
cmd.env(k, expand_env(v));
Expand All @@ -223,13 +258,50 @@ impl AcpConnection {
let mut proc = cmd
.spawn()
.map_err(|e| anyhow!("failed to spawn {command}: {e}"))?;
let child_pgid = proc.id()
.and_then(|pid| i32::try_from(pid).ok());
let child_pgid = proc.id().and_then(|pid| i32::try_from(pid).ok());

let stdout = proc.stdout.take().ok_or_else(|| anyhow!("no stdout"))?;
let stdin = proc.stdin.take().ok_or_else(|| anyhow!("no stdin"))?;
let stdin = Arc::new(Mutex::new(stdin));

// Stderr reader: log each line at warn level and keep a tail for error messages.
let stderr_tail: Arc<std::sync::Mutex<VecDeque<String>>> = Arc::new(std::sync::Mutex::new(
VecDeque::with_capacity(STDERR_TAIL_CAPACITY),
));
let (stderr_done_tx, stderr_done_rx) = oneshot::channel();
if let Some(stderr) = proc.stderr.take() {
let tail = stderr_tail.clone();
let done_tx = stderr_done_tx;
tokio::spawn(async move {
let mut reader = BufReader::new(stderr);
let mut line = String::new();
loop {
line.clear();
match reader.read_line(&mut line).await {
Ok(0) => break,
Err(e) => {
error!("stderr reader error: {e}");
break;
}
Ok(_) => {}
}
let trimmed = line.trim().to_string();
if trimmed.is_empty() {
continue;
}
warn!(target: "openab::agent", "[stderr] {trimmed}");
let mut t = tail.lock().unwrap();
if t.len() >= STDERR_TAIL_CAPACITY {
t.pop_front();
}
t.push_back(trimmed);
}
let _ = done_tx.send(());
});
} else {
let _ = stderr_done_tx.send(());
}

let pending: Arc<Mutex<HashMap<u64, oneshot::Sender<JsonRpcMessage>>>> =
Arc::new(Mutex::new(HashMap::new()));
let notify_tx: Arc<Mutex<Option<mpsc::UnboundedSender<JsonRpcMessage>>>> =
Expand All @@ -239,6 +311,8 @@ impl AcpConnection {
let pending = pending.clone();
let notify_tx = notify_tx.clone();
let stdin_clone = stdin.clone();
let stderr_tail_reader = stderr_tail.clone();
let stderr_done_rx = stderr_done_rx;
tokio::spawn(async move {
let mut reader = BufReader::new(stdout);
let mut line = String::new();
Expand Down Expand Up @@ -309,7 +383,20 @@ impl AcpConnection {
}
}

// Connection closed — resolve all pending with error
// Wait briefly for stderr to drain so fast-fail startup errors
// are consistently surfaced on the synthesized close message.
let _ = tokio::time::timeout(
std::time::Duration::from_millis(STDERR_DRAIN_TIMEOUT_MS),
stderr_done_rx,
)
.await;

// Connection closed — build error message, optionally with last stderr lines
let close_msg = {
let tail = stderr_tail_reader.lock().unwrap();
build_connection_closed_message(&tail)
};

let mut map = pending.lock().await;
for (_, tx) in map.drain() {
let _ = tx.send(JsonRpcMessage {
Expand All @@ -318,7 +405,7 @@ impl AcpConnection {
result: None,
error: Some(crate::acp::protocol::JsonRpcError {
code: -1,
message: "connection closed".into(),
message: close_msg.clone(),
}),
params: None,
});
Expand Down Expand Up @@ -403,19 +490,22 @@ impl AcpConnection {
.and_then(|c| c.get("loadSession"))
.and_then(|v| v.as_bool())
.unwrap_or(false);
info!(agent = agent_name, load_session = self.supports_load_session, "initialized");
info!(
agent = agent_name,
load_session = self.supports_load_session,
"initialized"
);
Ok(())
}

pub async fn session_new(&mut self, cwd: &str) -> Result<String> {
let resp = self
.send_request(
"session/new",
Some(json!({"cwd": cwd, "mcpServers": []})),
)
.send_request("session/new", Some(json!({"cwd": cwd, "mcpServers": []})))
.await?;

let session_id = resp.result.as_ref()
let session_id = resp
.result
.as_ref()
.and_then(|r| r.get("sessionId"))
.and_then(|s| s.as_str())
.ok_or_else(|| anyhow!("no sessionId in session/new response"))?
Expand All @@ -434,7 +524,11 @@ impl AcpConnection {

/// Set a config option (e.g. model, mode) via ACP session/set_config_option.
/// Returns the updated list of all config options.
pub async fn set_config_option(&mut self, config_id: &str, value: &str) -> Result<Vec<ConfigOption>> {
pub async fn set_config_option(
&mut self,
config_id: &str,
value: &str,
) -> Result<Vec<ConfigOption>> {
let session_id = self
.acp_session_id
.as_ref()
Expand Down Expand Up @@ -462,7 +556,10 @@ impl AcpConnection {
Err(_) => {
// Fall back: send as a slash command (e.g. "/model claude-sonnet-4")
let cmd = format!("/{config_id} {value}");
info!(cmd, "set_config_option not supported, falling back to prompt");
info!(
cmd,
"set_config_option not supported, falling back to prompt"
);
let _resp = self
.send_request(
"session/prompt",
Expand Down Expand Up @@ -503,10 +600,7 @@ impl AcpConnection {
let id = self.next_id();

// Convert content blocks to JSON
let prompt_json: Vec<Value> = content_blocks
.iter()
.map(|b| b.to_json())
.collect();
let prompt_json: Vec<Value> = content_blocks.iter().map(|b| b.to_json()).collect();

let req = JsonRpcRequest::new(
id,
Expand Down Expand Up @@ -572,11 +666,15 @@ impl AcpConnection {
#[cfg(unix)]
{
// Stage 1: SIGTERM the process group
unsafe { libc::kill(-pgid, libc::SIGTERM); }
unsafe {
libc::kill(-pgid, libc::SIGTERM);
}
// Stage 2: SIGKILL after brief grace (std::thread survives runtime shutdown)
std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_millis(1500));
unsafe { libc::kill(-pgid, libc::SIGKILL); }
unsafe {
libc::kill(-pgid, libc::SIGKILL);
}
});
}
#[cfg(not(unix))]
Expand All @@ -594,8 +692,12 @@ impl Drop for AcpConnection {

#[cfg(test)]
mod tests {
use super::{build_agent_env, build_permission_response, pick_best_option};
use super::{
build_agent_env, build_connection_closed_message, build_permission_response,
pick_best_option,
};
use serde_json::json;
use std::collections::VecDeque;

#[test]
fn picks_allow_always_over_other_options() {
Expand Down Expand Up @@ -727,4 +829,16 @@ mod tests {
assert!(!result.contains_key("OAB_TEST_NONEXISTENT_VAR_12345"));
assert!(inherited.is_empty());
}

#[test]
fn connection_closed_message_includes_stderr_tail() {
let mut tail = VecDeque::new();
tail.push_back("first".to_string());
tail.push_back("second".to_string());

assert_eq!(
build_connection_closed_message(&tail),
"connection closed; agent stderr: first | second"
);
}
}
Loading
Loading