snyvi 1.28.0

A fast, beautiful viewer for the documents your agents produce
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
//! Browse mode: read a folder straight from disk. Nothing of the folder is
//! stored, nothing reaches the library or the inbox. Files render on demand and
//! are cached in memory keyed by their modification time, so revisiting one is
//! instant and editing it on disk shows the new content.
//!
//! What is kept is the list of folders themselves, in `folders.json` beside the
//! token: a reader who opened three repositories finds the same three in the
//! sidebar after the daemon restarts, an upgrade included. Closing one from the
//! sidebar is what takes it out; a folder that is gone from disk when the
//! daemon comes up is dropped then.

use crate::render::{self, Renderer};
use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Component, Path, PathBuf};
use std::sync::{Mutex, RwLock};
use std::time::{Duration, Instant};

/// Files larger than this are described rather than rendered.
const MAX_RENDER_BYTES: u64 = 8 * 1024 * 1024;
/// Rendered pages held in memory across the whole browser.
const CACHE_ENTRIES: usize = 48;
/// Entries scanned for quick-open, and how long that scan is reused.
const FIND_CAP: usize = 40_000;
const FIND_TTL: Duration = Duration::from_secs(20);
/// Files and folders remembered per root for the change watcher: the ones most
/// recently rendered or listed, which is what a reader has on screen. Eight,
/// not thirty-two: a page shows one file and the folders open down to it,
/// and each one remembered is a stat on every tick for as long as the root
/// is open.
const WATCH_CAP: usize = 8;

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Root {
    pub id: String,
    pub name: String,
    pub path: String,
    pub opened_at: i64,
}

#[derive(Clone, Debug, Serialize)]
pub struct Entry {
    pub name: String,
    /// Path relative to the root, `/` separated. Empty for the root itself.
    pub path: String,
    pub dir: bool,
    pub size: u64,
}

#[derive(Debug, Serialize)]
pub struct FileView {
    pub path: String,
    pub name: String,
    /// markdown | code | diff | text | image | binary | large
    pub kind: String,
    pub lang: Option<String>,
    pub size: u64,
    pub modified: i64,
    pub html: String,
    /// "html" or "pdf" when this file can also be shown as a page, else None.
    pub preview: Option<String>,
    /// Where to point the preview frame. Path-shaped, so the page's own relative
    /// stylesheets and images resolve next to it.
    pub preview_url: Option<String>,
}

/// Something on screen that the watcher should keep an eye on.
#[derive(Clone, Debug)]
pub struct Watched {
    pub root: String,
    pub rel: String,
    pub dir: bool,
    pub path: PathBuf,
}

pub struct Browser {
    roots: RwLock<HashMap<String, Root>>,
    cache: Mutex<Vec<(String, String)>>,
    /// The rail's outline of a file, under the same key as its HTML. Parsing
    /// a long file for its declarations is the grammar's whole pass again --
    /// 1.9 s at 700 KB -- and the file has not changed since the last time.
    outlines: Mutex<Vec<(String, Vec<render::Outline>)>>,
    index: Mutex<HashMap<String, (Instant, Vec<String>)>>,
    /// Per root, most recent first.
    recent: Mutex<HashMap<String, Vec<Watched>>>,
    /// Where the list of open folders is kept between runs. None in tests.
    file: Option<PathBuf>,
    /// Folders closed since the daemon started, by id, so the page's Undo
    /// can put one back: the page holds no token, so it cannot open a path,
    /// but it can take back its own close.
    closed: Mutex<HashMap<String, Root>>,
}

impl Browser {
    pub fn new() -> Browser {
        Browser {
            roots: RwLock::new(HashMap::new()),
            cache: Mutex::new(Vec::new()),
            outlines: Mutex::new(Vec::new()),
            index: Mutex::new(HashMap::new()),
            recent: Mutex::new(HashMap::new()),
            file: None,
            closed: Mutex::new(HashMap::new()),
        }
    }

