Skip to main content

cellix_term/
files.rs

1//! Tiles handed over as files, where the terminal is on this machine and reads them.
2//!
3//! Inline, each tile is compressed, base64-encoded and sent in 4096-byte pieces, so a frame
4//! with many new tiles (the first, a resize, a drag of the side pane's edge, a theme change)
5//! is hundreds of kilobytes through the terminal. The Kitty protocol lets the terminal read a
6//! temporary file instead (`t=t`) and delete it once read: then only its name crosses.
7//!
8//! Only for Ghostty with nothing between (see `allowed`), only once a probe at start has shown
9//! the terminal takes a file, and only until anything goes wrong, when tiles go inline for the
10//! rest of the run. The files are raw pixels in a folder only this user can open, each written
11//! whole and closed before the terminal is told its name. `docs/DESIGN.md` has the reasoning.
12
13use std::path::PathBuf;
14#[cfg(unix)]
15use std::sync::{Arc, Mutex};
16
17/// Turns tile files off when set to 0.
18pub const SWITCH: &str = "CELLIX_TILE_FILES";
19
20/// What says Cellix's output doesn't go straight to a terminal on this machine: a connection
21/// from elsewhere, a multiplexer between, or Claude Code, whose pane shows its own pictures.
22const ELSEWHERE: [&str; 8] = [
23    "SSH_CONNECTION",
24    "SSH_CLIENT",
25    "SSH_TTY",
26    "TMUX",
27    "STY",
28    "ZELLIJ",
29    "CLAUDECODE",
30    "CELLIX_MOD",
31];
32
33/// Whether tiles may go as files here: Ghostty is the terminal, on this machine, with nothing
34/// between, and the switch isn't off. Set at all, even empty, a variable of `ELSEWHERE` says
35/// no: guessing wrong here costs nothing but bytes, and the other way costs every picture.
36pub fn allowed(var: impl Fn(&str) -> Option<String>) -> bool {
37    let off = var(SWITCH).is_some_and(|value| value.trim() == "0");
38    let ghostty = var("TERM_PROGRAM").is_some_and(|name| name.eq_ignore_ascii_case("ghostty"));
39    cfg!(unix) && !off && ghostty && ELSEWHERE.iter().all(|name| var(name).is_none())
40}
41
42/// Tiles waiting for the terminal to take them, at most. A first paint at 4K is a few hundred.
43pub const MOST_FILES: usize = 1024;
44/// Their bytes, at most: a first paint at 4K is about 25 MB of raw pixels.
45pub const MOST_BYTES: usize = 64 * 1024 * 1024;
46/// One tile's bytes, at most.
47pub const MOST_TILE: usize = 16 * 1024 * 1024;
48
49/// The ledger of tile files for one run, shared by every backend the run makes. Clones are
50/// the same ledger; the last one dropped clears what the terminal left.
51#[derive(Clone)]
52pub struct TileFiles {
53    #[cfg(unix)]
54    ledger: Arc<Mutex<unix::Ledger>>,
55}
56
57impl TileFiles {
58    /// A ledger where `allowed` says files may go, in the user's own temp folder. Nothing is
59    /// written until the probe.
60    pub fn for_terminal(var: impl Fn(&str) -> Option<String>) -> Option<Self> {
61        if !allowed(&var) {
62            return None;
63        }
64        #[cfg(unix)]
65        {
66            let root = unix::temp_root(var("TMPDIR"));
67            Some(Self::with_ledger(unix::Ledger::new(root)))
68        }
69        #[cfg(not(unix))]
70        {
71            None
72        }
73    }
74
75    #[cfg(unix)]
76    fn with_ledger(ledger: unix::Ledger) -> Self {
77        Self {
78            ledger: Arc::new(Mutex::new(ledger)),
79        }
80    }
81
82    /// A ledger in `root` whose probe was taken, for tests.
83    #[cfg(all(test, unix))]
84    pub(crate) fn for_test(root: PathBuf) -> Self {
85        Self::with_ledger(unix::Ledger::taken(root))
86    }
87
88    /// The question that asks whether the terminal takes a file, with `id` for its answer:
89    /// a 1 by 1 picture in a file of its own, queried rather than kept. `None` if the file
90    /// couldn't be written, and then files are off.
91    pub fn question(&self, id: u32) -> Option<String> {
92        #[cfg(unix)]
93        {
94            self.ledger.lock().ok()?.question(id)
95        }
96        #[cfg(not(unix))]
97        {
98            let _ = id;
99            None
100        }
101    }
102
103    /// What the terminal answered: whether it said OK. Files are on from now if it did and the
104    /// file is gone, as Ghostty deletes one it has read; off for the run otherwise.
105    pub fn answered(&self, ok: bool) -> bool {
106        #[cfg(unix)]
107        {
108            self.ledger
109                .lock()
110                .is_ok_and(|mut ledger| ledger.answered(ok))
111        }
112        #[cfg(not(unix))]
113        {
114            let _ = ok;
115            false
116        }
117    }
118
119    /// Whether tiles go as files.
120    pub fn on(&self) -> bool {
121        #[cfg(unix)]
122        {
123            self.ledger.lock().is_ok_and(|ledger| ledger.on())
124        }
125        #[cfg(not(unix))]
126        {
127            false
128        }
129    }
130
131    /// Writes a tile's pixels to a file of their own, whole and closed, and gives its path for
132    /// the terminal to read. `None` sends the tile inline: files are off, a cap is reached, or
133    /// the write failed, which turns files off for good.
134    pub fn write(&self, pixels: &[u8]) -> Option<PathBuf> {
135        #[cfg(unix)]
136        {
137            let now = std::time::Instant::now();
138            self.ledger.lock().ok()?.write(pixels, now)
139        }
140        #[cfg(not(unix))]
141        {
142            let _ = pixels;
143            None
144        }
145    }
146
147    /// The folder this run's files are in, once there is one, for a stop to clear.
148    pub fn folder(&self) -> Option<PathBuf> {
149        #[cfg(unix)]
150        {
151            self.ledger.lock().ok()?.folder()
152        }
153        #[cfg(not(unix))]
154        {
155            None
156        }
157    }
158
159    /// Turns files off and removes what the terminal hasn't taken, and the folder. For the end
160    /// of a run: the terminal may still be reading the last frame.
161    pub fn clear(&self) {
162        #[cfg(unix)]
163        if let Ok(mut ledger) = self.ledger.lock() {
164            ledger.clear();
165        }
166    }
167}
168
169/// What a file is named to the terminal: its path, in base64.
170pub fn payload(path: &std::path::Path) -> String {
171    use base64::Engine;
172    #[cfg(unix)]
173    let bytes = std::os::unix::ffi::OsStrExt::as_bytes(path.as_os_str()).to_vec();
174    #[cfg(not(unix))]
175    let bytes = path.to_string_lossy().into_owned().into_bytes();
176    base64::engine::general_purpose::STANDARD.encode(bytes)
177}
178
179#[cfg(unix)]
180mod unix {
181    use std::collections::VecDeque;
182    use std::fs::{self, DirBuilder, File, OpenOptions};
183    use std::io::{self, Read, Write};
184    use std::os::fd::AsRawFd;
185    use std::os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt, PermissionsExt};
186    use std::path::{Path, PathBuf};
187    use std::time::{Duration, Instant, SystemTime};
188
189    use super::{MOST_BYTES, MOST_FILES, MOST_TILE, payload};
190
191    /// How much may wait for the terminal at once.
192    #[derive(Clone, Copy)]
193    pub(super) struct Caps {
194        pub files: usize,
195        pub bytes: usize,
196        pub tile: usize,
197    }
198
199    const CAPS: Caps = Caps {
200        files: MOST_FILES,
201        bytes: MOST_BYTES,
202        tile: MOST_TILE,
203    };
204
205    /// Every file's name has this in it: Ghostty takes no temporary file without it.
206    pub(super) const NAMED: &str = "tty-graphics-protocol-";
207    /// Each run's folder, inside the user's.
208    const SESSION: &str = "session-";
209    /// How long the terminal has to take a file before files are given up for the run. It
210    /// reads them as it reads the frame, so one still there after this never will be.
211    pub(super) const TAKEN_WITHIN: Duration = Duration::from_secs(10);
212    /// How long after its answer the probe's file has to be gone.
213    const PROBE_TAKEN_WITHIN: Duration = Duration::from_millis(100);
214    /// A run's folder that nobody holds is cleared at the next start once it's this old: a
215    /// terminal may still be reading what a Cellix that just ended left.
216    pub(super) const STALE: Duration = Duration::from_secs(60);
217    /// Runs' folders there can be at once, live or left. Past this tiles go inline, so runs
218    /// that crash one after another can't fill the disk.
219    pub(super) const MOST_SESSIONS: usize = 16;
220
221    pub(super) fn effective_uid() -> u32 {
222        // SAFETY: geteuid takes nothing and can't fail.
223        unsafe { libc::geteuid() }
224    }
225
226    /// The user's own temp folder: `TMPDIR` where it's a folder only they can write to, as
227    /// macOS gives each user, or else `/tmp`. Ghostty takes a temporary file from either, and
228    /// from its own `TMPDIR`, which is this one when Cellix was started inside it.
229    pub(super) fn temp_root(tmpdir: Option<String>) -> PathBuf {
230        let own = tmpdir.map(PathBuf::from).filter(|dir| {
231            dir.is_absolute()
232                && fs::metadata(dir).is_ok_and(|meta| {
233                    meta.is_dir() && meta.uid() == effective_uid() && meta.mode() & 0o022 == 0
234                })
235        });
236        own.unwrap_or_else(|| PathBuf::from("/tmp"))
237    }
238
239    struct Waiting {
240        path: PathBuf,
241        bytes: usize,
242        since: Instant,
243    }
244
245    enum Probe {
246        NotAsked,
247        Asked(PathBuf),
248        Taken,
249    }
250
251    /// This run's folder, locked for as long as the run holds it, so another Cellix's start
252    /// can tell it from one left behind.
253    struct Session {
254        path: PathBuf,
255        _lock: File,
256    }
257
258    pub(super) struct Ledger {
259        root: PathBuf,
260        session: Option<Session>,
261        /// In the order the terminal was told them, which is the order it reads them.
262        waiting: VecDeque<Waiting>,
263        bytes: usize,
264        /// Given up for the rest of the run.
265        off: bool,
266        probe: Probe,
267        random: Option<File>,
268        pub(super) caps: Caps,
269    }
270
271    impl Ledger {
272        pub(super) fn new(root: PathBuf) -> Self {
273            Self {
274                root,
275                session: None,
276                waiting: VecDeque::new(),
277                bytes: 0,
278                off: false,
279                probe: Probe::NotAsked,
280                random: None,
281                caps: CAPS,
282            }
283        }
284
285        #[cfg(test)]
286        pub(super) fn taken(root: PathBuf) -> Self {
287            let mut ledger = Self::new(root);
288            ledger.probe = Probe::Taken;
289            ledger
290        }
291
292        pub(super) fn on(&self) -> bool {
293            !self.off && matches!(self.probe, Probe::Taken)
294        }
295
296        pub(super) fn folder(&self) -> Option<PathBuf> {
297            self.session.as_ref().map(|session| session.path.clone())
298        }
299
300        pub(super) fn question(&mut self, id: u32) -> Option<String> {
301            if self.off || !matches!(self.probe, Probe::NotAsked) {
302                return None;
303            }
304            // One pixel of RGB, as the question says.
305            match self.write_file(&[0, 0, 0], SystemTime::now()) {
306                Ok(path) => {
307                    let name = payload(&path);
308                    self.probe = Probe::Asked(path);
309                    Some(format!("\x1b_Gi={id},s=1,v=1,a=q,t=t,f=24;{name}\x1b\\"))
310                }
311                Err(_) => {
312                    self.off = true;
313                    None
314                }
315            }
316        }
317
318        pub(super) fn answered(&mut self, ok: bool) -> bool {
319            let Probe::Asked(path) = std::mem::replace(&mut self.probe, Probe::NotAsked) else {
320                self.off = true;
321                return false;
322            };
323            let deadline = Instant::now() + PROBE_TAKEN_WITHIN;
324            let mut taken = gone(&path);
325            while ok && !taken && Instant::now() < deadline {
326                std::thread::sleep(Duration::from_millis(5));
327                taken = gone(&path);
328            }
329            if ok && taken {
330                self.probe = Probe::Taken;
331                return true;
332            }
333            // Answered and done with, or never coming: either way nothing will read it now.
334            let _ = fs::remove_file(&path);
335            self.off = true;
336            false
337        }
338
339        pub(super) fn write(&mut self, pixels: &[u8], now: Instant) -> Option<PathBuf> {
340            if !self.on() || pixels.is_empty() || pixels.len() > self.caps.tile {
341                return None;
342            }
343            self.forget_taken(now);
344            let full = self.waiting.len() >= self.caps.files
345                || self.bytes + pixels.len() > self.caps.bytes;
346            if self.off || full {
347                return None;
348            }
349            match self.write_file(pixels, SystemTime::now()) {
350                Ok(path) => {
351                    self.bytes += pixels.len();
352                    self.waiting.push_back(Waiting {
353                        path: path.clone(),
354                        bytes: pixels.len(),
355                        since: now,
356                    });
357                    Some(path)
358                }
359                Err(_) => {
360                    // Not again every frame: whatever it was, inline works.
361                    self.off = true;
362                    None
363                }
364            }
365        }
366
367        /// Lets go of the files the terminal has taken, from the oldest, and gives files up
368        /// if the oldest it hasn't is too old. What it's left stays until the run ends: the
369        /// terminal could still open it.
370        fn forget_taken(&mut self, now: Instant) {
371            while let Some(oldest) = self.waiting.front() {
372                if !gone(&oldest.path) {
373                    if now.saturating_duration_since(oldest.since) >= TAKEN_WITHIN {
374                        self.off = true;
375                    }
376                    return;
377                }
378                self.bytes -= oldest.bytes;
379                self.waiting.pop_front();
380            }
381        }
382
383        /// A new file holding `bytes`, closed. Nothing is overwritten, and nothing outside
384        /// this run's folder is written.
385        fn write_file(&mut self, bytes: &[u8], now: SystemTime) -> io::Result<PathBuf> {
386            if self.session.is_none() {
387                self.session = Some(self.make_session(now)?);
388            }
389            let name = format!("{NAMED}{}", hex(&self.random_bytes::<8>()?));
390            let path = self.session.as_ref().expect("made above").path.join(name);
391            let mut file = OpenOptions::new()
392                .write(true)
393                .create_new(true)
394                .mode(0o600)
395                .custom_flags(libc::O_NOFOLLOW)
396                .open(&path)?;
397            let written = file.write_all(bytes);
398            // Closed before the terminal hears of it. No fsync: it reads the same page cache.
399            drop(file);
400            if let Err(error) = written {
401                let _ = fs::remove_file(&path);
402                return Err(error);
403            }
404            Ok(path)
405        }
406
407        fn random_bytes<const N: usize>(&mut self) -> io::Result<[u8; N]> {
408            if self.random.is_none() {
409                self.random = Some(File::open("/dev/urandom")?);
410            }
411            let mut bytes = [0; N];
412            self.random
413                .as_mut()
414                .expect("opened above")
415                .read_exact(&mut bytes)?;
416            Ok(bytes)
417        }
418
419        /// The user's folder in the temp folder, made if it isn't there, then this run's in
420        /// it: after clearing what runs that ended without clearing up left there.
421        fn make_session(&mut self, now: SystemTime) -> io::Result<Session> {
422            let parent = self.root.join(format!("cellix-tiles-{}", effective_uid()));
423            match DirBuilder::new().mode(0o700).create(&parent) {
424                Ok(()) => fs::set_permissions(&parent, fs::Permissions::from_mode(0o700))?,
425                Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
426                Err(error) => return Err(error),
427            }
428            // Ours and private, and not a link to somewhere else, or nothing goes in it.
429            open_private(&parent)?;
430            if sweep(&parent, now)? >= MOST_SESSIONS {
431                return Err(io::Error::other("too many runs' tile folders"));
432            }
433            for _ in 0..4 {
434                let path = parent.join(format!("{SESSION}{}", hex(&self.random_bytes::<16>()?)));
435                match DirBuilder::new().mode(0o700).create(&path) {
436                    Ok(()) => {}
437                    Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
438                    Err(error) => return Err(error),
439                }
440                let held = fs::set_permissions(&path, fs::Permissions::from_mode(0o700))
441                    .and_then(|()| open_private(&path))
442                    .and_then(|lock| lock_now(&lock).map(|()| lock));
443                return match held {
444                    Ok(lock) => Ok(Session { path, _lock: lock }),
445                    Err(error) => {
446                        let _ = fs::remove_dir(&path);
447                        Err(error)
448                    }
449                };
450            }
451            Err(io::Error::other("no free name for a tile folder"))
452        }
453
454        pub(super) fn clear(&mut self) {
455            self.off = true;
456            for waiting in self.waiting.drain(..) {
457                let _ = fs::remove_file(&waiting.path);
458            }
459            self.bytes = 0;
460            if let Probe::Asked(path) = std::mem::replace(&mut self.probe, Probe::NotAsked) {
461                let _ = fs::remove_file(path);
462            }
463            if let Some(session) = self.session.take() {
464                // Never recursive: anything else in it stays, for the next start to judge.
465                let _ = fs::remove_dir(&session.path);
466            }
467        }
468
469        #[cfg(test)]
470        pub(super) fn crash(&mut self) {
471            // As a run killed outright leaves it: files and folder there, and the lock let go.
472            self.waiting.clear();
473            self.session = None;
474            self.off = true;
475        }
476    }
477
478    impl Drop for Ledger {
479        fn drop(&mut self) {
480            self.clear();
481        }
482    }
483
484    fn gone(path: &Path) -> bool {
485        // Only "not there" is taken: a permission or I/O error says nothing of the terminal.
486        matches!(fs::symlink_metadata(path), Err(error) if error.kind() == io::ErrorKind::NotFound)
487    }
488
489    fn hex(bytes: &[u8]) -> String {
490        bytes.iter().map(|byte| format!("{byte:02x}")).collect()
491    }
492
493    /// Opens a folder without following a link, and only if it's the user's and private.
494    pub(super) fn open_private(path: &Path) -> io::Result<File> {
495        let folder = OpenOptions::new()
496            .read(true)
497            .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW)
498            .open(path)?;
499        let meta = folder.metadata()?;
500        if !meta.is_dir() || meta.uid() != effective_uid() || meta.mode() & 0o7777 != 0o700 {
501            return Err(io::Error::new(
502                io::ErrorKind::PermissionDenied,
503                "a tile folder that isn't private",
504            ));
505        }
506        Ok(folder)
507    }
508
509    /// Takes the folder's lock, or says another run holds it.
510    pub(super) fn lock_now(folder: &File) -> io::Result<()> {
511        // SAFETY: the descriptor is the open file's own; flock doesn't take it or read memory.
512        // The lock goes when the file is closed.
513        if unsafe { libc::flock(folder.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0 {
514            Ok(())
515        } else {
516            Err(io::Error::last_os_error())
517        }
518    }
519
520    /// Clears the runs' folders in `parent` that no run holds and that are older than `STALE`,
521    /// and gives how many are left. A folder holding anything but tile files is left whole.
522    pub(super) fn sweep(parent: &Path, now: SystemTime) -> io::Result<usize> {
523        let mut left = 0;
524        for entry in fs::read_dir(parent)? {
525            let entry = entry?;
526            let name = entry.file_name();
527            let ours = name
528                .to_str()
529                .and_then(|n| n.strip_prefix(SESSION))
530                .is_some_and(|rest| {
531                    rest.len() == 32 && rest.bytes().all(|b| b.is_ascii_hexdigit())
532                });
533            if !ours {
534                continue;
535            }
536            if !clear_left(&entry.path(), now) {
537                left += 1;
538            }
539            if left > MOST_SESSIONS {
540                break;
541            }
542        }
543        Ok(left)
544    }
545
546    /// Whether a run's folder was left and is now gone.
547    fn clear_left(folder: &Path, now: SystemTime) -> bool {
548        let Ok(lock) = open_private(folder) else {
549            return false;
550        };
551        if lock_now(&lock).is_err() {
552            return false;
553        }
554        let old = lock
555            .metadata()
556            .and_then(|meta| meta.modified())
557            .ok()
558            .and_then(|modified| now.duration_since(modified).ok())
559            .is_some_and(|age| age >= STALE);
560        if !old {
561            return false;
562        }
563        let Ok(entries) = fs::read_dir(folder) else {
564            return false;
565        };
566        let mut files = Vec::new();
567        for entry in entries.take(MOST_FILES + 2) {
568            let Ok(entry) = entry else {
569                return false;
570            };
571            let named = entry
572                .file_name()
573                .to_str()
574                .and_then(|n| n.strip_prefix(NAMED))
575                .is_some_and(|rest| {
576                    rest.len() == 16 && rest.bytes().all(|b| b.is_ascii_hexdigit())
577                });
578            let plain = fs::symlink_metadata(entry.path()).is_ok_and(|meta| {
579                meta.is_file() && meta.uid() == effective_uid() && meta.nlink() == 1
580            });
581            if !named || !plain {
582                return false;
583            }
584            files.push(entry.path());
585        }
586        if files.len() > MOST_FILES + 1 {
587            return false;
588        }
589        files.iter().all(|file| fs::remove_file(file).is_ok()) && fs::remove_dir(folder).is_ok()
590    }
591}
592
593#[cfg(all(test, unix))]
594mod tests {
595    use super::unix::*;
596    use super::*;
597    use std::fs;
598    use std::os::unix::fs::{MetadataExt, PermissionsExt};
599    use std::path::Path;
600    use std::time::{Duration, Instant, SystemTime};
601
602    /// A private folder of the test's own to stand for the temp folder, gone after.
603    struct Scratch(PathBuf);
604
605    impl Scratch {
606        fn new() -> Self {
607            let mut random = [0u8; 8];
608            use std::io::Read;
609            fs::File::open("/dev/urandom")
610                .unwrap()
611                .read_exact(&mut random)
612                .unwrap();
613            let name: String = random.iter().map(|b| format!("{b:02x}")).collect();
614            let path = std::env::temp_dir().join(format!("cellix-files-test-{name}"));
615            fs::create_dir(&path).unwrap();
616            fs::set_permissions(&path, fs::Permissions::from_mode(0o700)).unwrap();
617            Self(path)
618        }
619
620        fn parent(&self) -> PathBuf {
621            self.0.join(format!("cellix-tiles-{}", effective_uid()))
622        }
623    }
624
625    impl Drop for Scratch {
626        fn drop(&mut self) {
627            let _ = fs::remove_dir_all(&self.0);
628        }
629    }
630
631    fn ghostty(extra: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
632        let mut vars: Vec<(String, String)> = vec![("TERM_PROGRAM".into(), "ghostty".into())];
633        vars.extend(extra.iter().map(|(k, v)| (k.to_string(), v.to_string())));
634        move |name: &str| {
635            vars.iter()
636                .rev()
637                .find(|(k, _)| k == name)
638                .map(|(_, v)| v.clone())
639        }
640    }
641
642    /// What Ghostty does with a file it's named: reads it, then deletes it.
643    fn take(path: &Path) -> Vec<u8> {
644        let bytes = fs::read(path).unwrap();
645        fs::remove_file(path).unwrap();
646        bytes
647    }
648
649    fn mode(path: &Path) -> u32 {
650        fs::symlink_metadata(path).unwrap().mode() & 0o7777
651    }
652
653    #[test]
654    fn files_go_only_to_ghostty_on_this_machine_with_nothing_between() {
655        assert!(allowed(ghostty(&[])));
656        assert!(allowed(ghostty(&[("TERM_PROGRAM", "Ghostty")])));
657        assert!(allowed(ghostty(&[(SWITCH, "1")])));
658        assert!(
659            !allowed(ghostty(&[(SWITCH, "0")])),
660            "the switch turns it off"
661        );
662        for elsewhere in ELSEWHERE {
663            assert!(!allowed(ghostty(&[(elsewhere, "1")])), "{elsewhere}");
664            // Set but empty still says something's between.
665            assert!(!allowed(ghostty(&[(elsewhere, "")])), "{elsewhere} empty");
666        }
667        for other in ["kitty", "WezTerm", "iTerm.app", "vscode", ""] {
668            assert!(!allowed(ghostty(&[("TERM_PROGRAM", other)])), "{other}");
669        }
670        assert!(!allowed(|_: &str| None), "a terminal that doesn't say");
671        assert!(TileFiles::for_terminal(ghostty(&[("SSH_TTY", "/dev/ttys001")])).is_none());
672    }
673
674    #[test]
675    fn the_folder_is_the_users_own_temp_folder_when_its_private() {
676        let scratch = Scratch::new();
677        let own = scratch.0.to_str().unwrap().to_string();
678        assert_eq!(temp_root(Some(own.clone())), scratch.0);
679        assert_eq!(temp_root(Some(format!("{own}/"))), scratch.0.join(""));
680        // One others can write to, one that isn't there, a relative one, or none: /tmp.
681        fs::set_permissions(&scratch.0, fs::Permissions::from_mode(0o777)).unwrap();
682        assert_eq!(temp_root(Some(own.clone())), PathBuf::from("/tmp"));
683        fs::set_permissions(&scratch.0, fs::Permissions::from_mode(0o700)).unwrap();
684        assert_eq!(
685            temp_root(Some(format!("{own}/missing"))),
686            PathBuf::from("/tmp")
687        );
688        assert_eq!(temp_root(Some("tmp".into())), PathBuf::from("/tmp"));
689        assert_eq!(temp_root(None), PathBuf::from("/tmp"));
690    }
691
692    #[test]
693    fn a_tile_file_is_private_whole_and_unpredictably_named() {
694        let scratch = Scratch::new();
695        let files = TileFiles::for_test(scratch.0.clone());
696        let pixels: Vec<u8> = (0..=255).cycle().take(3 * 40 * 7).collect();
697        let first = files.write(&pixels).unwrap();
698        let second = files.write(b"\x01\x02\x03").unwrap();
699        assert_ne!(first, second);
700        let session = first.parent().unwrap();
701        assert_eq!(session, files.folder().unwrap());
702        assert_eq!(session.parent().unwrap(), scratch.parent());
703        // The user's folder and the run's are 0700, the file 0600, all theirs, none a link.
704        for (path, want) in [(&scratch.parent(), 0o700), (&session.into(), 0o700)] {
705            assert_eq!(mode(path), want, "{path:?}");
706        }
707        assert_eq!(mode(&first), 0o600);
708        let meta = fs::symlink_metadata(&first).unwrap();
709        assert!(meta.is_file());
710        assert_eq!(meta.uid(), effective_uid());
711        // Ghostty takes nothing without this in the name; the rest is 64 random bits.
712        let name = first.file_name().unwrap().to_str().unwrap();
713        let random = name.strip_prefix(NAMED).unwrap();
714        assert_eq!(random.len(), 16);
715        assert!(random.bytes().all(|b| b.is_ascii_hexdigit()));
716        assert_eq!(take(&first), pixels, "written whole before it was named");
717        assert_eq!(take(&second), b"\x01\x02\x03");
718        // And named to the terminal as its path in base64.
719        use base64::Engine;
720        let decoded = base64::engine::general_purpose::STANDARD
721            .decode(payload(&first))
722            .unwrap();
723        assert_eq!(Path::new(std::str::from_utf8(&decoded).unwrap()), first);
724    }
725
726    #[test]
727    fn a_parent_folder_that_isnt_private_or_is_a_link_takes_no_tiles() {
728        let scratch = Scratch::new();
729        let elsewhere = scratch.0.join("elsewhere");
730        fs::create_dir(&elsewhere).unwrap();
731        fs::set_permissions(&elsewhere, fs::Permissions::from_mode(0o700)).unwrap();
732        std::os::unix::fs::symlink(&elsewhere, scratch.parent()).unwrap();
733        let files = TileFiles::for_test(scratch.0.clone());
734        assert_eq!(files.write(b"abc"), None, "not through a link");
735        assert!(!files.on(), "and off for good");
736        assert_eq!(fs::read_dir(&elsewhere).unwrap().count(), 0);
737        fs::remove_file(scratch.parent()).unwrap();
738        fs::create_dir(scratch.parent()).unwrap();
739        fs::set_permissions(scratch.parent(), fs::Permissions::from_mode(0o755)).unwrap();
740        let files = TileFiles::for_test(scratch.0.clone());
741        assert_eq!(files.write(b"abc"), None, "not where others can look");
742        assert_eq!(fs::read_dir(scratch.parent()).unwrap().count(), 0);
743    }
744
745    #[test]
746    fn nothing_goes_as_a_file_until_the_terminal_has_taken_the_probe() {
747        let scratch = Scratch::new();
748        let files = TileFiles::with_ledger(Ledger::new(scratch.0.clone()));
749        assert!(!files.on());
750        assert_eq!(files.write(b"abc"), None, "before the probe");
751        let question = files.question(32).unwrap();
752        assert!(question.starts_with("\x1b_Gi=32,s=1,v=1,a=q,t=t,f=24;"));
753        assert_eq!(files.question(32), None, "one probe a run");
754        // The path it names holds one pixel.
755        use base64::Engine;
756        let name = question
757            .strip_prefix("\x1b_Gi=32,s=1,v=1,a=q,t=t,f=24;")
758            .and_then(|rest| rest.strip_suffix("\x1b\\"))
759            .unwrap();
760        let path = PathBuf::from(
761            String::from_utf8(
762                base64::engine::general_purpose::STANDARD
763                    .decode(name)
764                    .unwrap(),
765            )
766            .unwrap(),
767        );
768        assert_eq!(take(&path), [0, 0, 0]);
769        assert!(files.answered(true));
770        assert!(files.on());
771        assert!(files.write(b"abc").is_some());
772    }
773
774    #[test]
775    fn a_probe_unanswered_or_not_taken_keeps_tiles_inline_for_the_run() {
776        // No answer: its file is removed, and nothing goes as a file.
777        let scratch = Scratch::new();
778        let files = TileFiles::with_ledger(Ledger::new(scratch.0.clone()));
779        files.question(32).unwrap();
780        let session = files.folder().unwrap();
781        assert!(!files.answered(false));
782        assert_eq!(fs::read_dir(&session).unwrap().count(), 0, "probe removed");
783        assert_eq!(files.write(b"abc"), None);
784        // Answered OK, but the file is still there: a terminal that doesn't read it.
785        let files = TileFiles::with_ledger(Ledger::new(scratch.0.clone()));
786        files.question(32).unwrap();
787        let started = Instant::now();
788        assert!(!files.answered(true));
789        assert!(
790            started.elapsed() < Duration::from_secs(2),
791            "waited a moment"
792        );
793        assert_eq!(fs::read_dir(files.folder().unwrap()).unwrap().count(), 0);
794        assert_eq!(files.write(b"abc"), None);
795        // Never asked, as under tmux: off.
796        let files = TileFiles::with_ledger(Ledger::new(scratch.0.clone()));
797        assert!(!files.answered(true));
798        assert_eq!(files.question(32), None);
799    }
800
801    #[test]
802    fn past_a_cap_tiles_go_inline_until_the_terminal_takes_some() {
803        // The caps in use, as documented, and small ones to reach here.
804        assert_eq!(
805            (MOST_FILES, MOST_BYTES, MOST_TILE),
806            (1024, 64 << 20, 16 << 20)
807        );
808        let scratch = Scratch::new();
809        let small = |files, bytes, tile| {
810            let mut ledger = Ledger::taken(scratch.0.clone());
811            ledger.caps = Caps { files, bytes, tile };
812            TileFiles::with_ledger(ledger)
813        };
814        let files = small(3, 1000, 10);
815        assert_eq!(files.write(&[]), None, "nothing to send");
816        assert_eq!(files.write(&[7; 11]), None, "too big a tile");
817        assert!(files.on(), "a big tile goes inline, and files stay on");
818        let mut paths: Vec<PathBuf> = (0..3).map(|_| files.write(b"x").unwrap()).collect();
819        assert_eq!(files.write(b"x"), None, "past the count");
820        assert!(files.on());
821        take(&paths.remove(0));
822        assert!(
823            files.write(b"x").is_some(),
824            "room again once the oldest is taken"
825        );
826        let files = small(100, 25, 10);
827        let mut held: Vec<PathBuf> = (0..2).map(|_| files.write(&[1; 10]).unwrap()).collect();
828        assert_eq!(files.write(&[1; 6]), None, "past the bytes");
829        assert!(files.write(&[1; 5]).is_some(), "what still fits goes");
830        take(&held.remove(0));
831        assert!(files.write(&[1; 10]).is_some());
832    }
833
834    #[test]
835    fn a_file_the_terminal_never_takes_turns_files_off_but_isnt_pulled_from_under_it() {
836        let scratch = Scratch::new();
837        let mut ledger = Ledger::taken(scratch.0.clone());
838        let start = Instant::now();
839        let first = ledger.write(b"one", start).unwrap();
840        assert!(
841            ledger
842                .write(b"two", start + Duration::from_secs(9))
843                .is_some()
844        );
845        assert_eq!(ledger.write(b"three", start + TAKEN_WITHIN), None);
846        assert!(!ledger.on(), "given up for the run");
847        assert_eq!(fs::read(&first).unwrap(), b"one", "still there to be read");
848        take(&first);
849        assert_eq!(
850            ledger.write(b"four", start + TAKEN_WITHIN),
851            None,
852            "for good"
853        );
854    }
855
856    #[test]
857    fn a_write_that_fails_turns_files_off_for_good() {
858        let scratch = Scratch::new();
859        // A temp folder that's a file: nothing can be made in it.
860        let root = scratch.0.join("a-file");
861        fs::write(&root, b"").unwrap();
862        let files = TileFiles::for_test(root);
863        assert_eq!(files.write(b"abc"), None);
864        assert!(!files.on());
865        // A run's folder taken away under it.
866        let files = TileFiles::for_test(scratch.0.clone());
867        let path = files.write(b"abc").unwrap();
868        take(&path);
869        fs::remove_dir(files.folder().unwrap()).unwrap();
870        assert_eq!(files.write(b"abc"), None);
871        assert!(!files.on());
872    }
873
874    #[test]
875    fn the_end_of_a_run_clears_what_the_terminal_left() {
876        let scratch = Scratch::new();
877        let files = TileFiles::for_test(scratch.0.clone());
878        let paths: Vec<PathBuf> = (0..3).map(|n| files.write(&[n; 9]).unwrap()).collect();
879        take(&paths[0]);
880        let session = files.folder().unwrap();
881        let other = files.clone();
882        drop(files);
883        assert!(paths[1].exists(), "a clone keeps the ledger");
884        other.clear();
885        assert!(!paths[1].exists() && !paths[2].exists());
886        assert!(!session.exists());
887        assert!(scratch.parent().exists(), "the user's folder stays");
888        assert_eq!(other.write(b"abc"), None, "and nothing more is written");
889        // Dropping the last clone clears as well.
890        let files = TileFiles::for_test(scratch.0.clone());
891        let path = files.write(b"abc").unwrap();
892        drop(files);
893        assert!(!path.exists() && !path.parent().unwrap().exists());
894    }
895
896    #[test]
897    fn the_next_start_clears_what_a_run_that_was_killed_left() {
898        let scratch = Scratch::new();
899        let mut killed = Ledger::taken(scratch.0.clone());
900        let left = killed.write(b"left", Instant::now()).unwrap();
901        let left_folder = left.parent().unwrap().to_path_buf();
902        killed.crash();
903        drop(killed);
904        assert!(left.exists());
905        // A run still going holds its folder.
906        let mut live = Ledger::taken(scratch.0.clone());
907        let live_file = live.write(b"live", Instant::now()).unwrap();
908        let parent = scratch.parent();
909        let later = SystemTime::now() + STALE + Duration::from_secs(1);
910        // Just left, a terminal may still be reading it.
911        assert_eq!(sweep(&parent, SystemTime::now()).unwrap(), 2);
912        assert!(left.exists());
913        assert_eq!(
914            sweep(&parent, later).unwrap(),
915            1,
916            "only the live one is left"
917        );
918        assert!(!left.exists() && !left_folder.exists());
919        assert!(live_file.exists(), "a live run's files are never touched");
920        drop(live);
921        assert_eq!(sweep(&parent, later).unwrap(), 0);
922    }
923
924    #[test]
925    fn a_left_folder_with_anything_but_tile_files_is_left_alone() {
926        let scratch = Scratch::new();
927        let outside = scratch.0.join("outside");
928        fs::write(&outside, b"keep").unwrap();
929        let later = SystemTime::now() + STALE + Duration::from_secs(1);
930        let make = || {
931            let mut killed = Ledger::taken(scratch.0.clone());
932            let path = killed.write(b"left", Instant::now()).unwrap();
933            killed.crash();
934            path
935        };
936        // A link where a tile was: neither it nor what it points at is removed.
937        let tile = make();
938        fs::remove_file(&tile).unwrap();
939        std::os::unix::fs::symlink(&outside, &tile).unwrap();
940        assert_eq!(sweep(&scratch.parent(), later).unwrap(), 1);
941        assert!(fs::symlink_metadata(&tile).is_ok());
942        assert_eq!(fs::read(&outside).unwrap(), b"keep");
943        fs::remove_file(&tile).unwrap();
944        fs::remove_dir(tile.parent().unwrap()).unwrap();
945        // Something that isn't a tile.
946        let tile = make();
947        let other = tile.parent().unwrap().join("notes.txt");
948        fs::write(&other, b"keep").unwrap();
949        assert_eq!(sweep(&scratch.parent(), later).unwrap(), 1);
950        assert!(tile.exists() && other.exists());
951        // A folder that isn't a run's.
952        fs::create_dir(scratch.parent().join("mine")).unwrap();
953        assert_eq!(sweep(&scratch.parent(), later).unwrap(), 1);
954        assert!(scratch.parent().join("mine").exists());
955    }
956
957    #[test]
958    fn too_many_runs_folders_and_tiles_go_inline() {
959        let scratch = Scratch::new();
960        // Runs still going, each holding its folder.
961        let mut live = Vec::new();
962        for _ in 0..MOST_SESSIONS {
963            let mut ledger = Ledger::taken(scratch.0.clone());
964            assert!(ledger.write(b"x", Instant::now()).is_some());
965            live.push(ledger);
966        }
967        let files = TileFiles::for_test(scratch.0.clone());
968        assert_eq!(files.write(b"x"), None);
969        assert!(!files.on());
970        drop(live);
971        let files = TileFiles::for_test(scratch.0.clone());
972        assert!(files.write(b"x").is_some(), "room once they've ended");
973    }
974}