eclipse-core 0.13.1

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
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
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
//! `#499`: pictures on disk — the original at full size, and a copy small enough for the wire.
//!
//! A picture rides in every later request of the session, so a 2 MiB ceiling on what goes on the
//! wire is right. Applying that ceiling to the *file someone attached* was not: an 18 MB photo
//! from a camera could not enter the conversation at all, and the only options it left — shrink it
//! yourself, or put it on the box and pass a path — both lose the thing the person wanted.
//!
//! So two copies, and they mean different things:
//!
//! - **The original**, byte-identical to what was uploaded, under
//!   `<root>/<session>/<sha256[:16]>-<name>.<ext>`. Never rewritten; the hash in the name means a
//!   re-sent picture costs nothing and two sessions' copies stay distinct. A later turn can crop it
//!   at full resolution, hand it to a render as a reference, or send it as a file.
//! - **The working copy**, at or under [`COPY_TARGET_BYTES`], sent to the model. Shrunk to
//!   [`MAX_EDGE`] and then by quality, in that order, because resolution is what a model reads.
//!   PNG stays PNG (a screenshot re-encoded as JPEG rings around text, which is exactly what the
//!   model was asked about); JPEG stays JPEG at q88.
//!
//! A picture already under the target needs no second file: the original *is* the working copy, and
//! `Stored::resized` says so. That is the common case — a screenshot — and it costs one write.
//!
//! Nothing here calls a network, and nothing here modifies a file it did not create. The store is
//! `0600` in a `0700` directory, and [`Store::prune`] is least-recently-used against a byte budget,
//! because an 18 MB-per-photo default with no ceiling fills a disk.

use std::path::{Path, PathBuf};
use std::process::Stdio;

/// The wire limit a picture has to fit: what rides in the request body and in the history.
pub const WIRE_LIMIT_BYTES: usize = 2 * 1024 * 1024;

/// What a working copy aims for, so it has headroom under [`WIRE_LIMIT_BYTES`] rather than exactly
/// touching it — base64 padding and a header's own overhead are not worth a refusal.
pub const COPY_TARGET_BYTES: usize = 3 * 1024 * 1024 / 2;

/// The longest edge a working copy keeps. Enough for a model to read text in a screenshot and to
/// see detail in a photo, and small enough that the copy is a fraction of the original.
pub const MAX_EDGE: u32 = 2048;

/// A picture kept on disk.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Stored {
    /// The file exactly as uploaded.
    pub original: PathBuf,
    /// What the model is shown — the original itself when no shrink was needed.
    pub working: PathBuf,
    /// Bytes in the original.
    pub bytes: usize,
    /// Bytes in the working copy.
    pub working_bytes: usize,
    /// The original's pixel size, when the header could be read.
    pub size: Option<(u32, u32)>,
    /// Whether a second file was derived.
    pub resized: bool,
}

impl Stored {
    /// The line the user message carries, so the model knows it is looking at a copy and where the
    /// real file is (`#499` acceptance 2). One sentence, no second paragraph.
    pub fn note(&self, name: &str) -> String {
        let size = match self.size {
            Some((w, h)) => format!("{w}×{h}"),
            None => "unknown size".to_string(),
        };
        if self.resized {
            let edge = self.size.map(|(w, h)| w.max(h)).unwrap_or(MAX_EDGE);
            format!(
                "[attached: {name} — the original is at {} ({} KB, {size}). You are looking at a \
                 {} px copy; use the original's path with `read_file` or a tool if you need the \
                 full resolution.]",
                self.original.display(),
                self.bytes / 1024,
                edge.min(MAX_EDGE),
            )
        } else {
            format!(
                "[attached: {name} — {} KB, {size}, stored at {}. This is the original.]",
                self.bytes / 1024,
                self.original.display(),
            )
        }
    }
}

/// Where pictures are kept, and how much room they may take.
#[derive(Debug, Clone)]
pub struct Store {
    root: PathBuf,
    max_total_bytes: u64,
    /// The resize helper this process will use, probed once by [`Store::probe`].
    helper: Option<Helper>,
}

impl Store {
    /// `<state_dir>/attachments`, or the `[attachments] dir` override.
    pub fn new(root: PathBuf, max_total_bytes: u64) -> Self {
        Self {
            root,
            max_total_bytes,
            helper: Helper::probe(),
        }
    }

