1use std::env;
9use std::fs;
10use std::io::{self, BufRead, BufReader, ErrorKind, Write};
11#[cfg(unix)]
12use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
13#[cfg(unix)]
14use std::os::unix::net::{UnixListener, UnixStream};
15use std::path::{Path, PathBuf};
16use std::sync::mpsc::{Receiver, Sender, channel};
17use std::sync::{Arc, Mutex};
18use std::thread;
19use std::time::Duration;
20
21use cellix_review::Comment;
22use serde::{Deserialize, Serialize};
23
24pub mod context;
25pub mod hook;
26pub mod ide;
27mod loopback;
28pub mod team;
29
30const ANSWER_TIME: Duration = Duration::from_secs(2);
33const REPLY_TIME: Duration = Duration::from_secs(5);
36const PROOF_TIME: Duration = Duration::from_secs(2);
38
39pub type SharedComments = Arc<Mutex<Vec<Comment>>>;
41
42#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
43pub enum AgentState {
44 Working,
45 NeedsYou,
46 Idle,
47 Ended,
48}
49
50#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
52pub struct AgentEvent {
53 pub session: String,
54 pub agent: String,
55 pub state: AgentState,
56 pub detail: String,
57 pub folder: String,
58 #[serde(default)]
61 pub pid: Option<u32>,
62 #[serde(default, skip_serializing_if = "String::is_empty")]
64 pub transcript: String,
65 #[serde(default, skip_serializing_if = "String::is_empty")]
67 pub name: String,
68 #[serde(default, skip_serializing_if = "String::is_empty")]
71 pub prompt: String,
72}
73
74#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
76pub struct TestRun {
77 pub command: String,
78 pub passed: bool,
79 pub output: String,
80}
81
82#[derive(Clone, Debug, PartialEq, Eq)]
84pub enum Decision {
85 Approve(Option<String>),
87 SendBack(String),
88}
89
90#[derive(Debug)]
92pub enum Request {
93 Open {
96 path: PathBuf,
97 opened: Sender<String>,
98 },
99 CommentsTaken,
101 Agent(AgentEvent),
102 Test(TestRun),
103 Pane(String),
105 Reply {
107 id: u32,
108 author: String,
109 text: String,
110 found: Sender<bool>,
112 },
113 Suggest {
115 file: String,
116 line: usize,
117 kind: String,
118 quote: String,
119 text: String,
120 author: String,
121 made: Sender<u32>,
122 },
123 Threads(Sender<String>),
125 TakeThreads(Sender<String>),
127 Waiting(Sender<String>),
130 Alone {
134 key: u64,
135 reply: Sender<bool>,
136 },
137 Plan {
139 path: PathBuf,
140 reply: Sender<Decision>,
141 },
142 Team {
145 asked: team::Asked,
146 reply: Sender<String>,
147 },
148}
149
150fn fnv(text: &str) -> u64 {
151 text.bytes().fold(0xcbf29ce484222325, |hash, byte| {
152 (hash ^ byte as u64).wrapping_mul(0x100000001b3)
153 })
154}
155
156pub fn prompt_key(prompt: &str) -> u64 {
159 fnv(&prompt.split_whitespace().collect::<Vec<_>>().join(" "))
160}
161
162#[derive(Clone, Copy, Debug, PartialEq, Eq)]
164pub enum Transport {
165 #[cfg(unix)]
167 Unix,
168 Loopback,
170}
171
172impl Transport {
173 #[cfg(unix)]
175 pub const NATIVE: Self = Self::Unix;
176 #[cfg(not(unix))]
177 pub const NATIVE: Self = Self::Loopback;
178}
179
180pub(crate) fn new_token() -> io::Result<String> {
182 let mut bytes = [0u8; 16];
183 #[cfg(unix)]
184 io::Read::read_exact(&mut fs::File::open("/dev/urandom")?, &mut bytes)?;
185 #[cfg(not(unix))]
186 getrandom::fill(&mut bytes).map_err(io::Error::other)?;
187 Ok(bytes.iter().map(|b| format!("{b:02x}")).collect())
188}
189
190#[cfg(unix)]
193fn sockets_folder() -> PathBuf {
194 let uid = unsafe { libc::getuid() };
196 env::temp_dir().join(format!("cellix-{uid}"))
197}
198
199#[cfg(not(unix))]
200fn sockets_folder() -> PathBuf {
201 windows_sockets_folder(|name| env::var(name).ok())
202}
203
204#[cfg_attr(unix, allow(dead_code))]
207fn windows_sockets_folder(var: impl Fn(&str) -> Option<String>) -> PathBuf {
208 let local = var("LOCALAPPDATA")
209 .filter(|v| !v.is_empty())
210 .map(PathBuf::from);
211 local
212 .or_else(|| {
213 Some(
214 PathBuf::from(var("USERPROFILE")?)
215 .join("AppData")
216 .join("Local"),
217 )
218 })
219 .unwrap_or_else(env::temp_dir)
220 .join("cellix")
221 .join("sockets")
222}
223
224pub fn socket_path(root: &Path) -> PathBuf {
226 let root = dunce::simplified(root);
228 sockets_folder().join(format!("{:016x}.sock", fnv(&root.to_string_lossy())))
229}
230
231fn unescape(text: &str) -> String {
233 let mut out = String::with_capacity(text.len());
234 let mut chars = text.chars();
235 while let Some(c) = chars.next() {
236 match (c, chars.clone().next()) {
237 ('\\', Some('n')) => {
238 out.push('\n');
239 chars.next();
240 }
241 ('\\', Some('\\')) => {
242 out.push('\\');
243 chars.next();
244 }
245 (c, _) => out.push(c),
246 }
247 }
248 out
249}
250
251pub fn escape(text: &str) -> String {
253 text.replace('\\', "\\\\").replace('\n', "\\n")
254}
255
256static WAKE: std::sync::OnceLock<fn()> = std::sync::OnceLock::new();
259
260pub fn wake_with(wake: fn()) {
262 let _ = WAKE.set(wake);
263}
264
265pub(crate) fn wake() {
266 if let Some(wake) = WAKE.get() {
267 wake();
268 }
269}
270
271fn ask(requests: &Sender<Request>, request: Request) {
273 if requests.send(request).is_ok() {
274 wake();
275 }
276}
277
278fn answer(line: &str, comments: &SharedComments, requests: &Sender<Request>) -> io::Result<String> {
279 let mut parts = line.trim().splitn(2, ' ');
280 let list = |clear: bool| -> io::Result<String> {
281 let mut shared = comments.lock().map_err(|_| io::Error::other("poisoned"))?;
282 let json = serde_json::to_string(&*shared)?;
283 if clear {
284 shared.clear();
285 }
286 Ok(json)
287 };
288 match (parts.next(), parts.next()) {
289 (Some("comments"), None) => list(false),
290 (Some("take"), None) => {
291 let json = list(true)?;
292 if json != "[]" {
294 ask(requests, Request::CommentsTaken);
295 }
296 Ok(json)
297 }
298 (Some("open"), Some(path)) => {
299 let (opened, answer) = channel();
300 let path = PathBuf::from(path);
301 ask(requests, Request::Open { path, opened });
302 Ok(answer
304 .recv_timeout(ANSWER_TIME)
305 .unwrap_or_else(|_| "ok".to_string()))
306 }
307 (Some("threads"), None) => {
308 let (reply, threads) = channel();
309 ask(requests, Request::Threads(reply));
310 Ok(threads
311 .recv_timeout(ANSWER_TIME)
312 .unwrap_or_else(|_| "[]".to_string()))
313 }
314 (Some("waiting"), None) => {
317 let (reply, waiting) = channel();
318 ask(requests, Request::Waiting(reply));
319 Ok(waiting
320 .recv_timeout(ANSWER_TIME)
321 .unwrap_or_else(|_| "[]".to_string()))
322 }
323 (Some("take-threads"), None) => {
324 let (reply, threads) = channel();
325 ask(requests, Request::TakeThreads(reply));
326 Ok(threads
327 .recv_timeout(ANSWER_TIME)
328 .unwrap_or_else(|_| "[]".to_string()))
329 }
330 (Some("alone"), Some(key)) => {
332 let Ok(key) = u64::from_str_radix(key.trim(), 16) else {
333 return Ok("error: alone needs a prompt's key".into());
334 };
335 let (reply, alone) = channel();
336 ask(requests, Request::Alone { key, reply });
337 Ok(match alone.recv_timeout(ANSWER_TIME) {
338 Ok(true) => "yes".to_string(),
339 _ => "no".to_string(),
340 })
341 }
342 (Some("reply"), Some(rest)) => {
343 let Some((head, text)) = rest.split_once('\t') else {
344 return Ok("error: reply needs an id, an author and text".into());
345 };
346 let (id, author) = head.split_once(' ').unwrap_or((head, "Agent"));
347 let Ok(id) = id.parse() else {
348 return Ok("error: reply needs a comment's number".into());
349 };
350 let author: String = author.chars().filter(|c| !c.is_control()).collect();
353 let author = author.trim();
354 if author.is_empty() || author.eq_ignore_ascii_case(cellix_review::YOU) {
355 return Ok(format!(
356 "error: an agent can't reply as {}",
357 cellix_review::YOU
358 ));
359 }
360 let (author, text) = (author.to_string(), unescape(text));
361 let (found, answer) = channel();
362 ask(
363 requests,
364 Request::Reply {
365 id,
366 author,
367 text,
368 found,
369 },
370 );
371 Ok(match answer.recv_timeout(ANSWER_TIME) {
374 Ok(true) => "ok".to_string(),
375 Ok(false) => format!("error: there's no comment {id}"),
376 Err(_) => format!(
377 "error: Cellix was too busy to answer in time. Your reply goes under \
378 comment {id} when it gets to it, if there's such a comment, so don't send \
379 it again"
380 ),
381 })
382 }
383 (Some("suggest"), Some(json)) => {
384 let value: serde_json::Value = serde_json::from_str(json)?;
385 let field = |name: &str| value[name].as_str().unwrap_or_default().to_string();
386 let (made, answer) = channel();
387 ask(
388 requests,
389 Request::Suggest {
390 file: field("file"),
391 line: value["line"].as_u64().unwrap_or(1) as usize,
392 kind: field("kind"),
393 quote: field("quote"),
394 text: field("text"),
395 author: field("author"),
396 made,
397 },
398 );
399 Ok(match answer.recv_timeout(ANSWER_TIME) {
400 Ok(id) => format!("ok {id}"),
401 Err(_) => "error: Cellix didn't take the suggestion".to_string(),
402 })
403 }
404 (Some("pane"), Some(json)) => {
405 ask(requests, Request::Pane(json.to_string()));
406 Ok("ok".into())
407 }
408 (Some("event"), Some(json)) => {
409 ask(requests, Request::Agent(serde_json::from_str(json)?));
410 Ok("ok".into())
411 }
412 (Some("test"), Some(json)) => {
413 ask(requests, Request::Test(serde_json::from_str(json)?));
414 Ok("ok".into())
415 }
416 (Some("agent"), Some(json)) => {
417 let asked: team::Asked = serde_json::from_str(json)?;
418 let (reply, answered) = channel();
419 ask(requests, Request::Team { asked, reply });
420 Ok(answered.recv().unwrap_or_else(|_| {
422 team::Answer::fail(team::code::FAILED, "Cellix closed before it answered").line()
423 }))
424 }
425 (Some("plan"), Some(path)) => {
426 let (reply, decision) = channel();
427 let path = PathBuf::from(path);
428 ask(requests, Request::Plan { path, reply });
429 Ok(match decision.recv() {
431 Ok(Decision::Approve(None)) => "approve".to_string(),
432 Ok(Decision::Approve(Some(text))) => {
433 format!("approve {}", serde_json::to_string(&text)?)
434 }
435 Ok(Decision::SendBack(text)) => {
436 format!("send-back {}", serde_json::to_string(&text)?)
437 }
438 Err(_) => "pass".to_string(),
439 })
440 }
441 _ => Ok("error: unknown request".into()),
442 }
443}
444
445fn serve(
446 mut reader: impl BufRead,
447 mut stream: impl Write,
448 comments: &SharedComments,
449 requests: &Sender<Request>,
450) -> io::Result<()> {
451 let mut line = String::new();
452 reader.read_line(&mut line)?;
453 writeln!(stream, "{}", answer(&line, comments, requests)?)
454}
455
456pub struct Server {
458 path: PathBuf,
459 owner: Owner,
460 pub requests: Receiver<Request>,
461}
462
463#[derive(Clone)]
465enum Owner {
466 #[cfg(unix)]
468 Socket(Stamp),
469 Note(loopback::Note),
470}
471
472#[cfg(unix)]
475type Stamp = (u64, i64, i64);
476
477#[cfg(unix)]
478fn stamp(meta: &fs::Metadata) -> Stamp {
479 use std::os::unix::fs::MetadataExt;
480 (meta.ino(), meta.ctime(), meta.ctime_nsec())
481}
482
483#[derive(Clone)]
487pub struct Leftover {
488 path: PathBuf,
489 owner: Owner,
490}
491
492impl Leftover {
493 fn owned(&self) -> bool {
495 match &self.owner {
496 #[cfg(unix)]
497 Owner::Socket(made) => {
498 fs::symlink_metadata(&self.path).is_ok_and(|m| stamp(&m) == *made)
499 }
500 Owner::Note(note) => note.is_at(&self.path),
501 }
502 }
503
504 pub fn remove(&self) {
506 if self.owned() {
507 let _ = fs::remove_file(&self.path);
508 let _ = fs::remove_dir_all(self.path.with_extension(""));
509 }
510 }
511}
512
513impl Server {
514 pub fn leftover(&self) -> Leftover {
516 Leftover {
517 path: self.path.clone(),
518 owner: self.owner.clone(),
519 }
520 }
521
522 pub fn lost(&self) -> bool {
525 !self.leftover().owned()
526 }
527}
528
529impl Drop for Server {
530 fn drop(&mut self) {
531 self.leftover().remove();
534 }
535}
536
537fn private_folder(dir: &Path) -> io::Result<()> {
539 #[cfg(unix)]
540 {
541 fs::DirBuilder::new()
542 .recursive(true)
543 .mode(0o700)
544 .create(dir)?;
545 fs::set_permissions(dir, fs::Permissions::from_mode(0o700))?;
546 check_private(dir)
547 }
548 #[cfg(not(unix))]
550 fs::DirBuilder::new().recursive(true).create(dir)
551}
552
553#[cfg(unix)]
558fn check_private(dir: &Path) -> io::Result<()> {
559 let meta = fs::symlink_metadata(dir)?;
560 let uid = unsafe { libc::getuid() };
562 if owned_privately(&meta, uid) {
563 Ok(())
564 } else {
565 Err(io::Error::new(
566 ErrorKind::PermissionDenied,
567 format!(
568 "{} belongs to someone else or others can enter it, so it isn't used",
569 dir.display()
570 ),
571 ))
572 }
573}
574
575#[cfg(unix)]
577fn owned_privately(meta: &fs::Metadata, uid: u32) -> bool {
578 use std::os::unix::fs::MetadataExt;
579 meta.file_type().is_dir() && meta.uid() == uid && meta.mode() & 0o077 == 0
580}
581
582pub fn start(root: &Path, comments: SharedComments) -> io::Result<Server> {
584 start_with(root, comments, Transport::NATIVE)
585}
586
587pub fn start_with(
589 root: &Path,
590 comments: SharedComments,
591 transport: Transport,
592) -> io::Result<Server> {
593 bind(root, comments, transport, false)
594}
595
596pub fn take_over(root: &Path, comments: SharedComments) -> io::Result<Server> {
602 take_over_with(root, comments, Transport::NATIVE)
603}
604
605pub fn take_over_with(
607 root: &Path,
608 comments: SharedComments,
609 transport: Transport,
610) -> io::Result<Server> {
611 bind(root, comments, transport, true)
612}
613
614fn bind(
615 root: &Path,
616 comments: SharedComments,
617 transport: Transport,
618 replace: bool,
619) -> io::Result<Server> {
620 let path = socket_path(root);
621 let dir = path.parent().ok_or_else(|| io::Error::other("no parent"))?;
622 private_folder(dir)?;
623 let (sender, requests) = channel();
624 let owner = match transport {
625 #[cfg(unix)]
626 Transport::Unix => {
627 if !replace && UnixStream::connect(&path).is_ok() {
628 return Err(io::Error::new(ErrorKind::AddrInUse, "already running"));
629 }
630 let _ = fs::remove_file(&path);
631 let listener = UnixListener::bind(&path)?;
632 let made = stamp(&fs::symlink_metadata(&path)?);
633 thread::spawn(move || {
634 for stream in listener.incoming().flatten() {
635 let (comments, sender) = (comments.clone(), sender.clone());
638 thread::spawn(move || {
639 let reader = BufReader::new(stream.try_clone()?);
640 serve(reader, stream, &comments, &sender)
641 });
642 }
643 });
644 Owner::Socket(made)
645 }
646 Transport::Loopback => {
647 if !replace && loopback::alive(&path) {
648 return Err(io::Error::new(ErrorKind::AddrInUse, "already running"));
649 }
650 let _ = fs::remove_file(&path);
651 let listener = Arc::new(loopback::bind(&path)?);
652 let note = listener.note.clone();
653 thread::spawn(move || {
654 for stream in listener.incoming() {
655 let (comments, sender) = (comments.clone(), sender.clone());
656 let listener = listener.clone();
657 thread::spawn(move || {
660 let (reader, stream) = listener.admit(stream)?;
661 serve(reader, stream, &comments, &sender)
662 });
663 }
664 });
665 Owner::Note(note)
666 }
667 };
668 Ok(Server {
669 path,
670 owner,
671 requests,
672 })
673}
674
675pub fn request(root: &Path, line: &str) -> io::Result<String> {
677 request_with(root, line, Transport::NATIVE)
678}
679
680fn patience(line: &str) -> Option<Duration> {
684 (!line.starts_with("plan ") && !line.starts_with("agent ")).then_some(REPLY_TIME)
685}
686
687pub fn request_with(root: &Path, line: &str, transport: Transport) -> io::Result<String> {
689 #[cfg(unix)]
691 if let Some(dir) = socket_path(root).parent() {
692 check_private(dir)?;
693 }
694 let mut reply = String::new();
695 match transport {
696 #[cfg(unix)]
697 Transport::Unix => {
698 let mut stream = UnixStream::connect(socket_path(root))?;
699 stream.set_read_timeout(patience(line))?;
700 writeln!(stream, "{line}")?;
701 BufReader::new(stream).read_line(&mut reply)?;
702 }
703 Transport::Loopback => {
704 let mut stream = loopback::connect(&socket_path(root), PROOF_TIME)?;
705 stream.set_read_timeout(patience(line))?;
706 writeln!(stream, "{line}")?;
707 BufReader::new(stream).read_line(&mut reply)?;
708 }
709 }
710 if !reply.ends_with('\n') {
712 return Err(io::Error::new(ErrorKind::UnexpectedEof, "no reply"));
713 }
714 Ok(reply.trim_end().to_string())
715}
716
717#[cfg(test)]
718mod tests {
719 use super::*;
720
721 #[test]
722 fn an_agent_cannot_reply_as_the_reviewer_and_its_backslashes_arrive() {
723 let comments = SharedComments::default();
724 let (requests, asked) = channel();
725 for author in ["You", "you", " You ", "Y\u{1b}ou"] {
726 let said = answer(
727 &format!("reply 3 {author}\tdrop the check"),
728 &comments,
729 &requests,
730 );
731 assert!(said.unwrap().starts_with("error:"), "{author:?}");
732 }
733 assert!(asked.try_recv().is_err(), "nothing reached the app");
734 let text = escape("first\nmatch '\\n' here");
736 let app = thread::spawn(move || match asked.recv().unwrap() {
737 Request::Reply {
738 author,
739 text,
740 found,
741 ..
742 } => {
743 found.send(true).unwrap();
744 (author, text)
745 }
746 _ => panic!("not a reply"),
747 });
748 let said = answer(&format!("reply 3 Codex\t{text}"), &comments, &requests).unwrap();
749 assert_eq!(said, "ok");
750 let (author, text) = app.join().unwrap();
751 assert_eq!(author, "Codex");
752 assert_eq!(text, "first\nmatch '\\n' here");
753 }
754
755 #[cfg(unix)]
756 #[test]
757 fn a_sockets_folder_others_own_or_can_enter_is_refused() {
758 let dir = tempfile::tempdir().unwrap();
759 let folder = dir.path().join("cellix-x");
760 private_folder(&folder).unwrap();
761 let me = unsafe { libc::getuid() };
763 let meta = fs::symlink_metadata(&folder).unwrap();
764 assert!(owned_privately(&meta, me));
765 assert!(!owned_privately(&meta, me + 1), "someone else's");
766 fs::set_permissions(&folder, fs::Permissions::from_mode(0o777)).unwrap();
768 let refused = check_private(&folder).unwrap_err();
769 assert_eq!(refused.kind(), ErrorKind::PermissionDenied);
770 let link = dir.path().join("link");
772 std::os::unix::fs::symlink(&folder, &link).unwrap();
773 fs::set_permissions(&folder, fs::Permissions::from_mode(0o700)).unwrap();
774 assert!(check_private(&folder).is_ok());
775 assert!(check_private(&link).is_err());
776 }
777
778 fn comment() -> Comment {
779 Comment {
780 file: "a.rs".into(),
781 line: 3,
782 text: "why?".into(),
783 ..Comment::default()
784 }
785 }
786
787 #[test]
788 fn comments_can_be_read_and_taken() {
789 let dir = tempfile::tempdir().unwrap();
790 let shared: SharedComments = Arc::new(Mutex::new(vec![comment()]));
791 let server = start(dir.path(), shared.clone()).unwrap();
792 let json = request(dir.path(), "comments").unwrap();
793 let parsed: Vec<Comment> = serde_json::from_str(&json).unwrap();
794 assert_eq!(parsed, vec![comment()]);
795 assert_eq!(shared.lock().unwrap().len(), 1);
796 request(dir.path(), "take").unwrap();
797 assert!(shared.lock().unwrap().is_empty());
798 assert!(matches!(server.requests.recv(), Ok(Request::CommentsTaken)));
799 }
800
801 fn answer_open(server: &Server, want: &str, said: &str) {
803 match server.requests.recv() {
804 Ok(Request::Open { path, opened }) if path == Path::new(want) => {
805 opened.send(said.to_string()).unwrap();
806 }
807 other => panic!("not an open of {want}: {other:?}"),
808 }
809 }
810
811 #[test]
814 fn open_reaches_the_app_and_brings_back_what_came_of_it() {
815 let dir = tempfile::tempdir().unwrap();
816 let server = start(dir.path(), Arc::default()).unwrap();
817 let root = dir.path().to_path_buf();
818 let asked = thread::spawn(move || request(&root, "open /tmp/x.rs").unwrap());
819 answer_open(&server, "/tmp/x.rs", "Opened x.rs");
820 assert_eq!(asked.join().unwrap(), "Opened x.rs");
821 let root = dir.path().to_path_buf();
822 let asked = thread::spawn(move || request(&root, "open /tmp/gone.rs").unwrap());
823 answer_open(
824 &server,
825 "/tmp/gone.rs",
826 "error: Could not open /tmp/gone.rs",
827 );
828 assert_eq!(asked.join().unwrap(), "error: Could not open /tmp/gone.rs");
829 }
830
831 #[test]
836 fn a_cellix_opened_later_takes_the_folders_agents_and_gives_them_back() {
837 let dir = tempfile::tempdir().unwrap();
838 let older = start(dir.path(), Arc::default()).unwrap();
839 assert!(!older.lost());
840 let newer = take_over(dir.path(), Arc::default()).unwrap();
841 assert!(older.lost() && !newer.lost());
842 let root = dir.path().to_path_buf();
843 let asked = thread::spawn(move || request(&root, "open /tmp/x.rs").unwrap());
844 answer_open(&newer, "/tmp/x.rs", "Opened x.rs");
845 assert_eq!(asked.join().unwrap(), "Opened x.rs");
846 assert!(
847 older.requests.try_recv().is_err(),
848 "nothing reached the older"
849 );
850 older.leftover().remove();
852 assert!(socket_path(dir.path()).exists());
853 assert!(start(dir.path(), Arc::default()).is_err());
855 drop(newer);
856 assert!(!socket_path(dir.path()).exists());
857 let again = start(dir.path(), Arc::default()).unwrap();
858 assert!(!again.lost());
859 drop(older);
860 assert!(
861 socket_path(dir.path()).exists(),
862 "the older left the new socket be"
863 );
864 }
865
866 #[test]
868 fn a_reply_cellix_was_too_busy_for_isnt_called_a_missing_comment() {
869 let dir = tempfile::tempdir().unwrap();
870 let server = start(dir.path(), Arc::default()).unwrap();
871 let root = dir.path().to_path_buf();
872 let said = request(&root, "reply 7 Claude Code\tDone.").unwrap();
873 assert!(
874 said.contains("too busy") && !said.contains("no comment"),
875 "{said}"
876 );
877 assert!(matches!(
879 server.requests.try_recv(),
880 Ok(Request::Reply { id: 7, .. })
881 ));
882 }
883
884 #[test]
885 fn a_second_server_is_refused_and_stale_sockets_are_replaced() {
886 let dir = tempfile::tempdir().unwrap();
887 let server = start(dir.path(), Arc::default()).unwrap();
888 assert!(start(dir.path(), Arc::default()).is_err());
889 let path = server.path.clone();
890 std::mem::forget(server);
891 fs::remove_file(&path).unwrap();
892 fs::write(&path, "stale").unwrap();
893 assert!(start(dir.path(), Arc::default()).is_ok());
894 }
895
896 #[test]
897 fn a_closed_server_takes_its_plans_with_it() {
898 let dir = tempfile::tempdir().unwrap();
899 let server = start(dir.path(), Arc::default()).unwrap();
900 let plans = server.path.with_extension("").join("s1");
901 fs::create_dir_all(&plans).unwrap();
902 fs::write(plans.join("Plan.md"), "plan").unwrap();
903 let path = server.path.clone();
904 drop(server);
905 assert!(!path.exists());
906 assert!(!path.with_extension("").exists());
907 }
908
909 #[test]
911 fn agents_reach_cellix_over_loopback_with_its_token() {
912 let dir = tempfile::tempdir().unwrap();
913 let shared: SharedComments = Arc::new(Mutex::new(vec![comment()]));
914 let over = Transport::Loopback;
915 let server = start_with(dir.path(), shared.clone(), over).unwrap();
916 let note = fs::read_to_string(&server.path).unwrap();
918 let fields: Vec<&str> = note.split_whitespace().collect();
919 let port: u16 = fields[0].parse().unwrap();
920 assert_eq!((fields[1].len(), fields[2].len()), (32, 32));
921 assert_ne!(fields[1], fields[2]);
922 assert_eq!(fields[3], std::process::id().to_string());
923 #[cfg(unix)]
924 assert_eq!(
925 fs::metadata(&server.path).unwrap().permissions().mode() & 0o777,
926 0o600
927 );
928
929 let json = request_with(dir.path(), "comments", over).unwrap();
930 let parsed: Vec<Comment> = serde_json::from_str(&json).unwrap();
931 assert_eq!(parsed, vec![comment()]);
932 let root = dir.path().to_path_buf();
933 let asked = thread::spawn(move || request_with(&root, "open /tmp/x.rs", over).unwrap());
934 answer_open(&server, "/tmp/x.rs", "Opened x.rs");
935 assert_eq!(asked.join().unwrap(), "Opened x.rs");
936 request_with(dir.path(), "take", over).unwrap();
937 assert!(shared.lock().unwrap().is_empty());
938 assert!(matches!(server.requests.recv(), Ok(Request::CommentsTaken)));
939
940 for guess in ["comments", &"0".repeat(32)] {
943 let mut stranger = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap();
944 writeln!(stranger, "{guess}\ncomments").unwrap();
945 let mut reply = String::new();
946 let _ = BufReader::new(stranger).read_line(&mut reply);
947 assert_eq!(reply, "");
948 }
949 shared.lock().unwrap().push(comment());
950 assert_ne!(request_with(dir.path(), "comments", over).unwrap(), "[]");
951
952 assert!(start_with(dir.path(), Arc::default(), over).is_err());
954 let path = server.path.clone();
955 drop(server);
956 assert!(!path.exists());
957 }
958
959 fn note_for(port: u16, pid: u32) -> String {
961 let tokens = (new_token().unwrap(), new_token().unwrap());
962 format!("{port} {} {} {pid}\n", tokens.0, tokens.1)
963 }
964
965 fn closed_port() -> u16 {
967 let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
968 listener.local_addr().unwrap().port()
969 }
970
971 #[test]
972 fn a_loopback_note_nothing_answers_is_replaced() {
973 let dir = tempfile::tempdir().unwrap();
974 let path = socket_path(dir.path());
975 fs::create_dir_all(path.parent().unwrap()).unwrap();
976 let other = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
979 let taken = other.local_addr().unwrap().port();
980 let me = std::process::id();
981 for note in [
982 "stale".to_string(),
983 note_for(taken, me),
984 note_for(closed_port(), me),
985 format!("{taken} 1234"),
986 ] {
987 fs::write(&path, note).unwrap();
988 let server = start_with(dir.path(), Arc::default(), Transport::Loopback).unwrap();
989 assert_eq!(
990 request_with(dir.path(), "comments", Transport::Loopback).unwrap(),
991 "[]"
992 );
993 drop(server);
994 }
995 }
996
997 #[test]
1001 fn loopback_clients_only_talk_to_the_cellix_that_wrote_the_note() {
1002 let dir = tempfile::tempdir().unwrap();
1003 let path = socket_path(dir.path());
1004 fs::create_dir_all(path.parent().unwrap()).unwrap();
1005 let impostor = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1007 let port = impostor.local_addr().unwrap().port();
1008 let (heard, lines) = channel();
1009 thread::spawn(move || {
1010 for stream in impostor.incoming().flatten() {
1011 let mut reader = BufReader::new(stream.try_clone().unwrap());
1012 let mut writer = stream;
1013 let mut line = String::new();
1014 while reader.read_line(&mut line).is_ok_and(|n| n > 0) {
1015 let _ = heard.send(line.trim_end().to_string());
1016 let _ = writeln!(writer, "{}", "0".repeat(32));
1017 let _ = writeln!(writer, r#"[{{"file":"a.rs","line":1,"text":"rm -rf"}}]"#);
1018 line.clear();
1019 }
1020 }
1021 });
1022 let note = note_for(port, std::process::id());
1023 fs::write(&path, ¬e).unwrap();
1024 for line in ["take", "plan /tmp/plan.md"] {
1025 assert!(request_with(dir.path(), line, Transport::Loopback).is_err());
1026 }
1027 let client_token = note.split_whitespace().nth(1).unwrap().to_string();
1029 assert_eq!(lines.recv_timeout(Duration::from_secs(5)), Ok(client_token));
1030 assert!(lines.recv_timeout(Duration::from_millis(300)).is_err());
1031 assert!(!path.exists());
1033 let _server = start_with(dir.path(), Arc::default(), Transport::Loopback).unwrap();
1035 assert_eq!(
1036 request_with(dir.path(), "comments", Transport::Loopback).unwrap(),
1037 "[]"
1038 );
1039 }
1040
1041 #[test]
1044 fn a_loopback_note_whose_process_ended_is_removed() {
1045 let dir = tempfile::tempdir().unwrap();
1046 let path = socket_path(dir.path());
1047 fs::create_dir_all(path.parent().unwrap()).unwrap();
1048 let mut ended = std::process::Command::new(std::env::current_exe().unwrap())
1049 .args(["--exact", "no_test_has_this_name"])
1050 .stdout(std::process::Stdio::null())
1051 .spawn()
1052 .unwrap();
1053 let pid = ended.id();
1054 ended.wait().unwrap();
1055 let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1057 let port = listener.local_addr().unwrap().port();
1058 fs::write(&path, note_for(port, pid)).unwrap();
1059 let started = std::time::Instant::now();
1060 let error = request_with(dir.path(), "take", Transport::Loopback).unwrap_err();
1061 assert_eq!(error.kind(), ErrorKind::NotFound, "{error}");
1062 assert!(started.elapsed() < Duration::from_secs(1));
1063 assert!(!path.exists());
1064 listener.set_nonblocking(true).unwrap();
1065 assert!(listener.accept().is_err(), "it connected anyway");
1066
1067 fs::write(&path, note_for(closed_port(), std::process::id())).unwrap();
1069 let started = std::time::Instant::now();
1070 assert!(request_with(dir.path(), "take", Transport::Loopback).is_err());
1071 assert!(started.elapsed() < PROOF_TIME + Duration::from_secs(1));
1072 assert!(!path.exists());
1073 }
1074
1075 #[test]
1078 fn a_silent_cellix_holds_no_hook_up() {
1079 assert_eq!(patience("take"), Some(REPLY_TIME));
1080 assert_eq!(patience("event {}"), Some(REPLY_TIME));
1081 assert_eq!(patience("plan /tmp/p.md"), None);
1082 let dir = tempfile::tempdir().unwrap();
1083 let path = socket_path(dir.path());
1084 fs::create_dir_all(path.parent().unwrap()).unwrap();
1085
1086 let mute = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1088 fs::write(
1089 &path,
1090 note_for(mute.local_addr().unwrap().port(), std::process::id()),
1091 )
1092 .unwrap();
1093 let started = std::time::Instant::now();
1094 assert!(request_with(dir.path(), "take", Transport::Loopback).is_err());
1095 let took = started.elapsed();
1096 assert!(took < PROOF_TIME + Duration::from_secs(2), "{took:?}");
1097 assert!(path.exists());
1099
1100 let listener = loopback::bind(&path).unwrap();
1102 thread::spawn(move || {
1103 for stream in listener.incoming() {
1104 let admitted = listener.admit(stream);
1105 thread::sleep(Duration::from_secs(30));
1106 drop(admitted);
1107 }
1108 });
1109 let started = std::time::Instant::now();
1110 assert!(request_with(dir.path(), "take", Transport::Loopback).is_err());
1111 let took = started.elapsed();
1112 assert!(took >= REPLY_TIME / 2, "{took:?}");
1113 assert!(took < REPLY_TIME + Duration::from_secs(2), "{took:?}");
1114
1115 #[cfg(unix)]
1116 {
1117 let _ = fs::remove_file(&path);
1118 let socket = UnixListener::bind(&path).unwrap();
1119 thread::spawn(move || {
1120 let held: Vec<_> = socket.incoming().collect();
1121 drop(held);
1122 });
1123 let started = std::time::Instant::now();
1124 assert!(request_with(dir.path(), "take", Transport::Unix).is_err());
1125 assert!(started.elapsed() < REPLY_TIME + Duration::from_secs(2));
1126 }
1127 }
1128
1129 #[test]
1132 fn a_cellix_only_removes_its_own_socket_file() {
1133 for transport in [Transport::NATIVE, Transport::Loopback] {
1134 let dir = tempfile::tempdir().unwrap();
1135 let first = start_with(dir.path(), Arc::default(), transport).unwrap();
1136 let path = first.path.clone();
1137 fs::remove_file(&path).unwrap();
1138 let second = start_with(dir.path(), Arc::default(), transport).unwrap();
1139 drop(first);
1140 assert!(path.exists(), "{transport:?}");
1141 assert_eq!(
1142 request_with(dir.path(), "comments", transport).unwrap(),
1143 "[]"
1144 );
1145 drop(second);
1146 assert!(!path.exists(), "{transport:?}");
1147 }
1148 }
1149
1150 #[test]
1153 fn windows_keeps_sockets_in_local_app_data() {
1154 let var = |name: &str| match name {
1155 "LOCALAPPDATA" => Some(r"C:\Users\Zoë\AppData\Local".to_string()),
1156 "TEMP" => Some(r"D:\shared".to_string()),
1157 _ => None,
1158 };
1159 let local = PathBuf::from(r"C:\Users\Zoë\AppData\Local");
1160 assert_eq!(
1161 windows_sockets_folder(var),
1162 local.join("cellix").join("sockets")
1163 );
1164 let profile = |name: &str| (name == "USERPROFILE").then(|| r"C:\Users\Zoë".to_string());
1165 let local = PathBuf::from(r"C:\Users\Zoë").join("AppData").join("Local");
1166 assert_eq!(
1167 windows_sockets_folder(profile),
1168 local.join("cellix").join("sockets")
1169 );
1170 #[cfg(not(unix))]
1171 assert_eq!(
1172 socket_path(Path::new(r"C:\x")).parent(),
1173 Some(windows_sockets_folder(|n| env::var(n).ok()).as_path())
1174 );
1175 }
1176
1177 #[test]
1178 fn unknown_requests_get_an_error() {
1179 let dir = tempfile::tempdir().unwrap();
1180 let _server = start(dir.path(), Arc::default()).unwrap();
1181 assert!(
1182 request(dir.path(), "nonsense")
1183 .unwrap()
1184 .starts_with("error")
1185 );
1186 }
1187}