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