    /// The same store with a named helper — a test's only way to exercise the Pillow branch on a
    /// machine that also has ImageMagick (`#499` acceptance 6).
    pub fn with_helper(mut self, helper: Option<Helper>) -> Self {
        self.helper = helper;
        self
    }

    pub fn root(&self) -> &Path {
        &self.root
    }

    /// Keep a picture: the original untouched, and a working copy that fits the wire.
    ///
    /// Bytes are written once per distinct picture — the file name is the hash, so a re-sent
    /// picture is a touch for the LRU clock and no write.
    pub fn keep(
        &self,
        session: &str,
        name: &str,
        mime: &str,
        bytes: &[u8],
    ) -> Result<Stored, String> {
        if bytes.is_empty() {
            return Err("the picture carries no bytes".to_string());
        }
        let (_, ext) = kind(mime, bytes)?;
        let name = sanitise(name, ext);
        let digest = hex16(bytes);
        let dir = self.root.join(sanitise_segment(session));
        let original = dir.join(format!("{digest}-{name}"));
        std::fs::create_dir_all(&dir)
            .map_err(|e| format!("could not make {}: {e}", dir.display()))?;
        restrict(&dir, 0o700);
        if !original.exists() {
            let need = bytes.len() as u64;
            let total = self.total_bytes();
            if total + need > self.max_total_bytes {
                let freed = self.prune(need)?;
                if self.total_bytes() + need > self.max_total_bytes {
                    return Err(format!(
                        "the pictures on disk already hold {} MB of the {} MB budget{}; \
                         `/attachments clear` or a bigger `[attachments] max_total_bytes` makes \
                         room",
                        (self.total_bytes() - freed) / (1024 * 1024),
                        self.max_total_bytes / (1024 * 1024),
                        if freed > 0 {
                            format!(
                                ", and pruning {} MB of the oldest was not enough",
                                freed / (1024 * 1024)
                            )
                        } else {
                            String::new()
                        }
                    ));
                }
            }
            write_private(&original, bytes)?;
        } else {
            touch(&original);
        }
        let size = dimensions(bytes);
        // Under the target: the original is what the model gets, and there is no second file.
        if bytes.len() <= COPY_TARGET_BYTES {
            return Ok(Stored {
                working: original.clone(),
                original,
                bytes: bytes.len(),
                working_bytes: bytes.len(),
                size,
                resized: false,
            });
        }
        let Some(helper) = self.helper.clone() else {
            return Err(format!(
                "this picture is {} KB and has to be shrunk to {} KB for the request, and no \
                 helper was found to do it: install ImageMagick (`magick`), Python Pillow \
                 (`python3 -m pip install pillow`) or `ffmpeg`. The original is kept at {} — pass \
                 that path instead, and the agent can work on it at full size",
                bytes.len() / 1024,
                COPY_TARGET_BYTES / 1024,
                original.display()
            ));
        };
        let stem = original
            .file_stem()
            .map(|s| s.to_string_lossy().to_string())
            .unwrap_or_else(|| digest.clone());
        let out_name = format!("{stem}-{MAX_EDGE}.{ext}");
        let working = dir.join(out_name);
        if !working.exists() {
            shrink(helper, &original, &working, ext)?;
        }
        let working_bytes = std::fs::metadata(&working)
            .map(|m| m.len() as usize)
            .unwrap_or(0);
        if working_bytes == 0 || working_bytes > WIRE_LIMIT_BYTES {
            return Err(format!(
                "the copy at {} is {} KB, still over the {} KB a request may carry — the original \
                 is kept at {}",
                working.display(),
                working_bytes / 1024,
                WIRE_LIMIT_BYTES / 1024,
                original.display()
            ));
        }
        Ok(Stored {
            working,
            original,
            bytes: bytes.len(),
            working_bytes,
            size,
            resized: true,
        })
    }

    /// Every file and directory this store holds, oldest first — the pruning order.
    fn by_age(&self) -> Vec<(PathBuf, u64, std::time::SystemTime)> {
        let mut out = Vec::new();
        let Ok(sessions) = std::fs::read_dir(&self.root) else {
            return out;
        };
        for session in sessions.flatten() {
            let Ok(files) = std::fs::read_dir(session.path()) else {
                continue;
            };
            for file in files.flatten() {
                let Ok(meta) = file.metadata() else {
                    continue;
                };
                if !meta.is_file() {
                    continue;
                }
                let when = meta
                    .modified()
                    .or_else(|_| meta.accessed())
                    .unwrap_or(std::time::UNIX_EPOCH);
                out.push((file.path(), meta.len(), when));
            }
        }
        out.sort_by_key(|(_, _, when)| *when);
        out
    }