    /// A browser that remembers its folders in `file`, starting with whatever
    /// a previous run left there.
    ///
    /// Each remembered path is opened again the way a fresh one is, so a folder
    /// renamed or removed since is not a dead row in the sidebar: it is left
    /// out, and the file is rewritten without it. The original `opened_at` is
    /// kept so the sidebar's order does not shuffle on every restart.
    pub fn load(file: PathBuf) -> Browser {
        let mut b = Browser::new();
        let remembered: Vec<Root> = std::fs::read_to_string(&file)
            .ok()
            .and_then(|s| serde_json::from_str(&s).ok())
            .unwrap_or_default();
        b.file = Some(file);
        let remembered_n = remembered.len();
        let mut roots = HashMap::new();
        for r in remembered {
            let path = match Path::new(&r.path).canonicalize() {
                Ok(p) if p.is_dir() => p,
                _ => continue,
            };
            let key = path.to_string_lossy().to_string();
            let id = blake3::hash(key.as_bytes()).to_hex()[..8].to_string();
            roots.entry(id.clone()).or_insert(Root {
                id,
                name: path
                    .file_name()
                    .map(|n| n.to_string_lossy().to_string())
                    .unwrap_or_else(|| key.clone()),
                path: key,
                opened_at: r.opened_at,
            });
        }
        let dropped = roots.len() < remembered_n;
        *b.roots.write().unwrap() = roots;
        if dropped {
            b.save();
        }
        b
    }

    /// Write the open folders down, if this browser keeps them anywhere.
    /// Best effort: a folder that cannot be remembered is still open.
    fn save(&self) {
        let Some(file) = &self.file else { return };
        let roots = self.list();
        if let Some(dir) = file.parent() {
            let _ = std::fs::create_dir_all(dir);
        }
        if let Ok(json) = serde_json::to_string(&roots) {
            let _ = std::fs::write(file, json);
        }
    }

    pub fn open(&self, path: &Path) -> Result<Root> {
        let path = path
            .canonicalize()
            .with_context(|| format!("no such directory: {}", path.display()))?;
        if !path.is_dir() {
            bail!("{} is not a directory", path.display());
        }
        let key = path.to_string_lossy().to_string();
        // Re-opening the same folder returns the root already on screen.
        if let Some(existing) = self.roots.read().unwrap().values().find(|r| r.path == key) {
            return Ok(existing.clone());
        }
        let root = Root {
            id: blake3::hash(key.as_bytes()).to_hex()[..8].to_string(),
            name: path
                .file_name()
                .map(|n| n.to_string_lossy().to_string())
                .unwrap_or_else(|| key.clone()),
            path: key,
            opened_at: crate::store::now(),
        };
        self.roots
            .write()
            .unwrap()
            .insert(root.id.clone(), root.clone());
        self.save();
        Ok(root)
    }

    pub fn close(&self, id: &str) -> bool {
        self.index.lock().unwrap().remove(id);
        self.recent.lock().unwrap().remove(id);
        self.cache
            .lock()
            .unwrap()
            .retain(|(k, _)| !k.starts_with(id));
        self.outlines
            .lock()
            .unwrap()
            .retain(|(k, _)| !k.starts_with(id));
        let gone = self.roots.write().unwrap().remove(id);
        let was = gone.is_some();
        if let Some(root) = gone {
            self.closed.lock().unwrap().insert(root.id.clone(), root);
            self.save();
        }
        was
    }

    /// A close, taken back: the folder is open again under the same id, in
    /// the same place in the list. None when it was never closed here, or is
    /// no longer a folder.
    pub fn reopen(&self, id: &str) -> Option<Root> {
        let root = self.closed.lock().unwrap().remove(id)?;
        if !Path::new(&root.path).is_dir() {
            return None;
        }
        self.roots
            .write()
            .unwrap()
            .insert(root.id.clone(), root.clone());
        self.save();
        Some(root)
    }

    /// Forget what could be reopened: after a reset there is nothing to undo.
    pub fn forget_closed(&self) {
        self.closed.lock().unwrap().clear();
    }

    pub fn list(&self) -> Vec<Root> {
        let mut v: Vec<Root> = self.roots.read().unwrap().values().cloned().collect();
        v.sort_by_key(|r| r.opened_at);
        v
    }

    pub fn get(&self, id: &str) -> Option<Root> {
        self.roots.read().unwrap().get(id).cloned()
    }

