use super::*;
#[derive(Clone)]
pub(crate) enum TurnSink {
Claude(Arc<Mutex<Option<ChildStdin>>>),
Local(Sender<String>),
}
impl TurnSink {
pub(super) fn send_user(&self, content: &str) -> Result<()> {
match self {
TurnSink::Claude(writer) => {
let msg = json!({
"type": "user",
"message": { "role": "user", "content": content },
});
let mut w = writer.lock().unwrap();
let w = w.as_mut().context("claude stdin already closed")?;
writeln!(w, "{msg}").context("writing user turn to claude")?;
w.flush().context("flushing claude stdin")
}
TurnSink::Local(turns) => {
anyhow::ensure!(
turns.send(content.to_string()).is_ok(),
"the local turn worker is gone"
);
Ok(())
}
}
}
}
pub(super) fn parse_task_line(line: &str) -> (Option<String>, String) {
let Some(rest) = line.strip_prefix('@') else {
return (None, line.to_string());
};
match rest.split_once(char::is_whitespace) {
Some((file, task)) => (Some(file.to_string()), task.trim().to_string()),
None => (Some(rest.to_string()), String::new()),
}
}
pub(super) fn compose_turn_text(task: &str, file: Option<&str>, buffer: Option<&str>) -> String {
let mut content = String::new();
content.push_str(task);
match (file, buffer) {
(Some(file), Some(text)) => {
content.push_str(&format!(
"\n\n--- CURRENT BUFFER ({file}) ---\n{text}\n--- END BUFFER ---"
));
}
(Some(file), None) => {
content.push_str(&format!(
"\n\nTarget file: {file} (its buffer is not shared yet; \
read it with the collab tools before editing)"
));
}
(None, _) => {}
}
content
}
pub(super) fn numbered(content: &str) -> String {
content
.split('\n')
.enumerate()
.map(|(i, l)| format!("{i}|{l}"))
.collect::<Vec<_>>()
.join("\n")
}
pub(crate) fn compose_ask_turn(
file: &str,
range: (usize, usize),
selection: &str,
instruction: &str,
content: &str,
) -> String {
let mut text = String::new();
let (s, e) = range;
if s == e {
text.push_str(&format!(
"Your partner invoked you on {file} at line {s} (0-based; line {} in \
your partner's gutter).\n",
s + 1
));
} else {
text.push_str(&format!(
"Your partner invoked you on {file} at lines {s}-{e} (0-based; lines \
{}-{} in your partner's gutter).\n",
s + 1,
e + 1
));
}
if !selection.is_empty() {
text.push_str(&format!(
"--- SELECTED LINES ---\n{selection}\n--- END SELECTED ---\n"
));
}
text.push_str(&format!("\nTask: {instruction}\n"));
text.push_str(&format!(
"\n--- CURRENT BUFFER ({file}, each line prefixed with its 0-based \
number and '|') ---\n{}\n--- END BUFFER ---",
numbered(content)
));
text
}
pub(crate) fn compose_yield_turn(file: &str, content: &str, diff: Option<&str>) -> String {
let mut text = String::from(
"Your partner yielded the turn: review the file below and speak \
through NOTE fences anchored to the lines you mean. This turn is \
COMMENT-ONLY: any EDIT fence will be discarded by the host. \
Propose changes in your notes and wait to be asked.\n",
);
if let Some(diff) = diff {
text.push_str(&format!(
"\n--- CHANGES SINCE YOUR LAST LOOK ---\n{diff}\n--- END CHANGES ---\n"
));
}
text.push_str(&format!(
"\n--- CURRENT BUFFER ({file}, each line prefixed with its 0-based \
number and '|') ---\n{}\n--- END BUFFER ---",
numbered(content)
));
text
}
pub(crate) fn compose_reply_turn(
file: &str,
row: usize,
note_body: &str,
reply: &str,
content: &str,
) -> String {
format!(
"Your partner replied to your note on {file} at line {row} (0-based; \
line {gutter} in your partner's gutter).\n\
--- YOUR NOTE ---\n{note_body}\n--- END NOTE ---\n\
--- THEIR REPLY ---\n{reply}\n--- END REPLY ---\n\
If their reply asks you to make a change, make it with EDIT fences. \
Otherwise answer with NOTE fences (anchor follow-ups to the lines \
you mean; a NOTE re-anchored to row {row} continues this box).\n\
\n--- CURRENT BUFFER ({file}, each line prefixed with its 0-based \
number and '|') ---\n{}\n--- END BUFFER ---",
numbered(content),
gutter = row + 1,
)
}
pub(crate) fn send_turn(state: &Mutex<PairState>, sink: &TurnSink, line: &str) -> Result<()> {
let (file, task) = parse_task_line(line);
if let Some(file) = &file {
let mut st = state.lock().unwrap();
st.target_file = Some(file.clone());
st.session.request_file(file);
drop(st);
let deadline = Instant::now() + LIVE_TIMEOUT;
while Instant::now() < deadline {
let st = state.lock().unwrap();
if st.session.is_live(file) || !st.session.is_bootstrapping(file) {
break;
}
drop(st);
std::thread::sleep(Duration::from_millis(20));
}
}
let (file, buffer) = {
let st = state.lock().unwrap();
let file = st.target_file.clone();
let buffer = file
.as_deref()
.and_then(|f| st.session.doc_text(f))
.map(str::to_string);
(file, buffer)
};
if file.is_some() && buffer.is_none() {
diag(
state,
crate::output::OutputLevel::Warn,
"[pair] target file is not live (no owner answered); \
sending the task with the file name only",
);
}
let body = compose_turn_text(&task, file.as_deref(), buffer.as_deref());
write_user_turn(state, sink, body)
}
pub(crate) fn write_user_turn(
state: &Mutex<PairState>,
sink: &TurnSink,
body: String,
) -> Result<()> {
let (content, note) = {
let mut st = state.lock().unwrap();
let note = st.pending_note.take();
st.turn_active = true;
(with_pending_note(note.clone(), body), note)
};
let sent = sink.send_user(&content);
if sent.is_err() {
let mut st = state.lock().unwrap();
st.turn_active = false;
if st.pending_note.is_none() {
st.pending_note = note;
}
}
sent
}
pub(super) fn with_pending_note(note: Option<String>, body: String) -> String {
match note {
Some(n) => format!("{n}\n\n{body}"),
None => body,
}
}