use super::*;
use crate::collab::{ResolvedSpan, relay_serve};
use crate::lsp::manager::is_on_path;
#[test]
#[ignore = "needs a live Ollama; run explicitly with CROFT_SPIKE_OLLAMA=1"]
fn ollama_live_smoke_drives_seat_local_end_to_end() {
if std::env::var("CROFT_SPIKE_OLLAMA").is_err() {
eprintln!("skip: set CROFT_SPIKE_OLLAMA=1 to run the live smoke");
return;
}
let url =
std::env::var("CROFT_SPIKE_OLLAMA_URL").unwrap_or_else(|_| "http://localhost:11434".into());
let model =
std::env::var("CROFT_SPIKE_OLLAMA_MODEL").unwrap_or_else(|_| "qwen3-coder:30b".into());
let harness = OwnerHarness::start("def greet(name):\n return \"hi \" + name\n");
let pilot = seat_local(&harness.socket, "pilot", &url, &model, None).unwrap();
send_turn(
&pilot.state,
&pilot.sink,
"@demo.txt Rewrite greet to return the f-string f\"Hello, {name}!\" \
instead of concatenation, using an EDIT fence.",
)
.unwrap();
let end = pilot
.turn_rx
.recv_timeout(Duration::from_secs(300))
.expect("turn ends");
assert!(!end.is_error, "turn failed: {}", end.text);
harness.wait_until("the f-string edit to converge", |h| {
h.doc().is_some_and(|d| d.contains("f\"Hello, {name}!\""))
});
let doc = harness.doc().unwrap();
assert!(
!doc.contains("+ name"),
"the old concatenation must be gone:\n{doc}"
);
pilot.shutdown();
}
use std::sync::atomic::{AtomicBool, Ordering};
#[test]
fn turn_sink_claude_writes_stream_json_to_stdin() {
let mut child = Command::new("cat")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.expect("spawn cat");
let stdin = child.stdin.take().unwrap();
let stdout = child.stdout.take().unwrap();
let sink = TurnSink::Claude(Arc::new(Mutex::new(Some(stdin))));
sink.send_user("hello\nworld").unwrap();
let TurnSink::Claude(w) = &sink else {
unreachable!()
};
w.lock().unwrap().take(); let mut line = String::new();
std::io::BufReader::new(stdout)
.read_line(&mut line)
.unwrap();
let _ = child.wait();
let v: Value = serde_json::from_str(&line).expect("one stream-json line");
assert_eq!(v["type"], "user");
assert_eq!(v["message"]["role"], "user");
assert_eq!(v["message"]["content"], "hello\nworld");
}
#[test]
fn local_provider_appends_line_range_guidance() {
let prompt = system_prompt(&Provider::Local {
base_url: String::from("http://localhost:11434"),
});
assert!(prompt.starts_with(PAIR_SYSTEM_PROMPT));
assert!(
prompt.contains("<start_row>-<end_row>"),
"suffix must teach the two-integer whole-line header"
);
}
#[test]
fn claude_provider_prompt_is_unchanged() {
assert_eq!(system_prompt(&Provider::Claude), PAIR_SYSTEM_PROMPT);
}
fn settle<T: PartialEq>(expected: &T, mut read: impl FnMut() -> T) -> T {
let deadline = Instant::now() + Duration::from_secs(60);
loop {
let got = read();
if &got == expected || Instant::now() >= deadline {
return got;
}
std::thread::sleep(Duration::from_millis(10));
}
}
struct OwnerHarness {
_dir: tempfile::TempDir,
socket: PathBuf,
owner: Arc<Mutex<CollabSession>>,
events: Arc<Mutex<Vec<CollabEvent>>>,
stop: Arc<AtomicBool>,
pump: Option<std::thread::JoinHandle<()>>,
}
impl OwnerHarness {
fn start(text: &'static str) -> Self {
let dir = tempfile::tempdir().unwrap();
let socket = dir.path().join("p.collab.sock");
{
let s = socket.clone();
std::thread::spawn(move || {
let _ = relay_serve(&s);
});
}
let deadline = Instant::now() + Duration::from_secs(5);
let owner = loop {
if let Some(ch) = CollabChannel::connect(&socket, CollabRole::Owner) {
break CollabSession::new(ch, "owner".into());
}
assert!(Instant::now() < deadline, "relay never came up");
std::thread::sleep(Duration::from_millis(10));
};
let owner = Arc::new(Mutex::new(owner));
let events: Arc<Mutex<Vec<CollabEvent>>> = Arc::new(Mutex::new(Vec::new()));
let stop = Arc::new(AtomicBool::new(false));
let pump = {
let (owner, events, stop) = (owner.clone(), events.clone(), stop.clone());
std::thread::spawn(move || {
while !stop.load(Ordering::Relaxed) {
{
let mut o = owner.lock().unwrap();
let ev = o.poll(|_| Some(text.to_string()));
events.lock().unwrap().extend(ev);
}
std::thread::sleep(Duration::from_millis(5));
}
})
};
Self {
_dir: dir,
socket,
owner,
events,
stop,
pump: Some(pump),
}
}
fn doc(&self) -> Option<String> {
self.owner
.lock()
.unwrap()
.doc_text("demo.txt")
.map(str::to_string)
}
fn wait_until(&self, what: &str, mut cond: impl FnMut(&Self) -> bool) {
let deadline = Instant::now() + Duration::from_secs(60);
while !cond(self) {
assert!(Instant::now() < deadline, "timed out waiting for {what}");
std::thread::sleep(Duration::from_millis(10));
}
}
fn stream_states(&self) -> Vec<(String, bool)> {
self.events
.lock()
.unwrap()
.iter()
.filter_map(|e| match e {
CollabEvent::StreamState { name, active, .. } => Some((name.clone(), *active)),
_ => None,
})
.collect()
}
fn remote_edit_count(&self) -> usize {
self.events
.lock()
.unwrap()
.iter()
.filter(|e| matches!(e, CollabEvent::RemoteEdit { .. }))
.count()
}
fn carets(&self) -> Vec<(String, usize, usize)> {
self.events
.lock()
.unwrap()
.iter()
.filter_map(|e| match e {
CollabEvent::Caret { name, row, col, .. } => Some((name.clone(), *row, *col)),
_ => None,
})
.collect()
}
}
impl Drop for OwnerHarness {
fn drop(&mut self) {
self.stop.store(true, Ordering::Relaxed);
if let Some(p) = self.pump.take() {
let _ = p.join();
}
}
}
fn serve_sse_once(deltas: Vec<&'static str>) -> (String, std::thread::JoinHandle<()>) {
let mut body = String::new();
for d in deltas {
let ev = json!({
"type": "content_block_delta",
"index": 0,
"delta": { "type": "text_delta", "text": d },
});
body.push_str(&format!("event: content_block_delta\ndata: {ev}\n\n"));
}
body.push_str("event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n");
serve_http_once(format!(
"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\n\
connection: close\r\n\r\n{body}"
))
}
fn serve_http_once(resp: String) -> (String, std::thread::JoinHandle<()>) {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let base_url = format!("http://{}", listener.local_addr().unwrap());
let server = std::thread::spawn(move || {
let (mut sock, _) = listener.accept().unwrap();
let mut req = Vec::new();
let mut buf = [0u8; 4096];
loop {
let n = sock.read(&mut buf).unwrap_or(0);
if n == 0 {
break;
}
req.extend_from_slice(&buf[..n]);
let text = String::from_utf8_lossy(&req).to_ascii_lowercase();
if let Some(head_end) = text.find("\r\n\r\n") {
let content_length = text[..head_end]
.lines()
.find_map(|l| l.strip_prefix("content-length:"))
.and_then(|v| v.trim().parse::<usize>().ok())
.unwrap_or(0);
if req.len() >= head_end + 4 + content_length {
break;
}
}
}
let _ = sock.write_all(resp.as_bytes());
});
(base_url, server)
}
fn pumped_state(
harness: &OwnerHarness,
) -> (
Arc<Mutex<PairState>>,
Arc<AtomicBool>,
std::thread::JoinHandle<()>,
) {
let session = connect_session(&harness.socket, "pilot").unwrap();
let state = Arc::new(Mutex::new(PairState::new(session, None)));
let stop = Arc::new(AtomicBool::new(false));
let pump = {
let (state, stop) = (state.clone(), stop.clone());
let sink = TurnSink::Claude(Arc::new(Mutex::new(None)));
std::thread::spawn(move || {
let req_id = AtomicU64::new(0);
while !stop.load(Ordering::Relaxed) {
pump_session(&state, &sink, &req_id);
std::thread::sleep(Duration::from_millis(5));
}
})
};
(state, stop, pump)
}
#[test]
fn ui_reads_answer_instantly_while_the_pilot_mutex_is_held() {
let harness = OwnerHarness::start("hello world");
let host = crate::pair_host::PairHost::spawn(PairConfig {
socket: harness.socket.clone(),
workspace: harness._dir.path().to_path_buf(),
name: String::from("nav"),
model: Some(String::from("m")),
task: None,
provider: Provider::Local {
base_url: String::from("http://127.0.0.1:9"),
},
})
.unwrap();
let state = host.state_for_tests().expect("pilot state");
let (locked_tx, locked_rx) = std::sync::mpsc::channel();
let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();
let holder = std::thread::spawn(move || {
let _guard = state.lock().unwrap();
locked_tx.send(()).unwrap();
let _ = release_rx.recv();
});
locked_rx.recv().unwrap();
let (done_tx, done_rx) = std::sync::mpsc::channel();
let reader = std::thread::spawn(move || {
let busy = host.is_busy();
let _ = host.caret_sites();
let _ = host.notes_snapshot("demo.txt");
let seen = host.last_seen("demo.txt");
let rejected = host.send_yield_turn("demo.txt", "x").is_err();
done_tx.send((busy, seen, rejected)).unwrap();
drop(host);
});
let (busy, seen, rejected) = done_rx
.recv_timeout(Duration::from_secs(2))
.expect("UI reads must answer instantly while the pilot mutex is held");
assert!(busy, "contended = the pilot is mid-work = busy");
assert_eq!(seen, None, "no baseline is better than a blocked frame");
assert!(rejected, "a send under contention reports mid-turn");
release_tx.send(()).unwrap();
holder.join().unwrap();
reader.join().unwrap();
}
#[test]
fn the_seat_stays_busy_until_turn_done_is_consumed() {
if !is_on_path("python3") {
eprintln!("SKIPPED: python3 not on PATH");
return;
}
let harness = OwnerHarness::start("hello world");
let script = harness._dir.path().join("fake_claude.py");
std::fs::write(&script, FAKE_CLAUDE).unwrap();
let log = harness._dir.path().join("stdin.log");
let mut cmd = Command::new("python3");
cmd.arg(&script).arg(&log).arg("stream");
let mut host =
crate::pair_host::PairHost::spawn_cmd(&harness.socket, "nav", None, cmd).unwrap();
host.send_yield_turn("demo.txt", "hello world").unwrap();
let state = host.state_for_tests().expect("pilot state");
let deadline = Instant::now() + Duration::from_secs(60);
while state.lock().unwrap().turn_active() {
assert!(Instant::now() < deadline, "the fake turn never finished");
std::thread::sleep(Duration::from_millis(5));
}
assert!(
host.is_busy(),
"the turn's end has not been consumed yet: the seat is still busy"
);
let refused = host
.send_yield_turn("demo.txt", "hello world")
.expect_err("a send in the finish window must be refused");
assert!(
refused.to_string().contains("mid-turn"),
"the refusal names the reason: {refused}"
);
let deadline = Instant::now() + Duration::from_secs(5);
loop {
if host
.poll()
.iter()
.any(|e| matches!(e, crate::pair_host::PairEvent::TurnDone { .. }))
{
break;
}
assert!(Instant::now() < deadline, "TurnDone never arrived");
std::thread::sleep(Duration::from_millis(5));
}
assert!(
!settle(&false, || host.is_busy()),
"consumed: the seat is idle again"
);
drop(host);
}
#[test]
fn a_failed_yield_leaves_no_look_behind() {
if !is_on_path("python3") {
eprintln!("SKIPPED: python3 not on PATH");
return;
}
let harness = OwnerHarness::start("hello world");
let mut cmd = Command::new("python3");
cmd.arg("-c")
.arg("import os,time; os.close(0); os.close(1); time.sleep(60)");
let mut host =
crate::pair_host::PairHost::spawn_cmd(&harness.socket, "nav", None, cmd).unwrap();
let deadline = Instant::now() + Duration::from_secs(60);
loop {
if host
.poll()
.iter()
.any(|e| matches!(e, crate::pair_host::PairEvent::Died(_)))
{
break;
}
assert!(Instant::now() < deadline, "the child never died");
std::thread::sleep(Duration::from_millis(10));
}
let err = host.send_yield_turn("demo.txt", "hello world").unwrap_err();
assert!(
format!("{err:#}").contains("claude"),
"the send must fail at the claude sink, not before staging: {err:#}"
);
assert_eq!(
host.last_seen("demo.txt"),
None,
"a failed yield keeps no baseline"
);
assert!(
!settle(&false, || host.is_busy()),
"a failed yield keeps no busy latch"
);
drop(host);
}
#[test]
fn a_failed_send_unlatches_the_turn_and_keeps_the_cancel_note() {
let harness = OwnerHarness::start("hello world");
let (state, stop, pump) = pumped_state(&harness);
state.lock().unwrap().pending_note = Some(String::from("cancelled: f.rs"));
let dead = TurnSink::Claude(Arc::new(Mutex::new(None)));
let err = write_user_turn(&state, &dead, String::from("hi"))
.expect_err("a dead stdin must fail the send");
assert!(err.to_string().contains("stdin"), "{err}");
{
let st = state.lock().unwrap();
assert!(
!st.turn_active,
"a turn that never left must not stay active"
);
assert_eq!(
st.pending_note.as_deref(),
Some("cancelled: f.rs"),
"the cancel note is still owed to the model"
);
}
stop.store(true, Ordering::Relaxed);
pump.join().unwrap();
}
#[test]
fn join_teardowns_reaps_a_dropped_hosts_child() {
if !crate::lsp::manager::is_on_path("python3") {
eprintln!("SKIPPED: python3 not on PATH");
return;
}
let harness = OwnerHarness::start("hello world");
let marker = format!("croft-teardown-{}", std::process::id());
let mut cmd = std::process::Command::new("python3");
cmd.arg("-c")
.arg("import time; time.sleep(120)")
.arg(&marker);
let host = crate::pair_host::PairHost::spawn_cmd(&harness.socket, "nav", None, cmd).unwrap();
let alive = |m: &str| {
std::process::Command::new("pgrep")
.args(["-f", m])
.output()
.map(|o| !o.stdout.is_empty())
.unwrap_or(false)
};
assert!(alive(&marker), "the sleeper child must be running");
drop(host);
crate::pair_host::join_teardowns();
assert!(
!alive(&marker),
"after join_teardowns the dropped host's child must be reaped"
);
}
#[test]
fn an_unterminated_fence_header_never_leaks_into_commentary() {
let mut m = FenceMachine::new();
let mut events = m.push("thinking\n<<<NOTE src/f.rs:12>>>");
events.extend(m.finish());
let commentary = commentary_of(&events);
assert!(commentary.contains("thinking"));
assert!(
!commentary.contains("<<<NOTE"),
"protocol residue leaked: {commentary:?}"
);
let mut events = m.push("<<<EDIT src/f.rs:0:0-0:5>>>");
events.extend(m.finish());
assert!(
!commentary_of(&events).contains("<<<EDIT"),
"an EDIT header tail is the same class"
);
let mut events = m.push("<<<EDIT garbage");
events.extend(m.finish());
assert!(
commentary_of(&events).contains("<<<EDIT garbage"),
"a malformed tail stays commentary"
);
}
#[test]
fn park_caret_waits_for_bootstrap_then_broadcasts() {
let harness = OwnerHarness::start("l0\nl1\nl2");
let (state, stop, pump) = pumped_state(&harness);
{
let mut st = state.lock().unwrap();
st.begin_turn("demo.txt", "l0\nl1\nl2", false); st.park_caret("demo.txt", 1); }
harness.wait_until("the parked caret to broadcast", |h| {
h.carets()
.iter()
.any(|(n, r, c)| n == "pilot" && *r == 1 && *c == 0)
});
state.lock().unwrap().park_caret("demo.txt", 99);
harness.wait_until("the clamped caret", |h| {
h.carets().iter().any(|(n, r, _)| n == "pilot" && *r == 2)
});
stop.store(true, Ordering::Relaxed);
let _ = pump.join();
}
#[test]
fn a_landed_note_parks_the_pilot_caret_at_its_row() {
let harness = OwnerHarness::start("l0\nl1\nl2");
let (state, stop, pump) = pumped_state(&harness);
apply_fence_event(
&state,
FenceEvent::NoteStart {
file: "demo.txt".into(),
row: 2,
},
);
apply_fence_event(&state, FenceEvent::NoteBody("look here".into()));
apply_fence_event(&state, FenceEvent::NoteEnd);
harness.wait_until("the note's caret", |h| {
h.carets().iter().any(|(n, r, _)| n == "pilot" && *r == 2)
});
stop.store(true, Ordering::Relaxed);
let _ = pump.join();
}
#[test]
fn ask_and_reply_turns_park_the_navigator_caret() {
let harness = OwnerHarness::start("l0\nl1\nl2");
let mut cmd = Command::new("cat");
cmd.stdin(Stdio::piped());
let asker = crate::pair_host::PairHost::spawn_cmd(&harness.socket, "asker", None, cmd).unwrap();
asker
.send_ask_turn("demo.txt", (1, 1), "", "look at this", "l0\nl1\nl2")
.unwrap();
harness.wait_until("the ask turn's caret", |h| {
h.carets().iter().any(|(n, r, _)| n == "asker" && *r == 1)
});
harness.wait_until("the seat's per-file site ids (its wire identity)", |_| {
!asker.caret_sites().is_empty()
});
let mut cmd = Command::new("cat");
cmd.stdin(Stdio::piped());
let replier =
crate::pair_host::PairHost::spawn_cmd(&harness.socket, "replier", None, cmd).unwrap();
replier
.send_reply_turn("demo.txt", 2, "seed note", "why here?", "l0\nl1\nl2")
.unwrap();
harness.wait_until("the reply turn's caret", |h| {
h.carets().iter().any(|(n, r, _)| n == "replier" && *r == 2)
});
}
#[test]
fn a_stale_rollback_never_stomps_a_newer_turn() {
let harness = OwnerHarness::start("hello");
let session = connect_session(&harness.socket, "pilot").unwrap();
let state = Mutex::new(PairState::new(session, None));
let mut st = state.lock().unwrap();
let staged_a = st.stage_turn("demo.txt", "one", false);
let _staged_b = st.stage_turn("demo.txt", "two", true);
st.unstage_turn(staged_a); assert_eq!(
st.last_seen_of("demo.txt").as_deref(),
Some("two"),
"a stale rollback must not replace the live turn's baseline"
);
assert!(
st.comment_only,
"a stale rollback must not unlatch the live turn's comment-only"
);
}
#[test]
fn a_parked_rollback_blocks_sends_until_it_applies() {
let harness = OwnerHarness::start("hello");
let session = connect_session(&harness.socket, "pilot").unwrap();
let state = Mutex::new(PairState::new(session, None));
let staged = state.lock().unwrap().stage_turn("demo.txt", "one", false);
let parked = Mutex::new(Some(staged));
assert!(!crate::pair_host::drain_parked(&parked, || None));
assert!(parked.lock().unwrap().is_some(), "the undo is not lost");
assert!(crate::pair_host::drain_parked(&parked, || Some(
state.lock().unwrap()
)));
assert!(parked.lock().unwrap().is_none());
assert_eq!(
state.lock().unwrap().last_seen_of("demo.txt"),
None,
"the parked undo restored the pre-turn baseline"
);
}
#[test]
fn nested_rollbacks_unwind_to_the_original_state() {
let harness = OwnerHarness::start("hello");
let session = connect_session(&harness.socket, "pilot").unwrap();
let state = Mutex::new(PairState::new(session, None));
let mut st = state.lock().unwrap();
let staged_a = st.stage_turn("demo.txt", "one", false);
let staged_b = st.stage_turn("demo.txt", "two", true);
st.unstage_turn(staged_b); st.unstage_turn(staged_a); assert_eq!(
st.last_seen_of("demo.txt"),
None,
"both failed turns unwound: no baseline remains"
);
assert!(!st.comment_only, "the original comment-only state is back");
assert_eq!(st.target_file, None, "the original target is back");
}
#[test]
fn an_unsolicited_result_ends_no_turn() {
let harness = OwnerHarness::start("hello");
let session = connect_session(&harness.socket, "pilot").unwrap();
let state = Mutex::new(PairState::new(session, None));
let mut fence = FenceMachine::new();
let (turn_tx, turn_rx) = std::sync::mpsc::channel();
let result = json!({ "type": "result", "is_error": false, "result": "done" });
state.lock().unwrap().turn_active = true;
handle_claude_event(&state, &mut fence, &result, &turn_tx);
assert!(
turn_rx.try_recv().is_ok(),
"the genuine result ends the turn"
);
state.lock().unwrap().stage_turn("demo.txt", "one", true);
handle_claude_event(&state, &mut fence, &result, &turn_tx);
assert!(
turn_rx.try_recv().is_err(),
"a duplicate result must not queue a phantom TurnEnd"
);
assert!(
state.lock().unwrap().comment_only,
"a duplicate result must not clear the newer turn's comment-only staging"
);
}
#[test]
fn an_open_region_supersedes_a_pending_caret_park() {
let harness = OwnerHarness::start("l0\nl1\nl2");
let session = connect_session(&harness.socket, "pilot").unwrap();
let state = Mutex::new(PairState::new(session, None));
{
let mut st = state.lock().unwrap();
st.begin_turn("demo.txt", "l0\nl1\nl2", false);
st.park_caret("demo.txt", 1);
assert!(st.pending_caret.is_some(), "not live yet: the park waits");
}
let deadline = Instant::now() + Duration::from_secs(5);
loop {
let mut st = state.lock().unwrap();
let _ = st.session.poll(|_| None);
if st.session.is_live("demo.txt") {
break;
}
drop(st);
assert!(Instant::now() < deadline, "demo.txt never went live");
std::thread::sleep(Duration::from_millis(5));
}
let mut st = state.lock().unwrap();
open_region(&mut st, "demo.txt", (0, 0), (0, 0));
assert!(
st.pending_caret.is_none(),
"the edit's caret supersedes the pending park"
);
}
#[test]
fn an_inverted_fence_range_drops_the_edit_via_output_not_stderr() {
let harness = OwnerHarness::start("l0\nl1\nl2\nl3\nl4\nl5");
let session = connect_session(&harness.socket, "pilot").unwrap();
let state = Mutex::new(PairState::new(session, None));
state
.lock()
.unwrap()
.begin_turn("demo.txt", "l0\nl1\nl2\nl3\nl4\nl5", false);
let deadline = Instant::now() + Duration::from_secs(5);
loop {
let mut st = state.lock().unwrap();
let _ = st.session.poll(|_| None);
if st.session.is_live("demo.txt") {
break;
}
drop(st);
assert!(Instant::now() < deadline, "demo.txt never went live");
std::thread::sleep(Duration::from_millis(5));
}
let baseline = crate::output::snapshot("Navigator")
.unwrap_or_default()
.len();
let mut st = state.lock().unwrap();
open_region(&mut st, "demo.txt", (4, 0), (2, usize::MAX));
assert!(st.discarding, "the inverted edit's body must be discarded");
assert_eq!(
st.session.doc_text("demo.txt"),
Some("l0\nl1\nl2\nl3\nl4\nl5"),
"nothing may be applied"
);
let lines = crate::output::snapshot("Navigator").unwrap_or_default();
assert!(
lines
.iter()
.skip(baseline)
.any(|l| l.text.contains("inverted")),
"the drop is reported on the OUTPUT channel"
);
}
#[test]
fn stream_turn_applies_a_fenced_edit() {
let harness = OwnerHarness::start("hello world");
let (state, stop, pump) = pumped_state(&harness);
let (base_url, server) = serve_sse_once(vec![
"Let me fix that.\n",
"<<<EDIT demo.txt:0:6-0:11>",
">>\n",
"streamed",
" edit",
"\n<<<END>>>\nDone.\n",
]);
let (turn_tx, turn_rx) = std::sync::mpsc::channel();
let mut messages = vec![json!({ "role": "user", "content": "fix demo.txt" })];
local::stream_turn(
&base_url,
"test-model",
PAIR_SYSTEM_PROMPT,
&mut messages,
&state,
&turn_tx,
);
server.join().unwrap();
harness.wait_until("the streamed edit to converge", |h| {
h.doc().as_deref() == Some("hello streamed edit")
});
assert!(
harness.remote_edit_count() >= 3,
"the edit must arrive as multiple streamed ops, got {}",
harness.remote_edit_count()
);
let end = turn_rx.try_recv().expect("turn ended");
assert!(!end.is_error && !end.cancelled);
assert_eq!(messages.len(), 2, "assistant reply appended");
assert_eq!(messages[1]["role"], "assistant");
assert!(
messages[1]["content"]
.as_str()
.unwrap()
.contains("<<<EDIT demo.txt:0:6-0:11>>>"),
"conversation history carries the fence verbatim"
);
assert!(!state.lock().unwrap().turn_active());
stop.store(true, Ordering::Relaxed);
pump.join().unwrap();
}
#[test]
fn a_stream_is_announced_before_its_first_edit() {
let harness = OwnerHarness::start("hello world");
let (state, stop, pump) = pumped_state(&harness);
let (base_url, server) = serve_sse_once(vec![
"<<<EDIT demo.txt:0:6-0:11>>>\n",
"streamed",
"\n<<<END>>>\n",
]);
let (turn_tx, _turn_rx) = std::sync::mpsc::channel();
let mut messages = vec![json!({ "role": "user", "content": "fix demo.txt" })];
local::stream_turn(
&base_url,
"test-model",
PAIR_SYSTEM_PROMPT,
&mut messages,
&state,
&turn_tx,
);
server.join().unwrap();
harness.wait_until("the streamed edit to converge", |h| {
h.doc().as_deref() == Some("hello streamed")
});
harness.wait_until("the stream to end", |h| {
h.events
.lock()
.unwrap()
.iter()
.any(|e| matches!(e, CollabEvent::StreamState { active: false, .. }))
});
let events = harness.events.lock().unwrap();
let first = |pred: &dyn Fn(&CollabEvent) -> bool| events.iter().position(pred);
let announced = first(&|e| matches!(e, CollabEvent::StreamState { active: true, .. }))
.expect("the stream is announced");
let edited = first(&|e| matches!(e, CollabEvent::RemoteEdit { .. })).expect("the stream edits");
let ended = first(&|e| matches!(e, CollabEvent::StreamState { active: false, .. }))
.expect("the stream ends");
assert!(
announced < edited,
"announced at {announced}, first edit at {edited}"
);
let last_edit = events
.iter()
.rposition(|e| matches!(e, CollabEvent::RemoteEdit { .. }))
.unwrap();
assert!(
last_edit < ended,
"last edit at {last_edit}, ended at {ended}"
);
drop(events);
stop.store(true, Ordering::Relaxed);
pump.join().unwrap();
}
#[test]
fn stream_turn_names_a_dead_endpoint() {
let harness = OwnerHarness::start("hello world");
let (state, stop, pump) = pumped_state(&harness);
let dead = {
let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
format!("http://{}", l.local_addr().unwrap())
};
let (turn_tx, turn_rx) = std::sync::mpsc::channel();
let mut messages = vec![json!({ "role": "user", "content": "hi" })];
state.lock().unwrap().turn_active = true;
local::stream_turn(
&dead,
"test-model",
PAIR_SYSTEM_PROMPT,
&mut messages,
&state,
&turn_tx,
);
let end = turn_rx.try_recv().expect("turn ended");
assert!(end.is_error);
assert!(
end.text.contains(&dead),
"the failure names the endpoint: {}",
end.text
);
assert!(!state.lock().unwrap().turn_active());
assert!(
messages.is_empty(),
"the unanswered user message is popped so the next ask starts clean"
);
stop.store(true, Ordering::Relaxed);
pump.join().unwrap();
}
#[test]
fn a_mid_stream_drop_reports_failure_and_balances_the_conversation() {
let harness = OwnerHarness::start("hello world");
let (state, stop, pump) = pumped_state(&harness);
let ev = json!({
"type": "content_block_delta",
"index": 0,
"delta": { "type": "text_delta", "text": "half a rep" },
});
let (base_url, server) = serve_http_once(format!(
"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\n\
connection: close\r\n\r\nevent: content_block_delta\ndata: {ev}\n\n"
));
let (turn_tx, turn_rx) = std::sync::mpsc::channel();
let mut messages = vec![json!({ "role": "user", "content": "hi" })];
state.lock().unwrap().turn_active = true;
local::stream_turn(
&base_url,
"test-model",
PAIR_SYSTEM_PROMPT,
&mut messages,
&state,
&turn_tx,
);
server.join().unwrap();
let end = turn_rx.try_recv().expect("turn ended");
assert!(
end.is_error,
"an unclean stream end is a failure: {}",
end.text
);
assert!(
messages.is_empty(),
"the conversation stays balanced for the next ask"
);
stop.store(true, Ordering::Relaxed);
pump.join().unwrap();
}
#[test]
fn an_http_error_body_reaches_the_surfaced_failure() {
let harness = OwnerHarness::start("hello world");
let (state, stop, pump) = pumped_state(&harness);
let (base_url, server) = serve_http_once(String::from(
"HTTP/1.1 404 Not Found\r\ncontent-type: application/json\r\n\
connection: close\r\n\r\n{\"error\":\"model 'qwn3' not found, try pulling it\"}",
));
let (turn_tx, turn_rx) = std::sync::mpsc::channel();
let mut messages = vec![json!({ "role": "user", "content": "hi" })];
state.lock().unwrap().turn_active = true;
local::stream_turn(
&base_url,
"qwn3",
PAIR_SYSTEM_PROMPT,
&mut messages,
&state,
&turn_tx,
);
server.join().unwrap();
let end = turn_rx.try_recv().expect("turn ended");
assert!(end.is_error);
assert!(
end.text.contains("not found, try pulling it"),
"the body's own words must survive: {}",
end.text
);
assert!(messages.is_empty());
stop.store(true, Ordering::Relaxed);
pump.join().unwrap();
}
#[test]
fn a_token_limit_truncation_is_a_failed_turn() {
let harness = OwnerHarness::start("hello world");
let (state, stop, pump) = pumped_state(&harness);
let delta = json!({
"type": "content_block_delta",
"index": 0,
"delta": { "type": "text_delta", "text": "prose" },
});
let md = json!({
"type": "message_delta",
"delta": { "stop_reason": "max_tokens" },
});
let (base_url, server) = serve_http_once(format!(
"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\n\
connection: close\r\n\r\n\
event: content_block_delta\ndata: {delta}\n\n\
event: message_delta\ndata: {md}\n\n\
event: message_stop\ndata: {{\"type\":\"message_stop\"}}\n\n"
));
let (turn_tx, turn_rx) = std::sync::mpsc::channel();
let mut messages = vec![json!({ "role": "user", "content": "hi" })];
state.lock().unwrap().turn_active = true;
local::stream_turn(
&base_url,
"test-model",
PAIR_SYSTEM_PROMPT,
&mut messages,
&state,
&turn_tx,
);
server.join().unwrap();
let end = turn_rx.try_recv().expect("turn ended");
assert!(end.is_error, "truncation must not read as success");
assert!(end.text.contains("truncated"), "{}", end.text);
stop.store(true, Ordering::Relaxed);
pump.join().unwrap();
}
#[test]
fn the_credential_never_rides_cleartext_to_a_remote_host() {
use local::auth_for;
assert_eq!(
auth_for("http://box:8080", Some("secret")),
(String::from("croft"), None),
);
assert_eq!(
auth_for("http://localhost.evil.com:80", Some("secret")),
(String::from("croft"), None),
);
let bearer = Some(String::from("Bearer t"));
assert_eq!(
auth_for("http://localhost:11434", Some("t")),
(String::from("t"), bearer.clone()),
);
assert_eq!(
auth_for("http://127.0.0.1:11434", Some("t")),
(String::from("t"), bearer.clone()),
);
assert_eq!(
auth_for("http://[::1]:11434", Some("t")),
(String::from("t"), bearer.clone()),
);
assert_eq!(
auth_for("https://gw.example.com", Some("t")),
(String::from("t"), bearer),
);
assert_eq!(
auth_for("http://localhost:11434", None),
(String::from("croft"), None)
);
assert_eq!(
auth_for("http://localhost:pass@evil.example", Some("secret")),
(String::from("croft"), None),
);
assert_eq!(
auth_for("http://127.0.0.2:11434", Some("t")),
(String::from("t"), Some(String::from("Bearer t"))),
"any 127.x address is loopback"
);
}
#[test]
fn a_trickling_stream_is_cut_at_the_deadline() {
let harness = OwnerHarness::start("hello world");
let (state, stop, pump) = pumped_state(&harness);
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let base_url = format!("http://{}", listener.local_addr().unwrap());
let stop_trickle = Arc::new(AtomicBool::new(false));
let server = {
let stop_trickle = Arc::clone(&stop_trickle);
std::thread::spawn(move || {
let (mut sock, _) = listener.accept().unwrap();
let mut req = [0u8; 4096];
let _ = sock.read(&mut req);
let _ = sock.write_all(b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\n\r\n");
while !stop_trickle.load(Ordering::Relaxed) {
if sock.write_all(b".").is_err() {
break;
}
std::thread::sleep(Duration::from_millis(20));
}
})
};
let (turn_tx, turn_rx) = std::sync::mpsc::channel();
let mut messages = vec![json!({ "role": "user", "content": "hi" })];
state.lock().unwrap().turn_active = true;
let started = Instant::now();
local::stream_turn_until(
&base_url,
"test-model",
PAIR_SYSTEM_PROMPT,
&mut messages,
&state,
&turn_tx,
Instant::now() + Duration::from_millis(300),
);
let elapsed = started.elapsed();
stop_trickle.store(true, Ordering::Relaxed);
let _ = server.join();
let end = turn_rx.try_recv().expect("turn ended");
assert!(end.is_error, "a deadline cut is a failure: {}", end.text);
assert!(
elapsed < Duration::from_secs(3),
"the ceiling must interrupt the trickle promptly, took {elapsed:?}"
);
assert!(messages.is_empty(), "the conversation stays balanced");
stop.store(true, Ordering::Relaxed);
pump.join().unwrap();
}
#[test]
fn a_silent_stream_body_is_cut_at_the_deadline() {
let harness = OwnerHarness::start("hello world");
let (state, stop, pump) = pumped_state(&harness);
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let base_url = format!("http://{}", listener.local_addr().unwrap());
std::thread::spawn(move || {
let (mut sock, _) = listener.accept().unwrap();
let mut req = [0u8; 4096];
let _ = sock.read(&mut req);
let _ = sock.write_all(b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\n\r\n");
std::thread::sleep(Duration::from_secs(4));
});
let (turn_tx, turn_rx) = std::sync::mpsc::channel();
let mut messages = vec![json!({ "role": "user", "content": "hi" })];
state.lock().unwrap().turn_active = true;
let started = Instant::now();
local::stream_turn_until(
&base_url,
"test-model",
PAIR_SYSTEM_PROMPT,
&mut messages,
&state,
&turn_tx,
Instant::now() + Duration::from_millis(300),
);
let elapsed = started.elapsed();
let end = turn_rx.try_recv().expect("turn ended");
assert!(end.is_error, "a deadline cut is a failure: {}", end.text);
assert!(
elapsed < Duration::from_secs(3),
"the ceiling must interrupt a silent body promptly, took {elapsed:?}"
);
assert!(messages.is_empty(), "the conversation stays balanced");
stop.store(true, Ordering::Relaxed);
pump.join().unwrap();
}
#[test]
fn a_deadline_cut_releases_the_connection() {
let harness = OwnerHarness::start("hello world");
let (state, stop, pump) = pumped_state(&harness);
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let base_url = format!("http://{}", listener.local_addr().unwrap());
let (eof_tx, eof_rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let (mut sock, _) = listener.accept().unwrap();
let mut req = [0u8; 4096];
let _ = sock.read(&mut req);
let _ = sock.write_all(b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\n\r\n");
let mut probe = [0u8; 64];
loop {
match sock.read(&mut probe) {
Ok(0) | Err(_) => break,
Ok(_) => {}
}
}
let _ = eof_tx.send(());
});
let (turn_tx, turn_rx) = std::sync::mpsc::channel();
let mut messages = vec![json!({ "role": "user", "content": "hi" })];
state.lock().unwrap().turn_active = true;
local::stream_turn_until(
&base_url,
"test-model",
PAIR_SYSTEM_PROMPT,
&mut messages,
&state,
&turn_tx,
Instant::now() + Duration::from_millis(300),
);
let end = turn_rx.try_recv().expect("turn ended");
assert!(end.is_error, "a deadline cut is a failure: {}", end.text);
eof_rx
.recv_timeout(Duration::from_secs(2))
.expect("the deadline cut must close the connection, not park it until the socket timeout");
assert!(messages.is_empty(), "the conversation stays balanced");
stop.store(true, Ordering::Relaxed);
pump.join().unwrap();
}
#[test]
fn malformed_sse_data_fails_the_turn() {
let harness = OwnerHarness::start("hello world");
let (state, stop, pump) = pumped_state(&harness);
let (base_url, server) = serve_http_once(String::from(
"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\n\
connection: close\r\n\r\ndata: {not json\n\n\
event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n",
));
let (turn_tx, turn_rx) = std::sync::mpsc::channel();
let mut messages = vec![json!({ "role": "user", "content": "hi" })];
state.lock().unwrap().turn_active = true;
local::stream_turn(
&base_url,
"test-model",
PAIR_SYSTEM_PROMPT,
&mut messages,
&state,
&turn_tx,
);
server.join().unwrap();
let end = turn_rx.try_recv().expect("turn ended");
assert!(end.is_error);
assert!(end.text.contains("malformed"), "{}", end.text);
assert!(messages.is_empty());
stop.store(true, Ordering::Relaxed);
pump.join().unwrap();
}
#[test]
fn a_redirect_is_refused_not_followed() {
let harness = OwnerHarness::start("hello world");
let (state, stop, pump) = pumped_state(&harness);
let (base_url, server) = serve_http_once(String::from(
"HTTP/1.1 302 Found\r\nlocation: http://127.0.0.1:1/v1/messages\r\n\
connection: close\r\n\r\n",
));
let (turn_tx, turn_rx) = std::sync::mpsc::channel();
let mut messages = vec![json!({ "role": "user", "content": "hi" })];
state.lock().unwrap().turn_active = true;
local::stream_turn(
&base_url,
"test-model",
PAIR_SYSTEM_PROMPT,
&mut messages,
&state,
&turn_tx,
);
server.join().unwrap();
let end = turn_rx.try_recv().expect("turn ended");
assert!(end.is_error);
assert!(
end.text.contains("302"),
"the redirect is refused with its status, not followed: {}",
end.text
);
assert!(messages.is_empty());
stop.store(true, Ordering::Relaxed);
pump.join().unwrap();
}
#[test]
fn seat_local_drives_a_turn_end_to_end() {
let harness = OwnerHarness::start("hello world");
let (base_url, server) = serve_sse_once(vec![
"Let me fix that.\n",
"<<<EDIT demo.txt:0:6-0:11>",
">>\n",
"streamed",
" edit",
"\n<<<END>>>\nDone.\n",
]);
let pilot = seat_local(&harness.socket, "pilot", &base_url, "test-model", None).unwrap();
assert!(!pilot.reader_finished(), "a local seat never loses a child");
send_turn(&pilot.state, &pilot.sink, "fix demo.txt").unwrap();
let end = pilot
.turn_rx
.recv_timeout(Duration::from_secs(60))
.expect("turn ends");
assert!(!end.is_error && !end.cancelled, "{}", end.text);
server.join().unwrap();
harness.wait_until("the streamed edit to converge", |h| {
h.doc().as_deref() == Some("hello streamed edit")
});
harness.wait_until("stream-state inactive", |h| {
h.stream_states().contains(&("pilot".to_string(), false))
});
let start = Instant::now();
pilot.shutdown();
assert!(
start.elapsed() < Duration::from_secs(2),
"local shutdown must not block on a grace-kill"
);
}
#[test]
fn pair_host_spawns_local_backend_without_a_child() {
let harness = OwnerHarness::start("hello world");
let no_model = PairConfig {
socket: harness.socket.clone(),
workspace: harness._dir.path().to_path_buf(),
name: String::from("claude"),
model: None,
task: None,
provider: Provider::Local {
base_url: String::from("http://127.0.0.1:9"),
},
};
let err = match crate::pair_host::PairHost::spawn(no_model) {
Err(e) => e,
Ok(_) => panic!("a local provider without a model must refuse to seat"),
};
assert!(
err.to_string().contains("--model"),
"the refusal must hint at --model: {err}"
);
let (base_url, server) = serve_sse_once(vec![
"<<<EDIT demo.txt:0-0>",
">>\nhello streamed edit\n",
"<<<END>>>\n",
]);
let mut host = crate::pair_host::PairHost::spawn(PairConfig {
socket: harness.socket.clone(),
workspace: harness._dir.path().to_path_buf(),
name: String::from("claude"),
model: Some(String::from("test-model")),
task: None,
provider: Provider::Local { base_url },
})
.unwrap();
assert!(!host.is_busy());
host.send_ask_turn("demo.txt", (0, 0), "", "rewrite line 0", "hello world")
.unwrap();
server.join().unwrap();
harness.wait_until("the whole-line edit to converge", |h| {
h.doc().as_deref() == Some("hello streamed edit")
});
harness.wait_until("the turn to end", |h| {
let _ = h; host.poll().iter().any(|e| {
matches!(
e,
crate::pair_host::PairEvent::TurnDone {
cancelled: false,
failed: None
}
)
})
});
}
#[test]
fn local_navigator_badge_names_the_model() {
let harness = OwnerHarness::start("hello world");
let host = crate::pair_host::PairHost::spawn(PairConfig {
socket: harness.socket.clone(),
workspace: harness._dir.path().to_path_buf(),
name: String::from("claude"),
model: Some(String::from("test-model")),
task: None,
provider: Provider::Local {
base_url: String::from("http://127.0.0.1:9"),
},
})
.unwrap();
assert_eq!(host.title(), "claude (test-model)");
let mut cmd = Command::new("cat");
cmd.stdin(Stdio::piped());
let host =
crate::pair_host::PairHost::spawn_cmd(&harness.socket, "navigator", None, cmd).unwrap();
assert_eq!(host.title(), "navigator");
}
fn spawn_pilot(
socket: &Path,
script: &Path,
log: &Path,
mode: &str,
) -> std::thread::JoinHandle<Result<()>> {
let mut cmd = Command::new("python3");
cmd.arg(script).arg(log).arg(mode);
let socket = socket.to_path_buf();
std::thread::spawn(move || {
let pilot = seat_pilot(&socket, "pilot", cmd, None)?;
run_pilot(
pilot,
"pilot",
Some("fix demo.txt".into()),
&mut std::io::Cursor::new(Vec::new()),
)
})
}
#[test]
fn pilot_streams_a_fenced_edit_into_the_owner() {
if !is_on_path("python3") {
eprintln!("SKIPPED: python3 not on PATH");
return;
}
let harness = OwnerHarness::start("hello world");
let script = harness._dir.path().join("fake_claude.py");
std::fs::write(&script, FAKE_CLAUDE).unwrap();
let log = harness._dir.path().join("stdin.log");
let pilot = spawn_pilot(&harness.socket, &script, &log, "stream");
harness.wait_until("the streamed edit to converge", |h| {
h.doc().as_deref() == Some("hello streamed edit")
});
harness.wait_until("stream-state inactive", |h| {
h.stream_states().contains(&("pilot".to_string(), false))
});
assert!(
harness
.stream_states()
.contains(&("pilot".to_string(), true)),
"owner saw the stream start"
);
assert!(
harness.remote_edit_count() >= 3,
"the edit must arrive as multiple streamed ops, got {}",
harness.remote_edit_count()
);
pilot.join().unwrap().expect("pilot exits cleanly");
}
#[test]
fn pilot_exit_does_not_hang_on_a_lingering_claude() {
if !is_on_path("python3") {
eprintln!("SKIPPED: python3 not on PATH");
return;
}
let harness = OwnerHarness::start("hello world");
let script = harness._dir.path().join("fake_claude.py");
std::fs::write(&script, FAKE_CLAUDE).unwrap();
let log = harness._dir.path().join("stdin.log");
let pilot = spawn_pilot(&harness.socket, &script, &log, "linger");
harness.wait_until("the streamed edit to converge", |h| {
h.doc().as_deref() == Some("hello streamed edit")
});
let deadline = Instant::now() + Duration::from_secs(30);
while !pilot.is_finished() {
assert!(
Instant::now() < deadline,
"pilot exit hung on the lingering claude child"
);
std::thread::sleep(Duration::from_millis(50));
}
pilot.join().unwrap().expect("pilot exits cleanly");
}
#[test]
fn pilot_cancel_reverts_and_interrupts() {
if !is_on_path("python3") {
eprintln!("SKIPPED: python3 not on PATH");
return;
}
let harness = OwnerHarness::start("hello world");
let script = harness._dir.path().join("fake_claude.py");
std::fs::write(&script, FAKE_CLAUDE).unwrap();
let log = harness._dir.path().join("stdin.log");
let pilot = spawn_pilot(&harness.socket, &script, &log, "cancel");
harness.wait_until("the partial body to converge", |h| {
h.doc().is_some_and(|d| d.contains("streamed"))
});
harness.owner.lock().unwrap().send_stream_cancel();
harness.wait_until("the revert to converge", |h| {
h.doc().as_deref() == Some("hello world")
});
pilot.join().unwrap().expect("pilot exits cleanly");
assert_eq!(
harness.doc().as_deref(),
Some("hello world"),
"post-cancel deltas must never land"
);
harness.wait_until("stream-state inactive", |h| {
h.stream_states().contains(&("pilot".to_string(), false))
});
let log_text = std::fs::read_to_string(&log).unwrap();
assert!(
log_text.contains("control_request") && log_text.contains("interrupt"),
"the interrupt must land on claude's stdin: {log_text:?}"
);
}
fn run_chunks(input: &str, chunk: usize) -> Vec<FenceEvent> {
let mut m = FenceMachine::new();
let mut events = Vec::new();
let chars: Vec<char> = input.chars().collect();
for piece in chars.chunks(chunk) {
let s: String = piece.iter().collect();
events.extend(m.push(&s));
}
events.extend(m.finish());
events
}
fn body_of(events: &[FenceEvent]) -> String {
events
.iter()
.filter_map(|e| match e {
FenceEvent::EditBody(s) => Some(s.as_str()),
_ => None,
})
.collect()
}
fn commentary_of(events: &[FenceEvent]) -> String {
events
.iter()
.filter_map(|e| match e {
FenceEvent::Commentary(s) => Some(s.as_str()),
_ => None,
})
.collect()
}
fn note_body_of(events: &[FenceEvent]) -> String {
events
.iter()
.filter_map(|e| match e {
FenceEvent::NoteBody(s) => Some(s.as_str()),
_ => None,
})
.collect()
}
#[test]
fn note_fence_parses_across_delta_splits() {
let input = "Look at this.\n\
<<<NOTE src/f.rs:12>>>\n\
the caller in cli.rs:88\nstill expects Config\n\
<<<END>>>\n\
trailing\n";
for chunk in [1, 3, 7, input.len()] {
let events = run_chunks(input, chunk);
let start = events
.iter()
.find_map(|e| match e {
FenceEvent::NoteStart { file, row } => Some((file.clone(), *row)),
_ => None,
})
.unwrap_or_else(|| panic!("no NoteStart at chunk {chunk}"));
assert_eq!(start, ("src/f.rs".to_string(), 12), "chunk {chunk}");
assert_eq!(
note_body_of(&events),
"the caller in cli.rs:88\nstill expects Config",
"chunk {chunk}"
);
assert_eq!(
events
.iter()
.filter(|e| matches!(e, FenceEvent::NoteEnd))
.count(),
1,
"chunk {chunk}"
);
let commentary = commentary_of(&events);
assert!(commentary.contains("Look at this."), "chunk {chunk}");
assert!(commentary.contains("trailing"), "chunk {chunk}");
assert!(!commentary.contains("<<<NOTE"), "chunk {chunk}");
}
}
#[test]
fn malformed_note_headers_become_commentary() {
for bad in [
"<<<NOTE src/f.rs>>>\nbody\n<<<END>>>\n",
"<<<NOTE src/f.rs:x>>>\nbody\n<<<END>>>\n",
"<<<NOTE :3>>>\nbody\n<<<END>>>\n",
"<<<NOTE>>>\nbody\n<<<END>>>\n",
] {
let events = run_chunks(bad, 5);
assert!(
!events
.iter()
.any(|e| matches!(e, FenceEvent::NoteStart { .. })),
"{bad:?} must not start a note"
);
}
}
#[test]
fn unterminated_note_aborts_at_finish() {
let mut m = FenceMachine::new();
let mut events = m.push("<<<NOTE f.rs:3>>>\nhalf a thought");
events.extend(m.finish());
assert!(events.iter().any(|e| matches!(e, FenceEvent::NoteAbort)));
assert!(!events.iter().any(|e| matches!(e, FenceEvent::NoteEnd)));
}
#[test]
fn edit_and_note_fences_coexist_in_one_turn() {
let input = "<<<EDIT a.rs:0:0-0:0>>>\nnew\n<<<END>>>\n\
<<<NOTE b.rs:4>>>\nremark\n<<<END>>>\n";
let events = run_chunks(input, 2);
assert_eq!(body_of(&events), "new");
assert_eq!(note_body_of(&events), "remark");
assert_eq!(
events
.iter()
.filter(|e| matches!(e, FenceEvent::EditEnd))
.count(),
1
);
assert_eq!(
events
.iter()
.filter(|e| matches!(e, FenceEvent::NoteEnd))
.count(),
1
);
}
#[test]
fn fence_parses_identically_across_arbitrary_delta_splits() {
let input = "I will fix the loop.\n\
<<<EDIT src/f.rs:3:0-5:10>>>\n\
for x in xs {\n go(x);\n}\n\
<<<END>>>\n\
Done.\n";
for chunk in [1, 2, 3, 7, input.len()] {
let events = run_chunks(input, chunk);
let start = events
.iter()
.find_map(|e| match e {
FenceEvent::EditStart { file, start, end } => Some((file.clone(), *start, *end)),
_ => None,
})
.unwrap_or_else(|| panic!("no EditStart at chunk {chunk}"));
assert_eq!(
start,
("src/f.rs".to_string(), (3, 0), (5, 10)),
"chunk {chunk}"
);
assert_eq!(
body_of(&events),
"for x in xs {\n go(x);\n}",
"chunk {chunk}"
);
assert_eq!(
events
.iter()
.filter(|e| matches!(e, FenceEvent::EditEnd))
.count(),
1,
"chunk {chunk}"
);
let commentary = commentary_of(&events);
assert!(
commentary.contains("I will fix the loop."),
"chunk {chunk}: {commentary:?}"
);
assert!(commentary.contains("Done."), "chunk {chunk}");
assert!(
!commentary.contains("<<<EDIT"),
"header must not leak into commentary at chunk {chunk}"
);
}
let events = run_chunks(input, 1);
let bodies = events
.iter()
.filter(|e| matches!(e, FenceEvent::EditBody(_)))
.count();
assert!(bodies > 1, "body must stream, got {bodies} event(s)");
}
#[test]
fn parse_header_accepts_whole_line_range() {
let event = parse_header("<<<EDIT demo.txt:3-5>>>").expect("whole-line header parses");
let FenceEvent::EditStart { file, start, end } = event else {
panic!("not an EditStart: {event:?}");
};
assert_eq!(file, "demo.txt");
assert_eq!(start, (3, 0));
assert_eq!(end, (5, usize::MAX));
}
#[test]
fn whole_line_edit_replaces_entire_rows() {
let buffer = "def greet(name):\n return \"hi \" + name\n";
let input = "<<<EDIT greet.py:1-1>>>\n return f\"Hello, {name}!\"\n<<<END>>>\n";
let events = run_chunks(input, 3);
let (start, end) = events
.iter()
.find_map(|e| match e {
FenceEvent::EditStart { start, end, .. } => Some((*start, *end)),
_ => None,
})
.expect("whole-line fence opens an edit");
let lines: Vec<String> = buffer.split('\n').map(String::from).collect();
let (s, e) = range_bytes(&lines, start, end);
let result = format!("{}{}{}", &buffer[..s], body_of(&events), &buffer[e..]);
assert_eq!(result, "def greet(name):\n return f\"Hello, {name}!\"\n");
}
#[test]
fn truncated_four_int_header_stays_commentary() {
assert!(parse_header("<<<EDIT src/f.rs:3:0-5>>>").is_none());
}
#[test]
fn malformed_headers_become_commentary() {
for bad in [
"<<<EDIT src/f.rs:3:0-5>>>\nbody\n<<<END>>>\n",
"<<<EDIT src/f.rs>>>\nbody\n<<<END>>>\n",
"<<<EDIT src/f.rs:a:0-5:10>>>\nbody\n<<<END>>>\n",
"<<<EDIT>>>\nbody\n<<<END>>>\n",
] {
let events = run_chunks(bad, 5);
assert!(
!events
.iter()
.any(|e| matches!(e, FenceEvent::EditStart { .. })),
"{bad:?} must not start an edit"
);
assert!(
commentary_of(&events).contains("body"),
"{bad:?}: the un-fenced body is commentary"
);
}
}
#[test]
fn end_marker_strips_exactly_one_trailing_newline() {
let input = "<<<EDIT f:0:0-0:0>>>\nabc\n\n<<<END>>>\n";
for chunk in [1, 4, input.len()] {
assert_eq!(body_of(&run_chunks(input, chunk)), "abc\n", "chunk {chunk}");
}
}
#[test]
fn end_marker_with_trailing_chars_is_body() {
let input = "<<<EDIT f:0:0-0:0>>>\nkeep <<<END>>>ish\n<<<END>>>\n";
for chunk in [1, 3, input.len()] {
assert_eq!(
body_of(&run_chunks(input, chunk)),
"keep <<<END>>>ish",
"chunk {chunk}"
);
}
}
#[test]
fn multiple_fences_in_one_turn() {
let input = "<<<EDIT a:0:0-0:0>>>\nfirst\n<<<END>>>\n\
between\n\
<<<EDIT b:1:2-3:4>>>\nsecond\n<<<END>>>\n";
let events = run_chunks(input, 2);
let starts: Vec<String> = events
.iter()
.filter_map(|e| match e {
FenceEvent::EditStart { file, .. } => Some(file.clone()),
_ => None,
})
.collect();
assert_eq!(starts, ["a", "b"]);
assert_eq!(body_of(&events), "firstsecond");
assert_eq!(
events
.iter()
.filter(|e| matches!(e, FenceEvent::EditEnd))
.count(),
2
);
assert!(commentary_of(&events).contains("between"));
}
#[test]
fn unterminated_fence_aborts_at_finish() {
let mut m = FenceMachine::new();
let mut events = m.push("<<<EDIT f:0:0-0:0>>>\npartial body");
events.extend(m.finish());
assert!(
events.iter().any(|e| matches!(e, FenceEvent::EditAbort)),
"{events:?}"
);
let events = {
let mut e = m.push("plain text\n");
e.extend(m.finish());
e
};
assert!(commentary_of(&events).contains("plain text"));
}
#[test]
fn end_marker_at_end_of_turn_closes_the_fence() {
let mut m = FenceMachine::new();
let mut events = m.push("<<<EDIT f:0:0-0:0>>>\nbody\n<<<END>>>");
events.extend(m.finish());
assert!(events.iter().any(|e| matches!(e, FenceEvent::EditEnd)));
assert_eq!(body_of(&events), "body");
}
#[test]
fn header_files_with_colons_and_dashes_parse() {
let input = "<<<EDIT a-b:c.rs:10:2-11:0>>>\nx\n<<<END>>>\n";
let events = run_chunks(input, input.len());
match events
.iter()
.find(|e| matches!(e, FenceEvent::EditStart { .. }))
{
Some(FenceEvent::EditStart { file, start, end }) => {
assert_eq!(file, "a-b:c.rs");
assert_eq!((*start, *end), ((10, 2), (11, 0)));
}
other => panic!("expected EditStart, got {other:?}"),
}
}
#[test]
fn shift_offset_handles_before_straddle_and_after() {
let ins = ResolvedSpan {
at: 2,
deleted: 0,
inserted: "abc".into(),
};
assert_eq!(shift_offset(10, &ins), 13);
let del = ResolvedSpan {
at: 6,
deleted: 4,
inserted: String::new(),
};
assert_eq!(shift_offset(10, &del), 6);
let straddle = ResolvedSpan {
at: 8,
deleted: 6,
inserted: "Z".into(),
};
assert_eq!(shift_offset(10, &straddle), 9);
let after = ResolvedSpan {
at: 10,
deleted: 3,
inserted: "wxyz".into(),
};
assert_eq!(shift_offset(10, &after), 10);
let insert_at = ResolvedSpan {
at: 10,
deleted: 0,
inserted: "Q".into(),
};
assert_eq!(shift_offset(10, &insert_at), 11);
}
#[test]
fn shift_offset_sequences_track_a_region() {
let mut start = 20usize;
let mut anchor = 30usize;
let spans = [
ResolvedSpan {
at: 0,
deleted: 0,
inserted: "aaaaa".into(),
},
ResolvedSpan {
at: 40,
deleted: 5,
inserted: String::new(),
},
ResolvedSpan {
at: 23,
deleted: 5,
inserted: String::new(),
},
];
for span in &spans {
start = shift_offset(start, span);
anchor = shift_offset(anchor, span);
}
assert_eq!(start, 23);
assert_eq!(anchor, 30);
assert!(start <= anchor);
}
#[test]
fn fence_range_converts_to_byte_offsets() {
let lines: Vec<String> = ["let s = \"héllo\";", "next"]
.iter()
.map(|s| s.to_string())
.collect();
let (start, end) = range_bytes(&lines, (0, 10), (1, 2));
assert_eq!(start, crate::collab::byte_offset(&lines, 0, 10));
assert_eq!(end, crate::collab::byte_offset(&lines, 1, 2));
assert!(start < end);
}
#[test]
fn pair_host_emits_note_added_and_snapshots_rows() {
if !is_on_path("python3") {
eprintln!("SKIPPED: python3 not on PATH");
return;
}
let harness = OwnerHarness::start("hello world\nsecond line");
let script = harness._dir.path().join("fake_claude.py");
std::fs::write(&script, FAKE_CLAUDE).unwrap();
let log = harness._dir.path().join("stdin.log");
let mut cmd = Command::new("python3");
cmd.arg(&script).arg(&log).arg("notes");
let mut host =
crate::pair_host::PairHost::spawn_cmd(&harness.socket, "navigator", None, cmd).unwrap();
host.send_task("@demo.txt look this over").unwrap();
let deadline = Instant::now() + Duration::from_secs(60);
let mut events: Vec<crate::pair_host::PairEvent> = Vec::new();
while !(events
.iter()
.any(|e| matches!(e, crate::pair_host::PairEvent::TurnDone { .. }))
&& events
.iter()
.any(|e| matches!(e, crate::pair_host::PairEvent::NoteAdded { .. })))
{
assert!(
Instant::now() < deadline,
"no TurnDone + NoteAdded; saw {events:?}"
);
events.extend(host.poll());
std::thread::sleep(Duration::from_millis(10));
}
let note = events
.iter()
.find_map(|e| match e {
crate::pair_host::PairEvent::NoteAdded {
file, row, body, ..
} => Some((file.clone(), *row, body.clone())),
_ => None,
})
.unwrap_or_else(|| panic!("no NoteAdded; saw {events:?}"));
assert_eq!(note.0, "demo.txt");
assert_eq!(note.1, 1, "anchored to the fenced row");
assert!(note.2.contains("second line could be tighter"));
let expected = vec![(1, 1, "second line could be tighter".to_string())];
assert_eq!(
settle(&expected, || host.notes_snapshot("demo.txt")),
expected,
"(id, row, body): the first note of the seat gets id 1"
);
drop(host); }
#[test]
fn a_turn_is_rejected_while_another_is_streaming() {
if !is_on_path("python3") {
eprintln!("SKIPPED: python3 not on PATH");
return;
}
let harness = OwnerHarness::start("line zero\nline one");
let script = harness._dir.path().join("fake_claude.py");
std::fs::write(&script, FAKE_CLAUDE).unwrap();
let log = harness._dir.path().join("stdin.log");
let mut cmd = Command::new("python3");
cmd.arg(&script).arg(&log).arg("hang"); let host = crate::pair_host::PairHost::spawn_cmd(&harness.socket, "nav", None, cmd).unwrap();
host.send_ask_turn("demo.txt", (0, 0), "", "do a thing", "line zero\nline one")
.unwrap();
assert!(host.is_busy(), "the ask turn is streaming");
let err = host
.send_yield_turn("demo.txt", "line zero\nline one")
.unwrap_err();
assert!(
err.to_string().contains("mid-turn"),
"expected a mid-turn rejection, got: {err}"
);
assert!(host.is_busy(), "the original ask turn is untouched");
drop(host);
}
#[test]
fn host_adds_appends_and_removes_notes_by_id() {
if !is_on_path("python3") {
eprintln!("SKIPPED: python3 not on PATH");
return;
}
let harness = OwnerHarness::start("hello world\nsecond line");
let script = harness._dir.path().join("fake_claude.py");
std::fs::write(&script, FAKE_CLAUDE).unwrap();
let log = harness._dir.path().join("stdin.log");
let mut cmd = Command::new("python3");
cmd.arg(&script).arg(&log).arg("notes");
let host = crate::pair_host::PairHost::spawn_cmd(&harness.socket, "nav", None, cmd).unwrap();
let id_a = host
.add_note("demo.txt", 0, "turn summary")
.expect("demo.txt is served by the owner");
let id_b = host.add_note("demo.txt", 1, "second thought").unwrap();
assert_ne!(id_a, id_b, "every note gets its own id");
let expected = vec![
(id_a, 0, "turn summary".to_string()),
(id_b, 1, "second thought".to_string()),
];
assert_eq!(
settle(&expected, || host.notes_snapshot("demo.txt")),
expected
);
host.append_to_note(id_a, "you: tell me more");
let expected = vec![
(id_a, 0, "turn summary\nyou: tell me more".to_string()),
(id_b, 1, "second thought".to_string()),
];
assert_eq!(
settle(&expected, || host.notes_snapshot("demo.txt")),
expected
);
host.remove_note(id_a);
let expected = vec![(id_b, 1, "second thought".to_string())];
assert_eq!(
settle(&expected, || host.notes_snapshot("demo.txt")),
expected,
"only the ignored note is gone"
);
drop(host);
}
#[test]
fn notes_survive_a_new_turn_on_the_same_file() {
if !is_on_path("python3") {
eprintln!("SKIPPED: python3 not on PATH");
return;
}
let harness = OwnerHarness::start("hello world\nsecond line");
let script = harness._dir.path().join("fake_claude.py");
std::fs::write(&script, FAKE_CLAUDE).unwrap();
let log = harness._dir.path().join("stdin.log");
let mut cmd = Command::new("python3");
cmd.arg(&script).arg(&log).arg("notes");
let mut host =
crate::pair_host::PairHost::spawn_cmd(&harness.socket, "nav", None, cmd).unwrap();
host.send_task("@demo.txt look this over").unwrap();
let deadline = Instant::now() + Duration::from_secs(60);
while !host
.poll()
.iter()
.any(|e| matches!(e, crate::pair_host::PairEvent::TurnDone { .. }))
{
assert!(Instant::now() < deadline, "no TurnDone");
std::thread::sleep(Duration::from_millis(10));
}
let deadline = Instant::now() + Duration::from_secs(60);
let before = loop {
let snap = host.notes_snapshot("demo.txt");
if snap.len() == 1 {
break snap;
}
assert!(
Instant::now() < deadline,
"the scripted note landed: {snap:?}"
);
std::thread::sleep(Duration::from_millis(10));
};
host.send_yield_turn("demo.txt", "hello world\nsecond line")
.unwrap();
assert_eq!(
settle(&before, || host.notes_snapshot("demo.txt")),
before,
"open boxes survive the next turn"
);
drop(host);
}
#[test]
fn compose_reply_turn_carries_note_context_and_buffer() {
let text = compose_reply_turn(
"demo.txt",
3,
"this loop allocates per iteration",
"is that actually hot?",
"a\nb",
);
assert!(
text.contains("replied to your note on demo.txt at line 3 (0-based"),
"names the note's anchor: {text}"
);
assert!(
text.contains("this loop allocates per iteration"),
"quotes the note body: {text}"
);
assert!(
text.contains("is that actually hot?"),
"carries the reply: {text}"
);
assert!(
text.contains("If their reply asks you to make a change, make it with EDIT fences"),
"a reply asking for the change may edit: {text}"
);
assert!(
!text.contains("COMMENT-ONLY") && !text.contains("will be discarded"),
"a reply is not a comment-only turn: {text}"
);
assert!(
text.contains("0|a\n1|b"),
"grounds the model with the numbered buffer: {text}"
);
}
#[test]
fn dropping_the_host_does_not_block_the_ui_thread() {
if !is_on_path("python3") {
eprintln!("SKIPPED: python3 not on PATH");
return;
}
let harness = OwnerHarness::start("line zero\nline one");
let script = harness._dir.path().join("fake_claude.py");
std::fs::write(&script, FAKE_CLAUDE).unwrap();
let log = harness._dir.path().join("stdin.log");
let mut cmd = Command::new("python3");
cmd.arg(&script).arg(&log).arg("linger"); let mut host =
crate::pair_host::PairHost::spawn_cmd(&harness.socket, "nav", None, cmd).unwrap();
host.send_ask_turn("demo.txt", (0, 0), "", "do a thing", "line zero\nline one")
.unwrap();
let deadline = Instant::now() + Duration::from_secs(60);
while !host
.poll()
.iter()
.any(|e| matches!(e, crate::pair_host::PairEvent::TurnDone { .. }))
{
assert!(Instant::now() < deadline, "turn never finished");
std::thread::sleep(Duration::from_millis(10));
}
let t = Instant::now();
drop(host);
assert!(
t.elapsed() < Duration::from_secs(1),
"Drop blocked on the grace-kill for {:?}; teardown must be detached",
t.elapsed()
);
}
#[test]
fn claude_resolves_to_an_absolute_path_off_a_stripped_path() {
assert_eq!(
resolve_claude_in(true, &[]).as_deref(),
Some("claude"),
"an on-PATH claude spawns by bare name"
);
let empty = tempfile::tempdir().unwrap();
assert_eq!(
resolve_claude_in(false, &[empty.path().to_path_buf()]),
None
);
let dir = tempfile::tempdir().unwrap();
let claude = dir.path().join("claude");
std::fs::write(&claude, "#!/bin/sh\n").unwrap();
let got = resolve_claude_in(false, &[dir.path().to_path_buf()]).unwrap();
assert_eq!(got, claude.to_string_lossy());
assert!(
Path::new(&got).is_absolute(),
"GUI launch must get an absolute path, got {got}"
);
}
#[test]
fn system_prompt_teaches_note_fence_and_yield_rules() {
assert!(PAIR_SYSTEM_PROMPT.contains("<<<NOTE <file>:<row>>>>"));
assert!(PAIR_SYSTEM_PROMPT.contains("<<<NOTE demo.txt:4>>>"));
assert!(PAIR_SYSTEM_PROMPT.contains("COMMENT-ONLY"));
assert!(
PAIR_SYSTEM_PROMPT.contains("- A reply turn answers one of your notes"),
"the reply turn kind is taught (#1965)"
);
assert!(PAIR_SYSTEM_PROMPT.contains("N|"));
assert!(PAIR_SYSTEM_PROMPT.contains("0-based row"));
}
#[test]
fn the_navigator_claude_cannot_reach_past_the_workspace() {
let cfg = PairConfig {
socket: PathBuf::from("/nonexistent/relay.sock"),
workspace: std::env::temp_dir(),
name: String::from("claude"),
model: None,
task: None,
provider: Provider::Claude,
};
let cmd = claude_command(&cfg).expect("claude command");
let args: Vec<String> = cmd
.get_args()
.map(|a| a.to_string_lossy().into_owned())
.collect();
let value_of = |flag: &str| {
let at = args
.iter()
.position(|a| a == flag)
.unwrap_or_else(|| panic!("{flag} missing from {args:?}"));
args[at + 1].clone()
};
assert_eq!(value_of("--setting-sources"), "user");
assert_eq!(value_of("--tools"), "Read,Grep,Glob");
assert_eq!(value_of("--permission-mode"), "dontAsk");
let allowed: Vec<String> = value_of("--allowedTools")
.split(',')
.map(|t| t.trim().to_string())
.collect();
assert!(
allowed.iter().all(|t| t.starts_with("mcp__croft-collab__")),
"a bare built-in allow rule matches every path: {allowed:?}"
);
assert!(args.iter().any(|a| a == "--strict-mcp-config"));
}
#[test]
fn compose_ask_turn_numbers_content_and_includes_selection() {
let text = compose_ask_turn(
"src/a.rs",
(3, 5),
"let x = 1;\nlet y = 2;",
"simplify these",
"l0\nl1\nl2\nlet x = 1;\nmid\nlet y = 2;",
);
assert!(text.contains("simplify these"));
assert!(text.contains("lines 3-5"));
assert!(text.contains("0-based"));
assert!(text.contains("--- SELECTED LINES ---"));
assert!(text.contains("let y = 2;"));
assert!(text.contains("0|l0"));
assert!(text.contains("3|let x = 1;"));
let one = compose_ask_turn("src/a.rs", (2, 2), "", "why is this here", "a\nb\nc");
assert!(one.contains("line 2"));
assert!(!one.contains("--- SELECTED LINES ---"));
assert!(one.contains("2|c"));
}
#[test]
fn turns_name_the_gutter_line_beside_the_row() {
let one = compose_ask_turn("src/a.rs", (4, 4), "", "fix this", "a\nb\nc\nd\ne");
assert!(
one.contains("at line 4 (0-based; line 5 in your partner's gutter)"),
"{one}"
);
assert!(
!one.contains("line 4 (0-based)."),
"bare 0-based row: {one}"
);
let range = compose_ask_turn("src/a.rs", (0, 2), "a\nb\nc", "tidy", "a\nb\nc");
assert!(
range.contains("at lines 0-2 (0-based; lines 1-3 in your partner's gutter)"),
"{range}"
);
assert!(
!range.contains("lines 0-2 (0-based)."),
"bare 0-based rows: {range}"
);
let reply = compose_reply_turn("main.py", 4, "a note", "correct this", "a\nb\nc\nd\ne");
assert!(
reply.contains("at line 4 (0-based; line 5 in your partner's gutter)"),
"{reply}"
);
assert!(
!reply.contains("line 4 (0-based)."),
"bare 0-based row: {reply}"
);
assert!(
reply.contains("a NOTE re-anchored to row 4 continues this box"),
"the re-anchor target is a row: {reply}"
);
assert!(
!reply.contains("re-anchoring to line 4"),
"the re-anchor row called a line: {reply}"
);
assert!(
PAIR_SYSTEM_PROMPT.contains("row N is line N+1"),
"the system prompt teaches gutter numbers for prose"
);
}
#[test]
fn system_prompt_numbers_lines_only_by_the_gutter() {
let prompt = system_prompt(&Provider::Local {
base_url: String::new(),
});
for text in prompt.lines() {
for (at, _) in text.match_indices("line") {
let after = &text[at + "line".len()..];
let after = after.strip_prefix('s').unwrap_or(after);
let numbered = after
.strip_prefix(' ')
.is_some_and(|rest| rest.starts_with(|c: char| c.is_ascii_digit()));
if numbered {
assert!(
text[..at].ends_with("gutter "),
"a 0-based row called a line: {text}"
);
}
}
}
assert!(prompt.contains("row 0 of demo.txt, your partner's gutter line 1"));
assert!(prompt.contains("rows 3-4 of src/lib.rs, gutter lines 4-5"));
assert!(prompt.contains("row 4 of demo.txt, gutter line 5"));
assert!(prompt.contains("row 1 (gutter line 2)"));
}
#[test]
fn compose_yield_turn_carries_diff_and_forbids_edits() {
let with_diff = compose_yield_turn(
"src/a.rs",
"line one\nline 2\n",
Some("@@ -1,2 +1,2 @@\n line one\n-line two\n+line 2\n"),
);
assert!(with_diff.contains("COMMENT-ONLY"));
assert!(with_diff.contains("--- CHANGES SINCE YOUR LAST LOOK ---"));
assert!(with_diff.contains("+line 2"));
assert!(with_diff.contains("0|line one"));
let first_look = compose_yield_turn("src/a.rs", "just this\n", None);
assert!(first_look.contains("COMMENT-ONLY"));
assert!(!first_look.contains("--- CHANGES SINCE YOUR LAST LOOK ---"));
}
#[test]
fn yield_turn_suppresses_edits() {
if !is_on_path("python3") {
eprintln!("SKIPPED: python3 not on PATH");
return;
}
let harness = OwnerHarness::start("hello world");
let script = harness._dir.path().join("fake_claude.py");
std::fs::write(&script, FAKE_CLAUDE).unwrap();
let log = harness._dir.path().join("stdin.log");
let mut cmd = Command::new("python3");
cmd.arg(&script).arg(&log).arg("stream"); let mut host =
crate::pair_host::PairHost::spawn_cmd(&harness.socket, "navigator", None, cmd).unwrap();
host.send_yield_turn("demo.txt", "hello world").unwrap();
let deadline = Instant::now() + Duration::from_secs(60);
let mut events: Vec<crate::pair_host::PairEvent> = Vec::new();
while !events
.iter()
.any(|e| matches!(e, crate::pair_host::PairEvent::TurnDone { .. }))
{
assert!(Instant::now() < deadline, "no TurnDone; saw {events:?}");
events.extend(host.poll());
std::thread::sleep(Duration::from_millis(10));
}
assert_eq!(harness.remote_edit_count(), 0, "edit must be suppressed");
assert!(
!events.iter().any(|e| matches!(
e,
crate::pair_host::PairEvent::Commentary(c)
if c.contains("suppressed") || c.contains("[claude]")
)),
"diagnostics must not become comment boxes; saw {events:?}"
);
let wait_output = |needle: &str| {
let deadline = Instant::now() + Duration::from_secs(5);
loop {
let lines = crate::output::snapshot("Navigator").unwrap_or_default();
if lines.iter().any(|l| l.text.contains(needle)) {
return;
}
assert!(
Instant::now() < deadline,
"OUTPUT never carried {needle:?}: {lines:?}"
);
std::thread::sleep(Duration::from_millis(10));
}
};
wait_output("suppressed");
wait_output("[claude] mcp server starting");
drop(host);
}
fn wait_turn_done(host: &mut crate::pair_host::PairHost) -> Vec<crate::pair_host::PairEvent> {
let deadline = Instant::now() + Duration::from_secs(60);
let mut events = Vec::new();
while !events
.iter()
.any(|e| matches!(e, crate::pair_host::PairEvent::TurnDone { .. }))
{
assert!(Instant::now() < deadline, "no TurnDone; saw {events:?}");
events.extend(host.poll());
std::thread::sleep(Duration::from_millis(10));
}
events
}
#[test]
fn a_reply_turn_can_edit_the_buffer() {
if !is_on_path("python3") {
eprintln!("SKIPPED: python3 not on PATH");
return;
}
let harness = OwnerHarness::start("hello world");
let script = harness._dir.path().join("fake_claude.py");
std::fs::write(&script, FAKE_CLAUDE).unwrap();
let log = harness._dir.path().join("stdin.log");
let mut cmd = Command::new("python3");
cmd.arg(&script).arg(&log).arg("stream"); let mut host =
crate::pair_host::PairHost::spawn_cmd(&harness.socket, "navigator", None, cmd).unwrap();
host.send_reply_turn("demo.txt", 0, "rename world", "correct this", "hello world")
.unwrap();
wait_turn_done(&mut host);
harness.wait_until("the reply's edit on the owner", |h| {
h.doc().as_deref() == Some("hello streamed edit")
});
drop(host);
}
#[test]
fn a_yield_after_a_reply_still_discards_edits() {
if !is_on_path("python3") {
eprintln!("SKIPPED: python3 not on PATH");
return;
}
let harness = OwnerHarness::start("hello world");
let script = harness._dir.path().join("fake_claude.py");
std::fs::write(&script, FAKE_CLAUDE).unwrap();
let log = harness._dir.path().join("stdin.log");
let mut cmd = Command::new("python3");
cmd.arg(&script).arg(&log).arg("repeat"); let mut host =
crate::pair_host::PairHost::spawn_cmd(&harness.socket, "navigator", None, cmd).unwrap();
host.send_reply_turn("demo.txt", 0, "a note", "correct this", "hello world")
.unwrap();
wait_turn_done(&mut host);
harness.wait_until("reply 1's edit on the owner", |h| {
h.doc().as_deref() == Some("1hello world")
});
host.send_yield_turn("demo.txt", "1hello world").unwrap();
wait_turn_done(&mut host);
let seen = std::fs::read_to_string(&log).unwrap();
assert!(
seen.contains("yielded the turn"),
"the yield turn never reached the model: {seen}"
);
host.send_reply_turn("demo.txt", 0, "a note", "and again", "1hello world")
.unwrap();
wait_turn_done(&mut host);
harness.wait_until("reply 3's edit on the owner", |h| {
h.doc().is_some_and(|d| d.starts_with('3'))
});
assert_eq!(
harness.doc().as_deref(),
Some("31hello world"),
"the yield's edit must be suppressed"
);
drop(host);
}
#[test]
fn note_offsets_shift_on_remote_edit() {
let mut notes = vec![
Note {
id: 1,
file: "a.rs".into(),
offset: 10,
body: "n1".into(),
},
Note {
id: 2,
file: "b.rs".into(),
offset: 10,
body: "n2".into(),
},
];
let spans = [
ResolvedSpan {
at: 0,
deleted: 0,
inserted: "abc".into(),
},
ResolvedSpan {
at: 40,
deleted: 2,
inserted: String::new(),
},
];
shift_notes(&mut notes, "a.rs", &spans);
assert_eq!(notes[0].offset, 13);
assert_eq!(notes[1].offset, 10, "other file's note must not move");
}
#[test]
fn an_aborted_edit_un_shifts_the_notes_it_moved() {
let harness = OwnerHarness::start("hello world");
let (state, stop, pump) = pumped_state(&harness);
{
let mut st = state.lock().unwrap();
st.begin_turn("demo.txt", "hello world", false);
for offset in [8usize, 0, 2] {
let id = st.take_note_id();
st.notes.push(Note {
id,
file: String::from("demo.txt"),
offset,
body: String::from("remark"),
});
}
}
apply_fence_event(
&state,
FenceEvent::EditStart {
file: String::from("demo.txt"),
start: (0, 0),
end: (0, 5),
},
);
apply_fence_event(
&state,
FenceEvent::EditBody(String::from("hi there friend")),
);
apply_fence_event(&state, FenceEvent::EditAbort);
let offsets: Vec<usize> = state
.lock()
.unwrap()
.notes
.iter()
.map(|n| n.offset)
.collect();
assert_eq!(
offsets,
vec![8, 0, 2],
"the revert must restore every note anchor the edit had moved"
);
stop.store(true, Ordering::Relaxed);
pump.join().unwrap();
}
#[test]
fn note_anchor_row_clamps_past_eof() {
let lines: Vec<String> = ["ab", "cd"].iter().map(|s| s.to_string()).collect();
assert_eq!(note_offset(&lines, 0), 0);
assert_eq!(note_offset(&lines, 1), 3);
assert_eq!(note_offset(&lines, 99), 3);
}
#[test]
fn compose_turn_always_names_target_file() {
let live = compose_turn_text("fix the error", Some("src/a.rs"), Some("body"));
assert!(live.contains("--- CURRENT BUFFER (src/a.rs) ---"));
assert!(live.contains("body"));
let dead = compose_turn_text("fix the error", Some("src/a.rs"), None);
assert!(
dead.contains("src/a.rs"),
"file must be named without a live buffer: {dead}"
);
assert!(dead.contains("fix the error"));
let noted = with_pending_note(Some("stream was cancelled".into()), "task".into());
assert!(noted.starts_with("stream was cancelled"));
assert!(noted.contains("task"));
}