use super::*;
pub(super) const LIVE_TIMEOUT: Duration = Duration::from_secs(4);
pub(super) struct StreamRegion {
file: String,
start: usize,
anchor: usize,
original: String,
displaced: Vec<(u64, usize)>,
}
pub(super) fn wait_live(state: &Mutex<PairState>, file: &str) -> bool {
let deadline = Instant::now() + LIVE_TIMEOUT;
loop {
let st = state.lock().unwrap();
if st.session.is_live(file) {
return true;
}
if !st.session.is_bootstrapping(file) || Instant::now() >= deadline {
return false;
}
drop(st);
std::thread::sleep(Duration::from_millis(20));
}
}
pub(super) fn apply_fence_event(state: &Mutex<PairState>, event: FenceEvent) {
match event {
FenceEvent::Commentary(text) => {
say(state, &text);
}
FenceEvent::EditStart { file, start, end } => {
{
let mut st = state.lock().unwrap();
if st.cancelled {
st.discarding = true;
return;
}
if st.comment_only {
st.discarding = true;
drop(st);
diag(
state,
crate::output::OutputLevel::Warn,
"[pair] edit suppressed: this is a yielded, comment-only turn",
);
return;
}
st.target_file = Some(file.clone());
st.session.request_file(&file);
}
if wait_live(state, &file) {
let mut st = state.lock().unwrap();
open_region(&mut st, &file, start, end);
} else {
state.lock().unwrap().discarding = true;
diag(
state,
crate::output::OutputLevel::Warn,
&format!(
"[pair] no live croft session serves {file}; edit dropped \
(start croft in this workspace first)"
),
);
}
}
FenceEvent::EditBody(delta) => {
let mut st = state.lock().unwrap();
if st.cancelled || st.discarding {
return;
}
let Some((file, anchor)) = st.region.as_ref().map(|r| (r.file.clone(), r.anchor))
else {
return;
};
let Some(doc) = st.session.doc_text(&file).map(str::to_string) else {
return;
};
let anchor = anchor.min(doc.len());
let new = format!("{}{}{}", &doc[..anchor], delta, &doc[anchor..]);
st.session.local_change(&file, &new);
let span = ResolvedSpan {
at: anchor,
deleted: 0,
inserted: delta.clone(),
};
shift_notes(&mut st.notes, &file, std::slice::from_ref(&span));
let next = anchor + delta.len();
if let Some(r) = st.region.as_mut() {
r.anchor = next;
}
let lines: Vec<String> = new.split('\n').map(String::from).collect();
let (row, col) = position(&lines, next);
st.caret_now(&file, row, col);
}
FenceEvent::EditEnd => {
let mut st = state.lock().unwrap();
st.discarding = false;
if st.cancelled {
return; }
if let Some(r) = st.region.take() {
st.session.send_stream_state(&r.file, false);
}
}
FenceEvent::EditAbort => {
let mut st = state.lock().unwrap();
st.discarding = false;
if st.cancelled {
st.region = None;
return;
}
revert_region(&mut st);
}
FenceEvent::NoteStart { file, row } => {
let mut st = state.lock().unwrap();
if st.cancelled {
return;
}
st.session.request_file(&file);
st.note_in_flight = Some((file, row, String::new()));
}
FenceEvent::NoteBody(delta) => {
let mut st = state.lock().unwrap();
if let Some((_, _, body)) = st.note_in_flight.as_mut() {
body.push_str(&delta);
}
}
FenceEvent::NoteEnd => {
let pending = {
let mut st = state.lock().unwrap();
let pending = st.note_in_flight.take();
if st.cancelled { None } else { pending }
};
let Some((file, row, body)) = pending else {
return;
};
if !wait_live(state, &file) {
diag(
state,
crate::output::OutputLevel::Warn,
&format!(
"[pair] no live croft session serves {file}; note dropped \
(start croft in this workspace first)"
),
);
return;
}
let mut st = state.lock().unwrap();
let Some(lines) = st.doc_lines(&file) else {
drop(st);
diag(
state,
crate::output::OutputLevel::Warn,
&format!(
"[pair] no live croft session serves {file}; note dropped \
(start croft in this workspace first)"
),
);
return;
};
let offset = note_offset(&lines, row);
let row_now = position(&lines, offset).0;
st.caret_now(&file, row_now, 0);
let id = st.take_note_id();
let sink = st.events.clone();
st.notes.push(Note {
id,
file: file.clone(),
offset,
body: body.clone(),
});
match sink {
Some(tx) => {
let _ = tx.send(crate::pair_host::PairEvent::NoteAdded {
file,
row: row_now,
body,
});
}
None => {
drop(st);
say(state, &format!("[note {file}:{}] {body}\n", row_now + 1));
}
}
}
FenceEvent::NoteAbort => {
state.lock().unwrap().note_in_flight = None;
}
}
}
pub(super) fn open_region(
st: &mut PairState,
file: &str,
start: (usize, usize),
end: (usize, usize),
) {
let Some(doc) = st.session.doc_text(file).map(str::to_string) else {
st.discarding = true;
return;
};
let lines: Vec<String> = doc.split('\n').map(String::from).collect();
let (s, e) = range_bytes(&lines, start, end);
let (s, e) = (s.min(doc.len()), e.min(doc.len()));
if s > e {
st.discarding = true;
crate::output::push(
"Navigator",
crate::output::OutputLevel::Warn,
"fence range is inverted; edit dropped",
);
return;
}
let original = doc[s..e].to_string();
let new = format!("{}{}", &doc[..s], &doc[e..]);
st.session.send_stream_state(file, true);
st.session.local_change(file, &new);
let displaced: Vec<(u64, usize)> = st
.notes
.iter()
.filter(|n| n.file == file && (s..e).contains(&n.offset))
.map(|n| (n.id, n.offset - s))
.collect();
let span = ResolvedSpan {
at: s,
deleted: e - s,
inserted: String::new(),
};
shift_notes(&mut st.notes, file, std::slice::from_ref(&span));
st.region = Some(StreamRegion {
file: file.to_string(),
start: s,
anchor: s,
original,
displaced,
});
st.discarding = false;
let lines: Vec<String> = new.split('\n').map(String::from).collect();
let (row, col) = position(&lines, s);
st.caret_now(file, row, col);
}
pub(super) fn revert_region(st: &mut PairState) {
let Some(r) = st.region.take() else {
return;
};
if let Some(doc) = st.session.doc_text(&r.file).map(str::to_string) {
let start = r.start.min(doc.len());
let anchor = r.anchor.clamp(start, doc.len());
let new = format!("{}{}{}", &doc[..start], r.original, &doc[anchor..]);
st.session.local_change(&r.file, &new);
let span = ResolvedSpan {
at: start,
deleted: anchor - start,
inserted: r.original.clone(),
};
shift_notes(&mut st.notes, &r.file, std::slice::from_ref(&span));
for (id, delta) in &r.displaced {
if let Some(n) = st
.notes
.iter_mut()
.find(|n| n.id == *id && n.file == r.file)
{
n.offset = start + delta;
}
}
}
st.session.send_stream_state(&r.file, false);
}
pub(super) fn pump_session(state: &Mutex<PairState>, sink: &TurnSink, req_id: &AtomicU64) {
let mut interrupt = false;
{
let mut st = state.lock().unwrap();
let events = st.session.poll(|_| None);
for event in events {
match event {
CollabEvent::RemoteEdit { file, spans, .. } => {
if let Some(r) = st.region.as_mut()
&& r.file == file
{
for span in &spans {
r.start = shift_offset(r.start, span);
r.anchor = shift_offset(r.anchor, span);
}
}
shift_notes(&mut st.notes, &file, &spans);
}
CollabEvent::StreamCancel => {
if !st.turn_active || st.cancelled {
continue;
}
st.cancelled = true;
st.pending_note = Some(
"Note: your previous streamed edit was cancelled and reverted by a \
participant. Stop that approach and ask what they want instead."
.to_string(),
);
revert_region(&mut st);
interrupt = st.can_interrupt;
match st.events.clone() {
Some(tx) => {
let _ = tx.send(crate::pair_host::PairEvent::Commentary(
"[stream cancelled by a participant; reverted]".to_string(),
));
}
None => println!("\n[stream cancelled by a participant; reverted]"),
}
}
_ => {}
}
}
st.resolve_pending_caret();
}
if interrupt {
let TurnSink::Claude(writer) = sink else {
return; };
if let Some(w) = writer.lock().unwrap().as_mut() {
let id = req_id.fetch_add(1, Ordering::Relaxed);
let msg = json!({
"type": "control_request",
"request_id": format!("croft-pair-{id}"),
"request": { "subtype": "interrupt" },
});
let _ = writeln!(w, "{msg}");
let _ = w.flush();
}
}
}