use std::path::PathBuf;
#[cfg(feature = "runtime")]
use copilot_sdk::{CliProgram, ErrorKind, SpawnedProcessOptions};
use copilot_sdk::{
Client, ClientOptions, HAS_BUNDLED_CLI, RuntimeConnection, install_bundled_cli,
install_bundled_runtime,
};
#[cfg(all(feature = "bundled-cli", has_bundled_cli))]
use copilot_sdk::{CreateSessionOptions, OwnedRuntimeOptions};
use serial_test::serial;
#[cfg(feature = "runtime")]
#[allow(dead_code)]
#[path = "support/fake_runtime.rs"]
mod fake_runtime;
#[cfg(all(not(feature = "bundled-cli"), has_extracted_cli))]
#[allow(dead_code)]
#[path = "../src/platform_dirs/mod.rs"]
mod platform_dirs;
#[cfg(all(not(feature = "bundled-cli"), has_extracted_cli))]
#[path = "../src/cache_paths.rs"]
mod cache_paths;
fn unset_env(key: &str) {
unsafe { std::env::remove_var(key) };
}
fn set_env(key: &str, value: &str) {
unsafe { std::env::set_var(key, value) };
}
#[tokio::test(flavor = "current_thread")]
#[serial(copilot_cli_path)]
async fn env_override_resolves_to_pointed_file() {
let tmp = tempfile::NamedTempFile::new().expect("create tempfile");
let path = tmp.path().to_path_buf();
set_env(
"COPILOT_CLI_PATH",
path.to_str().expect("utf-8 tempfile path"),
);
let opts = ClientOptions::new(copilot_sdk::ClientMode::CodingAgent).with_runtime(
RuntimeConnection::for_spawned_stdio(
SpawnedProcessOptions::new().with_program(CliProgram::Resolve),
),
);
let result = Client::start(opts).await;
unset_env("COPILOT_CLI_PATH");
match result {
Ok(_) => {}
Err(e) => {
let msg = format!("{e}");
assert!(
!msg.contains("not found"),
"expected COPILOT_CLI_PATH to win; got {msg}"
);
}
}
drop(tmp);
let _ = path;
}
#[cfg(feature = "runtime")]
#[tokio::test(flavor = "current_thread")]
async fn cli_selection_respects_transport_and_environment() {
const CHILD_TRANSPORT: &str = "COPILOT_RESOLUTION_TEST_TRANSPORT";
if let Ok(transport) = std::env::var(CHILD_TRANSPORT) {
let cli_path = std::env::var("COPILOT_CLI_PATH").expect("explicit path");
let fallback =
std::env::var("COPILOT_CLI_EXTRACT_DIR").expect("owned extraction directory");
let mut options = ClientOptions::new(copilot_sdk::ClientMode::CodingAgent);
if transport != "external" {
options = options.with_github(|group| group.with_use_logged_in_user(false));
}
let mut process = SpawnedProcessOptions::new()
.with_program(CliProgram::Resolve)
.with_owned(|owned| {
owned
.with_bundled_cli_extract_directory(&fallback)
.with_base_directory(PathBuf::from(&fallback).join("home"))
});
if transport == "external" {
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0))
.await
.expect("owned external server");
let port = listener.local_addr().expect("server address").port();
let server = async {
let (mut stream, _) = listener.accept().await.expect("external connection");
let connect = fake_runtime::read_frame(&mut stream).await;
assert_eq!(connect["method"], "connect");
fake_runtime::write_frame(
&mut stream,
serde_json::json!({
"jsonrpc": "2.0", "id": connect["id"],
"result": { "ok": true, "protocolVersion": 4, "version": "test" }
}),
)
.await;
stream
};
let start = async {
Client::start(options.with_runtime(RuntimeConnection::Tcp(
copilot_sdk::TcpRuntimeOptions {
host: "127.0.0.1".to_string(),
port,
connection_token: None,
},
)))
.await
.expect("external transport ignores local CLI selection")
};
let (client, _server) =
tokio::time::timeout(std::time::Duration::from_secs(10), async {
tokio::join!(start, server)
})
.await
.expect("external handshake must complete");
client.stop().await.expect("stop external client");
return;
}
let mut selected_path = cli_path.clone();
let relative_child = transport == "child-relative";
let valid_child = transport == "child-valid" || relative_child;
if transport == "child-override" || valid_child {
selected_path = PathBuf::from(&fallback)
.join("child-copilot")
.to_string_lossy()
.into_owned();
if valid_child {
std::fs::create_dir_all(&fallback).expect("owned CLI directory");
std::fs::write(&selected_path, b"not an executable")
.expect("selected but unlaunchable CLI");
}
if relative_child {
process = process
.with_working_directory(transport.as_str())
.with_env([("COPILOT_CLI_PATH", "./child-copilot")]);
} else {
process = process.with_env([("COPILOT_CLI_PATH", &selected_path)]);
}
} else if transport == "child-remove" {
process = process.with_env_remove(["COPILOT_CLI_PATH"]);
}
let removed = !process.env_remove.is_empty();
let runtime = match transport.as_str() {
"stdio" | "child-override" | "child-valid" | "child-relative" | "child-remove" => {
RuntimeConnection::SpawnedStdio(process)
}
"tcp" => RuntimeConnection::SpawnedTcp(copilot_sdk::SpawnedTcpRuntimeOptions {
process,
port: 0,
connection_token: None,
}),
#[cfg(feature = "in-process")]
"inprocess" => RuntimeConnection::for_in_process(
copilot_sdk::InProcessRuntimeOptions::new().with_owned(|_| process.owned),
),
other => panic!("unexpected transport: {other}"),
};
let result = Client::start(options.with_runtime(runtime)).await;
if removed {
result
.expect("removed host override permits bundled discovery")
.stop()
.await
.expect("stop bundled runtime");
return;
}
let error = match result {
Ok(client) => {
client.stop().await.expect("stop substituted runtime");
panic!("an invalid explicit path started a different runtime");
}
Err(error) => error,
};
if valid_child {
assert!(matches!(error.kind(), ErrorKind::Io), "{error}");
} else {
assert!(
matches!(error.kind(), ErrorKind::BinaryNotFound { .. }),
"{error}"
);
}
let message = error.to_string();
if !valid_child {
assert!(message.contains("COPILOT_CLI_PATH"), "{message}");
}
assert!(message.contains(&selected_path), "{message}");
return;
}
let temp = tempfile::tempdir().expect("owned process environment");
let transports = [
"stdio",
"tcp",
"external",
"child-override",
"child-valid",
"child-relative",
#[cfg(all(feature = "bundled-cli", has_bundled_cli))]
"child-remove",
#[cfg(feature = "in-process")]
"inprocess",
];
for transport in transports {
let mut command =
tokio::process::Command::new(std::env::current_exe().expect("test binary"));
command
.args([
"--exact",
"cli_selection_respects_transport_and_environment",
"--nocapture",
])
.env(CHILD_TRANSPORT, transport)
.env("COPILOT_CLI_PATH", temp.path().join("missing-copilot"))
.env("COPILOT_CLI_EXTRACT_DIR", temp.path().join(transport))
.kill_on_drop(true);
if transport == "child-relative" {
command.current_dir(temp.path());
}
let output = tokio::time::timeout(std::time::Duration::from_secs(60), command.output())
.await
.expect("resolver child must exit")
.expect("run resolver child");
assert!(
output.status.success(),
"{transport}: stdout:\n{}\nstderr:\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
}
}
#[cfg(all(not(feature = "bundled-cli"), has_extracted_cli))]
#[test]
#[serial(copilot_cli_path)]
fn extracted_binary_present_at_conventional_path() {
let cache_identity = env!("COPILOT_SDK_CLI_CACHE_ID");
let binary = if cfg!(windows) {
"copilot-runtime.exe"
} else {
"copilot-runtime"
};
let path = cache_paths::extracted_runtime_install_dir(cache_identity)
.expect("protected extraction directory")
.join(binary);
assert!(
path.is_file(),
"expected build.rs to extract the CLI to {} (`bundled-cli` off)",
path.display()
);
}
#[cfg(all(not(feature = "bundled-cli"), has_extracted_cli))]
#[tokio::test(flavor = "current_thread")]
#[serial(copilot_cli_path)]
async fn unbundled_resolver_finds_extracted_binary() {
unset_env("COPILOT_CLI_PATH");
unset_env("COPILOT_CLI_EXTRACT_DIR");
let opts = ClientOptions::new(copilot_sdk::ClientMode::CodingAgent).with_runtime(
RuntimeConnection::for_spawned_stdio(
SpawnedProcessOptions::new().with_program(CliProgram::Resolve),
),
);
let result = Client::start(opts).await;
if let Err(e) = result {
assert!(
!matches!(e.kind(), ErrorKind::BinaryNotFound { .. }),
"resolver returned BinaryNotFound with `bundled-cli` off: {e}"
);
}
}
#[cfg(all(not(feature = "bundled-cli"), has_extracted_cli))]
#[tokio::test(flavor = "current_thread")]
#[serial(copilot_cli_path)]
async fn extract_dir_runtime_override_is_honored() {
let tmp = tempfile::tempdir().expect("create tempdir");
let binary = if cfg!(windows) {
"copilot-runtime.exe"
} else {
"copilot-runtime"
};
let fake = tmp.path().join(binary);
std::fs::write(&fake, b"runtime").expect("write fake binary");
std::fs::write(tmp.path().join("runtime.node"), b"runtime").expect("write runtime.node");
unset_env("COPILOT_CLI_PATH");
set_env(
"COPILOT_CLI_EXTRACT_DIR",
tmp.path().to_str().expect("utf-8 tempdir path"),
);
let opts = ClientOptions::new(copilot_sdk::ClientMode::CodingAgent).with_runtime(
RuntimeConnection::for_spawned_stdio(
SpawnedProcessOptions::new().with_program(CliProgram::Resolve),
),
);
let result = Client::start(opts).await;
unset_env("COPILOT_CLI_EXTRACT_DIR");
if let Err(e) = result {
assert!(
!matches!(e.kind(), ErrorKind::BinaryNotFound { .. }),
"EXTRACT_DIR-redirected resolver returned BinaryNotFound: {e}"
);
}
drop(tmp);
let _ = fake;
}
#[test]
fn pin_file_when_present_is_well_formed() {
let manifest_dir = env!("CARGO_MANIFEST_DIR");
for filename in ["cli-version.txt", "cli-version-in-process.txt"] {
let pin = PathBuf::from(manifest_dir).join(filename);
if !pin.is_file() {
continue;
}
let contents = std::fs::read_to_string(&pin).expect("read CLI version snapshot");
let version = contents
.lines()
.filter_map(|line| line.split_once('='))
.find_map(|(key, value)| (key.trim() == "version").then_some(value.trim()))
.unwrap_or_else(|| panic!("{filename} missing `version=` line"));
let mut package_count = 0;
for raw in contents.lines() {
let line = raw.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let (key, value) = line
.split_once('=')
.unwrap_or_else(|| panic!("malformed line: {raw:?}"));
assert!(!value.trim().is_empty(), "empty value for key {key:?}");
if key.trim() == "version" {
continue;
} else if key.trim() == "release-url" {
assert!(
value.trim()
== format!(
"https://github.com/github/copilot-cli/releases/download/v{version}"
)
|| value.trim()
== format!(
"https://github.com/microsoft/copilot-sdk/releases/download/runtime-{version}"
),
"unexpected release URL in {filename}"
);
} else {
assert_eq!(
value.trim().len(),
64,
"invalid SHA-256 hash for key {key:?}"
);
assert!(
value.trim().bytes().all(|byte| byte.is_ascii_hexdigit()),
"invalid SHA-256 hash for key {key:?}"
);
package_count += 1;
}
}
assert_eq!(
package_count, 8,
"{filename} has incomplete platform hashes"
);
}
}
#[cfg(all(feature = "bundled-cli", has_bundled_cli))]
#[test]
fn install_bundled_cli_returns_extracted_path() {
const { assert!(HAS_BUNDLED_CLI) };
let first = install_bundled_cli().expect("bundled CLI should install");
assert!(
first.is_file(),
"install_bundled_cli returned a path that is not a file: {}",
first.display()
);
assert_eq!(
first.file_name().and_then(|name| name.to_str()),
Some(if cfg!(windows) {
"copilot.exe"
} else {
"copilot"
})
);
let second = install_bundled_cli().expect("second call should also succeed");
assert_eq!(
first, second,
"install_bundled_cli must be idempotent across calls"
);
}
#[cfg(all(feature = "bundled-cli", has_bundled_cli))]
#[test]
fn bundled_cli_is_distinct_from_runtime_and_supports_version_probe() {
let cli = install_bundled_cli().expect("bundled CLI should install");
let runtime = install_bundled_runtime().expect("bundled runtime should install");
assert_ne!(cli, runtime);
assert_ne!(
std::fs::metadata(&cli).expect("CLI metadata").len(),
std::fs::metadata(&runtime)
.expect("runtime wrapper metadata")
.len(),
"the full CLI must not alias the runtime wrapper bytes"
);
let output = std::process::Command::new(&cli)
.arg("--binary-version")
.output()
.expect("run bundled CLI version probe");
assert!(
output.status.success(),
"bundled CLI version probe failed: {}",
String::from_utf8_lossy(&output.stderr)
);
assert!(
String::from_utf8_lossy(&output.stdout).contains(env!("COPILOT_SDK_CLI_VERSION")),
"bundled CLI version output did not contain {}: {}",
env!("COPILOT_SDK_CLI_VERSION"),
String::from_utf8_lossy(&output.stdout)
);
}
#[cfg(not(all(feature = "bundled-cli", has_bundled_cli)))]
#[test]
fn install_bundled_cli_is_none_without_embed() {
const { assert!(!HAS_BUNDLED_CLI) };
assert!(
install_bundled_cli().is_none(),
"install_bundled_cli must not fall back to the dev-cache path"
);
}
#[cfg(all(feature = "bundled-cli", has_bundled_cli))]
#[test]
fn install_bundled_runtime_returns_wrapper_bundle() {
let first = install_bundled_runtime().expect("bundled runtime should install");
assert_eq!(
first.file_name().and_then(|name| name.to_str()),
Some(if cfg!(windows) {
"copilot-runtime.exe"
} else {
"copilot-runtime"
})
);
let runtime_node = first
.parent()
.expect("install directory")
.join("runtime.node");
assert!(
runtime_node.is_file(),
"runtime.node was not installed: {}",
runtime_node.display()
);
#[cfg(feature = "in-process")]
{
let runtime_library = first
.parent()
.expect("install directory")
.join(if cfg!(windows) {
"copilot_runtime.dll"
} else if cfg!(target_os = "macos") {
"libcopilot_runtime.dylib"
} else {
"libcopilot_runtime.so"
});
assert!(
runtime_library.is_file(),
"bundled runtime library was not installed: {}",
runtime_library.display()
);
}
let second = install_bundled_runtime().expect("second call should also succeed");
assert_eq!(first, second);
}
#[cfg(all(feature = "bundled-cli", has_bundled_cli))]
#[tokio::test(flavor = "current_thread")]
#[serial(copilot_cli_path)]
async fn bundled_runtime_clean_extract_starts_without_cli_host() {
let temp = tempfile::tempdir().expect("create tempdir");
let extract_dir = temp.path().join("runtime");
let empty_path = temp.path().join("empty-path");
let working_dir = temp.path().join("work");
std::fs::create_dir(&empty_path).expect("create empty PATH directory");
std::fs::create_dir(&working_dir).expect("create working directory");
assert!(!extract_dir.exists());
let options = ClientOptions::new(copilot_sdk::ClientMode::CodingAgent)
.with_runtime(RuntimeConnection::for_spawned_stdio(
SpawnedProcessOptions::new()
.with_working_directory(&working_dir)
.with_env(std::env::vars_os().chain([("PATH".into(), empty_path.into_os_string())]))
.with_env_remove([
"COPILOT_RUNTIME_HOST_COMMAND",
"COPILOT_CLI_PATH",
"COPILOT_RUNTIME_PROVIDER_LIB",
])
.with_owned(|_| {
OwnedRuntimeOptions::new().with_bundled_cli_extract_directory(&extract_dir)
}),
))
.with_github(|group| group.with_use_logged_in_user(false));
let client = Client::start(options)
.await
.expect("start bundled runtime from clean extraction");
let response = client
.ping(Some("hostless runtime"))
.await
.expect("ping bundled runtime");
assert_eq!(response.message, "pong: hostless runtime");
let session = client
.create_session(CreateSessionOptions::default())
.await
.expect("create session");
session.disconnect().await.expect("disconnect session");
client.stop().await.expect("stop bundled runtime");
assert!(extract_dir.join("runtime.node").is_file());
assert!(
extract_dir
.join(if cfg!(windows) {
"copilot-runtime.exe"
} else {
"copilot-runtime"
})
.is_file()
);
assert!(
!extract_dir
.join(if cfg!(windows) {
"copilot.exe"
} else {
"copilot"
})
.exists()
);
}
#[cfg(not(all(feature = "bundled-cli", has_bundled_cli)))]
#[test]
fn install_bundled_runtime_is_none_without_embed() {
assert!(
install_bundled_runtime().is_none(),
"install_bundled_runtime must not fall back to the dev-cache path"
);
}