use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{mpsc, Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};
use blyte_agent::approval::{Approval, Approver};
use blyte_cli::http::{Request, Response};
use blyte_cli::mcp::McpManager;
use blyte_cli::serve::{generate_token, route, OpenCodes, Surface, MESSAGE_HEADER, TOKEN_HEADER};
use blyte_cli::session::{EntryBody, PromptRunner, Session};
use serde_json::{json, Value};
type PromptLog = Arc<Mutex<Vec<String>>>;
struct CancellableRunner {
started_tx: mpsc::Sender<String>,
seen_prompts: PromptLog,
cancelled_prompts: PromptLog,
block_prompt: Option<String>,
cancel: Option<Arc<AtomicBool>>,
}
impl CancellableRunner {
fn new(block_prompt: Option<&str>) -> (Self, mpsc::Receiver<String>, PromptLog, PromptLog) {
let (started_tx, started_rx) = mpsc::channel();
let seen_prompts = Arc::new(Mutex::new(Vec::new()));
let cancelled_prompts = Arc::new(Mutex::new(Vec::new()));
(
Self {
started_tx,
seen_prompts: Arc::clone(&seen_prompts),
cancelled_prompts: Arc::clone(&cancelled_prompts),
block_prompt: block_prompt.map(str::to_string),
cancel: None,
},
started_rx,
seen_prompts,
cancelled_prompts,
)
}
}
impl PromptRunner for CancellableRunner {
fn set_cancel_flag(&mut self, cancel: Arc<AtomicBool>) {
self.cancel = Some(cancel);
}
fn run(
&mut self,
prompt: &str,
_model: &str,
emit: &(dyn Fn(EntryBody) + Sync),
) -> Result<(), String> {
self.seen_prompts.lock().unwrap().push(prompt.to_string());
let _ = self.started_tx.send(prompt.to_string());
if self.block_prompt.as_deref() == Some(prompt) {
let deadline = Instant::now() + Duration::from_secs(10);
while Instant::now() < deadline {
if self
.cancel
.as_ref()
.is_some_and(|flag| flag.load(Ordering::SeqCst))
{
self.cancelled_prompts
.lock()
.unwrap()
.push(prompt.to_string());
return Ok(());
}
thread::sleep(Duration::from_millis(5));
}
return Err("timed out waiting for cancellation".to_string());
}
emit(EntryBody::Turn {
n: 1,
text: format!("reply: {prompt}"),
input_tokens: 1,
output_tokens: 1,
cost_usd: None,
cached_tokens: None,
thinking_tokens: None,
first_event_ms: None,
first_output_ms: None,
total_ms: None,
retries: None,
retry_wait_ms: None,
});
Ok(())
}
}
struct ApprovalBlockingRunner {
approver: Arc<dyn Approver>,
approval_started_tx: mpsc::Sender<()>,
seen_prompts: Arc<Mutex<Vec<String>>>,
denied_prompts: Arc<Mutex<Vec<String>>>,
}
impl PromptRunner for ApprovalBlockingRunner {
fn run(
&mut self,
prompt: &str,
_model: &str,
emit: &(dyn Fn(EntryBody) + Sync),
) -> Result<(), String> {
self.seen_prompts.lock().unwrap().push(prompt.to_string());
if prompt == "needs approval" {
let _ = self.approval_started_tx.send(());
let decision = self.approver.ask("echo hi", "needs approval");
if matches!(decision, Approval::Denied) {
self.denied_prompts.lock().unwrap().push(prompt.to_string());
return Ok(());
}
}
emit(EntryBody::Turn {
n: 1,
text: format!("reply: {prompt}"),
input_tokens: 1,
output_tokens: 1,
cost_usd: None,
cached_tokens: None,
thinking_tokens: None,
first_event_ms: None,
first_output_ms: None,
total_ms: None,
retries: None,
retry_wait_ms: None,
});
Ok(())
}
}
fn make_surface(root: PathBuf, session: Session) -> Surface {
let repo = root
.file_name()
.and_then(|s| s.to_str())
.unwrap_or("repo")
.to_string();
let mcp = Arc::new(McpManager::empty_in(&root));
Surface {
surface_id: "s00000000000000cc".to_string(),
surface_name: repo.clone(),
root,
repo,
session,
session_id: "sess-interrupt-1".to_string(),
started_at: 1_700_000_000,
runtime: blyte_cli::surface_version::SurfaceRuntimeInfo::current().unwrap(),
days: 14,
token: generate_token().unwrap(),
message_credential: generate_token().unwrap(),
open_codes: OpenCodes::new(),
requests: Arc::new(blyte_cli::requests::RequestsState::new()),
publisher: Arc::new(blyte_cli::requests::RealPublisher),
mcp,
reconcile_lock: Mutex::new(()),
reconcile_requested: AtomicBool::new(false),
}
}
fn post_message(surface: &Surface, body: Value) -> Response {
let req = Request {
method: "POST".to_string(),
path: "/api/session/messages".to_string(),
query: Vec::new(),
headers: vec![
(TOKEN_HEADER.to_string(), surface.token.clone()),
("content-type".to_string(), "application/json".to_string()),
],
body: serde_json::to_vec(&body).unwrap(),
};
route(surface, &req, 1_700_000_010)
}
fn post_peer_message(surface: &Surface, body: Value) -> Response {
let req = Request {
method: "POST".to_string(),
path: "/api/peer/messages".to_string(),
query: Vec::new(),
headers: vec![
(
MESSAGE_HEADER.to_string(),
surface.message_credential.clone(),
),
("content-type".to_string(), "application/json".to_string()),
],
body: serde_json::to_vec(&body).unwrap(),
};
route(surface, &req, 1_700_000_010)
}
fn wait_until_idle_with_prompts(
session: &Session,
seen_prompts: &Arc<Mutex<Vec<String>>>,
expected: usize,
) {
let deadline = Instant::now() + Duration::from_secs(5);
while Instant::now() < deadline {
let count = seen_prompts.lock().unwrap().len();
if count >= expected && !session.info().busy {
return;
}
thread::sleep(Duration::from_millis(10));
}
panic!(
"timed out waiting for {expected} prompts and idle state (seen={:?}, busy={})",
seen_prompts.lock().unwrap(),
session.info().busy
);
}
#[test]
fn post_messages_interrupt_true_while_idle_runs_normally() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("repo");
std::fs::create_dir_all(&root).unwrap();
let (runner, _started_rx, seen_prompts, cancelled_prompts) = CancellableRunner::new(None);
let session = Session::start(Box::new(runner), "gemini-4-neon".to_string());
let surface = make_surface(root, session);
let bad = post_message(&surface, json!({ "text": "bad", "interrupt": "yes" }));
assert_eq!(bad.status, 400);
let resp = post_message(&surface, json!({ "text": "hello idle", "interrupt": true }));
assert_eq!(resp.status, 200);
wait_until_idle_with_prompts(&surface.session, &seen_prompts, 1);
assert_eq!(
*seen_prompts.lock().unwrap(),
vec!["hello idle".to_string()]
);
assert!(cancelled_prompts.lock().unwrap().is_empty());
let entries = surface.session.entries_after(0, Duration::ZERO);
assert!(entries.iter().any(|e| matches!(
&e.body,
EntryBody::UserMessage { text, queued: false, .. } if text == "hello idle"
)));
assert!(entries.iter().any(|e| matches!(
&e.body,
EntryBody::Turn { text, .. } if text == "reply: hello idle"
)));
}
#[test]
fn post_messages_interrupt_true_while_busy_cancels_in_flight_turn_and_runs_ahead_of_queue() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("repo");
std::fs::create_dir_all(&root).unwrap();
let (runner, started_rx, seen_prompts, cancelled_prompts) =
CancellableRunner::new(Some("first slow turn"));
let session = Session::start(Box::new(runner), "gemini-4-neon".to_string());
let surface = make_surface(root, session);
let first = post_message(&surface, json!({ "text": "first slow turn" }));
assert_eq!(first.status, 200);
assert_eq!(
started_rx
.recv_timeout(Duration::from_secs(5))
.expect("first turn did not start"),
"first slow turn"
);
let queued_one = post_message(&surface, json!({ "text": "queued one" }));
assert_eq!(queued_one.status, 200);
let queued_two = post_message(&surface, json!({ "text": "queued two" }));
assert_eq!(queued_two.status, 200);
let interrupting = post_message(
&surface,
json!({ "text": "urgent interrupt", "interrupt": true }),
);
assert_eq!(interrupting.status, 200);
wait_until_idle_with_prompts(&surface.session, &seen_prompts, 4);
assert_eq!(
*cancelled_prompts.lock().unwrap(),
vec!["first slow turn".to_string()]
);
assert_eq!(
*seen_prompts.lock().unwrap(),
vec![
"first slow turn".to_string(),
"urgent interrupt".to_string(),
"queued one".to_string(),
"queued two".to_string(),
]
);
let entries = surface.session.entries_after(0, Duration::ZERO);
let replies: Vec<String> = entries
.iter()
.filter_map(|e| match &e.body {
EntryBody::Turn { text, .. } => Some(text.clone()),
_ => None,
})
.collect();
assert_eq!(
replies,
vec![
"reply: urgent interrupt".to_string(),
"reply: queued one".to_string(),
"reply: queued two".to_string(),
]
);
}
#[test]
fn post_messages_interrupt_true_denies_pending_approval_and_runs_immediately_next() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("repo");
std::fs::create_dir_all(&root).unwrap();
let (approval_started_tx, approval_started_rx) = mpsc::channel();
let seen_prompts = Arc::new(Mutex::new(Vec::new()));
let denied_prompts = Arc::new(Mutex::new(Vec::new()));
let seen_clone = Arc::clone(&seen_prompts);
let denied_clone = Arc::clone(&denied_prompts);
let session = Session::start_with("gemini-4-neon".to_string(), |approver| {
Box::new(ApprovalBlockingRunner {
approver,
approval_started_tx,
seen_prompts: seen_clone,
denied_prompts: denied_clone,
})
});
let surface = make_surface(root, session);
assert_eq!(
post_message(&surface, json!({ "text": "needs approval" })).status,
200
);
approval_started_rx
.recv_timeout(Duration::from_secs(5))
.expect("approval turn did not start");
let deadline = Instant::now() + Duration::from_secs(5);
while Instant::now() < deadline {
let has_approval = surface
.session
.entries_after(0, Duration::ZERO)
.iter()
.any(|e| matches!(e.body, EntryBody::ApprovalRequested { .. }));
if has_approval {
break;
}
thread::sleep(Duration::from_millis(5));
}
assert_eq!(
post_message(&surface, json!({ "text": "queued after approval" })).status,
200
);
assert_eq!(
post_message(
&surface,
json!({ "text": "interrupt approval", "interrupt": true })
)
.status,
200
);
wait_until_idle_with_prompts(&surface.session, &seen_prompts, 3);
assert_eq!(
*denied_prompts.lock().unwrap(),
vec!["needs approval".to_string()]
);
assert_eq!(
*seen_prompts.lock().unwrap(),
vec![
"needs approval".to_string(),
"interrupt approval".to_string(),
"queued after approval".to_string(),
]
);
}
#[test]
fn peer_tell_messages_reject_interrupt_field() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("repo");
std::fs::create_dir_all(&root).unwrap();
let (runner, _started_rx, seen_prompts, _) = CancellableRunner::new(None);
let session = Session::start(Box::new(runner), "gemini-4-neon".to_string());
let surface = make_surface(root, session);
let resp = post_peer_message(
&surface,
json!({
"from_name": "other-surface",
"from_repository": "other-repo",
"text": "hello peer",
"interrupt": true,
}),
);
assert_eq!(resp.status, 400);
assert!(seen_prompts.lock().unwrap().is_empty());
}