    /// Bytes on disk across every session.
    pub fn total_bytes(&self) -> u64 {
        self.by_age().iter().map(|(_, len, _)| *len).sum()
    }

    /// Delete the oldest files until `need` bytes are freed, or nothing is left to delete.
    ///
    /// Least-recently-used, not per-session: the budget is about the disk, and a session nobody has
    /// opened in a month is the right thing to lose. Returns the bytes freed.
    pub fn prune(&self, need: u64) -> Result<u64, String> {
        let mut freed = 0;
        for (path, len, _) in self.by_age() {
            if freed >= need {
                break;
            }
            match std::fs::remove_file(&path) {
                Ok(()) => freed += len,
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
                Err(e) => return Err(format!("could not remove {}: {e}", path.display())),
            }
        }
        // Directories are left alone: pruning deletes files, and a directory emptied by pruning is
        // the caller's own attach in progress — `forget` is what removes a session's directory.
        Ok(freed)
    }

    /// Remove every picture a session kept (`sessions delete`).
    pub fn forget(&self, session: &str) -> Result<(), String> {
        let dir = self.root.join(sanitise_segment(session));
        match std::fs::remove_dir_all(&dir) {
            Ok(()) => Ok(()),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
            Err(e) => Err(format!("could not remove {}: {e}", dir.display())),
        }
    }
}

/// One of the three helpers this build knows how to drive, chosen by what is installed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Helper {
    /// ImageMagick 7's `magick`, or IM 6's `convert`.
    Magick(PathBuf),
    /// `python3` with Pillow importable.
    Pillow(PathBuf),
    Ffmpeg(PathBuf),
}

impl Helper {
    /// The first that works, in the order the issue asked for: ImageMagick, Pillow, ffmpeg.
    pub fn probe() -> Option<Self> {
        for candidate in ["magick", "convert"] {
            if let Some(path) = which(candidate) {
                if works(&path, &["-version"]) {
                    return Some(Self::Magick(path));
                }
            }
        }
        if let Some(path) = which("python3") {
            if works(
                &path,
                &[
                    "-c",
                    "import PIL.Image, sys; sys.exit(0 if PIL.Image.__version__ else 1)",
                ],
            ) {
                return Some(Self::Pillow(path));
            }
        }
        which("ffmpeg")
            .filter(|path| works(path, &["-version"]))
            .map(Self::Ffmpeg)
    }

    /// What `doctor` says about it.
    pub fn name(&self) -> String {
        match self {
            Self::Magick(p) => format!("ImageMagick ({})", p.display()),
            Self::Pillow(p) => format!("Pillow via {}", p.display()),
            Self::Ffmpeg(p) => format!("ffmpeg ({})", p.display()),
        }
    }
}

/// Shrink `from` into `to`, stepping quality first and resolution second.
///
/// Resolution is what a model reads, so it goes last: a 2048 px copy at q70 still has the text in
/// it, and a 1024 px copy at q95 does not.
fn shrink(helper: Helper, from: &Path, to: &Path, ext: &str) -> Result<(), String> {
    let jpeg = ext.eq_ignore_ascii_case("jpg") || ext.eq_ignore_ascii_case("jpeg");
    let steps = if jpeg {
        vec![(MAX_EDGE, 88), (MAX_EDGE, 78), (1536, 82), (1024, 80)]
    } else {
        // PNG is lossless: the only step that works is fewer pixels.
        vec![(MAX_EDGE, 0), (1536, 0), (1024, 0), (768, 0)]
    };
    let mut last = String::new();
    for (edge, quality) in steps {
        match run(helper.clone(), from, to, edge, quality) {
            Ok(()) => {
                let len = std::fs::metadata(to).map(|m| m.len() as usize).unwrap_or(0);
                if len > 0 && len <= COPY_TARGET_BYTES {
                    return Ok(());
                }
                last = format!("{} KB at {edge} px", len / 1024);
            }
            Err(e) => last = e,
        }
    }
    // Something was written and is merely bigger than the target: the caller checks the hard limit,
    // so a copy under the wire limit is still a copy worth sending.
    if to.exists() && std::fs::metadata(to).map(|m| m.len() as usize).unwrap_or(0) > 0 {
        return Ok(());
    }
    Err(format!("could not shrink the picture ({last})"))
}