    /// Absolute path for a root-relative path, refusing anything that escapes the root.
    pub fn resolve(&self, id: &str, rel: &str) -> Result<PathBuf> {
        let root = self.get(id).context("no such browse root")?;
        let root_path = PathBuf::from(&root.path);
        let rel = rel.trim_matches('/');
        if rel.is_empty() {
            return Ok(root_path);
        }
        let relp = Path::new(rel);
        if relp
            .components()
            .any(|c| !matches!(c, Component::Normal(_)))
        {
            bail!("path escapes the browse root");
        }
        let joined = root_path.join(relp);
        // Symlinks could still point outside, so compare canonical paths.
        let canon = joined
            .canonicalize()
            .with_context(|| format!("no such path: {rel}"))?;
        if !canon.starts_with(&root_path) {
            bail!("path escapes the browse root");
        }
        Ok(canon)
    }

    /// One directory level, folders first, honouring .gitignore and skipping hidden files.
    pub fn entries(&self, id: &str, rel: &str) -> Result<Vec<Entry>> {
        let dir = self.resolve(id, rel)?;
        let prefix = rel.trim_matches('/');
        self.note(id, prefix, true, dir.clone());
        let mut out = vec![];
        let walker = ignore::WalkBuilder::new(&dir)
            .max_depth(Some(1))
            .parents(true)
            .git_ignore(true)
            .git_global(true)
            .require_git(false)
            .hidden(true)
            .follow_links(false)
            .build();
        for entry in walker.flatten() {
            if entry.depth() == 0 {
                continue;
            }
            let meta = entry.metadata().ok();
            let name = entry.file_name().to_string_lossy().to_string();
            out.push(Entry {
                path: if prefix.is_empty() {
                    name.clone()
                } else {
                    format!("{prefix}/{name}")
                },
                dir: meta.as_ref().map(|m| m.is_dir()).unwrap_or(false),
                size: meta.as_ref().map(|m| m.len()).unwrap_or(0),
                name,
            });
        }
        out.sort_by(|a, b| {
            b.dir
                .cmp(&a.dir)
                .then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
        });
        Ok(out)
    }

    /// The declarations in a file, for the rail: empty for anything that is not
    /// code. Cached like `file`, by path plus modification time and size.
    pub fn outline(
        &self,
        id: &str,
        rel: &str,
        renderer: &Renderer,
    ) -> Result<Vec<render::Outline>> {
        let path = self.resolve(id, rel)?;
        let meta = std::fs::metadata(&path)?;
        let modified = meta
            .modified()
            .ok()
            .and_then(|m| m.duration_since(std::time::UNIX_EPOCH).ok())
            .map(|d| d.as_nanos())
            .unwrap_or(0);
        let key = format!("{id}\u{0}{rel}\u{0}{modified}\u{0}{}", meta.len());
        if let Some(hit) = self
            .outlines
            .lock()
            .unwrap()
            .iter()
            .find(|(k, _)| *k == key)
        {
            return Ok(hit.1.clone());
        }
        let bytes = std::fs::read(&path)?;
        let items = if render::looks_binary(&bytes) {
            vec![]
        } else {
            let text = String::from_utf8_lossy(&bytes);
            match renderer.detect(Some(&path.to_string_lossy()), None, &text) {
                (render::Kind::Code, lang) => renderer.outline(lang.as_deref(), &text),
                _ => vec![],
            }
        };
        let mut cache = self.outlines.lock().unwrap();
        if cache.len() >= CACHE_ENTRIES {
            cache.remove(0);
        }
        cache.push((key, items.clone()));
        Ok(items)
    }

