use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::process::Stdio;
use std::sync::Arc;
use std::time::Duration;
use serde_json::Value;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::process::{Child, ChildStdin, ChildStdout, Command};
use tokio::sync::{broadcast, mpsc, oneshot, watch};
use tokio::task::JoinHandle;
use tracing::{debug, warn};
use crate::Claude;
use crate::command::spawn_args::{SharedSpawnArgs, shell_quote};
use crate::error::{Error, Result};
use crate::tool_pattern::ToolPattern;
use crate::types::{Effort, HermeticScope, PermissionMode};
pub const DEFAULT_SUBSCRIBER_CAPACITY: usize = 256;
#[derive(Debug, Clone)]
pub struct PermissionRequest {
pub request_id: String,
pub tool_name: String,
pub input: Value,
pub raw: Value,
}
#[derive(Debug, Clone)]
pub enum PermissionDecision {
Allow {
updated_input: Option<Value>,
},
Deny {
message: String,
},
Defer,
}
type PermissionFuture = Pin<Box<dyn Future<Output = PermissionDecision> + Send + 'static>>;
type PermissionFn = dyn Fn(PermissionRequest) -> PermissionFuture + Send + Sync + 'static;
#[derive(Clone)]
pub struct PermissionHandler {
inner: Arc<PermissionFn>,
}
impl PermissionHandler {
pub fn new<F, Fut>(f: F) -> Self
where
F: Fn(PermissionRequest) -> Fut + Send + Sync + 'static,
Fut: Future<Output = PermissionDecision> + Send + 'static,
{
Self {
inner: Arc::new(move |req| Box::pin(f(req))),
}
}
fn invoke(&self, req: PermissionRequest) -> PermissionFuture {
(self.inner)(req)
}
}
impl std::fmt::Debug for PermissionHandler {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PermissionHandler").finish_non_exhaustive()
}
}
#[derive(Debug, Default, Clone)]
pub struct DuplexOptions {
shared: SharedSpawnArgs,
additional_args: Vec<String>,
subscriber_capacity: Option<usize>,
on_permission: Option<PermissionHandler>,
}
impl DuplexOptions {
#[must_use]
pub fn model(mut self, model: impl Into<String>) -> Self {
self.shared.model = Some(model.into());
self
}
#[must_use]
pub fn system_prompt(mut self, prompt: impl Into<String>) -> Self {
self.shared.system_prompt = Some(prompt.into());
self
}
#[must_use]
pub fn append_system_prompt(mut self, prompt: impl Into<String>) -> Self {
self.shared.append_system_prompt = Some(prompt.into());
self
}
#[must_use]
pub fn resume(mut self, session_id: impl Into<String>) -> Self {
self.shared.resume = Some(session_id.into());
self
}
#[must_use]
pub fn continue_session(mut self) -> Self {
self.shared.continue_session = true;
self
}
#[must_use]
pub fn worktree(mut self, name: Option<impl Into<String>>) -> Self {
self.shared.worktree = true;
if let Some(n) = name {
self.shared.worktree_name = Some(n.into());
}
self
}
#[must_use]
pub fn agent(mut self, name: impl Into<String>) -> Self {
self.shared.agent = Some(name.into());
self
}
#[must_use]
pub fn agents_json(mut self, json: impl Into<String>) -> Self {
self.shared.agents_json = Some(json.into());
self
}
#[must_use]
pub fn permission_mode(mut self, mode: PermissionMode) -> Self {
self.shared.permission_mode = Some(mode);
self
}
#[must_use]
pub fn dangerously_skip_permissions(mut self) -> Self {
self.shared.dangerously_skip_permissions = true;
self
}
#[must_use]
pub fn session_id(mut self, id: impl Into<String>) -> Self {
self.shared.session_id = Some(id.into());
self
}
#[must_use]
pub fn json_schema(mut self, schema: impl Into<String>) -> Self {
self.shared.json_schema = Some(schema.into());
self
}
#[must_use]
pub fn allowed_tools<I, T>(mut self, tools: I) -> Self
where
I: IntoIterator<Item = T>,
T: Into<ToolPattern>,
{
self.shared
.allowed_tools
.extend(tools.into_iter().map(Into::into));
self
}
#[must_use]
pub fn allowed_tool(mut self, tool: impl Into<ToolPattern>) -> Self {
self.shared.allowed_tools.push(tool.into());
self
}
#[must_use]
pub fn disallowed_tools<I, T>(mut self, tools: I) -> Self
where
I: IntoIterator<Item = T>,
T: Into<ToolPattern>,
{
self.shared
.disallowed_tools
.extend(tools.into_iter().map(Into::into));
self
}
#[must_use]
pub fn disallowed_tool(mut self, tool: impl Into<ToolPattern>) -> Self {
self.shared.disallowed_tools.push(tool.into());
self
}
#[must_use]
pub fn max_turns(mut self, turns: u32) -> Self {
self.shared.max_turns = Some(turns);
self
}
#[must_use]
pub fn max_budget_usd(mut self, budget: f64) -> Self {
self.shared.max_budget_usd = Some(budget);
self
}
#[must_use]
pub fn fallback_model(mut self, model: impl Into<String>) -> Self {
self.shared.fallback_model = Some(model.into());
self
}
#[must_use]
pub fn effort(mut self, effort: Effort) -> Self {
self.shared.effort = Some(effort);
self
}
#[must_use]
pub fn add_dir(mut self, dir: impl Into<String>) -> Self {
self.shared.add_dir.push(dir.into());
self
}
#[must_use]
pub fn mcp_config(mut self, path: impl Into<String>) -> Self {
self.shared.mcp_config.push(path.into());
self
}
#[must_use]
pub fn strict_mcp_config(mut self) -> Self {
self.shared.strict_mcp_config = true;
self
}
#[must_use]
pub fn setting_sources(mut self, sources: impl Into<String>) -> Self {
self.shared.setting_sources = Some(sources.into());
self
}
#[must_use]
pub fn hermetic(mut self) -> Self {
self.shared.apply_hermetic(HermeticScope::Full);
self
}
#[must_use]
pub fn hermetic_scoped(mut self, scope: HermeticScope) -> Self {
self.shared.apply_hermetic(scope);
self
}
#[must_use]
pub fn no_session_persistence(mut self) -> Self {
self.shared.no_session_persistence = true;
self
}
#[must_use]
pub fn tools(mut self, tools: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.shared.tools.extend(tools.into_iter().map(Into::into));
self
}
#[must_use]
pub fn file(mut self, spec: impl Into<String>) -> Self {
self.shared.file.push(spec.into());
self
}
#[must_use]
pub fn settings(mut self, settings: impl Into<String>) -> Self {
self.shared.settings = Some(settings.into());
self
}
#[must_use]
pub fn fork_session(mut self) -> Self {
self.shared.fork_session = true;
self
}
#[must_use]
pub fn debug_filter(mut self, filter: impl Into<String>) -> Self {
self.shared.debug_filter = Some(filter.into());
self
}
#[must_use]
pub fn debug_file(mut self, path: impl Into<String>) -> Self {
self.shared.debug_file = Some(path.into());
self
}
#[must_use]
pub fn betas(mut self, betas: impl Into<String>) -> Self {
self.shared.betas = Some(betas.into());
self
}
#[must_use]
pub fn plugin_dir(mut self, dir: impl Into<String>) -> Self {
self.shared.plugin_dirs.push(dir.into());
self
}
#[must_use]
pub fn plugin_url(mut self, url: impl Into<String>) -> Self {
self.shared.plugin_urls.push(url.into());
self
}
#[must_use]
pub fn tmux(mut self) -> Self {
self.shared.tmux = true;
self
}
#[must_use]
pub fn bare(mut self) -> Self {
self.shared.bare = true;
self
}
#[must_use]
pub fn safe_mode(mut self) -> Self {
self.shared.safe_mode = true;
self
}
#[must_use]
pub fn disable_slash_commands(mut self) -> Self {
self.shared.disable_slash_commands = true;
self
}
#[must_use]
pub fn include_hook_events(mut self) -> Self {
self.shared.include_hook_events = true;
self
}
#[must_use]
pub fn exclude_dynamic_system_prompt_sections(mut self) -> Self {
self.shared.exclude_dynamic_system_prompt_sections = true;
self
}
#[must_use]
pub fn name(mut self, name: impl Into<String>) -> Self {
self.shared.name = Some(name.into());
self
}
#[must_use]
pub fn arg(mut self, arg: impl Into<String>) -> Self {
self.additional_args.push(arg.into());
self
}
#[must_use]
pub fn subscriber_capacity(mut self, capacity: usize) -> Self {
self.subscriber_capacity = Some(capacity);
self
}
#[must_use]
pub fn on_permission(mut self, handler: PermissionHandler) -> Self {
self.on_permission = Some(handler);
self
}
fn build_args(&self) -> Vec<String> {
let mut args = vec![
"--print".to_string(),
"--verbose".to_string(),
"--output-format".to_string(),
"stream-json".to_string(),
"--input-format".to_string(),
"stream-json".to_string(),
];
self.shared.append_to(&mut args);
if self.on_permission.is_some() {
args.push("--permission-prompt-tool".to_string());
args.push("stdio".to_string());
}
args.extend(self.additional_args.iter().cloned());
args
}
fn spawn_command_args(&self, claude: &Claude) -> Vec<String> {
let mut args = claude.global_args.clone();
args.extend(self.build_args());
args
}
#[must_use]
pub fn to_command_string(&self, claude: &Claude) -> String {
let args = self.spawn_command_args(claude);
let quoted_args = args.iter().map(|arg| shell_quote(arg)).collect::<Vec<_>>();
format!("{} {}", claude.binary().display(), quoted_args.join(" "))
}
}
#[derive(Debug, Clone)]
pub struct TurnResult {
pub result: Value,
pub events: Vec<Value>,
}
impl TurnResult {
#[must_use]
pub fn result_text(&self) -> Option<&str> {
self.result.get("result").and_then(Value::as_str)
}
#[must_use]
pub fn session_id(&self) -> Option<&str> {
self.result.get("session_id").and_then(Value::as_str)
}
#[must_use]
pub fn total_cost_usd(&self) -> Option<f64> {
self.result
.get("total_cost_usd")
.or_else(|| self.result.get("cost_usd"))
.and_then(Value::as_f64)
}
#[must_use]
pub fn duration_ms(&self) -> Option<u64> {
self.result.get("duration_ms").and_then(Value::as_u64)
}
}
#[derive(Debug, Clone)]
pub enum InboundEvent {
SystemInit {
session_id: String,
},
Assistant(Value),
StreamEvent(Value),
User(Value),
Other(Value),
}
fn classify(msg: &Value) -> InboundEvent {
match msg.get("type").and_then(Value::as_str) {
Some("system") => {
if msg.get("subtype").and_then(Value::as_str) == Some("init")
&& let Some(id) = msg.get("session_id").and_then(Value::as_str)
{
return InboundEvent::SystemInit {
session_id: id.to_string(),
};
}
InboundEvent::Other(msg.clone())
}
Some("assistant") => InboundEvent::Assistant(msg.clone()),
Some("stream_event") => InboundEvent::StreamEvent(msg.clone()),
Some("user") => InboundEvent::User(msg.clone()),
_ => InboundEvent::Other(msg.clone()),
}
}
#[derive(Debug, Clone)]
pub enum SessionExitStatus {
Running,
Completed,
Failed(String),
}
#[derive(Debug)]
pub struct DuplexSession {
outbound_tx: mpsc::UnboundedSender<OutboundMsg>,
events_tx: broadcast::Sender<InboundEvent>,
exit_rx: watch::Receiver<SessionExitStatus>,
join: JoinHandle<Result<()>>,
}
#[derive(Debug)]
enum OutboundMsg {
Send {
prompt: String,
reply: oneshot::Sender<Result<TurnResult>>,
},
PermissionResponse {
request_id: String,
decision: PermissionDecision,
},
Interrupt {
reply: oneshot::Sender<Result<()>>,
},
}
impl DuplexSession {
pub async fn spawn(claude: &Claude, opts: DuplexOptions) -> Result<Self> {
let capacity = opts
.subscriber_capacity
.unwrap_or(DEFAULT_SUBSCRIBER_CAPACITY);
let permission_handler = opts.on_permission.clone();
let command_args = opts.spawn_command_args(claude);
debug!(
binary = %claude.binary.display(),
args = ?command_args,
"spawning duplex claude session"
);
let mut cmd = Command::new(&claude.binary);
cmd.args(&command_args)
.env_remove("CLAUDECODE")
.env_remove("CLAUDE_CODE_ENTRYPOINT")
.envs(&claude.env)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
if let Some(ref dir) = claude.working_dir {
cmd.current_dir(dir);
}
let mut child = cmd.spawn().map_err(|e| Error::Io {
message: format!("failed to spawn claude: {e}"),
source: e,
working_dir: claude.working_dir.clone(),
})?;
let stdin = child.stdin.take().expect("stdin was piped");
let stdout = child.stdout.take().expect("stdout was piped");
let (outbound_tx, outbound_rx) = mpsc::unbounded_channel();
let (events_tx, _initial_rx) = broadcast::channel(capacity);
let (exit_tx, exit_rx) = watch::channel(SessionExitStatus::Running);
let join = tokio::spawn(run_session(
child,
stdin,
stdout,
outbound_rx,
events_tx.clone(),
permission_handler,
exit_tx,
));
Ok(Self {
outbound_tx,
events_tx,
exit_rx,
join,
})
}
pub async fn send(&self, prompt: impl Into<String>) -> Result<TurnResult> {
let (reply_tx, reply_rx) = oneshot::channel();
self.outbound_tx
.send(OutboundMsg::Send {
prompt: prompt.into(),
reply: reply_tx,
})
.map_err(|_| Error::DuplexClosed)?;
reply_rx.await.map_err(|_| Error::DuplexClosed)?
}
#[must_use]
pub fn subscribe(&self) -> broadcast::Receiver<InboundEvent> {
self.events_tx.subscribe()
}
#[must_use]
pub fn is_alive(&self) -> bool {
matches!(*self.exit_rx.borrow(), SessionExitStatus::Running)
}
#[must_use]
pub fn exit_status(&self) -> SessionExitStatus {
self.exit_rx.borrow().clone()
}
pub async fn wait_for_exit(&self) -> SessionExitStatus {
let mut rx = self.exit_rx.clone();
loop {
{
let value = rx.borrow_and_update();
if !matches!(*value, SessionExitStatus::Running) {
return value.clone();
}
}
if rx.changed().await.is_err() {
return rx.borrow().clone();
}
}
}
pub fn respond_to_permission(
&self,
request_id: impl Into<String>,
decision: PermissionDecision,
) -> Result<()> {
if matches!(decision, PermissionDecision::Defer) {
warn!("respond_to_permission called with Defer; ignoring");
return Ok(());
}
self.outbound_tx
.send(OutboundMsg::PermissionResponse {
request_id: request_id.into(),
decision,
})
.map_err(|_| Error::DuplexClosed)?;
Ok(())
}
pub async fn interrupt(&self) -> Result<()> {
let (reply_tx, reply_rx) = oneshot::channel();
self.outbound_tx
.send(OutboundMsg::Interrupt { reply: reply_tx })
.map_err(|_| Error::DuplexClosed)?;
reply_rx.await.map_err(|_| Error::DuplexClosed)?
}
pub async fn close(self) -> Result<()> {
drop(self.outbound_tx);
drop(self.events_tx);
match self.join.await {
Ok(result) => result,
Err(e) if e.is_cancelled() => Ok(()),
Err(e) => Err(Error::Io {
message: format!("duplex session task panicked: {e}"),
source: std::io::Error::other(e.to_string()),
working_dir: None,
}),
}
}
}
const SHUTDOWN_BUDGET: Duration = Duration::from_secs(5);
async fn run_session(
mut child: Child,
mut stdin: ChildStdin,
stdout: ChildStdout,
mut outbound_rx: mpsc::UnboundedReceiver<OutboundMsg>,
events_tx: broadcast::Sender<InboundEvent>,
permission_handler: Option<PermissionHandler>,
exit_tx: watch::Sender<SessionExitStatus>,
) -> Result<()> {
let mut lines = BufReader::new(stdout).lines();
let mut pending: Option<(oneshot::Sender<Result<TurnResult>>, Vec<Value>)> = None;
let mut pending_control: HashMap<String, oneshot::Sender<Result<()>>> = HashMap::new();
let mut next_control_id: u64 = 0;
let mut stream_err: Option<Error> = None;
loop {
tokio::select! {
biased;
line = lines.next_line() => match line {
Ok(Some(l)) => {
if l.trim().is_empty() {
continue;
}
let parsed = match serde_json::from_str::<Value>(&l) {
Ok(v) => v,
Err(e) => {
debug!(line = %l, error = %e, "failed to parse duplex event, skipping");
continue;
}
};
match handle_inbound(parsed, &mut pending, &events_tx) {
InboundAction::None => {}
InboundAction::Permission(req) => {
let request_id = req.request_id.clone();
let decision = match permission_handler.as_ref() {
Some(h) => h.invoke(req).await,
None => {
warn!(
request_id = %request_id,
"received can_use_tool with no permission handler; auto-denying"
);
PermissionDecision::Deny {
message:
"no permission handler configured on duplex session"
.into(),
}
}
};
if matches!(decision, PermissionDecision::Defer) {
debug!(
request_id = %request_id,
"permission handler deferred; waiting for respond_to_permission"
);
} else if let Err(e) =
write_permission_response(&mut stdin, &request_id, &decision).await
{
warn!(error = %e, "failed to write permission response");
}
}
InboundAction::ControlResponse { request_id, outcome } => {
if let Some(reply) = pending_control.remove(&request_id) {
let _ = reply.send(outcome);
} else {
debug!(
request_id = %request_id,
"received control_response with no pending request"
);
}
}
}
}
Ok(None) => break,
Err(e) => {
stream_err = Some(Error::Io {
message: "failed to read duplex stdout".to_string(),
source: e,
working_dir: None,
});
break;
}
},
msg = outbound_rx.recv() => match msg {
Some(OutboundMsg::Send { prompt, reply }) => {
if pending.is_some() {
let _ = reply.send(Err(Error::DuplexTurnInFlight));
continue;
}
if let Err(e) = write_user(&mut stdin, &prompt).await {
let _ = reply.send(Err(e));
continue;
}
pending = Some((reply, Vec::new()));
}
Some(OutboundMsg::PermissionResponse { request_id, decision }) => {
if let Err(e) =
write_permission_response(&mut stdin, &request_id, &decision).await
{
warn!(error = %e, "failed to write deferred permission response");
}
}
Some(OutboundMsg::Interrupt { reply }) => {
next_control_id += 1;
let request_id = format!("interrupt-{next_control_id}");
if let Err(e) =
write_control_request(&mut stdin, &request_id, "interrupt").await
{
let _ = reply.send(Err(e));
continue;
}
pending_control.insert(request_id, reply);
}
None => break,
},
}
}
drop(stdin);
match tokio::time::timeout(SHUTDOWN_BUDGET, child.wait()).await {
Ok(Ok(_status)) => {}
Ok(Err(e)) => {
warn!(error = %e, "failed to wait for duplex child");
}
Err(_) => {
warn!("duplex child did not exit within shutdown budget; killing");
let _ = child.kill().await;
}
}
if let Some((reply, _)) = pending.take() {
let _ = reply.send(Err(Error::DuplexClosed));
}
for (_, reply) in pending_control.drain() {
let _ = reply.send(Err(Error::DuplexClosed));
}
let result = match stream_err {
Some(e) => Err(e),
None => Ok(()),
};
let final_state = match &result {
Ok(()) => SessionExitStatus::Completed,
Err(e) => SessionExitStatus::Failed(e.to_string()),
};
let _ = exit_tx.send(final_state);
result
}
enum InboundAction {
None,
Permission(PermissionRequest),
ControlResponse {
request_id: String,
outcome: Result<()>,
},
}
fn handle_inbound(
msg: Value,
pending: &mut Option<(oneshot::Sender<Result<TurnResult>>, Vec<Value>)>,
events_tx: &broadcast::Sender<InboundEvent>,
) -> InboundAction {
match msg.get("type").and_then(Value::as_str) {
Some("result") => {
if let Some((reply, events)) = pending.take() {
let _ = reply.send(Ok(TurnResult {
result: msg,
events,
}));
} else {
debug!("dropping orphan result event with no pending turn");
}
InboundAction::None
}
Some("control_request") => {
if msg
.get("request")
.and_then(|r| r.get("subtype"))
.and_then(Value::as_str)
== Some("can_use_tool")
&& let Some(req) = parse_permission_request(&msg)
{
if let Some((_, events)) = pending.as_mut() {
events.push(msg);
}
return InboundAction::Permission(req);
}
debug!(
?msg,
"received unhandled control_request; treating as Other"
);
let _ = events_tx.send(InboundEvent::Other(msg.clone()));
if let Some((_, events)) = pending.as_mut() {
events.push(msg);
}
InboundAction::None
}
Some("control_response") => {
if let Some((request_id, outcome)) = parse_control_response(&msg) {
return InboundAction::ControlResponse {
request_id,
outcome,
};
}
debug!(
?msg,
"received malformed control_response; treating as Other"
);
let _ = events_tx.send(InboundEvent::Other(msg.clone()));
if let Some((_, events)) = pending.as_mut() {
events.push(msg);
}
InboundAction::None
}
_ => {
let _ = events_tx.send(classify(&msg));
if let Some((_, events)) = pending.as_mut() {
events.push(msg);
} else {
debug!("dropping inbound event with no pending turn");
}
InboundAction::None
}
}
}
fn parse_permission_request(msg: &Value) -> Option<PermissionRequest> {
let request_id = msg.get("request_id").and_then(Value::as_str)?;
let request = msg.get("request")?;
let tool_name = request.get("tool_name").and_then(Value::as_str)?;
let input = request.get("input").cloned().unwrap_or(Value::Null);
Some(PermissionRequest {
request_id: request_id.to_string(),
tool_name: tool_name.to_string(),
input,
raw: request.clone(),
})
}
fn parse_control_response(msg: &Value) -> Option<(String, Result<()>)> {
let response = msg.get("response")?;
let request_id = response.get("request_id").and_then(Value::as_str)?;
let outcome = match response.get("subtype").and_then(Value::as_str) {
Some("success") => Ok(()),
Some("error") => {
let message = response
.get("error")
.and_then(Value::as_str)
.unwrap_or("unknown control_response error")
.to_string();
Err(Error::DuplexControlFailed { message })
}
_ => return None,
};
Some((request_id.to_string(), outcome))
}
async fn write_user(stdin: &mut ChildStdin, prompt: &str) -> Result<()> {
let user_msg = serde_json::json!({
"type": "user",
"message": {
"role": "user",
"content": prompt,
},
"parent_tool_use_id": null,
});
write_line(stdin, &user_msg, "user message").await
}
async fn write_control_request(
stdin: &mut ChildStdin,
request_id: &str,
subtype: &str,
) -> Result<()> {
let envelope = serde_json::json!({
"type": "control_request",
"request_id": request_id,
"request": { "subtype": subtype },
});
write_line(stdin, &envelope, "control_request").await
}
async fn write_permission_response(
stdin: &mut ChildStdin,
request_id: &str,
decision: &PermissionDecision,
) -> Result<()> {
let inner = match decision {
PermissionDecision::Allow { updated_input } => {
let mut obj = serde_json::Map::new();
obj.insert("behavior".to_string(), Value::String("allow".to_string()));
if let Some(input) = updated_input {
obj.insert("updatedInput".to_string(), input.clone());
}
Value::Object(obj)
}
PermissionDecision::Deny { message } => serde_json::json!({
"behavior": "deny",
"message": message,
}),
PermissionDecision::Defer => {
return Ok(());
}
};
let envelope = serde_json::json!({
"type": "control_response",
"response": {
"request_id": request_id,
"subtype": "success",
"response": inner,
},
});
write_line(stdin, &envelope, "control_response").await
}
async fn write_line(stdin: &mut ChildStdin, value: &Value, what: &'static str) -> Result<()> {
let mut line = serde_json::to_string(value).map_err(|e| Error::Json {
message: format!("failed to serialize duplex {what}"),
source: e,
})?;
line.push('\n');
stdin
.write_all(line.as_bytes())
.await
.map_err(|e| Error::Io {
message: format!("failed to write {what} to duplex stdin"),
source: e,
working_dir: None,
})?;
stdin.flush().await.map_err(|e| Error::Io {
message: "failed to flush duplex stdin".to_string(),
source: e,
working_dir: None,
})?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn build_args_default_includes_required_flags() {
let args = DuplexOptions::default().build_args();
assert!(args.contains(&"--print".to_string()));
assert!(args.contains(&"--verbose".to_string()));
assert!(
args.windows(2)
.any(|w| w == ["--output-format", "stream-json"])
);
assert!(
args.windows(2)
.any(|w| w == ["--input-format", "stream-json"])
);
}
#[test]
fn build_args_includes_model() {
let args = DuplexOptions::default().model("haiku").build_args();
assert!(args.windows(2).any(|w| w == ["--model", "haiku"]));
}
#[test]
fn build_args_includes_system_prompts() {
let args = DuplexOptions::default()
.system_prompt("be concise")
.append_system_prompt("also polite")
.build_args();
assert!(
args.windows(2)
.any(|w| w == ["--system-prompt", "be concise"])
);
assert!(
args.windows(2)
.any(|w| w == ["--append-system-prompt", "also polite"])
);
}
#[test]
fn build_args_appends_raw_args_last() {
let args = DuplexOptions::default()
.arg("--add-dir")
.arg("/tmp/foo")
.build_args();
assert_eq!(&args[args.len() - 2..], &["--add-dir", "/tmp/foo"]);
}
fn preview_claude() -> Claude {
Claude::builder()
.binary("/usr/local/bin/claude")
.build()
.unwrap()
}
#[test]
fn spawn_command_args_prepends_global_args() {
let claude = Claude::builder()
.binary("/usr/local/bin/claude")
.arg("--debug")
.build()
.unwrap();
let args = DuplexOptions::default()
.model("haiku")
.spawn_command_args(&claude);
assert_eq!(args[0], "--debug");
assert_eq!(args[1], "--print");
assert!(args.windows(2).any(|w| w == ["--model", "haiku"]));
}
#[test]
fn to_command_string_is_binary_plus_spawn_args() {
let claude = Claude::builder()
.binary("/usr/local/bin/claude")
.arg("--debug")
.build()
.unwrap();
let opts = DuplexOptions::default().agent("reviewer");
let expected = format!(
"/usr/local/bin/claude {}",
opts.spawn_command_args(&claude).join(" ")
);
assert_eq!(opts.to_command_string(&claude), expected);
}
#[test]
fn to_command_string_includes_persona_flags() {
let command_str = DuplexOptions::default()
.agent("reviewer")
.allowed_tool("Read")
.allowed_tool("Bash(git:*)")
.setting_sources("project")
.to_command_string(&preview_claude());
assert!(command_str.starts_with("/usr/local/bin/claude"));
assert!(command_str.contains("--agent reviewer"));
assert!(command_str.contains("--allowed-tools 'Read,Bash(git:*)'"));
assert!(command_str.contains("--setting-sources project"));
}
#[test]
fn to_command_string_quotes_args_with_spaces() {
let command_str = DuplexOptions::default()
.system_prompt("be concise")
.to_command_string(&preview_claude());
assert!(command_str.contains("--system-prompt 'be concise'"));
}
#[test]
fn to_command_string_does_not_consume_options() {
let claude = preview_claude();
let opts = DuplexOptions::default().model("haiku");
let first = opts.to_command_string(&claude);
let second = opts.to_command_string(&claude);
assert_eq!(first, second);
}
#[test]
fn build_args_includes_resume_when_set() {
let args = DuplexOptions::default().resume("abc-123").build_args();
assert!(args.windows(2).any(|w| w == ["--resume", "abc-123"]));
}
#[test]
fn build_args_omits_resume_by_default() {
let args = DuplexOptions::default().build_args();
assert!(
!args.iter().any(|a| a == "--resume"),
"--resume should not appear without an explicit resume(...) call; got {args:?}"
);
}
#[test]
fn build_args_includes_continue_when_set() {
let args = DuplexOptions::default().continue_session().build_args();
assert!(args.iter().any(|a| a == "--continue"));
}
#[test]
fn build_args_omits_continue_by_default() {
let args = DuplexOptions::default().build_args();
assert!(!args.iter().any(|a| a == "--continue"));
}
#[test]
fn build_args_includes_worktree_flag_without_name() {
let args = DuplexOptions::default().worktree(None::<&str>).build_args();
assert!(args.iter().any(|a| a == "--worktree"));
let pos = args.iter().position(|a| a == "--worktree").unwrap();
assert!(
args.get(pos + 1).is_none_or(|a| a.starts_with("--")),
"--worktree without a name should not be followed by a positional; got {args:?}"
);
}
#[test]
fn build_args_includes_worktree_flag_with_name() {
let args = DuplexOptions::default()
.worktree(Some("agent-xyz"))
.build_args();
let pos = args.iter().position(|a| a == "--worktree").unwrap();
assert_eq!(args.get(pos + 1).map(String::as_str), Some("agent-xyz"));
}
#[test]
fn build_args_omits_worktree_by_default() {
let args = DuplexOptions::default().build_args();
assert!(
!args.iter().any(|a| a == "--worktree"),
"--worktree should not appear without an explicit worktree(...) call; got {args:?}"
);
}
#[test]
fn worktree_lands_before_additional_args() {
let args = DuplexOptions::default()
.worktree(Some("foo"))
.arg("--")
.arg("trailing")
.build_args();
let wt_pos = args.iter().position(|a| a == "--worktree").unwrap();
let dash_dash_pos = args.iter().position(|a| a == "--").unwrap();
assert!(
wt_pos < dash_dash_pos,
"--worktree must precede `--` separator; got {args:?}"
);
}
#[test]
fn build_args_includes_agent_when_set() {
let args = DuplexOptions::default().agent("rust-qa").build_args();
assert!(
args.windows(2).any(|w| w == ["--agent", "rust-qa"]),
"missing --agent rust-qa in {args:?}"
);
}
#[test]
fn build_args_omits_agent_by_default() {
let args = DuplexOptions::default().build_args();
assert!(
!args.iter().any(|a| a == "--agent"),
"--agent should not appear without an explicit agent(...) call; got {args:?}"
);
}
#[test]
fn build_args_includes_agents_json_when_set() {
let json = r#"{"reviewer":{"description":"r","prompt":"p"}}"#;
let args = DuplexOptions::default().agents_json(json).build_args();
let pos = args.iter().position(|a| a == "--agents").unwrap();
assert_eq!(args.get(pos + 1).map(String::as_str), Some(json));
}
#[test]
fn build_args_omits_agents_json_by_default() {
let args = DuplexOptions::default().build_args();
assert!(!args.iter().any(|a| a == "--agents"));
}
#[test]
fn agent_and_agents_json_compose() {
let json = r#"{"reviewer":{"description":"r","prompt":"p"}}"#;
let args = DuplexOptions::default()
.agents_json(json)
.agent("reviewer")
.build_args();
assert!(args.iter().any(|a| a == "--agents"));
assert!(args.iter().any(|a| a == "--agent"));
}
#[test]
fn agent_lands_before_additional_args() {
let args = DuplexOptions::default()
.agent("rust-qa")
.arg("--")
.arg("trailing")
.build_args();
let agent_pos = args.iter().position(|a| a == "--agent").unwrap();
let dash_dash_pos = args.iter().position(|a| a == "--").unwrap();
assert!(
agent_pos < dash_dash_pos,
"--agent must precede `--` separator; got {args:?}"
);
}
#[test]
fn agents_json_lands_before_additional_args() {
let args = DuplexOptions::default()
.agents_json("{}")
.arg("--")
.arg("trailing")
.build_args();
let agents_pos = args.iter().position(|a| a == "--agents").unwrap();
let dash_dash_pos = args.iter().position(|a| a == "--").unwrap();
assert!(
agents_pos < dash_dash_pos,
"--agents must precede `--` separator; got {args:?}"
);
}
#[test]
fn build_args_includes_session_id() {
let args = DuplexOptions::default().session_id("sid-9").build_args();
assert!(args.windows(2).any(|w| w == ["--session-id", "sid-9"]));
}
#[test]
fn build_args_includes_setting_sources() {
let args = DuplexOptions::default()
.setting_sources("user,project")
.build_args();
assert!(
args.windows(2)
.any(|w| w == ["--setting-sources", "user,project"]),
"got {args:?}"
);
}
#[test]
fn build_args_omits_setting_sources_by_default() {
let args = DuplexOptions::default().build_args();
assert!(!args.iter().any(|a| a == "--setting-sources"));
}
#[test]
fn build_args_hermetic_emits_full_seal() {
let args = DuplexOptions::default().hermetic().build_args();
assert!(
args.windows(2)
.any(|w| w[0] == "--setting-sources" && w[1].is_empty()),
"got {args:?}"
);
assert!(args.iter().any(|a| a == "--strict-mcp-config"));
assert!(
args.iter()
.any(|a| a == "--exclude-dynamic-system-prompt-sections")
);
assert!(!args.iter().any(|a| a == "--bare"));
}
#[test]
fn build_args_hermetic_scoped_project_keeps_user() {
let args = DuplexOptions::default()
.hermetic_scoped(HermeticScope::Project)
.build_args();
assert!(args.windows(2).any(|w| w == ["--setting-sources", "user"]));
assert!(args.iter().any(|a| a == "--strict-mcp-config"));
}
#[test]
fn build_args_includes_json_schema() {
let schema = r#"{"type":"object"}"#;
let args = DuplexOptions::default().json_schema(schema).build_args();
assert!(args.windows(2).any(|w| w == ["--json-schema", schema]));
}
#[test]
fn build_args_joins_allowed_tools_comma_separated() {
let args = DuplexOptions::default()
.allowed_tools(["Read", "Bash(git log:*)"])
.allowed_tool("Write")
.build_args();
assert!(
args.windows(2)
.any(|w| w == ["--allowed-tools", "Read,Bash(git log:*),Write"]),
"missing joined --allowed-tools in {args:?}"
);
}
#[test]
fn build_args_joins_disallowed_tools_comma_separated() {
let args = DuplexOptions::default()
.disallowed_tools(["WebSearch"])
.disallowed_tool("WebFetch")
.build_args();
assert!(
args.windows(2)
.any(|w| w == ["--disallowed-tools", "WebSearch,WebFetch"]),
"missing joined --disallowed-tools in {args:?}"
);
}
#[test]
fn build_args_includes_caps() {
let args = DuplexOptions::default()
.max_turns(4)
.max_budget_usd(0.25)
.build_args();
assert!(args.windows(2).any(|w| w == ["--max-turns", "4"]));
assert!(args.windows(2).any(|w| w == ["--max-budget-usd", "0.25"]));
}
#[test]
fn build_args_includes_fallback_model_and_effort() {
let args = DuplexOptions::default()
.fallback_model("haiku")
.effort(Effort::Low)
.build_args();
assert!(args.windows(2).any(|w| w == ["--fallback-model", "haiku"]));
assert!(args.windows(2).any(|w| w == ["--effort", "low"]));
}
#[test]
fn build_args_repeats_add_dir_and_mcp_config() {
let args = DuplexOptions::default()
.add_dir("/a")
.add_dir("/b")
.mcp_config("x.json")
.strict_mcp_config()
.build_args();
assert!(args.windows(2).any(|w| w == ["--add-dir", "/a"]));
assert!(args.windows(2).any(|w| w == ["--add-dir", "/b"]));
assert!(args.windows(2).any(|w| w == ["--mcp-config", "x.json"]));
assert!(args.iter().any(|a| a == "--strict-mcp-config"));
}
#[test]
fn build_args_includes_no_session_persistence() {
let args = DuplexOptions::default()
.no_session_persistence()
.build_args();
assert!(args.iter().any(|a| a == "--no-session-persistence"));
}
#[test]
fn build_args_joins_tools_comma_separated() {
let args = DuplexOptions::default()
.tools(["Bash", "Read", "Edit"])
.build_args();
assert!(
args.windows(2).any(|w| w == ["--tools", "Bash,Read,Edit"]),
"missing joined --tools in {args:?}"
);
}
#[test]
fn build_args_repeats_file_per_spec() {
let args = DuplexOptions::default()
.file("file_a:doc.txt")
.file("file_b:notes.md")
.build_args();
assert_eq!(args.iter().filter(|a| *a == "--file").count(), 2);
assert!(args.iter().any(|a| a == "file_a:doc.txt"));
assert!(args.iter().any(|a| a == "file_b:notes.md"));
}
#[test]
fn build_args_includes_settings() {
let args = DuplexOptions::default()
.settings("/tmp/settings.json")
.build_args();
assert!(
args.windows(2)
.any(|w| w == ["--settings", "/tmp/settings.json"])
);
}
#[test]
fn build_args_includes_fork_session() {
let args = DuplexOptions::default().fork_session().build_args();
assert!(args.iter().any(|a| a == "--fork-session"));
}
#[test]
fn build_args_includes_debug_filter_and_file() {
let args = DuplexOptions::default()
.debug_filter("api,hooks")
.debug_file("/tmp/debug.log")
.build_args();
assert!(args.windows(2).any(|w| w == ["--debug", "api,hooks"]));
assert!(
args.windows(2)
.any(|w| w == ["--debug-file", "/tmp/debug.log"])
);
}
#[test]
fn build_args_includes_betas() {
let args = DuplexOptions::default().betas("feature-x").build_args();
assert!(args.windows(2).any(|w| w == ["--betas", "feature-x"]));
}
#[test]
fn build_args_repeats_plugin_dir_and_url() {
let args = DuplexOptions::default()
.plugin_dir("/plugins/a")
.plugin_dir("/plugins/b")
.plugin_url("https://example.com/p.zip")
.build_args();
assert_eq!(args.iter().filter(|a| *a == "--plugin-dir").count(), 2);
assert!(
args.windows(2)
.any(|w| w == ["--plugin-url", "https://example.com/p.zip"])
);
}
#[test]
fn build_args_includes_bare_family_bool_flags() {
let args = DuplexOptions::default()
.tmux()
.bare()
.safe_mode()
.disable_slash_commands()
.include_hook_events()
.exclude_dynamic_system_prompt_sections()
.build_args();
for flag in [
"--tmux",
"--bare",
"--safe-mode",
"--disable-slash-commands",
"--include-hook-events",
"--exclude-dynamic-system-prompt-sections",
] {
assert!(args.iter().any(|a| a == flag), "missing {flag} in {args:?}");
}
}
#[test]
fn build_args_includes_name() {
let args = DuplexOptions::default().name("my session").build_args();
assert!(args.windows(2).any(|w| w == ["--name", "my session"]));
}
#[test]
fn build_args_omits_promoted_parity_flags_by_default() {
let args = DuplexOptions::default().build_args();
for flag in [
"--tools",
"--file",
"--settings",
"--fork-session",
"--debug",
"--debug-file",
"--betas",
"--plugin-dir",
"--plugin-url",
"--tmux",
"--bare",
"--safe-mode",
"--disable-slash-commands",
"--include-hook-events",
"--exclude-dynamic-system-prompt-sections",
"--name",
] {
assert!(
!args.iter().any(|a| a == flag),
"{flag} should be absent by default; got {args:?}"
);
}
}
#[test]
fn parity_flags_land_before_additional_args() {
let args = DuplexOptions::default()
.max_turns(2)
.json_schema("{}")
.arg("--")
.arg("trailing")
.build_args();
let dash_dash_pos = args.iter().position(|a| a == "--").unwrap();
for flag in ["--max-turns", "--json-schema"] {
let pos = args.iter().position(|a| a == flag).unwrap();
assert!(
pos < dash_dash_pos,
"{flag} must precede `--` separator; got {args:?}"
);
}
}
#[test]
fn build_args_omits_parity_flags_by_default() {
let args = DuplexOptions::default().build_args();
for flag in [
"--session-id",
"--json-schema",
"--allowed-tools",
"--disallowed-tools",
"--max-turns",
"--max-budget-usd",
"--fallback-model",
"--effort",
"--add-dir",
"--mcp-config",
"--strict-mcp-config",
"--no-session-persistence",
] {
assert!(
!args.iter().any(|a| a == flag),
"{flag} should not appear by default; got {args:?}"
);
}
}
#[test]
fn resume_lands_before_additional_args() {
let args = DuplexOptions::default()
.resume("xyz")
.arg("--")
.arg("trailing")
.build_args();
let resume_pos = args.iter().position(|a| a == "--resume").unwrap();
let dash_dash_pos = args.iter().position(|a| a == "--").unwrap();
assert!(
resume_pos < dash_dash_pos,
"--resume must precede `--` separator; got {args:?}"
);
}
#[test]
fn turn_result_accessors_pull_from_result() {
let r = TurnResult {
result: json!({
"type": "result",
"result": "hello",
"session_id": "sess-123",
"total_cost_usd": 0.0042,
"duration_ms": 1234_u64,
}),
events: vec![],
};
assert_eq!(r.result_text(), Some("hello"));
assert_eq!(r.session_id(), Some("sess-123"));
assert_eq!(r.total_cost_usd(), Some(0.0042));
assert_eq!(r.duration_ms(), Some(1234));
}
#[test]
fn turn_result_total_cost_falls_back_to_legacy_field() {
let r = TurnResult {
result: json!({ "cost_usd": 0.5 }),
events: vec![],
};
assert_eq!(r.total_cost_usd(), Some(0.5));
}
#[test]
fn turn_result_accessors_return_none_when_missing() {
let r = TurnResult {
result: json!({}),
events: vec![],
};
assert_eq!(r.result_text(), None);
assert_eq!(r.session_id(), None);
assert_eq!(r.total_cost_usd(), None);
assert_eq!(r.duration_ms(), None);
}
#[test]
fn handle_inbound_appends_non_result_to_pending_events() {
let (tx, _reply_rx) = oneshot::channel::<Result<TurnResult>>();
let (events_tx, _events_rx) = broadcast::channel(16);
let mut pending = Some((tx, Vec::new()));
handle_inbound(
json!({ "type": "assistant", "message": {} }),
&mut pending,
&events_tx,
);
let (_, events) = pending.as_ref().unwrap();
assert_eq!(events.len(), 1);
assert_eq!(
events[0].get("type").and_then(Value::as_str),
Some("assistant")
);
}
#[test]
fn handle_inbound_resolves_pending_on_result() {
let (tx, rx) = oneshot::channel::<Result<TurnResult>>();
let (events_tx, _events_rx) = broadcast::channel(16);
let mut pending = Some((tx, vec![json!({ "type": "assistant" })]));
handle_inbound(
json!({ "type": "result", "result": "ok" }),
&mut pending,
&events_tx,
);
assert!(pending.is_none());
let received = rx.blocking_recv().unwrap().unwrap();
assert_eq!(received.result_text(), Some("ok"));
assert_eq!(received.events.len(), 1);
}
#[test]
fn handle_inbound_drops_orphans_without_pending_turn() {
let (events_tx, _events_rx) = broadcast::channel(16);
let mut pending: Option<(oneshot::Sender<Result<TurnResult>>, Vec<Value>)> = None;
handle_inbound(json!({ "type": "assistant" }), &mut pending, &events_tx);
handle_inbound(
json!({ "type": "result", "result": "ok" }),
&mut pending,
&events_tx,
);
assert!(pending.is_none());
}
#[test]
fn handle_inbound_broadcasts_classified_event() {
let (tx, _reply_rx) = oneshot::channel::<Result<TurnResult>>();
let (events_tx, mut events_rx) = broadcast::channel(16);
let mut pending = Some((tx, Vec::new()));
handle_inbound(
json!({ "type": "assistant", "message": { "role": "assistant" } }),
&mut pending,
&events_tx,
);
let event = events_rx.try_recv().expect("classified event broadcast");
assert!(matches!(event, InboundEvent::Assistant(_)));
}
#[test]
fn handle_inbound_does_not_broadcast_result() {
let (tx, _reply_rx) = oneshot::channel::<Result<TurnResult>>();
let (events_tx, mut events_rx) = broadcast::channel(16);
let mut pending = Some((tx, Vec::new()));
handle_inbound(
json!({ "type": "result", "result": "ok" }),
&mut pending,
&events_tx,
);
assert!(events_rx.try_recv().is_err());
}
#[test]
fn classify_system_init_pulls_session_id() {
let v = json!({
"type": "system",
"subtype": "init",
"session_id": "sess-abc",
});
match classify(&v) {
InboundEvent::SystemInit { session_id } => assert_eq!(session_id, "sess-abc"),
other => panic!("expected SystemInit, got {other:?}"),
}
}
#[test]
fn classify_system_without_init_subtype_is_other() {
let v = json!({ "type": "system", "subtype": "compaction" });
assert!(matches!(classify(&v), InboundEvent::Other(_)));
}
#[test]
fn classify_system_init_without_session_id_is_other() {
let v = json!({ "type": "system", "subtype": "init" });
assert!(matches!(classify(&v), InboundEvent::Other(_)));
}
#[test]
fn classify_assistant_stream_event_user() {
assert!(matches!(
classify(&json!({ "type": "assistant" })),
InboundEvent::Assistant(_)
));
assert!(matches!(
classify(&json!({ "type": "stream_event" })),
InboundEvent::StreamEvent(_)
));
assert!(matches!(
classify(&json!({ "type": "user" })),
InboundEvent::User(_)
));
}
#[test]
fn classify_unknown_type_is_other() {
assert!(matches!(
classify(&json!({ "type": "control_request" })),
InboundEvent::Other(_)
));
assert!(matches!(
classify(&json!({ "type": "future_thing" })),
InboundEvent::Other(_)
));
assert!(matches!(classify(&json!({})), InboundEvent::Other(_)));
}
#[test]
fn build_args_does_not_emit_subscriber_capacity_flag() {
let args = DuplexOptions::default()
.subscriber_capacity(64)
.build_args();
assert!(!args.iter().any(|a| a.contains("subscriber")));
assert!(!args.iter().any(|a| a.contains("capacity")));
}
#[test]
fn build_args_includes_permission_prompt_tool_when_handler_set() {
let handler = PermissionHandler::new(|_req| async move {
PermissionDecision::Allow {
updated_input: None,
}
});
let args = DuplexOptions::default().on_permission(handler).build_args();
assert!(
args.windows(2)
.any(|w| w == ["--permission-prompt-tool", "stdio"])
);
}
#[test]
fn build_args_omits_permission_prompt_tool_without_handler() {
let args = DuplexOptions::default().build_args();
assert!(!args.iter().any(|a| a == "--permission-prompt-tool"));
}
#[test]
fn build_args_emits_permission_mode_flag() {
let args = DuplexOptions::default()
.permission_mode(PermissionMode::AcceptEdits)
.build_args();
assert!(
args.windows(2)
.any(|w| w == ["--permission-mode", "acceptEdits"]),
"missing --permission-mode acceptEdits in {args:?}"
);
}
#[test]
fn build_args_emits_plan_mode() {
let args = DuplexOptions::default()
.permission_mode(PermissionMode::Plan)
.build_args();
assert!(args.windows(2).any(|w| w == ["--permission-mode", "plan"]));
}
#[test]
fn build_args_omits_permission_mode_by_default() {
let args = DuplexOptions::default().build_args();
assert!(!args.iter().any(|a| a == "--permission-mode"));
}
#[test]
fn build_args_emits_dangerously_skip_permissions_flag() {
let args = DuplexOptions::default()
.dangerously_skip_permissions()
.build_args();
assert!(args.iter().any(|a| a == "--dangerously-skip-permissions"));
}
#[test]
fn build_args_omits_dangerously_skip_by_default() {
let args = DuplexOptions::default().build_args();
assert!(!args.iter().any(|a| a == "--dangerously-skip-permissions"));
}
#[test]
fn parse_permission_request_extracts_fields() {
let msg = json!({
"type": "control_request",
"request_id": "req-1",
"request": {
"subtype": "can_use_tool",
"tool_name": "Bash",
"input": { "command": "ls" }
}
});
let req = parse_permission_request(&msg).expect("permission request");
assert_eq!(req.request_id, "req-1");
assert_eq!(req.tool_name, "Bash");
assert_eq!(req.input, json!({ "command": "ls" }));
assert_eq!(
req.raw.get("subtype").and_then(Value::as_str),
Some("can_use_tool")
);
}
#[test]
fn parse_permission_request_returns_none_when_missing_request_id() {
let msg = json!({
"type": "control_request",
"request": {
"subtype": "can_use_tool",
"tool_name": "Bash",
}
});
assert!(parse_permission_request(&msg).is_none());
}
#[test]
fn parse_permission_request_returns_none_when_missing_tool_name() {
let msg = json!({
"type": "control_request",
"request_id": "req-1",
"request": { "subtype": "can_use_tool" }
});
assert!(parse_permission_request(&msg).is_none());
}
#[test]
fn parse_permission_request_handles_missing_input() {
let msg = json!({
"type": "control_request",
"request_id": "req-1",
"request": {
"subtype": "can_use_tool",
"tool_name": "Bash",
}
});
let req = parse_permission_request(&msg).expect("request");
assert_eq!(req.input, Value::Null);
}
#[test]
fn handle_inbound_returns_permission_for_can_use_tool() {
let (tx, _reply_rx) = oneshot::channel::<Result<TurnResult>>();
let (events_tx, _events_rx) = broadcast::channel(16);
let mut pending = Some((tx, Vec::new()));
let action = handle_inbound(
json!({
"type": "control_request",
"request_id": "req-1",
"request": {
"subtype": "can_use_tool",
"tool_name": "Bash",
"input": { "command": "ls" }
}
}),
&mut pending,
&events_tx,
);
match action {
InboundAction::Permission(req) => {
assert_eq!(req.request_id, "req-1");
assert_eq!(req.tool_name, "Bash");
}
InboundAction::None | InboundAction::ControlResponse { .. } => {
panic!("expected Permission action");
}
}
let (_, events) = pending.as_ref().unwrap();
assert_eq!(events.len(), 1);
}
#[test]
fn handle_inbound_treats_unknown_control_request_as_other() {
let (tx, _reply_rx) = oneshot::channel::<Result<TurnResult>>();
let (events_tx, mut events_rx) = broadcast::channel(16);
let mut pending = Some((tx, Vec::new()));
let action = handle_inbound(
json!({
"type": "control_request",
"request_id": "req-2",
"request": { "subtype": "future_subtype" }
}),
&mut pending,
&events_tx,
);
assert!(matches!(action, InboundAction::None));
let event = events_rx.try_recv().expect("broadcast");
assert!(matches!(event, InboundEvent::Other(_)));
}
#[tokio::test]
async fn permission_handler_invokes_closure_async() {
let handler = PermissionHandler::new(|req| async move {
if req.tool_name == "Bash" {
PermissionDecision::Deny {
message: "no bash".into(),
}
} else {
PermissionDecision::Allow {
updated_input: None,
}
}
});
let req = PermissionRequest {
request_id: "r1".into(),
tool_name: "Bash".into(),
input: Value::Null,
raw: Value::Null,
};
match handler.invoke(req).await {
PermissionDecision::Deny { message } => assert_eq!(message, "no bash"),
other => panic!("expected Deny, got {other:?}"),
}
}
#[test]
fn parse_control_response_extracts_success() {
let msg = json!({
"type": "control_response",
"response": {
"request_id": "interrupt-1",
"subtype": "success",
"response": {}
}
});
let (id, outcome) = parse_control_response(&msg).expect("parsed");
assert_eq!(id, "interrupt-1");
assert!(outcome.is_ok());
}
#[test]
fn parse_control_response_extracts_error_with_message() {
let msg = json!({
"type": "control_response",
"response": {
"request_id": "interrupt-2",
"subtype": "error",
"error": "no turn in flight"
}
});
let (id, outcome) = parse_control_response(&msg).expect("parsed");
assert_eq!(id, "interrupt-2");
match outcome {
Err(Error::DuplexControlFailed { message }) => {
assert_eq!(message, "no turn in flight");
}
other => panic!("expected DuplexControlFailed, got {other:?}"),
}
}
#[test]
fn parse_control_response_returns_none_on_missing_request_id() {
let msg = json!({
"type": "control_response",
"response": { "subtype": "success" }
});
assert!(parse_control_response(&msg).is_none());
}
#[test]
fn parse_control_response_returns_none_on_unknown_subtype() {
let msg = json!({
"type": "control_response",
"response": { "request_id": "x", "subtype": "future_subtype" }
});
assert!(parse_control_response(&msg).is_none());
}
#[test]
fn handle_inbound_returns_control_response_action() {
let (tx, _reply_rx) = oneshot::channel::<Result<TurnResult>>();
let (events_tx, _events_rx) = broadcast::channel(16);
let mut pending = Some((tx, Vec::new()));
let action = handle_inbound(
json!({
"type": "control_response",
"response": {
"request_id": "interrupt-1",
"subtype": "success",
"response": {}
}
}),
&mut pending,
&events_tx,
);
match action {
InboundAction::ControlResponse {
request_id,
outcome,
} => {
assert_eq!(request_id, "interrupt-1");
assert!(outcome.is_ok());
}
InboundAction::None | InboundAction::Permission(_) => {
panic!("expected ControlResponse action");
}
}
}
#[test]
fn handle_inbound_treats_malformed_control_response_as_other() {
let (tx, _reply_rx) = oneshot::channel::<Result<TurnResult>>();
let (events_tx, mut events_rx) = broadcast::channel(16);
let mut pending = Some((tx, Vec::new()));
let action = handle_inbound(
json!({
"type": "control_response",
"response": { "subtype": "success" }
}),
&mut pending,
&events_tx,
);
assert!(matches!(action, InboundAction::None));
let event = events_rx.try_recv().expect("broadcast");
assert!(matches!(event, InboundEvent::Other(_)));
}
#[tokio::test]
async fn permission_handler_clones_arc() {
let handler = PermissionHandler::new(|_req| async move {
PermissionDecision::Allow {
updated_input: None,
}
});
let cloned = handler.clone();
let req = PermissionRequest {
request_id: "r1".into(),
tool_name: "Read".into(),
input: Value::Null,
raw: Value::Null,
};
let _ = handler.invoke(req.clone()).await;
let _ = cloned.invoke(req).await;
}
fn fake_session(
initial: SessionExitStatus,
) -> (
DuplexSession,
watch::Sender<SessionExitStatus>,
oneshot::Sender<()>,
) {
let (outbound_tx, outbound_rx) = mpsc::unbounded_channel::<OutboundMsg>();
let (events_tx, _events_rx) = broadcast::channel::<InboundEvent>(16);
let (exit_tx, exit_rx) = watch::channel(initial);
let (stop_tx, stop_rx) = oneshot::channel::<()>();
let join = tokio::spawn(async move {
let _outbound_rx = outbound_rx;
let _ = stop_rx.await;
Ok::<(), Error>(())
});
let session = DuplexSession {
outbound_tx,
events_tx,
exit_rx,
join,
};
(session, exit_tx, stop_tx)
}
#[tokio::test]
async fn is_alive_true_while_running() {
let (session, _exit_tx, _stop) = fake_session(SessionExitStatus::Running);
assert!(session.is_alive());
}
#[tokio::test]
async fn is_alive_false_after_completed() {
let (session, exit_tx, _stop) = fake_session(SessionExitStatus::Running);
exit_tx.send(SessionExitStatus::Completed).unwrap();
assert!(!session.is_alive());
}
#[tokio::test]
async fn is_alive_false_after_failed() {
let (session, exit_tx, _stop) = fake_session(SessionExitStatus::Running);
exit_tx
.send(SessionExitStatus::Failed("boom".into()))
.unwrap();
assert!(!session.is_alive());
}
#[tokio::test]
async fn exit_status_reports_running_initially() {
let (session, _exit_tx, _stop) = fake_session(SessionExitStatus::Running);
assert!(matches!(session.exit_status(), SessionExitStatus::Running));
}
#[tokio::test]
async fn exit_status_reflects_completed() {
let (session, exit_tx, _stop) = fake_session(SessionExitStatus::Running);
exit_tx.send(SessionExitStatus::Completed).unwrap();
assert!(matches!(
session.exit_status(),
SessionExitStatus::Completed
));
}
#[tokio::test]
async fn exit_status_reflects_failed_with_message() {
let (session, exit_tx, _stop) = fake_session(SessionExitStatus::Running);
exit_tx
.send(SessionExitStatus::Failed("oh no".into()))
.unwrap();
match session.exit_status() {
SessionExitStatus::Failed(msg) => assert_eq!(msg, "oh no"),
other => panic!("expected Failed, got {other:?}"),
}
}
#[tokio::test]
async fn wait_for_exit_returns_immediately_when_already_terminal() {
let (session, exit_tx, _stop) = fake_session(SessionExitStatus::Running);
exit_tx.send(SessionExitStatus::Completed).unwrap();
let status = tokio::time::timeout(Duration::from_secs(1), session.wait_for_exit())
.await
.expect("wait_for_exit should not block when already terminal");
assert!(matches!(status, SessionExitStatus::Completed));
}
#[tokio::test]
async fn wait_for_exit_blocks_until_state_transitions() {
let (session, exit_tx, _stop) = fake_session(SessionExitStatus::Running);
let waiter = async { session.wait_for_exit().await };
let driver = async {
tokio::time::sleep(Duration::from_millis(20)).await;
exit_tx.send(SessionExitStatus::Completed).unwrap();
};
let (status, ()) = tokio::join!(waiter, driver);
assert!(matches!(status, SessionExitStatus::Completed));
}
#[tokio::test]
async fn wait_for_exit_supports_multiple_observers() {
let (session, exit_tx, _stop) = fake_session(SessionExitStatus::Running);
let waiter1 = async { session.wait_for_exit().await };
let waiter2 = async { session.wait_for_exit().await };
let driver = async {
tokio::time::sleep(Duration::from_millis(20)).await;
exit_tx
.send(SessionExitStatus::Failed("crash".into()))
.unwrap();
};
let (s1, s2, ()) = tokio::join!(waiter1, waiter2, driver);
match s1 {
SessionExitStatus::Failed(msg) => assert_eq!(msg, "crash"),
other => panic!("waiter1 expected Failed, got {other:?}"),
}
match s2 {
SessionExitStatus::Failed(msg) => assert_eq!(msg, "crash"),
other => panic!("waiter2 expected Failed, got {other:?}"),
}
}
#[tokio::test]
async fn wait_for_exit_returns_last_value_when_sender_dropped() {
let (session, exit_tx, _stop) = fake_session(SessionExitStatus::Running);
let waiter = async { session.wait_for_exit().await };
let driver = async {
tokio::time::sleep(Duration::from_millis(20)).await;
drop(exit_tx);
};
let (status, ()) = tokio::time::timeout(Duration::from_secs(1), async {
tokio::join!(waiter, driver)
})
.await
.expect("wait_for_exit must not hang when sender is dropped");
assert!(matches!(status, SessionExitStatus::Running));
}
}