fn run(helper: Helper, from: &Path, to: &Path, edge: u32, quality: u32) -> Result<(), String> {
    let (program, args) = match helper {
        Helper::Magick(bin) => {
            let mut args: Vec<String> = vec![
                from.display().to_string(),
                "-resize".into(),
                format!("{edge}x{edge}>"),
                "-strip".into(),
            ];
            if quality > 0 {
                args.push("-quality".into());
                args.push(quality.to_string());
            }
            args.push(to.display().to_string());
            (bin, args)
        }
        Helper::Pillow(bin) => {
            // `thumbnail` keeps the aspect ratio and never enlarges; `sys.argv` keeps the script
            // free of anything a shell would have to quote.
            let script = "import sys\n\
                          from PIL import Image\n\
                          src, dst, edge, quality = sys.argv[1], sys.argv[2], int(sys.argv[3]), int(sys.argv[4])\n\
                          im = Image.open(src)\n\
                          im.thumbnail((edge, edge))\n\
                          if quality:\n\
                          \x20   im.save(dst, quality=quality, optimize=True)\n\
                          else:\n\
                          \x20   im.save(dst, optimize=True)\n";
            (
                bin,
                vec![
                    "-c".into(),
                    script.into(),
                    from.display().to_string(),
                    to.display().to_string(),
                    edge.to_string(),
                    quality.to_string(),
                ],
            )
        }
        Helper::Ffmpeg(bin) => {
            let mut args: Vec<String> = vec![
                "-y".into(),
                "-loglevel".into(),
                "error".into(),
                "-i".into(),
                from.display().to_string(),
                "-vf".into(),
                format!(
                    "scale='min({edge},iw)':'min({edge},ih)':force_original_aspect_ratio=decrease"
                ),
            ];
            if quality > 0 {
                args.push("-q:v".into());
                // ffmpeg's JPEG scale is 2–31 and runs the other way.
                args.push((31u32.saturating_sub(quality / 4)).clamp(2, 31).to_string());
            }
            args.push(to.display().to_string());
            (bin, args)
        }
    };
    let out = std::process::Command::new(&program)
        .args(&args)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::piped())
        .output()
        .map_err(|e| format!("{} could not run: {e}", program.display()))?;
    if !out.status.success() {
        let err = String::from_utf8_lossy(&out.stderr);
        return Err(format!(
            "{} failed on {}: {}",
            program.display(),
            from.display(),
            err.lines().next().unwrap_or("no message")
        ));
    }
    Ok(())
}

fn which(bin: &str) -> Option<PathBuf> {
    let path = std::env::var_os("PATH")?;
    std::env::split_paths(&path)
        .map(|dir| dir.join(bin))
        .find(|p| p.is_file())
}

fn works(bin: &Path, args: &[&str]) -> bool {
    std::process::Command::new(bin)
        .args(args)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
}

/// The extension for a picture, and a refusal for anything else — the same four types the wire
/// carries, checked against the bytes rather than the header's word for them.
fn kind(mime: &str, bytes: &[u8]) -> Result<(&'static str, &'static str), String> {
    let found = if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
        ("image/png", "png")
    } else if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) {
        ("image/jpeg", "jpg")
    } else if bytes.len() > 12 && &bytes[0..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
        ("image/webp", "webp")
    } else if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {
        ("image/gif", "gif")
    } else {
        return Err(format!(
            "the bytes are not a picture this build can carry ({mime}); a picture has to be PNG, \
             JPEG, WebP or GIF"
        ));
    };
    Ok(found)
}

/// The pixel size, read from the header — PNG, JPEG, WebP and GIF, no decoder.
///
/// This is deliberately a header read and not a decode: it costs nothing, it cannot fail on a valid
/// file the helpers can still open, and the number is only used to tell the model what it has.
pub fn dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
    if bytes.len() > 24 && bytes.starts_with(b"\x89PNG\r\n\x1a\n") && &bytes[12..16] == b"IHDR" {
        let w = u32::from_be_bytes(bytes[16..20].try_into().ok()?);
        let h = u32::from_be_bytes(bytes[20..24].try_into().ok()?);
        return Some((w, h));
    }
    if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {
        if bytes.len() < 10 {
            return None;
        }
        let w = u16::from_le_bytes([bytes[6], bytes[7]]) as u32;
        let h = u16::from_le_bytes([bytes[8], bytes[9]]) as u32;
        return Some((w, h));
    }
    if bytes.len() > 30 && &bytes[0..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
        return webp_size(bytes);
    }
    if bytes.starts_with(&[0xFF, 0xD8]) {
        return jpeg_size(bytes);
    }
    None
}