    /// Render a file. Cached by path plus modification time, so an edit invalidates it.
    pub fn file(&self, id: &str, rel: &str, renderer: &Renderer) -> Result<FileView> {
        let path = self.resolve(id, rel)?;
        let meta = std::fs::metadata(&path)?;
        if meta.is_dir() {
            bail!("{rel} is a directory");
        }
        self.note(id, rel, false, path.clone());
        let modified = meta
            .modified()
            .ok()
            .and_then(|m| m.duration_since(std::time::UNIX_EPOCH).ok())
            .map(|d| d.as_secs() as i64)
            .unwrap_or(0);
        let name = path
            .file_name()
            .map(|n| n.to_string_lossy().to_string())
            .unwrap_or_default();
        let ext = path
            .extension()
            .map(|e| e.to_string_lossy().to_ascii_lowercase())
            .unwrap_or_default();
        // A page or a PDF can also be shown as itself, framed at its own raw URL so
        // its relative assets resolve. The source view stays the default for pages.
        // The modification time rides along so a refresh after an edit is not
        // answered from the browser's cache.
        let preview = render::preview_kind(&ext);
        let nanos = meta
            .modified()
            .ok()
            .and_then(|m| m.duration_since(std::time::UNIX_EPOCH).ok())
            .map(|d| d.as_nanos())
            .unwrap_or(0);
        let fresh_url = format!("{}?m={nanos}", raw_url(id, rel));
        let view = |kind: &str, lang: Option<String>, html: String| FileView {
            kind: kind.to_string(),
            lang,
            html,
            path: rel.to_string(),
            name: name.clone(),
            size: meta.len(),
            modified,
            preview: preview.map(str::to_string),
            preview_url: preview.map(|_| fresh_url.clone()),
        };

        if render::is_image_ext(&ext) {
            return Ok(view(
                "image",
                None,
                format!(
                    "<p class=\"browse-image\"><img src=\"{}\" alt=\"{}\" loading=\"lazy\" decoding=\"async\"></p>",
                    fresh_url,
                    html_escape::encode_double_quoted_attribute(&name)
                ),
            ));
        }
        // Played where it is, a range at a time, whatever its size.
        if let Some(kind) = render::media_kind(&ext) {
            return Ok(view(kind, None, render::media_body(&fresh_url, &ext)));
        }
        if meta.len() > MAX_RENDER_BYTES {
            return Ok(view(
                "large",
                None,
                render::placeholder(&format!(
                    "{} is {} MB, too large to display.",
                    name,
                    meta.len() / 1_048_576
                )),
            ));
        }

        let key = format!("{id}\u{0}{rel}\u{0}{modified}\u{0}{}", meta.len());
        if let Some(hit) = self.cache.lock().unwrap().iter().find(|(k, _)| *k == key) {
            let (kind, lang) = renderer.detect(Some(&path.to_string_lossy()), None, "");
            return Ok(view(kind.as_str(), lang, hit.1.clone()));
        }

        let bytes = std::fs::read(&path)?;
        // A PDF is for its viewer, not for reading as text, whether or not the first
        // block happens to hold a null byte.
        if preview == Some("pdf") || render::looks_binary(&bytes) {
            return Ok(view(
                "binary",
                None,
                render::placeholder(&render::describe_bytes(&name, meta.len())),
            ));
        }
        let text = String::from_utf8_lossy(&bytes).into_owned();
        let (kind, lang) = renderer.detect(Some(&path.to_string_lossy()), None, &text);
        // A browsed file keeps its own H1; there is no separate title to duplicate.
        // Cut before it is cached, so a revisit is not cut again.
        // Relative images resolve beside the file, through the raw route: left
        // alone they resolve against the page's own /b/ address, which answers
        // with the viewer rather than the picture.
        let dir = rel.rsplit_once('/').map_or("", |(d, _)| d);
        let base = if dir.is_empty() {
            raw_url(id, "")
        } else {
            format!("{}/", raw_url(id, dir))
        };
        let html = render::chunk_code(&renderer.render_with_base(
            kind,
            lang.as_deref(),
            &text,
            Some(&base),
        ))
        .into_owned();

        let mut cache = self.cache.lock().unwrap();
        if cache.len() >= CACHE_ENTRIES {
            cache.remove(0);
        }
        cache.push((key, html.clone()));
        drop(cache);

        Ok(view(kind.as_str(), lang, html))
    }

    /// Remember something as on screen, most recent first, so the watcher looks at it.
    fn note(&self, id: &str, rel: &str, dir: bool, path: PathBuf) {
        let rel = rel.trim_matches('/').to_string();
        let mut recent = self.recent.lock().unwrap();
        let list = recent.entry(id.to_string()).or_default();
        list.retain(|w| w.rel != rel);
        list.insert(
            0,
            Watched {
                root: id.to_string(),
                rel,
                dir,
                path,
            },
        );
        list.truncate(WATCH_CAP);
    }

