Skip to main content

cellix_agent/
lib.rs

1//! The local socket any agent can use to reach a running Cellix. One line in, one line
2//! out: `comments`, `take` (comments, then clear them), `threads`, `take-threads` (those an
3//! agent hasn't seen), `reply <id> <author>` then a tab and the text, or `open <path>`.
4//!
5//! It's a Unix socket where there are those, and elsewhere a port on 127.0.0.1 behind a token,
6//! as `loopback` describes. Agents call `cellix`, so only this crate tells the two apart.
7
8use 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 hook;
25pub mod ide;
26mod loopback;
27
28/// How long a request waits on the app, which may be busy or gone. An agent's hook must never
29/// hang on it.
30const ANSWER_TIME: Duration = Duration::from_secs(2);
31/// How long a client waits for a reply: longer than the app is given, so a busy app's own
32/// answer arrives. A hook asks several things per prompt, so it's never much more.
33const REPLY_TIME: Duration = Duration::from_secs(5);
34/// How long a client waits for a Cellix to connect and prove itself.
35const PROOF_TIME: Duration = Duration::from_secs(2);
36
37/// Comments shared between the app and the socket thread.
38pub type SharedComments = Arc<Mutex<Vec<Comment>>>;
39
40#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
41pub enum AgentState {
42    Working,
43    NeedsYou,
44    Idle,
45    Ended,
46}
47
48/// What an agent is doing, as its hooks report it.
49#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
50pub struct AgentEvent {
51    pub session: String,
52    pub agent: String,
53    pub state: AgentState,
54    pub detail: String,
55    pub folder: String,
56}
57
58/// A test command an agent ran.
59#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
60pub struct TestRun {
61    pub command: String,
62    pub passed: bool,
63    pub output: String,
64}
65
66/// The reviewer's answer to a plan.
67#[derive(Clone, Debug, PartialEq, Eq)]
68pub enum Decision {
69    /// With the plan's new text, if the reviewer edited it.
70    Approve(Option<String>),
71    SendBack(String),
72}
73
74/// Requests that need the app itself, drained on its next tick.
75#[derive(Debug)]
76pub enum Request {
77    Open(PathBuf),
78    /// The socket thread already emptied the shared list.
79    CommentsTaken,
80    Agent(AgentEvent),
81    Test(TestRun),
82    /// Input for a Cellix running as a pane, as the mod's JSON.
83    Pane(String),
84    /// An agent answering a comment.
85    Reply {
86        id: u32,
87        author: String,
88        text: String,
89        /// Whether that comment exists, so an answer can't vanish with a success.
90        found: Sender<bool>,
91    },
92    /// An agent suggesting a comment the reviewer didn't make. Answers with its number.
93    Suggest {
94        file: String,
95        line: usize,
96        kind: String,
97        quote: String,
98        text: String,
99        author: String,
100        made: Sender<u32>,
101    },
102    /// Wants the comments on the project, as JSON.
103    Threads(Sender<String>),
104    /// Wants the comments no agent has seen, as JSON, and marks them seen.
105    TakeThreads(Sender<String>),
106    /// A plan is waiting. The connection stays open until `reply` is answered or dropped.
107    Plan {
108        path: PathBuf,
109        reply: Sender<Decision>,
110    },
111}
112
113fn fnv(text: &str) -> u64 {
114    text.bytes().fold(0xcbf29ce484222325, |hash, byte| {
115        (hash ^ byte as u64).wrapping_mul(0x100000001b3)
116    })
117}
118
119/// How agents reach a Cellix.
120#[derive(Clone, Copy, Debug, PartialEq, Eq)]
121pub enum Transport {
122    /// A Unix socket at `socket_path`.
123    #[cfg(unix)]
124    Unix,
125    /// A port on 127.0.0.1, named with its token in a file at `socket_path`.
126    Loopback,
127}
128
129impl Transport {
130    /// What `start` and `request` use here.
131    #[cfg(unix)]
132    pub const NATIVE: Self = Self::Unix;
133    #[cfg(not(unix))]
134    pub const NATIVE: Self = Self::Loopback;
135}
136
137/// A token no one else can guess.
138pub(crate) fn new_token() -> io::Result<String> {
139    let mut bytes = [0u8; 16];
140    #[cfg(unix)]
141    io::Read::read_exact(&mut fs::File::open("/dev/urandom")?, &mut bytes)?;
142    #[cfg(not(unix))]
143    getrandom::fill(&mut bytes).map_err(io::Error::other)?;
144    Ok(bytes.iter().map(|b| format!("{b:02x}")).collect())
145}
146
147/// The folder the sockets live in, which only this user can enter. On Unix it's named for
148/// the user in the shared temp folder, and made private.
149#[cfg(unix)]
150fn sockets_folder() -> PathBuf {
151    // SAFETY: getuid has no preconditions and cannot fail.
152    let uid = unsafe { libc::getuid() };
153    env::temp_dir().join(format!("cellix-{uid}"))
154}
155
156#[cfg(not(unix))]
157fn sockets_folder() -> PathBuf {
158    windows_sockets_folder(|name| env::var(name).ok())
159}
160
161/// The folder the sockets live in on Windows: the user's own local app data, which only they
162/// and administrators can read, wherever TEMP has been pointed.
163#[cfg_attr(unix, allow(dead_code))]
164fn windows_sockets_folder(var: impl Fn(&str) -> Option<String>) -> PathBuf {
165    let local = var("LOCALAPPDATA")
166        .filter(|v| !v.is_empty())
167        .map(PathBuf::from);
168    local
169        .or_else(|| {
170            Some(
171                PathBuf::from(var("USERPROFILE")?)
172                    .join("AppData")
173                    .join("Local"),
174            )
175        })
176        .unwrap_or_else(env::temp_dir)
177        .join("cellix")
178        .join("sockets")
179}
180
181/// One socket per workspace, in a directory only this user can enter.
182pub fn socket_path(root: &Path) -> PathBuf {
183    // `\\?\C:\x` and `C:\x` are one folder, so they share a socket. Unix paths are as they are.
184    let root = dunce::simplified(root);
185    sockets_folder().join(format!("{:016x}.sock", fnv(&root.to_string_lossy())))
186}
187
188fn answer(line: &str, comments: &SharedComments, requests: &Sender<Request>) -> io::Result<String> {
189    let mut parts = line.trim().splitn(2, ' ');
190    let list = |clear: bool| -> io::Result<String> {
191        let mut shared = comments.lock().map_err(|_| io::Error::other("poisoned"))?;
192        let json = serde_json::to_string(&*shared)?;
193        if clear {
194            shared.clear();
195        }
196        Ok(json)
197    };
198    match (parts.next(), parts.next()) {
199        (Some("comments"), None) => list(false),
200        (Some("take"), None) => {
201            let json = list(true)?;
202            // The hook takes on every prompt, and an empty take isn't news.
203            if json != "[]" {
204                let _ = requests.send(Request::CommentsTaken);
205            }
206            Ok(json)
207        }
208        (Some("open"), Some(path)) => {
209            let _ = requests.send(Request::Open(PathBuf::from(path)));
210            Ok("ok".into())
211        }
212        (Some("threads"), None) => {
213            let (reply, threads) = channel();
214            let _ = requests.send(Request::Threads(reply));
215            Ok(threads
216                .recv_timeout(ANSWER_TIME)
217                .unwrap_or_else(|_| "[]".to_string()))
218        }
219        (Some("take-threads"), None) => {
220            let (reply, threads) = channel();
221            let _ = requests.send(Request::TakeThreads(reply));
222            Ok(threads
223                .recv_timeout(ANSWER_TIME)
224                .unwrap_or_else(|_| "[]".to_string()))
225        }
226        (Some("reply"), Some(rest)) => {
227            let Some((head, text)) = rest.split_once('\t') else {
228                return Ok("error: reply needs an id, an author and text".into());
229            };
230            let (id, author) = head.split_once(' ').unwrap_or((head, "Agent"));
231            let Ok(id) = id.parse() else {
232                return Ok("error: reply needs a comment's number".into());
233            };
234            let (author, text) = (author.to_string(), text.replace("\\n", "\n"));
235            let (found, answer) = channel();
236            let _ = requests.send(Request::Reply {
237                id,
238                author,
239                text,
240                found,
241            });
242            Ok(match answer.recv_timeout(ANSWER_TIME) {
243                Ok(true) => "ok".to_string(),
244                _ => format!("error: there's no comment {id}"),
245            })
246        }
247        (Some("suggest"), Some(json)) => {
248            let value: serde_json::Value = serde_json::from_str(json)?;
249            let field = |name: &str| value[name].as_str().unwrap_or_default().to_string();
250            let (made, answer) = channel();
251            let _ = requests.send(Request::Suggest {
252                file: field("file"),
253                line: value["line"].as_u64().unwrap_or(1) as usize,
254                kind: field("kind"),
255                quote: field("quote"),
256                text: field("text"),
257                author: field("author"),
258                made,
259            });
260            Ok(match answer.recv_timeout(ANSWER_TIME) {
261                Ok(id) => format!("ok {id}"),
262                Err(_) => "error: Cellix didn't take the suggestion".to_string(),
263            })
264        }
265        (Some("pane"), Some(json)) => {
266            let _ = requests.send(Request::Pane(json.to_string()));
267            Ok("ok".into())
268        }
269        (Some("event"), Some(json)) => {
270            let _ = requests.send(Request::Agent(serde_json::from_str(json)?));
271            Ok("ok".into())
272        }
273        (Some("test"), Some(json)) => {
274            let _ = requests.send(Request::Test(serde_json::from_str(json)?));
275            Ok("ok".into())
276        }
277        (Some("plan"), Some(path)) => {
278            let (reply, decision) = channel();
279            let path = PathBuf::from(path);
280            let _ = requests.send(Request::Plan { path, reply });
281            // Quitting drops the sender, and the agent goes back to asking as usual.
282            Ok(match decision.recv() {
283                Ok(Decision::Approve(None)) => "approve".to_string(),
284                Ok(Decision::Approve(Some(text))) => {
285                    format!("approve {}", serde_json::to_string(&text)?)
286                }
287                Ok(Decision::SendBack(text)) => {
288                    format!("send-back {}", serde_json::to_string(&text)?)
289                }
290                Err(_) => "pass".to_string(),
291            })
292        }
293        _ => Ok("error: unknown request".into()),
294    }
295}
296
297fn serve(
298    mut reader: impl BufRead,
299    mut stream: impl Write,
300    comments: &SharedComments,
301    requests: &Sender<Request>,
302) -> io::Result<()> {
303    let mut line = String::new();
304    reader.read_line(&mut line)?;
305    writeln!(stream, "{}", answer(&line, comments, requests)?)
306}
307
308/// The running server. Dropping it removes the socket file, and the plans kept beside it.
309pub struct Server {
310    path: PathBuf,
311    owner: Owner,
312    pub requests: Receiver<Request>,
313}
314
315/// What tells this server's socket file from one a later Cellix put in its place.
316enum Owner {
317    /// The Unix socket's inode.
318    #[cfg(unix)]
319    Socket(u64),
320    Note(loopback::Note),
321}
322
323impl Server {
324    /// Whether the socket file is still this server's own.
325    fn owns_its_file(&self) -> bool {
326        match &self.owner {
327            #[cfg(unix)]
328            Owner::Socket(inode) => {
329                use std::os::unix::fs::MetadataExt;
330                fs::symlink_metadata(&self.path).is_ok_and(|m| m.ino() == *inode)
331            }
332            Owner::Note(note) => note.is_at(&self.path),
333        }
334    }
335}
336
337impl Drop for Server {
338    fn drop(&mut self) {
339        // Two starting at once can both find no one here, and the second's file replaces the
340        // first's. The first mustn't take it with it.
341        if self.owns_its_file() {
342            let _ = fs::remove_file(&self.path);
343            let _ = fs::remove_dir_all(self.path.with_extension(""));
344        }
345    }
346}
347
348/// Makes the folder the sockets live in, which only this user can enter.
349fn private_folder(dir: &Path) -> io::Result<()> {
350    #[cfg(unix)]
351    {
352        fs::DirBuilder::new()
353            .recursive(true)
354            .mode(0o700)
355            .create(dir)?;
356        fs::set_permissions(dir, fs::Permissions::from_mode(0o700))
357    }
358    // Inside the user's own local app data, which only they and administrators can read.
359    #[cfg(not(unix))]
360    fs::DirBuilder::new().recursive(true).create(dir)
361}
362
363/// Binds the workspace socket. Fails if another Cellix already serves this workspace.
364pub fn start(root: &Path, comments: SharedComments) -> io::Result<Server> {
365    start_with(root, comments, Transport::NATIVE)
366}
367
368/// `start`, over the transport given.
369pub fn start_with(
370    root: &Path,
371    comments: SharedComments,
372    transport: Transport,
373) -> io::Result<Server> {
374    let path = socket_path(root);
375    let dir = path.parent().ok_or_else(|| io::Error::other("no parent"))?;
376    private_folder(dir)?;
377    let (sender, requests) = channel();
378    let owner = match transport {
379        #[cfg(unix)]
380        Transport::Unix => {
381            if UnixStream::connect(&path).is_ok() {
382                return Err(io::Error::new(ErrorKind::AddrInUse, "already running"));
383            }
384            let _ = fs::remove_file(&path);
385            let listener = UnixListener::bind(&path)?;
386            let inode = std::os::unix::fs::MetadataExt::ino(&fs::symlink_metadata(&path)?);
387            thread::spawn(move || {
388                for stream in listener.incoming().flatten() {
389                    // One thread each, because a plan holds its connection open for as long as
390                    // the reviewer takes.
391                    let (comments, sender) = (comments.clone(), sender.clone());
392                    thread::spawn(move || {
393                        let reader = BufReader::new(stream.try_clone()?);
394                        serve(reader, stream, &comments, &sender)
395                    });
396                }
397            });
398            Owner::Socket(inode)
399        }
400        Transport::Loopback => {
401            if loopback::alive(&path) {
402                return Err(io::Error::new(ErrorKind::AddrInUse, "already running"));
403            }
404            let _ = fs::remove_file(&path);
405            let listener = Arc::new(loopback::bind(&path)?);
406            let note = listener.note.clone();
407            thread::spawn(move || {
408                for stream in listener.incoming() {
409                    let (comments, sender) = (comments.clone(), sender.clone());
410                    let listener = listener.clone();
411                    // Admitted on its own thread, so a stranger that never sends a token
412                    // holds up no one else.
413                    thread::spawn(move || {
414                        let (reader, stream) = listener.admit(stream)?;
415                        serve(reader, stream, &comments, &sender)
416                    });
417                }
418            });
419            Owner::Note(note)
420        }
421    };
422    Ok(Server {
423        path,
424        owner,
425        requests,
426    })
427}
428
429/// Sends one request to the Cellix serving `root`.
430pub fn request(root: &Path, line: &str) -> io::Result<String> {
431    request_with(root, line, Transport::NATIVE)
432}
433
434/// How long to wait for the reply to `line`. A plan waits for the reviewer, however long they
435/// take; anything else is answered at once or not at all, and a hook mustn't hang on it.
436fn patience(line: &str) -> Option<Duration> {
437    (!line.starts_with("plan ")).then_some(REPLY_TIME)
438}
439
440/// `request`, over the transport given.
441pub fn request_with(root: &Path, line: &str, transport: Transport) -> io::Result<String> {
442    let mut reply = String::new();
443    match transport {
444        #[cfg(unix)]
445        Transport::Unix => {
446            let mut stream = UnixStream::connect(socket_path(root))?;
447            stream.set_read_timeout(patience(line))?;
448            writeln!(stream, "{line}")?;
449            BufReader::new(stream).read_line(&mut reply)?;
450        }
451        Transport::Loopback => {
452            let mut stream = loopback::connect(&socket_path(root), PROOF_TIME)?;
453            stream.set_read_timeout(patience(line))?;
454            writeln!(stream, "{line}")?;
455            BufReader::new(stream).read_line(&mut reply)?;
456        }
457    }
458    // A reply cut short isn't one.
459    if !reply.ends_with('\n') {
460        return Err(io::Error::new(ErrorKind::UnexpectedEof, "no reply"));
461    }
462    Ok(reply.trim_end().to_string())
463}
464
465#[cfg(test)]
466mod tests {
467    use super::*;
468
469    fn comment() -> Comment {
470        Comment {
471            file: "a.rs".into(),
472            line: 3,
473            text: "why?".into(),
474            ..Comment::default()
475        }
476    }
477
478    #[test]
479    fn comments_can_be_read_and_taken() {
480        let dir = tempfile::tempdir().unwrap();
481        let shared: SharedComments = Arc::new(Mutex::new(vec![comment()]));
482        let server = start(dir.path(), shared.clone()).unwrap();
483        let json = request(dir.path(), "comments").unwrap();
484        let parsed: Vec<Comment> = serde_json::from_str(&json).unwrap();
485        assert_eq!(parsed, vec![comment()]);
486        assert_eq!(shared.lock().unwrap().len(), 1);
487        request(dir.path(), "take").unwrap();
488        assert!(shared.lock().unwrap().is_empty());
489        assert!(matches!(server.requests.recv(), Ok(Request::CommentsTaken)));
490    }
491
492    #[test]
493    fn open_reaches_the_app() {
494        let dir = tempfile::tempdir().unwrap();
495        let server = start(dir.path(), Arc::default()).unwrap();
496        assert_eq!(request(dir.path(), "open /tmp/x.rs").unwrap(), "ok");
497        assert!(matches!(
498            server.requests.recv(),
499            Ok(Request::Open(path)) if path == Path::new("/tmp/x.rs")
500        ));
501    }
502
503    #[test]
504    fn a_second_server_is_refused_and_stale_sockets_are_replaced() {
505        let dir = tempfile::tempdir().unwrap();
506        let server = start(dir.path(), Arc::default()).unwrap();
507        assert!(start(dir.path(), Arc::default()).is_err());
508        let path = server.path.clone();
509        std::mem::forget(server);
510        fs::remove_file(&path).unwrap();
511        fs::write(&path, "stale").unwrap();
512        assert!(start(dir.path(), Arc::default()).is_ok());
513    }
514
515    #[test]
516    fn a_closed_server_takes_its_plans_with_it() {
517        let dir = tempfile::tempdir().unwrap();
518        let server = start(dir.path(), Arc::default()).unwrap();
519        let plans = server.path.with_extension("").join("s1");
520        fs::create_dir_all(&plans).unwrap();
521        fs::write(plans.join("Plan.md"), "plan").unwrap();
522        let path = server.path.clone();
523        drop(server);
524        assert!(!path.exists());
525        assert!(!path.with_extension("").exists());
526    }
527
528    /// What Windows uses, proved on every platform.
529    #[test]
530    fn agents_reach_cellix_over_loopback_with_its_token() {
531        let dir = tempfile::tempdir().unwrap();
532        let shared: SharedComments = Arc::new(Mutex::new(vec![comment()]));
533        let over = Transport::Loopback;
534        let server = start_with(dir.path(), shared.clone(), over).unwrap();
535        // Where the socket would be, a note of the port, a token each way, and the process.
536        let note = fs::read_to_string(&server.path).unwrap();
537        let fields: Vec<&str> = note.split_whitespace().collect();
538        let port: u16 = fields[0].parse().unwrap();
539        assert_eq!((fields[1].len(), fields[2].len()), (32, 32));
540        assert_ne!(fields[1], fields[2]);
541        assert_eq!(fields[3], std::process::id().to_string());
542        #[cfg(unix)]
543        assert_eq!(
544            fs::metadata(&server.path).unwrap().permissions().mode() & 0o777,
545            0o600
546        );
547
548        let json = request_with(dir.path(), "comments", over).unwrap();
549        let parsed: Vec<Comment> = serde_json::from_str(&json).unwrap();
550        assert_eq!(parsed, vec![comment()]);
551        assert_eq!(
552            request_with(dir.path(), "open /tmp/x.rs", over).unwrap(),
553            "ok"
554        );
555        assert!(matches!(
556            server.requests.recv(),
557            Ok(Request::Open(path)) if path == Path::new("/tmp/x.rs")
558        ));
559        request_with(dir.path(), "take", over).unwrap();
560        assert!(shared.lock().unwrap().is_empty());
561        assert!(matches!(server.requests.recv(), Ok(Request::CommentsTaken)));
562
563        // Anything else that finds the port gets nothing without the token, even with a
564        // guess as long as it.
565        for guess in ["comments", &"0".repeat(32)] {
566            let mut stranger = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap();
567            writeln!(stranger, "{guess}\ncomments").unwrap();
568            let mut reply = String::new();
569            let _ = BufReader::new(stranger).read_line(&mut reply);
570            assert_eq!(reply, "");
571        }
572        shared.lock().unwrap().push(comment());
573        assert_ne!(request_with(dir.path(), "comments", over).unwrap(), "[]");
574
575        // A second Cellix here is refused while this one answers.
576        assert!(start_with(dir.path(), Arc::default(), over).is_err());
577        let path = server.path.clone();
578        drop(server);
579        assert!(!path.exists());
580    }
581
582    /// A note as a Cellix writes it, for a port and process of the test's choosing.
583    fn note_for(port: u16, pid: u32) -> String {
584        let tokens = (new_token().unwrap(), new_token().unwrap());
585        format!("{port} {} {} {pid}\n", tokens.0, tokens.1)
586    }
587
588    /// A port that refuses connections, as one whose Cellix has gone does.
589    fn closed_port() -> u16 {
590        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
591        listener.local_addr().unwrap().port()
592    }
593
594    #[test]
595    fn a_loopback_note_nothing_answers_is_replaced() {
596        let dir = tempfile::tempdir().unwrap();
597        let path = socket_path(dir.path());
598        fs::create_dir_all(path.parent().unwrap()).unwrap();
599        // Something that isn't Cellix, then a port nothing listens on, then a note from before
600        // notes named their process.
601        let other = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
602        let taken = other.local_addr().unwrap().port();
603        let me = std::process::id();
604        for note in [
605            "stale".to_string(),
606            note_for(taken, me),
607            note_for(closed_port(), me),
608            format!("{taken} 1234"),
609        ] {
610            fs::write(&path, note).unwrap();
611            let server = start_with(dir.path(), Arc::default(), Transport::Loopback).unwrap();
612            assert_eq!(
613                request_with(dir.path(), "comments", Transport::Loopback).unwrap(),
614                "[]"
615            );
616            drop(server);
617        }
618    }
619
620    /// Whoever answers on the port must prove it's the Cellix that wrote the note before a
621    /// client says what it wants, so nothing else can feed an agent comments or approve its
622    /// plan.
623    #[test]
624    fn loopback_clients_only_talk_to_the_cellix_that_wrote_the_note() {
625        let dir = tempfile::tempdir().unwrap();
626        let path = socket_path(dir.path());
627        fs::create_dir_all(path.parent().unwrap()).unwrap();
628        // An impostor holds the port, and answers whatever it's sent with its own guess.
629        let impostor = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
630        let port = impostor.local_addr().unwrap().port();
631        let (heard, lines) = channel();
632        thread::spawn(move || {
633            for stream in impostor.incoming().flatten() {
634                let mut reader = BufReader::new(stream.try_clone().unwrap());
635                let mut writer = stream;
636                let mut line = String::new();
637                while reader.read_line(&mut line).is_ok_and(|n| n > 0) {
638                    let _ = heard.send(line.trim_end().to_string());
639                    let _ = writeln!(writer, "{}", "0".repeat(32));
640                    let _ = writeln!(writer, r#"[{{"file":"a.rs","line":1,"text":"rm -rf"}}]"#);
641                    line.clear();
642                }
643            }
644        });
645        let note = note_for(port, std::process::id());
646        fs::write(&path, &note).unwrap();
647        for line in ["take", "plan /tmp/plan.md"] {
648            assert!(request_with(dir.path(), line, Transport::Loopback).is_err());
649        }
650        // It heard the client's token and nothing after it.
651        let client_token = note.split_whitespace().nth(1).unwrap().to_string();
652        assert_eq!(lines.recv_timeout(Duration::from_secs(5)), Ok(client_token));
653        assert!(lines.recv_timeout(Duration::from_millis(300)).is_err());
654        // And the note it can't answer for is gone, so the next hook doesn't ask.
655        assert!(!path.exists());
656        // So a real Cellix starts here, though the impostor still answers.
657        let _server = start_with(dir.path(), Arc::default(), Transport::Loopback).unwrap();
658        assert_eq!(
659            request_with(dir.path(), "comments", Transport::Loopback).unwrap(),
660            "[]"
661        );
662    }
663
664    /// A note outlives its Cellix when Windows closes the window under it. Its process is
665    /// gone, so the note goes without a connection being tried.
666    #[test]
667    fn a_loopback_note_whose_process_ended_is_removed() {
668        let dir = tempfile::tempdir().unwrap();
669        let path = socket_path(dir.path());
670        fs::create_dir_all(path.parent().unwrap()).unwrap();
671        let mut ended = std::process::Command::new(std::env::current_exe().unwrap())
672            .args(["--exact", "no_test_has_this_name"])
673            .stdout(std::process::Stdio::null())
674            .spawn()
675            .unwrap();
676        let pid = ended.id();
677        ended.wait().unwrap();
678        // Something listens there, and would be asked if the process weren't checked.
679        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
680        let port = listener.local_addr().unwrap().port();
681        fs::write(&path, note_for(port, pid)).unwrap();
682        let started = std::time::Instant::now();
683        let error = request_with(dir.path(), "take", Transport::Loopback).unwrap_err();
684        assert_eq!(error.kind(), ErrorKind::NotFound, "{error}");
685        assert!(started.elapsed() < Duration::from_secs(1));
686        assert!(!path.exists());
687        listener.set_nonblocking(true).unwrap();
688        assert!(listener.accept().is_err(), "it connected anyway");
689
690        // A refused port removes its note too, and quickly.
691        fs::write(&path, note_for(closed_port(), std::process::id())).unwrap();
692        let started = std::time::Instant::now();
693        assert!(request_with(dir.path(), "take", Transport::Loopback).is_err());
694        assert!(started.elapsed() < PROOF_TIME + Duration::from_secs(1));
695        assert!(!path.exists());
696    }
697
698    /// A Cellix that takes a connection and never answers holds a hook up for a few seconds
699    /// at most, whichever way it's reached. Only a plan waits on.
700    #[test]
701    fn a_silent_cellix_holds_no_hook_up() {
702        assert_eq!(patience("take"), Some(REPLY_TIME));
703        assert_eq!(patience("event {}"), Some(REPLY_TIME));
704        assert_eq!(patience("plan /tmp/p.md"), None);
705        let dir = tempfile::tempdir().unwrap();
706        let path = socket_path(dir.path());
707        fs::create_dir_all(path.parent().unwrap()).unwrap();
708
709        // Silent before proving itself.
710        let mute = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
711        fs::write(
712            &path,
713            note_for(mute.local_addr().unwrap().port(), std::process::id()),
714        )
715        .unwrap();
716        let started = std::time::Instant::now();
717        assert!(request_with(dir.path(), "take", Transport::Loopback).is_err());
718        let took = started.elapsed();
719        assert!(took < PROOF_TIME + Duration::from_secs(2), "{took:?}");
720        // A Cellix too slow to prove itself may only be busy, so its note stays.
721        assert!(path.exists());
722
723        // Proving itself, then silent: the reply time bounds it.
724        let listener = loopback::bind(&path).unwrap();
725        thread::spawn(move || {
726            for stream in listener.incoming() {
727                let admitted = listener.admit(stream);
728                thread::sleep(Duration::from_secs(30));
729                drop(admitted);
730            }
731        });
732        let started = std::time::Instant::now();
733        assert!(request_with(dir.path(), "take", Transport::Loopback).is_err());
734        let took = started.elapsed();
735        assert!(took >= REPLY_TIME / 2, "{took:?}");
736        assert!(took < REPLY_TIME + Duration::from_secs(2), "{took:?}");
737
738        #[cfg(unix)]
739        {
740            let _ = fs::remove_file(&path);
741            let socket = UnixListener::bind(&path).unwrap();
742            thread::spawn(move || {
743                let held: Vec<_> = socket.incoming().collect();
744                drop(held);
745            });
746            let started = std::time::Instant::now();
747            assert!(request_with(dir.path(), "take", Transport::Unix).is_err());
748            assert!(started.elapsed() < REPLY_TIME + Duration::from_secs(2));
749        }
750    }
751
752    /// Two starting at once can both find the place empty, and the second's file replaces the
753    /// first's. Closing the first leaves the second's alone.
754    #[test]
755    fn a_cellix_only_removes_its_own_socket_file() {
756        for transport in [Transport::NATIVE, Transport::Loopback] {
757            let dir = tempfile::tempdir().unwrap();
758            let first = start_with(dir.path(), Arc::default(), transport).unwrap();
759            let path = first.path.clone();
760            fs::remove_file(&path).unwrap();
761            let second = start_with(dir.path(), Arc::default(), transport).unwrap();
762            drop(first);
763            assert!(path.exists(), "{transport:?}");
764            assert_eq!(
765                request_with(dir.path(), "comments", transport).unwrap(),
766                "[]"
767            );
768            drop(second);
769            assert!(!path.exists(), "{transport:?}");
770        }
771    }
772
773    /// Windows keeps sockets in the user's local app data, not wherever TEMP points, and
774    /// doesn't name the folder for the user at all.
775    #[test]
776    fn windows_keeps_sockets_in_local_app_data() {
777        let var = |name: &str| match name {
778            "LOCALAPPDATA" => Some(r"C:\Users\Zoë\AppData\Local".to_string()),
779            "TEMP" => Some(r"D:\shared".to_string()),
780            _ => None,
781        };
782        let local = PathBuf::from(r"C:\Users\Zoë\AppData\Local");
783        assert_eq!(
784            windows_sockets_folder(var),
785            local.join("cellix").join("sockets")
786        );
787        let profile = |name: &str| (name == "USERPROFILE").then(|| r"C:\Users\Zoë".to_string());
788        let local = PathBuf::from(r"C:\Users\Zoë").join("AppData").join("Local");
789        assert_eq!(
790            windows_sockets_folder(profile),
791            local.join("cellix").join("sockets")
792        );
793        #[cfg(not(unix))]
794        assert_eq!(
795            socket_path(Path::new(r"C:\x")).parent(),
796            Some(windows_sockets_folder(|n| env::var(n).ok()).as_path())
797        );
798    }
799
800    #[test]
801    fn unknown_requests_get_an_error() {
802        let dir = tempfile::tempdir().unwrap();
803        let _server = start(dir.path(), Arc::default()).unwrap();
804        assert!(
805            request(dir.path(), "nonsense")
806                .unwrap()
807                .starts_with("error")
808        );
809    }
810}