/// A JPEG's size lives in whichever start-of-frame marker comes first, after a run of segments.
fn jpeg_size(bytes: &[u8]) -> Option<(u32, u32)> {
    let mut i = 2;
    while i + 9 < bytes.len() {
        if bytes[i] != 0xFF {
            i += 1;
            continue;
        }
        let marker = bytes[i + 1];
        // Standalone markers carry no length.
        if (0xD0..=0xD9).contains(&marker) || marker == 0x01 {
            i += 2;
            continue;
        }
        let len = u16::from_be_bytes([bytes[i + 2], bytes[i + 3]]) as usize;
        // SOF0..SOF15, except the four that are not frames (DHT, JPG, DAC).
        if (0xC0..=0xCF).contains(&marker) && !matches!(marker, 0xC4 | 0xC8 | 0xCC) {
            let h = u16::from_be_bytes([bytes[i + 5], bytes[i + 6]]) as u32;
            let w = u16::from_be_bytes([bytes[i + 7], bytes[i + 8]]) as u32;
            return Some((w, h));
        }
        i += 2 + len;
    }
    None
}

fn webp_size(bytes: &[u8]) -> Option<(u32, u32)> {
    let chunk = &bytes[12..16];
    match chunk {
        b"VP8X" if bytes.len() >= 30 => {
            let w = 1 + u32::from_le_bytes([bytes[24], bytes[25], bytes[26], 0]);
            let h = 1 + u32::from_le_bytes([bytes[27], bytes[28], bytes[29], 0]);
            Some((w, h))
        }
        b"VP8 " if bytes.len() >= 30 => {
            let w = u16::from_le_bytes([bytes[26], bytes[27]]) as u32 & 0x3FFF;
            let h = u16::from_le_bytes([bytes[28], bytes[29]]) as u32 & 0x3FFF;
            Some((w, h))
        }
        b"VP8L" if bytes.len() >= 25 => {
            let bits = u32::from_le_bytes([bytes[21], bytes[22], bytes[23], bytes[24]]);
            let w = (bits & 0x3FFF) + 1;
            let h = ((bits >> 14) & 0x3FFF) + 1;
            Some((w, h))
        }
        _ => None,
    }
}

/// The hash in the file name: the first 16 hex characters of SHA-256.
fn hex16(bytes: &[u8]) -> String {
    let digest = ring::digest::digest(&ring::digest::SHA256, bytes);
    digest.as_ref()[..8]
        .iter()
        .map(|b| format!("{b:02x}"))
        .collect()
}

/// A name safe to put on disk: no separators, no dots at the front, nothing shell-special.
fn sanitise(name: &str, ext: &str) -> String {
    let stem = name
        .rsplit('/')
        .next()
        .unwrap_or("picture")
        .rsplit_once('.')
        .map(|(stem, _)| stem)
        .unwrap_or(name);
    let cleaned: String = stem
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
                c
            } else {
                '-'
            }
        })
        .collect();
    let cleaned = cleaned.trim_matches('-');
    let stem = if cleaned.is_empty() {
        "picture"
    } else {
        cleaned
    };
    format!("{}.{ext}", stem.chars().take(40).collect::<String>())
}

fn sanitise_segment(session: &str) -> String {
    let cleaned: String = session
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
                c
            } else {
                '-'
            }
        })
        .collect();
    if cleaned.is_empty() {
        "unknown".to_string()
    } else {
        cleaned
    }
}

fn write_private(path: &Path, bytes: &[u8]) -> Result<(), String> {
    use std::io::Write;
    let mut file = std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(path)
        .map_err(|e| format!("could not create {}: {e}", path.display()))?;
    file.write_all(bytes)
        .map_err(|e| format!("could not write {}: {e}", path.display()))?;
    restrict(path, 0o600);
    Ok(())
}

#[cfg(unix)]
fn restrict(path: &Path, mode: u32) {
    use std::os::unix::fs::PermissionsExt;
    let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode));
}

#[cfg(not(unix))]
fn restrict(_path: &Path, _mode: u32) {}