    /// Everything the watcher should look at, across every open root.
    pub fn watched(&self) -> Vec<Watched> {
        self.recent
            .lock()
            .unwrap()
            .values()
            .flat_map(|v| v.iter().cloned())
            .collect()
    }

    /// The file a root opens on: a README if there is one, else nothing.
    pub fn landing(&self, id: &str) -> Option<String> {
        let entries = self.entries(id, "").ok()?;
        entries
            .iter()
            .find(|e| !e.dir && e.name.to_lowercase().starts_with("readme."))
            .map(|e| e.path.clone())
    }

    /// Quick-open: every path under the root, capped, cached briefly.
    pub fn find(&self, id: &str, q: &str, limit: usize) -> Result<Vec<String>> {
        let all = self.paths(id)?;
        let q = q.trim().to_lowercase();
        if q.is_empty() {
            let mut v = all;
            v.truncate(limit);
            return Ok(v);
        }
        let mut hits: Vec<(u8, usize, String)> = all
            .into_iter()
            .filter_map(|p| {
                let lower = p.to_lowercase();
                let base = lower.rsplit('/').next().unwrap_or(&lower).to_string();
                let rank = if base.starts_with(&q) {
                    0
                } else if base.contains(&q) {
                    1
                } else if lower.contains(&q) {
                    2
                } else {
                    return None;
                };
                Some((rank, p.len(), p))
            })
            .collect();
        hits.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
        hits.truncate(limit);
        Ok(hits.into_iter().map(|(_, _, p)| p).collect())
    }

    fn paths(&self, id: &str) -> Result<Vec<String>> {
        if let Some((at, list)) = self.index.lock().unwrap().get(id) {
            if at.elapsed() < FIND_TTL {
                return Ok(list.clone());
            }
        }
        let root = self.get(id).context("no such browse root")?;
        let root_path = PathBuf::from(&root.path);
        let mut out = vec![];
        for entry in ignore::WalkBuilder::new(&root_path)
            .parents(true)
            .git_ignore(true)
            .git_global(true)
            .require_git(false)
            .hidden(true)
            .follow_links(false)
            .build()
            .flatten()
        {
            if entry.depth() == 0 || entry.file_type().map(|t| t.is_dir()).unwrap_or(true) {
                continue;
            }
            if let Ok(rel) = entry.path().strip_prefix(&root_path) {
                out.push(rel.to_string_lossy().replace('\\', "/"));
            }
            if out.len() >= FIND_CAP {
                break;
            }
        }
        out.sort();
        self.index
            .lock()
            .unwrap()
            .insert(id.to_string(), (Instant::now(), out.clone()));
        Ok(out)
    }
}

/// The path-shaped raw URL for a file in a browsed root. Path-shaped rather than
/// `?path=`, so a framed page resolves `./style.css` to the file beside it.
fn raw_url(id: &str, rel: &str) -> String {
    format!("/api/browse/{id}/raw/{}", urlencode(rel))
}

