use std::io::{BufRead, BufReader, Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use serde_json::Value;
const UV_TOOL_BIN: &str = ".local/bin/abstractcore";
const LOCAL_VENV_BIN: &str = ".venv/bin/abstractcore";
#[derive(Clone, Debug, PartialEq)]
pub enum CliErrorKind {
NotFound,
Spawn,
Timeout,
Exit(i32),
BadJson,
Cancelled,
}
#[derive(Clone, Debug)]
pub struct CliError {
pub kind: CliErrorKind,
pub message: String,
pub program: &'static str,
pub reason_code: Option<String>,
}
impl CliError {
pub fn core(kind: CliErrorKind, message: String) -> CliError {
CliError {
kind,
message,
program: "abstractcore",
reason_code: None,
}
}
pub fn chat(kind: CliErrorKind, message: String) -> CliError {
CliError {
kind,
message,
program: "abstractcore-chat",
reason_code: None,
}
}
pub fn headline(&self) -> String {
let p = self.program;
match self.kind {
CliErrorKind::NotFound => format!("{p} CLI not found"),
CliErrorKind::Spawn => format!("could not start {p}"),
CliErrorKind::Timeout => format!("{p} timed out"),
CliErrorKind::Exit(code) => format!("{p} exited with {code}"),
CliErrorKind::BadJson => format!("{p} answered, but not with JSON"),
CliErrorKind::Cancelled => format!("{p} command cancelled"),
}
}
pub fn hint(&self) -> &'static str {
match self.kind {
CliErrorKind::NotFound => {
"set $ABSTRACTCORE_CLI, or install abstractcore on PATH — the file mirror still works"
}
CliErrorKind::Spawn => "check the binary is executable ($ABSTRACTCORE_CLI?)",
CliErrorKind::Timeout => "the Python side hung — retry with r",
CliErrorKind::Exit(_) => "the message above is the CLI's own error",
CliErrorKind::BadJson => "an abstractcore too old for --json? check its version",
CliErrorKind::Cancelled => "cancelled on request — nothing was stored",
}
}
}
impl std::fmt::Display for CliError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}: {}", self.headline(), self.message)
}
}
#[derive(Clone, Debug)]
pub struct CliInfo {
pub bin: PathBuf,
pub source: &'static str,
}
pub fn resolve_bin(
env: &dyn Fn(&str) -> Option<String>,
home: &Path,
cwd: &Path,
exists: &dyn Fn(&Path) -> bool,
) -> Option<CliInfo> {
for (var, source) in [
("ABSTRACTCORE_CLI", "$ABSTRACTCORE_CLI"),
("ABSTRACTCORE_BIN", "$ABSTRACTCORE_BIN (legacy alias)"),
] {
if let Some(explicit) = env(var).filter(|v| !v.trim().is_empty()) {
return Some(CliInfo {
bin: PathBuf::from(explicit.trim()),
source,
});
}
}
if let Some(paths) = env("PATH") {
for dir in std::env::split_paths(&paths) {
let candidate = dir.join("abstractcore");
if exists(&candidate) {
return Some(CliInfo {
bin: candidate,
source: "PATH",
});
}
}
}
if !home.as_os_str().is_empty() {
let shim = home.join(UV_TOOL_BIN);
if exists(&shim) {
return Some(CliInfo {
bin: shim,
source: "~/.local/bin (uv tool)",
});
}
}
let venv = cwd.join(LOCAL_VENV_BIN);
if exists(&venv) {
return Some(CliInfo {
bin: venv,
source: "./.venv",
});
}
None
}
pub fn resolve_bin_from_env() -> Option<CliInfo> {
let home = std::env::var("HOME").map(PathBuf::from).unwrap_or_default();
let cwd = std::env::current_dir().unwrap_or_default();
resolve_bin(&|k| std::env::var(k).ok(), &home, &cwd, &|p| p.is_file())
}
pub struct CoreCli {
pub bin: PathBuf,
pub chat_bin: Option<PathBuf>,
pub chat_from_path: bool,
}
pub fn resolve_chat_bin(
core_bin: &Path,
exists: &dyn Fn(&Path) -> bool,
) -> Option<(PathBuf, bool)> {
let sibling = core_bin.with_file_name("abstractcore-chat");
if exists(&sibling) {
return Some((sibling, false));
}
if let Some(paths) = std::env::var_os("PATH") {
for dir in std::env::split_paths(&paths) {
let candidate = dir.join("abstractcore-chat");
if exists(&candidate) {
return Some((candidate, true));
}
}
}
None
}
#[derive(Clone, Debug)]
pub struct CliOutput {
pub value: Value,
pub fallback_warnings: Vec<String>,
}
impl CoreCli {
pub fn new(bin: PathBuf) -> CoreCli {
let resolved = resolve_chat_bin(&bin, &|p| p.is_file());
let chat_from_path = resolved.as_ref().is_some_and(|(_, from_path)| *from_path);
CoreCli {
bin,
chat_bin: resolved.map(|(p, _)| p),
chat_from_path,
}
}
#[cfg(test)]
pub fn bare(bin: PathBuf) -> CoreCli {
CoreCli {
bin,
chat_bin: None,
chat_from_path: false,
}
}
pub fn run_chat(
&self,
args: &[&str],
timeout: Duration,
) -> Result<(String, Vec<String>), CliError> {
let chat = self.chat_bin.as_ref().ok_or_else(|| {
CliError::chat(
CliErrorKind::NotFound,
"abstractcore-chat not found beside abstractcore or on PATH".into(),
)
})?;
let label = format!("abstractcore-chat {}", args.join(" "));
let (status, stdout, stderr) =
run_raw_at(chat, args, &label, timeout).map_err(|mut e| {
e.program = "abstractcore-chat";
e
})?;
if !status.success() {
return Err(CliError::chat(
CliErrorKind::Exit(status.code().unwrap_or(-1)),
error_line(&stdout, &stderr),
));
}
Ok((stdout, fallback_lines(&stderr)))
}
pub fn run_setter(
&self,
args: &[&str],
redacted_label: &str,
timeout: Duration,
) -> Result<Vec<String>, CliError> {
let (status, stdout, stderr) = self.run_raw(args, redacted_label, timeout)?;
if !status.success() {
return Err(CliError::core(
CliErrorKind::Exit(status.code().unwrap_or(-1)),
error_line(&stdout, &stderr),
));
}
if let Some(l) = stdout
.lines()
.find(|l| l.contains("❌") || l.contains("Error:"))
{
return Err(CliError::core(
CliErrorKind::Exit(0),
format!("{} (the CLI still exited 0)", l.trim()),
));
}
Ok(fallback_lines(&stderr))
}
pub fn run_json(&self, args: &[&str], timeout: Duration) -> Result<CliOutput, CliError> {
let label = format!("abstractcore {}", args.join(" "));
let (status, stdout, stderr) = self.run_raw(args, &label, timeout)?;
if !status.success() {
let code = status.code().unwrap_or(-1);
return Err(CliError::core(
CliErrorKind::Exit(code),
error_line(&stdout, &stderr),
));
}
let value = serde_json::from_str(&stdout).map_err(|e| {
CliError::core(
CliErrorKind::BadJson,
format!("{e} — first bytes: {}", head(&stdout, 120)),
)
})?;
Ok(CliOutput {
value,
fallback_warnings: fallback_lines(&stderr),
})
}
pub fn run_json_last(&self, args: &[&str], timeout: Duration) -> Result<CliOutput, CliError> {
let label = format!("abstractcore {}", args.join(" "));
let (status, stdout, stderr) = self.run_raw(args, &label, timeout)?;
let last = last_json_object(&stdout);
if !status.success() {
let code = status.code().unwrap_or(-1);
let msg = last
.as_ref()
.and_then(job_error_text)
.unwrap_or_else(|| error_line(&stdout, &stderr));
return Err(CliError::core(CliErrorKind::Exit(code), msg));
}
let value = last.ok_or_else(|| {
CliError::core(
CliErrorKind::BadJson,
format!(
"no JSON object on stdout — first bytes: {}",
head(&stdout, 120)
),
)
})?;
Ok(CliOutput {
value,
fallback_warnings: fallback_lines(&stderr),
})
}
pub fn run_email(
&self,
args: &[&str],
stdin: Option<&str>,
redacted_label: &str,
timeout: Duration,
) -> Result<CliOutput, CliError> {
let (status, stdout, stderr) =
run_raw_at_stdin(&self.bin, args, stdin, redacted_label, timeout)?;
email_outcome(status, &stdout, &stderr)
}
pub fn run_email_streaming(
&self,
args: &[&str],
stdin: Option<&str>,
redacted_label: &str,
timeout: Duration,
on_prompt: Box<dyn Fn(Value) + Send>,
cancel: &AtomicBool,
) -> Result<CliOutput, CliError> {
let on_line: Box<dyn FnMut(&str) + Send> = Box::new(move |line: &str| {
if let Some(p) = oauth_prompt_of(line) {
on_prompt(p);
}
});
let (status, stdout, stderr) = run_raw_streaming_at(
&self.bin,
args,
stdin,
redacted_label,
timeout,
on_line,
cancel,
)?;
email_outcome(status, &stdout, &stderr)
}
pub fn run_email_discover(&self, address: &str, timeout: Duration) -> Result<Value, CliError> {
let args = email_discover_argv(address);
let argv: Vec<&str> = args.iter().map(String::as_str).collect();
let label = format!("abstractcore email discover {address}");
let (status, stdout, stderr) = self.run_raw(&argv, &label, timeout)?;
match last_json_object(&stdout) {
Some(doc) if doc.get("found").is_some() => Ok(doc),
_ => email_outcome(status, &stdout, &stderr).map(|o| o.value),
}
}
fn run_raw(
&self,
args: &[&str],
redacted_label: &str,
timeout: Duration,
) -> Result<(std::process::ExitStatus, String, String), CliError> {
run_raw_at(&self.bin, args, redacted_label, timeout)
}
}
pub fn email_discover_argv(address: &str) -> Vec<String> {
vec![
"email".into(),
"discover".into(),
address.trim().to_string(),
"--json".into(),
]
}
fn email_outcome(
status: std::process::ExitStatus,
stdout: &str,
stderr: &str,
) -> Result<CliOutput, CliError> {
let doc = last_json_object(stdout);
if !status.success() {
let code = status.code().unwrap_or(-1);
let msg = doc
.as_ref()
.and_then(email_error_text)
.unwrap_or_else(|| error_line(stdout, stderr));
let mut err = CliError::core(CliErrorKind::Exit(code), msg);
err.reason_code = doc.as_ref().and_then(email_reason_code);
return Err(err);
}
let value = doc.ok_or_else(|| {
CliError::core(
CliErrorKind::BadJson,
format!(
"no JSON object on stdout — first bytes: {}",
head(stdout, 120)
),
)
})?;
Ok(CliOutput {
value,
fallback_warnings: fallback_lines(stderr),
})
}
pub fn oauth_prompt_of(line: &str) -> Option<Value> {
let v: Value = serde_json::from_str(line.trim()).ok()?;
v.get("oauth_prompt").filter(|p| p.is_object()).cloned()
}
fn own_process_group(command: &mut Command) {
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
command.process_group(0);
}
#[cfg(not(unix))]
{
let _ = command;
}
}
pub(crate) fn build_command(bin: &Path, args: &[&str], stdin_piped: bool) -> Command {
let mut command = Command::new(bin);
command
.args(args)
.stdin(if stdin_piped {
Stdio::piped()
} else {
Stdio::null()
})
.stdout(Stdio::piped())
.stderr(Stdio::piped());
own_process_group(&mut command);
command
}
fn feed_stdin(child: &mut std::process::Child, data: Option<&str>) {
if let (Some(mut pipe), Some(data)) = (child.stdin.take(), data) {
let data = data.to_string();
std::thread::spawn(move || {
let _ = pipe.write_all(data.as_bytes());
drop(pipe);
});
}
}
fn kill_tree(child: &mut std::process::Child) {
#[cfg(unix)]
{
if let Ok(pgid) = i32::try_from(child.id()) {
if pgid > 1 {
unsafe {
libc::kill(-pgid, libc::SIGKILL);
}
}
}
}
let _ = child.kill();
let _ = child.wait();
}
pub(crate) fn run_raw_streaming_at(
bin: &Path,
args: &[&str],
stdin: Option<&str>,
redacted_label: &str,
timeout: Duration,
mut on_line: Box<dyn FnMut(&str) + Send>,
cancel: &AtomicBool,
) -> Result<(std::process::ExitStatus, String, String), CliError> {
let mut child = build_command(bin, args, stdin.is_some())
.spawn()
.map_err(|e| CliError::core(CliErrorKind::Spawn, format!("{}: {e}", bin.display())))?;
feed_stdin(&mut child, stdin);
let stdout = child.stdout.take().expect("piped");
let stderr = child.stderr.take().expect("piped");
let out_h = std::thread::spawn(move || read_all(stdout));
let err_h = std::thread::spawn(move || {
let mut all = String::new();
let mut reader = BufReader::new(stderr);
let mut buf = Vec::new();
loop {
buf.clear();
match reader.read_until(b'\n', &mut buf) {
Ok(0) | Err(_) => break,
Ok(_) => {
let line = String::from_utf8_lossy(&buf).into_owned();
on_line(&line);
all.push_str(&line);
}
}
}
all
});
let deadline = Instant::now() + timeout;
let status = loop {
match child.try_wait() {
Ok(Some(status)) => break status,
Ok(None) => {
let cancelled = cancel.load(Ordering::SeqCst);
if cancelled || Instant::now() >= deadline {
kill_tree(&mut child);
drop(out_h);
drop(err_h);
return Err(if cancelled {
CliError::core(
CliErrorKind::Cancelled,
format!("cancelled: {redacted_label}"),
)
} else {
CliError::core(
CliErrorKind::Timeout,
format!("no answer within {}s: {redacted_label}", timeout.as_secs()),
)
});
}
std::thread::sleep(Duration::from_millis(25));
}
Err(e) => return Err(CliError::core(CliErrorKind::Spawn, e.to_string())),
}
};
let stdout = out_h.join().unwrap_or_default();
let stderr = err_h.join().unwrap_or_default();
Ok((status, stdout, stderr))
}
pub(crate) fn run_raw_at(
bin: &Path,
args: &[&str],
redacted_label: &str,
timeout: Duration,
) -> Result<(std::process::ExitStatus, String, String), CliError> {
run_raw_at_stdin(bin, args, None, redacted_label, timeout)
}
pub(crate) fn run_raw_at_stdin(
bin: &Path,
args: &[&str],
stdin: Option<&str>,
redacted_label: &str,
timeout: Duration,
) -> Result<(std::process::ExitStatus, String, String), CliError> {
let mut child = build_command(bin, args, stdin.is_some())
.spawn()
.map_err(|e| CliError::core(CliErrorKind::Spawn, format!("{}: {e}", bin.display())))?;
feed_stdin(&mut child, stdin);
let stdout = child.stdout.take().expect("piped");
let stderr = child.stderr.take().expect("piped");
let out_h = std::thread::spawn(move || read_all(stdout));
let err_h = std::thread::spawn(move || read_all(stderr));
let deadline = Instant::now() + timeout;
let status = loop {
match child.try_wait() {
Ok(Some(status)) => break status,
Ok(None) => {
if Instant::now() >= deadline {
kill_tree(&mut child);
drop(out_h);
drop(err_h);
return Err(CliError::core(
CliErrorKind::Timeout,
format!("no answer within {}s: {redacted_label}", timeout.as_secs()),
));
}
std::thread::sleep(Duration::from_millis(25));
}
Err(e) => return Err(CliError::core(CliErrorKind::Spawn, e.to_string())),
}
};
let stdout = out_h.join().unwrap_or_default();
let stderr = err_h.join().unwrap_or_default();
Ok((status, stdout, stderr))
}
fn fallback_lines(stderr: &str) -> Vec<String> {
stderr
.lines()
.filter(|l| l.contains("#FALLBACK"))
.map(|l| l.trim().to_string())
.collect()
}
pub fn email_reason_code(doc: &Value) -> Option<String> {
doc.get("reason_code")
.or_else(|| doc.get("error").and_then(|e| e.get("code")))
.and_then(Value::as_str)
.filter(|c| !c.is_empty())
.map(str::to_string)
}
pub fn email_error_text(doc: &Value) -> Option<String> {
let words = |v: &Value| -> Option<String> {
let cause = v.get("cause").and_then(Value::as_str)?;
Some(match v.get("fix").and_then(Value::as_str) {
Some(fix) if !fix.is_empty() => format!("{cause} — Fix: {fix}"),
_ => cause.to_string(),
})
};
if let Some(e) = doc.get("error") {
if let Some(w) = words(e) {
return Some(w);
}
}
for leg in ["imap", "smtp"] {
if let Some(l) = doc.get(leg) {
if l.get("ok").and_then(Value::as_bool) == Some(false) {
let name = if leg == "imap" { "IMAP" } else { "SMTP" };
return words(l).map(|w| format!("{name}: {w}"));
}
}
}
doc.get("message")
.and_then(Value::as_str)
.map(str::to_string)
}
fn read_all(mut r: impl Read) -> String {
let mut buf = Vec::new();
let _ = r.read_to_end(&mut buf);
String::from_utf8_lossy(&buf).into_owned()
}
pub(crate) fn error_line(stdout: &str, stderr: &str) -> String {
if let Some(l) = stdout.lines().find(|l| l.contains("Error:")) {
return l.trim().to_string();
}
if let Some(l) = stderr.lines().rev().find(|l| !l.trim().is_empty()) {
return l.trim().to_string();
}
if let Some(l) = stdout.lines().find(|l| !l.trim().is_empty()) {
return l.trim().to_string();
}
"(no output)".into()
}
pub(crate) fn last_json_object(stdout: &str) -> Option<Value> {
let trimmed = stdout.trim();
if trimmed.is_empty() {
return None;
}
if let Ok(v) = serde_json::from_str::<Value>(trimmed) {
return v.is_object().then_some(v);
}
trimmed
.lines()
.rev()
.find_map(|l| serde_json::from_str::<Value>(l.trim()).ok())
.filter(Value::is_object)
}
fn job_error_text(v: &Value) -> Option<String> {
let err = v.get("error");
let text = err
.and_then(Value::as_str)
.or_else(|| err.and_then(|e| e.get("message")).and_then(Value::as_str))
.or_else(|| v.get("message").and_then(Value::as_str))?;
let text = text.trim();
(!text.is_empty()).then(|| text.to_string())
}
pub(crate) fn head(s: &str, n: usize) -> String {
let t: String = s.chars().take(n).collect();
t.replace('\n', " ")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bin_resolution_order() {
let home = Path::new("/home/u");
let cwd = Path::new("/work/proj");
let info = resolve_bin(
&|k| match k {
"ABSTRACTCORE_CLI" => Some("/opt/ac".to_string()),
"ABSTRACTCORE_BIN" => Some("/opt/legacy".to_string()),
_ => None,
},
home,
cwd,
&|_| false,
)
.unwrap();
assert_eq!(info.bin, PathBuf::from("/opt/ac"));
assert_eq!(info.source, "$ABSTRACTCORE_CLI");
let info = resolve_bin(
&|k| (k == "ABSTRACTCORE_BIN").then(|| "/opt/legacy".to_string()),
home,
cwd,
&|_| false,
)
.unwrap();
assert_eq!(info.bin, PathBuf::from("/opt/legacy"));
let info = resolve_bin(
&|k| (k == "PATH").then(|| "/a:/b".to_string()),
home,
cwd,
&|p| {
p == Path::new("/b/abstractcore")
|| p.starts_with("/home")
|| p.starts_with("/work")
},
)
.unwrap();
assert_eq!(info.bin, PathBuf::from("/b/abstractcore"));
assert_eq!(info.source, "PATH");
let info = resolve_bin(&|_| None, home, cwd, &|p| {
p == Path::new("/home/u/.local/bin/abstractcore")
|| p == Path::new("/work/proj/.venv/bin/abstractcore")
})
.unwrap();
assert_eq!(info.bin, PathBuf::from("/home/u/.local/bin/abstractcore"));
let info = resolve_bin(&|_| None, home, cwd, &|p| {
p == Path::new("/work/proj/.venv/bin/abstractcore")
})
.unwrap();
assert_eq!(info.bin, PathBuf::from("/work/proj/.venv/bin/abstractcore"));
assert_eq!(info.source, "./.venv");
assert!(resolve_bin(&|_| None, home, cwd, &|p| {
p == Path::new("/home/u/tmp/abstractframework/.venv/bin/abstractcore")
})
.is_none());
assert!(resolve_bin(&|_| None, home, cwd, &|_| false).is_none());
}
#[test]
fn email_refusals_speak_in_the_clis_typed_words() {
use serde_json::json;
let refused = json!({"ok": false, "error": {"code": "email_auth_failed",
"cause": "The IMAP server rejected the user name or password.", "fix": "Check the password."}});
assert_eq!(
email_error_text(&refused).as_deref(),
Some("The IMAP server rejected the user name or password. — Fix: Check the password.")
);
let test = json!({"imap": {"ok": true}, "smtp": {"ok": false, "cause": "TLS failed.", "fix": "Check the port."}, "ok": false});
assert_eq!(
email_error_text(&test).as_deref(),
Some("SMTP: TLS failed. — Fix: Check the port.")
);
let msg =
json!({"ok": false, "status": "refused", "message": "Re-run with --yes to confirm."});
assert_eq!(
email_error_text(&msg).as_deref(),
Some("Re-run with --yes to confirm.")
);
assert_eq!(email_error_text(&json!({"ok": true})), None);
}
#[test]
fn email_discover_reads_found_and_not_found_and_refusals() {
use std::os::unix::fs::PermissionsExt;
let dir = std::env::temp_dir().join(format!(
"acore-console-discover-{}-{:?}",
std::process::id(),
std::thread::current().id()
));
std::fs::create_dir_all(&dir).unwrap();
let bin = dir.join("abstractcore");
std::fs::write(
&bin,
r#"#!/bin/sh
[ "$1 $2 $4" = "email discover --json" ] || { echo "bad argv: $*" >&2; exit 9; }
case "$3" in
me@nowhere.test) echo '{"address":"me@nowhere.test","found":false,"tried":[]}'; exit 1;;
bad) echo '{"ok":false,"error":{"code":"email_invalid_settings","cause":"bad is not valid.","fix":"Give name@example.com."}}'; exit 1;;
*) echo "{\"address\":\"$3\",\"found\":true}"; exit 0;;
esac
"#,
)
.unwrap();
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
let cli = CoreCli::new(bin);
let t = Duration::from_secs(10);
let run = |addr: &str| {
for _ in 0..50 {
match cli.run_email_discover(addr, t) {
Err(e) if e.kind == CliErrorKind::Spawn => {
std::thread::sleep(Duration::from_millis(20))
}
other => return other,
}
}
cli.run_email_discover(addr, t)
};
let found = run("me@fastmail.test").unwrap();
assert_eq!(found["found"], serde_json::json!(true));
let missing = run("me@nowhere.test").unwrap();
assert_eq!(missing["found"], serde_json::json!(false));
let err = run("bad").unwrap_err();
assert_eq!(
err.message,
"bad is not valid. — Fix: Give name@example.com."
);
assert_eq!(err.reason_code.as_deref(), Some("email_invalid_settings"));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn error_line_prefers_the_cli_error() {
let out = "some noise\n❌ Error: Unknown provider 'x'\nmore";
assert_eq!(error_line(out, ""), "❌ Error: Unknown provider 'x'");
assert_eq!(
error_line("", "Traceback...\nValueError: boom"),
"ValueError: boom"
);
assert_eq!(error_line("", ""), "(no output)");
}
#[test]
fn run_json_parses_and_times_out() {
let echo = CoreCli::new(PathBuf::from("/bin/echo"));
let out = echo
.run_json(&["{\"ok\": true}"], Duration::from_secs(5))
.unwrap();
assert_eq!(out.value.get("ok").and_then(Value::as_bool), Some(true));
assert!(out.fallback_warnings.is_empty());
let sleep = CoreCli::new(PathBuf::from("/bin/sleep"));
let err = sleep
.run_json(&["5"], Duration::from_millis(200))
.unwrap_err();
assert_eq!(err.kind, CliErrorKind::Timeout);
let missing = CoreCli::new(PathBuf::from("/nonexistent/bin"));
let err = missing.run_json(&[], Duration::from_secs(1)).unwrap_err();
assert_eq!(err.kind, CliErrorKind::Spawn);
}
#[test]
fn run_json_last_takes_the_final_ndjson_line() {
let sh = CoreCli::new(PathBuf::from("/bin/sh"));
let ok = sh
.run_json_last(
&[
"-c",
r#"echo '{"schema":"host_job_v1","status":"running","percent":10.0}'
echo '{"schema":"host_job_v1","status":"running","percent":90.0}'
echo '{"schema":"host_job_v1","status":"completed","ok":true,"results":[{"status":"downloaded","message":"done"}]}'"#,
],
Duration::from_secs(5),
)
.unwrap();
assert_eq!(ok.value["status"], "completed");
assert_eq!(ok.value["results"][0]["status"], "downloaded");
assert_eq!(
sh.run_json(
&["-c", "echo '{\"a\":1}'; echo '{\"a\":2}'"],
Duration::from_secs(5)
)
.unwrap_err()
.kind,
CliErrorKind::BadJson
);
let failed = sh
.run_json_last(
&[
"-c",
r#"echo '{"schema":"host_job_v1","status":"running"}'
echo '{"schema":"host_job_v1","status":"failed","error":"pull failed: manifest unknown"}'
exit 1"#,
],
Duration::from_secs(5),
)
.unwrap_err();
assert_eq!(failed.kind, CliErrorKind::Exit(1));
assert!(failed.to_string().contains("manifest unknown"), "{failed}");
let empty = sh
.run_json_last(&["-c", "echo not json"], Duration::from_secs(5))
.unwrap_err();
assert_eq!(empty.kind, CliErrorKind::BadJson);
}
#[test]
fn exit_zero_stderr_fallback_is_surfaced() {
let sh = CoreCli::new(PathBuf::from("/bin/sh"));
let out = sh
.run_json(
&[
"-c",
"echo '#FALLBACK abstractcore config could not be parsed; \
falling back to DEFAULTS' >&2; echo '{\"ok\": true}'",
],
Duration::from_secs(5),
)
.unwrap();
assert_eq!(out.value.get("ok").and_then(Value::as_bool), Some(true));
assert_eq!(out.fallback_warnings.len(), 1);
assert!(out.fallback_warnings[0].contains("falling back to DEFAULTS"));
}
#[test]
fn email_streaming_delivers_the_prompt_before_the_answer() {
use std::sync::mpsc;
let sh = CoreCli::new(PathBuf::from("/bin/sh"));
let (tx, rx) = mpsc::channel::<Value>();
let never = AtomicBool::new(false);
let out = sh
.run_email_streaming(
&[
"-c",
r#"echo 'plain noise' >&2
echo '{"oauth_prompt": {"flow": "device", "user_code": "WDJB-MJHT", "verification_uri": "https://example.test/device"}}' >&2
sleep 0.3
echo '{"ok": true, "schema": "email_settings_v1", "auth_kind": "oauth2"}'"#,
],
None,
"email connect --oauth",
Duration::from_secs(10),
Box::new(move |p| {
let _ = tx.send(p);
}),
&never,
)
.unwrap();
assert_eq!(out.value["auth_kind"], "oauth2");
let prompts: Vec<Value> = rx.try_iter().collect();
assert_eq!(prompts.len(), 1, "{prompts:?}");
assert_eq!(prompts[0]["user_code"], "WDJB-MJHT");
assert_eq!(oauth_prompt_of("plain noise"), None);
assert_eq!(
oauth_prompt_of("{\"oauth_prompt\": \"not an object\"}"),
None
);
}
#[test]
fn email_streaming_cancel_kills_the_command() {
let sh = CoreCli::new(PathBuf::from("/bin/sh"));
let cancel = std::sync::Arc::new(AtomicBool::new(false));
let c2 = cancel.clone();
std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(150));
c2.store(true, Ordering::SeqCst);
});
let started = Instant::now();
let err = sh
.run_email_streaming(
&["-c", "sleep 30; true"],
None,
"email connect --oauth",
Duration::from_secs(60),
Box::new(|_| {}),
&cancel,
)
.unwrap_err();
assert_eq!(err.kind, CliErrorKind::Cancelled);
assert!(started.elapsed() < Duration::from_secs(10));
}
}
#[cfg(all(test, unix))]
mod stdin_secret_tests {
use super::*;
use crate::ui::email::{connect_action, oauth_action, ConnectFields, OAuthFields};
use crate::worker::run_email_action;
const BOUND: Duration = Duration::from_secs(10);
const FAKE_CLI: &str = r#"#!/bin/sh
[ -n "$FAKE_CLI_PROBE" ] && exit 0
IFS= read -r line
rest=$(cat)
hex() { printf '%s' "$1" | od -An -tx1 | tr -d ' \n'; }
printf '{"ok": true, "line": "%s", "rest": "%s", "argv": "%s"}\n' "$(hex "$line")" "$(hex "$rest")" "$(hex "$*")"
"#;
fn fake_cli() -> PathBuf {
use std::os::unix::fs::PermissionsExt;
let dir = std::env::temp_dir().join(format!(
"acore-console-fake-cli-{}-{:?}",
std::process::id(),
std::thread::current().id()
));
std::fs::create_dir_all(&dir).unwrap();
let bin = dir.join("abstractcore");
std::fs::write(&bin, FAKE_CLI).unwrap();
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
for _ in 0..100 {
match Command::new(&bin)
.env("FAKE_CLI_PROBE", "1")
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
{
Err(e) if e.raw_os_error() == Some(26) => {
std::thread::sleep(Duration::from_millis(20))
}
_ => break,
}
}
bin
}
fn unhex(s: &str) -> String {
let bytes: Vec<u8> = (0..s.len())
.step_by(2)
.map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap())
.collect();
String::from_utf8(bytes).unwrap()
}
fn seen(out: &CliOutput) -> (String, String, String) {
let f = |k: &str| unhex(out.value[k].as_str().unwrap());
(f("line"), f("rest"), f("argv"))
}
#[test]
fn the_password_reaches_the_child_on_stdin_and_never_in_argv() {
let pw = " pw-SENTINEL-c0de é \"x\" ";
let action = connect_action(
&ConnectFields {
address: "me@example.test".into(),
password: pw.into(),
imap_host: "imap.example.test".into(),
..ConnectFields::default()
},
None,
)
.unwrap();
let cli = CoreCli::new(fake_cli());
let never = AtomicBool::new(false);
let out = run_email_action(&cli, &action, BOUND, Box::new(|_| {}), &never).unwrap();
let (line, rest, argv) = seen(&out);
assert_eq!(line, pw);
assert_eq!(rest, "", "exactly one line on stdin, then EOF");
assert!(
argv.starts_with("email connect --address=me@example.test --password-stdin"),
"{argv}"
);
assert!(!argv.contains("SENTINEL"), "{argv}");
}
#[test]
fn the_client_secret_reaches_the_child_on_stdin_and_never_in_argv() {
let action = oauth_action(
&OAuthFields {
address: "me@example.test".into(),
client_id: "mine".into(),
client_secret: "cs-SENTINEL-51".into(),
..OAuthFields::default()
},
None,
)
.unwrap();
assert!(action.oauth);
let cli = CoreCli::new(fake_cli());
let never = AtomicBool::new(false);
let out = run_email_action(&cli, &action, BOUND, Box::new(|_| {}), &never).unwrap();
let (line, rest, argv) = seen(&out);
assert_eq!(line, "cs-SENTINEL-51");
assert_eq!(rest, "");
assert!(argv.contains("--client-secret-stdin"), "{argv}");
assert!(!argv.contains("SENTINEL"), "{argv}");
}
#[test]
fn no_secret_means_null_stdin() {
let cli = CoreCli::new(fake_cli());
let out = cli
.run_email(&["status"], None, "email status", Duration::from_secs(10))
.unwrap();
let (line, rest, argv) = seen(&out);
assert_eq!(
(line.as_str(), rest.as_str(), argv.as_str()),
("", "", "status")
);
}
}