fn touch(path: &Path) {
    // The mtime is the LRU clock, so a picture sent again has to read as recent — and nothing in
    // the file may change to make that true.
    if let Ok(file) = std::fs::OpenOptions::new().read(true).open(path) {
        let _ = file.set_modified(std::time::SystemTime::now());
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A valid PNG of the requested size, built here rather than shipped as a fixture.
    ///
    /// The IDAT holds *stored* deflate blocks (no compression at all), which keeps the encoder to
    /// arithmetic this file already has to do and makes a picture big enough to exercise the shrink
    /// path without committing megabytes to the repository.
    pub fn png(width: u32, height: u32, rgb: [u8; 3]) -> Vec<u8> {
        let mut raw = Vec::with_capacity((height * (1 + width * 3)) as usize);
        for y in 0..height {
            raw.push(0); // filter: none
            for x in 0..width {
                // A pattern rather than a flat fill: a flat image compresses to nothing, and the
                // point of this fixture is a file with real size.
                raw.extend_from_slice(&[
                    rgb[0].wrapping_add((x % 251) as u8),
                    rgb[1].wrapping_add((y % 241) as u8),
                    rgb[2],
                ]);
            }
        }
        let zlib = stored_zlib(&raw);
        let mut png = Vec::new();
        png.extend_from_slice(b"\x89PNG\r\n\x1a\n");
        let mut ihdr = Vec::new();
        ihdr.extend_from_slice(&width.to_be_bytes());
        ihdr.extend_from_slice(&height.to_be_bytes());
        ihdr.extend_from_slice(&[8, 2, 0, 0, 0]); // 8-bit RGB, no interlace
        chunk(&mut png, b"IHDR", &ihdr);
        chunk(&mut png, b"IDAT", &zlib);
        chunk(&mut png, b"IEND", &[]);
        png
    }

    fn chunk(out: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
        out.extend_from_slice(&(data.len() as u32).to_be_bytes());
        out.extend_from_slice(kind);
        out.extend_from_slice(data);
        let mut crc_input = kind.to_vec();
        crc_input.extend_from_slice(data);
        out.extend_from_slice(&crc(&crc_input).to_be_bytes());
    }

    fn crc(data: &[u8]) -> u32 {
        let mut crc = 0xFFFF_FFFFu32;
        for byte in data {
            crc ^= *byte as u32;
            for _ in 0..8 {
                let mask = (crc & 1).wrapping_neg();
                crc = (crc >> 1) ^ (0xEDB8_8320 & mask);
            }
        }
        !crc
    }

    fn stored_zlib(raw: &[u8]) -> Vec<u8> {
        let mut out = vec![0x78, 0x01];
        let mut rest = raw;
        loop {
            let take = rest.len().min(65535);
            let last = take == rest.len();
            out.push(if last { 1 } else { 0 });
            out.extend_from_slice(&(take as u16).to_le_bytes());
            out.extend_from_slice(&(!(take as u16)).to_le_bytes());
            out.extend_from_slice(&rest[..take]);
            rest = &rest[take..];
            if last {
                break;
            }
        }
        let mut a: u32 = 1;
        let mut b: u32 = 0;
        for byte in raw {
            a = (a + *byte as u32) % 65521;
            b = (b + a) % 65521;
        }
        out.extend_from_slice(&((b << 16) | a).to_be_bytes());
        out
    }

    /// A store with a real helper, or `None` when this machine has none installed.
    ///
    /// A test that needs bytes actually shrunk has to skip where no resizer exists — CI has none of
    /// the three — rather than assert something only this box can do. What the shrink *decides* is
    /// covered by the step list and the size reader, which need no helper at all.
    fn store_with_helper() -> Option<(tempfile::TempDir, Store)> {
        let helper = Helper::probe()?;
        let dir = tempfile::tempdir().unwrap();
        let store = Store::new(dir.path().join("attachments"), 2 * 1024 * 1024 * 1024)
            .with_helper(Some(helper));
        Some((dir, store))
    }

    fn store() -> (tempfile::TempDir, Store) {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::new(dir.path().join("attachments"), 2 * 1024 * 1024 * 1024);
        (dir, store)
    }

    #[test]
    fn the_header_reads_the_size_without_decoding_anything() {
        let picture = png(37, 19, [10, 20, 30]);
        assert_eq!(dimensions(&picture), Some((37, 19)));
        // A JPEG built by hand: SOI, an APP0 segment, then SOF0 with the size.
        let mut jpeg = vec![0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10];
        jpeg.extend_from_slice(&[0u8; 14]);
        jpeg.extend_from_slice(&[0xFF, 0xC0, 0x00, 0x11, 0x08]);
        jpeg.extend_from_slice(&[0x01, 0x2C]); // 300 rows
        jpeg.extend_from_slice(&[0x01, 0xF4]); // 500 columns
        jpeg.extend_from_slice(&[0u8; 12]);
        assert_eq!(dimensions(&jpeg), Some((500, 300)));
        assert_eq!(dimensions(b"not a picture"), None);
    }

    #[test]
    fn a_small_picture_is_its_own_working_copy_and_is_written_once() {
        let (_dir, store) = store();
        let picture = png(64, 64, [1, 2, 3]);
        let first = store.keep("s1", "shot.png", "image/png", &picture).unwrap();
        assert!(!first.resized);
        assert_eq!(first.working, first.original);
        assert_eq!(std::fs::read(&first.original).unwrap(), picture);
        // The same bytes again: no second file, and the note says it is the original.
        let again = store.keep("s1", "shot.png", "image/png", &picture).unwrap();
        assert_eq!(again.original, first.original);
        assert!(again.note("shot.png").contains("This is the original"));
    }

    #[test]
    fn the_original_is_byte_identical_and_the_directory_is_private() {
        use std::os::unix::fs::PermissionsExt;
        let (_dir, store) = store();
        let picture = png(64, 64, [9, 9, 9]);
        let kept = store
            .keep("s1", "../../etc/passwd.png", "image/png", &picture)
            .unwrap();
        assert_eq!(std::fs::read(&kept.original).unwrap(), picture);
        assert!(
            kept.original.starts_with(store.root()),
            "a name cannot escape the store: {}",
            kept.original.display()
        );
        let mode = std::fs::metadata(&kept.original)
            .unwrap()
            .permissions()
            .mode()
            & 0o777;
        assert_eq!(mode, 0o600);
        let dir_mode = std::fs::metadata(kept.original.parent().unwrap())
            .unwrap()
            .permissions()
            .mode()
            & 0o777;
        assert_eq!(dir_mode, 0o700);
    }

    #[test]
    fn a_bigger_picture_is_kept_whole_and_shrunk_for_the_wire() {
        let Some((_dir, store)) = store_with_helper() else {
            return;
        };
        let picture = png(1200, 1200, [200, 30, 40]);
        assert!(
            picture.len() > COPY_TARGET_BYTES,
            "the fixture has to be over the target: {} bytes",
            picture.len()
        );
        let kept = store
            .keep("s1", "photo.png", "image/png", &picture)
            .unwrap_or_else(|why| panic!("{why}"));
        assert!(kept.resized, "a picture over the target gets a copy");
        assert_eq!(std::fs::read(&kept.original).unwrap(), picture);
        assert_ne!(kept.working, kept.original);
        assert!(
            kept.working_bytes <= COPY_TARGET_BYTES,
            "the copy is {} bytes",
            kept.working_bytes
        );
        let copy = std::fs::read(&kept.working).unwrap();
        let (w, h) = dimensions(&copy).expect("the copy is a picture");
        assert!(w.max(h) <= MAX_EDGE, "{}×{}", w, h);
        let note = kept.note("photo.png");
        assert!(note.contains("copy"), "{note}");
        assert!(
            note.contains(&kept.original.display().to_string()),
            "{note}"
        );
    }

    #[test]
    fn the_original_keeps_its_pixels_while_the_copy_is_smaller() {
        // The case the issue was filed about: a picture from a camera, far over the wire limit.
        let Some((_dir, store)) = store_with_helper() else {
            return;
        };
        let picture = png(3000, 2000, [90, 120, 150]);
        assert!(picture.len() > 8 * 1024 * 1024, "{} bytes", picture.len());
        let kept = store
            .keep("s1", "camera.png", "image/png", &picture)
            .unwrap_or_else(|why| panic!("{why}"));
        // Acceptance 1 and 3: the file on disk is the upload, and it is still 3000×2000 — so a
        // later turn can crop it at full resolution.
        assert_eq!(std::fs::read(&kept.original).unwrap(), picture);
        assert_eq!(dimensions(&picture), Some((3000, 2000)));
        assert_eq!(kept.size, Some((3000, 2000)));
        // Acceptance 1: the copy fits the wire.
        assert!(
            kept.working_bytes <= COPY_TARGET_BYTES,
            "{}",
            kept.working_bytes
        );
        assert!(kept.working_bytes < kept.bytes);
        // Acceptance 2: the message says both facts, and names the copy a copy.
        let note = kept.note("camera.png");
        assert!(note.contains("3000×2000"), "{note}");
        assert!(note.contains("copy"), "{note}");
        assert!(
            note.contains(&kept.original.display().to_string()),
            "{note}"
        );
        // The copy is a second file, so the note's promise is true.
        assert!(kept.working.exists());
        assert_ne!(kept.working, kept.original);
    }

    #[test]
    fn with_no_helper_the_original_is_still_kept_and_the_refusal_says_so() {
        let (_dir, store) = store();
        let store = store.with_helper(None);
        let picture = png(1200, 1200, [5, 6, 7]);
        let why = store
            .keep("s1", "photo.png", "image/png", &picture)
            .expect_err("no helper, no copy");
        assert!(why.contains("ImageMagick"), "{why}");
        assert!(why.contains("ffmpeg"), "{why}");
        assert!(why.contains("original is kept"), "{why}");
    }

    #[test]
    fn the_pillow_branch_shrinks_a_picture_on_its_own() {
        let Some(pillow) = which("python3").filter(|p| works(p, &["-c", "import PIL.Image"]))
        else {
            return; // Pillow is not installed here: the ffmpeg branch covers this box.
        };
        let (_dir, store) = store();
        let store = store.with_helper(Some(Helper::Pillow(pillow)));
        let picture = png(1500, 900, [12, 200, 12]);
        let kept = store.keep("s1", "wide.png", "image/png", &picture).unwrap();
        assert!(kept.resized);
        let copy = std::fs::read(&kept.working).unwrap();
        let (w, h) = dimensions(&copy).expect("still a picture");
        assert!(w.max(h) <= MAX_EDGE, "{}×{}", w, h);
        assert!(
            copy.len() < picture.len(),
            "{} vs {}",
            copy.len(),
            picture.len()
        );
    }

    #[test]
    fn the_budget_prunes_the_oldest_first_and_then_refuses() {
        let dir = tempfile::tempdir().unwrap();
        let picture = png(1200, 1200, [1, 1, 1]);
        let one = picture.len() as u64;
        let Some(helper) = Helper::probe() else {
            return;
        };
        let store = Store::new(dir.path().join("a"), one * 2).with_helper(Some(helper));
        store.keep("old", "a.png", "image/png", &picture).unwrap();
        std::thread::sleep(std::time::Duration::from_millis(20));
        store.keep("new", "b.png", "image/png", &picture).unwrap();
        // A third would exceed the budget: the oldest session's files go first, and the attach
        // succeeds rather than being refused.
        std::thread::sleep(std::time::Duration::from_millis(20));
        let third = png(1200, 1200, [2, 2, 2]);
        store.keep("newer", "c.png", "image/png", &third).unwrap();
        assert!(
            std::fs::read_dir(store.root().join("old"))
                .map(|mut d| d.next().is_none())
                .unwrap_or(true),
            "the oldest session was pruned"
        );
        assert!(
            std::fs::read_dir(store.root().join("newer"))
                .unwrap()
                .count()
                > 0
        );
    }

    #[test]
    fn a_budget_too_small_for_one_picture_names_the_budget() {
        let dir = tempfile::tempdir().unwrap();
        let picture = png(1200, 1200, [3, 3, 3]);
        let store = Store::new(dir.path().join("a"), 1024);
        let why = store
            .keep("s1", "big.png", "image/png", &picture)
            .expect_err("over budget");
        assert!(why.contains("budget"), "{why}");
        assert!(why.contains("max_total_bytes"), "{why}");
    }

    #[test]
    fn forgetting_a_session_removes_its_pictures() {
        let (_dir, store) = store();
        let picture = png(32, 32, [0, 0, 0]);
        let kept = store.keep("s1", "a.png", "image/png", &picture).unwrap();
        store.forget("s1").unwrap();
        assert!(!kept.original.exists());
        store.forget("s1").unwrap(); // idempotent
    }

    #[test]
    fn bytes_that_are_not_a_picture_are_refused_by_their_content_not_their_name() {
        let (_dir, store) = store();
        let why = store
            .keep("s1", "notes.png", "image/png", b"plain text")
            .expect_err("not a picture");
        assert!(why.contains("not a picture"), "{why}");
    }

    #[test]
    fn a_name_with_nothing_usable_in_it_still_lands_somewhere_sane() {
        assert_eq!(sanitise("", "png"), "picture.png");
        assert_eq!(sanitise("../../", "png"), "picture.png");
        assert_eq!(sanitise("my shot.PNG", "png"), "my-shot.png");
    }
}