pub(crate) fn urlencode(s: &str) -> String {
    s.bytes()
        .map(|b| match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => {
                (b as char).to_string()
            }
            _ => format!("%{b:02X}"),
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::store::tempdir::Dir;

    fn fixture() -> (Browser, Dir) {
        let d = Dir::new("snyvi-browse");
        std::fs::create_dir_all(d.path.join("src")).unwrap();
        std::fs::create_dir_all(d.path.join("node_modules/junk")).unwrap();
        std::fs::create_dir_all(d.path.join(".hidden")).unwrap();
        std::fs::write(d.path.join("README.md"), "# Title\n\nhello browse\n").unwrap();
        std::fs::write(d.path.join(".gitignore"), "node_modules/\nbuild.log\n").unwrap();
        std::fs::write(d.path.join("build.log"), "noise").unwrap();
        std::fs::write(d.path.join("src/main.rs"), "fn main() { let x = 1; }\n").unwrap();
        std::fs::write(d.path.join("node_modules/junk/x.js"), "junk").unwrap();
        std::fs::write(d.path.join(".hidden/secret"), "shh").unwrap();
        std::fs::write(d.path.join("blob.bin"), [0u8, 1, 2, 3]).unwrap();
        std::fs::write(d.path.join("page.html"), "<h1>hi</h1>").unwrap();
        // No null byte in the header, so only the extension marks it as a PDF.
        std::fs::write(d.path.join("paper.pdf"), b"%PDF-1.4\n1 0 obj\n").unwrap();
        (Browser::new(), d)
    }

    #[test]
    fn remembers_open_folders_across_a_restart() {
        let (_, d) = fixture();
        let file = d.path.join("folders.json");
        let gone = d.path.join("gone");
        std::fs::create_dir_all(&gone).unwrap();

        // A first daemon opens two folders and stops.
        let first = Browser::load(file.clone());
        let src = first.open(&d.path.join("src")).unwrap();
        let g = first.open(&gone).unwrap();
        assert!(file.exists(), "opening a folder writes it down");
        drop(first);

        // One of them is removed from disk in the meantime.
        std::fs::remove_dir(&gone).unwrap();

        // The next daemon has the one that is still there, under the same id,
        // and has already forgotten the other.
        let second = Browser::load(file.clone());
        let ids: Vec<String> = second.list().into_iter().map(|r| r.id).collect();
        assert_eq!(ids, vec![src.id.clone()], "kept: {ids:?}");
        assert_eq!(second.get(&src.id).unwrap().opened_at, src.opened_at);
        assert!(second.get(&g.id).is_none());
        let on_disk: Vec<Root> =
            serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap();
        assert_eq!(on_disk.len(), 1, "the missing folder is written out too");

        // Closing is what forgets a folder on purpose.
        assert!(second.close(&src.id));
        let on_disk: Vec<Root> =
            serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap();
        assert!(on_disk.is_empty());
        assert!(Browser::load(file).list().is_empty());

        // A browser with nowhere to write remembers nothing and writes nothing.
        let plain = Browser::new();
        plain.open(&d.path.join("src")).unwrap();
        assert!(!d.path.join("src").join("folders.json").exists());
    }

    #[test]
    fn lists_one_level_and_respects_ignores() {
        let (b, d) = fixture();
        let r = b.open(&d.path).unwrap();
        let names: Vec<String> = b
            .entries(&r.id, "")
            .unwrap()
            .into_iter()
            .map(|e| e.name)
            .collect();
        assert_eq!(
            names.first().map(String::as_str),
            Some("src"),
            "directories sort first: {names:?}"
        );
        assert!(names.contains(&"README.md".to_string()));
        assert!(
            !names.contains(&"node_modules".to_string()),
            "gitignored: {names:?}"
        );
        assert!(
            !names.contains(&"build.log".to_string()),
            "gitignored: {names:?}"
        );
        assert!(!names.contains(&".hidden".to_string()), "hidden: {names:?}");
        let sub: Vec<String> = b
            .entries(&r.id, "src")
            .unwrap()
            .into_iter()
            .map(|e| e.path)
            .collect();
        assert_eq!(sub, vec!["src/main.rs"]);
    }

    #[test]
    fn markdown_images_resolve_beside_the_file() {
        let (b, d) = fixture();
        std::fs::create_dir_all(d.path.join("docs")).unwrap();
        std::fs::write(d.path.join("top.md"), "![a](a.png)\n").unwrap();
        std::fs::write(
            d.path.join("docs/kit.md"),
            "![b](./img/b.png) ![c](https://h/c.png) ![e](/abs.png)\n",
        )
        .unwrap();
        let rn = Renderer::new();
        let r = b.open(&d.path).unwrap();
        let top = b.file(&r.id, "top.md", &rn).unwrap().html;
        assert!(
            top.contains(&format!("src=\"/api/browse/{}/raw/a.png\"", r.id)),
            "{top}"
        );
        let kit = b.file(&r.id, "docs/kit.md", &rn).unwrap().html;
        assert!(
            kit.contains(&format!("src=\"/api/browse/{}/raw/docs/img/b.png\"", r.id)),
            "{kit}"
        );
        assert!(kit.contains("src=\"https://h/c.png\""), "{kit}");
        assert!(kit.contains("src=\"/abs.png\""), "{kit}");
    }

    #[test]
    fn renders_files_and_classifies_special_ones() {
        let (b, d) = fixture();
        let rn = Renderer::new();
        let r = b.open(&d.path).unwrap();
        let md = b.file(&r.id, "README.md", &rn).unwrap();
        assert_eq!(md.kind, "markdown");
        assert!(
            md.html.contains("<h1"),
            "browsed markdown keeps its own H1: {}",
            md.html
        );
        assert!(md.html.contains("hello browse"));
        let rs = b.file(&r.id, "src/main.rs", &rn).unwrap();
        assert_eq!(rs.kind, "code");
        assert!(rs.html.contains("class=\"k\""));
        let bin = b.file(&r.id, "blob.bin", &rn).unwrap();
        assert_eq!(bin.kind, "binary");
        assert!(bin.html.contains("binary file"));
        assert_eq!(b.landing(&r.id).as_deref(), Some("README.md"));

        // A page keeps its markup as the default view, and offers itself as a preview
        // at a path-shaped URL so its relative assets resolve beside it.
        let page = b.file(&r.id, "page.html", &rn).unwrap();
        assert_eq!(page.kind, "code");
        assert_eq!(page.preview.as_deref(), Some("html"));
        let purl = page.preview_url.as_deref().unwrap();
        assert!(
            purl.starts_with(&format!("/api/browse/{}/raw/page.html?m=", r.id)),
            "path-shaped, stamped with the mtime: {purl}"
        );

        // A PDF is for its viewer, not for reading as text, null byte or not.
        let pdf = b.file(&r.id, "paper.pdf", &rn).unwrap();
        assert_eq!(pdf.kind, "binary");
        assert_eq!(pdf.preview.as_deref(), Some("pdf"));
        assert!(pdf.html.contains("binary file"));

        // Everything else offers no preview at all.
        assert!(md.preview.is_none());
        assert!(bin.preview.is_none());
    }

    #[test]
    fn watched_is_what_was_rendered_or_listed_most_recently() {
        let (b, d) = fixture();
        let rn = Renderer::new();
        let r = b.open(&d.path).unwrap();
        assert!(b.watched().is_empty());
        b.entries(&r.id, "").unwrap();
        b.file(&r.id, "src/main.rs", &rn).unwrap();
        b.file(&r.id, "README.md", &rn).unwrap();
        b.file(&r.id, "src/main.rs", &rn).unwrap();
        let w = b.watched();
        let rels: Vec<(&str, bool)> = w.iter().map(|w| (w.rel.as_str(), w.dir)).collect();
        assert_eq!(
            rels,
            vec![("src/main.rs", false), ("README.md", false), ("", true)],
            "most recent first, no duplicates, the listed root folder included"
        );
        assert!(w[0].path.ends_with("src/main.rs"));
        assert!(w[2].path.is_dir());
        assert!(b.close(&r.id));
        assert!(b.watched().is_empty(), "closing a root forgets its files");
    }

    #[test]
    fn refuses_paths_outside_the_root() {
        let (b, d) = fixture();
        let r = b.open(&d.path).unwrap();
        for bad in ["../etc/passwd", "src/../../x", "/etc/passwd"] {
            assert!(b.resolve(&r.id, bad).is_err(), "{bad} should be refused");
        }
        assert!(b.resolve(&r.id, "src/main.rs").is_ok());
        assert!(b.resolve("nope", "README.md").is_err());
    }

    #[test]
    fn find_ranks_basename_matches_first_and_close_drops_the_root() {
        let (b, d) = fixture();
        let r = b.open(&d.path).unwrap();
        let hits = b.find(&r.id, "main", 10).unwrap();
        assert_eq!(hits, vec!["src/main.rs"]);
        assert!(b
            .find(&r.id, "", 10)
            .unwrap()
            .contains(&"README.md".to_string()));
        assert!(
            b.find(&r.id, "junk", 10).unwrap().is_empty(),
            "ignored files stay out of quick-open"
        );
        // Opening the same folder twice is the same root.
        assert_eq!(b.open(&d.path).unwrap().id, r.id);
        assert!(b.close(&r.id));
        assert!(!b.close(&r.id));
        assert!(b.list().is_empty());
        // And taken back: the same root, once.
        assert_eq!(b.reopen(&r.id).map(|x| x.id), Some(r.id.clone()));
        assert_eq!(b.list().len(), 1);
        assert!(b.reopen(&r.id).is_none(), "open already");
        assert!(b.reopen("nope").is_none());
    }
}