Skip to main content

adk_surface/
evidence.rs

1//! Approve with the image (spec 3.7 §7.8, §8.2, X11): a held call that sends, keeps or acts
2//! on an image shows that exact image on its card.
3//!
4//! A held call carries its images as [`adk_core::Evidence`] — each image's digest, its
5//! artifact, its size and an overlay of the regions the egress gate covered — and its
6//! fingerprint binds the digests, so a decision applies to the images the approver saw and no
7//! other. The engine projects that evidence into [`CardMedia`] beside the card's call:
8//!
9//! | Part | From |
10//! |---|---|
11//! | The image, its size and digest, and its regions | The inbox entry's evidence |
12//! | What was covered, by class, and whether everything was | The regions the gate filled |
13//! | Where it goes, what it is, the estimated cost, what it was cut from | A feature's [`MediaFacts`], through a [`CardHint`](crate::CardHint) |
14//! | Kept until, or deleted | The source ([`Source::evidence_kept`](crate::Source::evidence_kept)) and the retention |
15//!
16//! The image itself never travels in a card: a surface loads it from the source with the
17//! viewer's own authorisation (`GET /api/surface/decisions/{id}/evidence/{index}` on the web
18//! home), and the source checks its digest before serving it.
19//!
20//! What a surface may answer follows the boards' choices (A13, A15, A17, A18):
21//!
22//! | Situation | Answers |
23//! |---|---|
24//! | The image is deleted, or every pixel of it is covered | Deny only, on every surface: there is nothing to send |
25//! | Voice | Deny only: voice cannot show the image, so it cannot say yes to sending it |
26//! | Chat and the tray, through the engine | Deny and "Open in home"; a chat adapter that attaches the image offers Allow once itself |
27//! | The web home, the phone, the terminal | As for any card, without **Always allow** |
28//!
29//! # Example
30//!
31//! ```rust
32//! use adk_surface::{ImageFacts, MediaFacts};
33//!
34//! let facts = MediaFacts::new()
35//!     .to("Claude", "claude-sonnet-5-5", ["api.anthropic.com"])
36//!     .with_data_class("document_crop")
37//!     .with_estimated_cost(4_400, Some("851 image tokens".into()))
38//!     .with_cut_from("Page 2 of claim-0412.pdf")
39//!     .with_image(ImageFacts::new().with_field("Document kind"));
40//! assert_eq!(facts.hosts, vec!["api.anthropic.com".to_string()]);
41//! ```
42
43use chrono::{DateTime, Duration, FixedOffset, Utc};
44use schemars::JsonSchema;
45use serde::{Deserialize, Serialize};
46use serde_json::Value;
47
48use crate::words;
49
50/// How many days an image held as evidence is kept, unless a feature says otherwise
51/// (spec 3.7 Q13).
52pub const EVIDENCE_RETENTION_DAYS: u32 = 30;
53
54/// The share of an image's pixels that counts as all of it, so rounding at the edges of a
55/// covering box never leaves a "nothing to send" image allowable.
56const ALL_COVERED: f64 = 0.995;
57
58// ---------------------------------------------------------------------------
59// What a feature says
60// ---------------------------------------------------------------------------
61
62/// What a feature knows about the images one of its calls would send, which the evidence
63/// alone does not say: where they go, what they are, the estimated cost and what they were cut
64/// from (spec 3.7 §8.2). A [`CardHint`](crate::CardHint) carries it.
65///
66/// # Example
67///
68/// ```rust
69/// use adk_surface::{CardHint, MediaFacts};
70///
71/// let hint = CardHint::new().with_media(
72///     MediaFacts::new().to("Gemini", "gemini-3.8-flash", ["generativelanguage.googleapis.com"]),
73/// );
74/// assert!(hint.media.is_some());
75/// ```
76#[derive(Debug, Clone, Default, PartialEq, Eq)]
77pub struct MediaFacts {
78    /// Who receives the images, as a person knows them: "Claude".
79    pub provider: Option<String>,
80    /// The model: `claude-sonnet-5-5`.
81    pub model: Option<String>,
82    /// The hosts the images go to: `api.anthropic.com`.
83    pub hosts: Vec<String>,
84    /// The data class the images are released as, such as `document_crop`.
85    pub data_class: Option<String>,
86    /// The estimated cost of the call in micro-USD: the preflight's hold.
87    pub estimated_cost_micro_usd: Option<u64>,
88    /// What the estimate counts: "851 image tokens".
89    pub estimate_detail: Option<String>,
90    /// What the call cost, once it ran.
91    pub actual_cost_micro_usd: Option<u64>,
92    /// What the actual cost counts: "851 image tokens, 63 answer tokens".
93    pub actual_detail: Option<String>,
94    /// What the images were cut from: "Page 2 of claim-0412.pdf".
95    pub cut_from: Option<String>,
96    /// How they were cut: "nothing resized".
97    pub cut_note: Option<String>,
98    /// Where an authorised viewer opens the source image: a path in the home. Absent when the
99    /// viewer may not (board choice A9).
100    pub source_href: Option<String>,
101    /// How many days the images are kept as evidence; [`EVIDENCE_RETENTION_DAYS`] when unset.
102    pub retention_days: Option<u32>,
103    /// One entry per image, in the order of the evidence.
104    pub images: Vec<ImageFacts>,
105}
106
107impl MediaFacts {
108    /// Facts that say nothing.
109    pub fn new() -> Self {
110        Self::default()
111    }
112
113    /// The images go to `provider`'s `model` at `hosts`.
114    #[must_use]
115    pub fn to(
116        mut self,
117        provider: impl Into<String>,
118        model: impl Into<String>,
119        hosts: impl IntoIterator<Item = impl Into<String>>,
120    ) -> Self {
121        self.provider = Some(provider.into());
122        self.model = Some(model.into());
123        self.hosts = hosts.into_iter().map(Into::into).collect();
124        self
125    }
126
127    /// The images are released as `class`, such as `document_crop`.
128    #[must_use]
129    pub fn with_data_class(mut self, class: impl Into<String>) -> Self {
130        self.data_class = Some(class.into());
131        self
132    }
133
134    /// The preflight estimates `micro_usd`, counting `detail`.
135    #[must_use]
136    pub fn with_estimated_cost(mut self, micro_usd: u64, detail: Option<String>) -> Self {
137        self.estimated_cost_micro_usd = Some(micro_usd);
138        self.estimate_detail = detail;
139        self
140    }
141
142    /// The call cost `micro_usd`, counting `detail`.
143    #[must_use]
144    pub fn with_actual_cost(mut self, micro_usd: u64, detail: Option<String>) -> Self {
145        self.actual_cost_micro_usd = Some(micro_usd);
146        self.actual_detail = detail;
147        self
148    }
149
150    /// The images were cut from `source`.
151    #[must_use]
152    pub fn with_cut_from(mut self, source: impl Into<String>) -> Self {
153        self.cut_from = Some(source.into());
154        self
155    }
156
157    /// How they were cut: "nothing resized".
158    #[must_use]
159    pub fn with_cut_note(mut self, note: impl Into<String>) -> Self {
160        self.cut_note = Some(note.into());
161        self
162    }
163
164    /// An authorised viewer opens the source image at `href`, a path in the home.
165    #[must_use]
166    pub fn with_source_href(mut self, href: impl Into<String>) -> Self {
167        self.source_href = Some(href.into());
168        self
169    }
170
171    /// The images are kept as evidence for `days`.
172    #[must_use]
173    pub fn with_retention_days(mut self, days: u32) -> Self {
174        self.retention_days = Some(days);
175        self
176    }
177
178    /// Adds the facts of the next image.
179    #[must_use]
180    pub fn with_image(mut self, image: ImageFacts) -> Self {
181        self.images.push(image);
182        self
183    }
184
185    /// These facts with `later`'s where these set none.
186    pub(crate) fn then(self, later: Self) -> Self {
187        Self {
188            provider: self.provider.or(later.provider),
189            model: self.model.or(later.model),
190            hosts: if self.hosts.is_empty() { later.hosts } else { self.hosts },
191            data_class: self.data_class.or(later.data_class),
192            estimated_cost_micro_usd: self
193                .estimated_cost_micro_usd
194                .or(later.estimated_cost_micro_usd),
195            estimate_detail: self.estimate_detail.or(later.estimate_detail),
196            actual_cost_micro_usd: self.actual_cost_micro_usd.or(later.actual_cost_micro_usd),
197            actual_detail: self.actual_detail.or(later.actual_detail),
198            cut_from: self.cut_from.or(later.cut_from),
199            cut_note: self.cut_note.or(later.cut_note),
200            source_href: self.source_href.or(later.source_href),
201            retention_days: self.retention_days.or(later.retention_days),
202            images: if self.images.is_empty() { later.images } else { self.images },
203        }
204    }
205}
206
207/// What a feature knows about one image of a call: the field it shows and why it was sent.
208///
209/// # Example
210///
211/// ```rust
212/// use adk_surface::ImageFacts;
213///
214/// let po = ImageFacts::new().with_field("PO number").with_why("Handwriting");
215/// assert_eq!(po.why.as_deref(), Some("Handwriting"));
216/// ```
217#[derive(Debug, Clone, Default, PartialEq, Eq)]
218pub struct ImageFacts {
219    /// The field the image shows: "PO number".
220    pub field: Option<String>,
221    /// Why it is sent rather than read here: "Handwriting".
222    pub why: Option<String>,
223}
224
225impl ImageFacts {
226    /// Facts that say nothing.
227    pub fn new() -> Self {
228        Self::default()
229    }
230
231    /// The image shows `field`.
232    #[must_use]
233    pub fn with_field(mut self, field: impl Into<String>) -> Self {
234        self.field = Some(field.into());
235        self
236    }
237
238    /// The image is sent because of `why`.
239    #[must_use]
240    pub fn with_why(mut self, why: impl Into<String>) -> Self {
241        self.why = Some(why.into());
242        self
243    }
244}
245
246/// Whether an evidence image is still kept, as the source knows it.
247///
248/// # Example
249///
250/// ```rust
251/// use adk_surface::EvidenceKept;
252///
253/// assert_ne!(EvidenceKept::Kept, EvidenceKept::Deleted);
254/// ```
255#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
256#[serde(rename_all = "camelCase")]
257pub enum EvidenceKept {
258    /// The image is stored.
259    Kept,
260    /// The image is gone: its retention ran out, or it went with its source.
261    Deleted,
262    /// The source cannot tell: the card shows the image and the image route says.
263    Unknown,
264}
265
266// ---------------------------------------------------------------------------
267// What the card carries
268// ---------------------------------------------------------------------------
269
270/// What a region on an evidence image covers, by the class the egress gate redacted it as
271/// (spec 3.7 §7.8 step 3).
272#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
273#[serde(rename_all = "camelCase")]
274pub enum CoverClass {
275    /// A face, or the whole person where no face was found (spec 3.7 Q3).
276    Face,
277    /// Personal text: names, emails, phone numbers and numbers like them.
278    PersonalText,
279    /// A field the document schema marks personal.
280    SchemaField,
281    /// A box the person covered.
282    Marked,
283    /// Another class a feature names.
284    Other,
285}
286
287/// A region drawn over an evidence image, in the image's own pixels.
288#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
289#[serde(rename_all = "camelCase")]
290pub struct EvidenceRegion {
291    /// The class.
292    pub class: CoverClass,
293    /// The region's tag on a large picture: "face", or "face · whole person" for a person
294    /// covered whole.
295    pub tag: String,
296    /// The tag on a small picture: "face".
297    pub short_tag: String,
298    /// Left edge, pixels.
299    pub x0: f64,
300    /// Top edge, pixels.
301    pub y0: f64,
302    /// Right edge, pixels, exclusive.
303    pub x1: f64,
304    /// Bottom edge, pixels, exclusive.
305    pub y1: f64,
306}
307
308/// What was covered of one class, as a line of "Covered before it leaves".
309#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
310#[serde(rename_all = "camelCase")]
311pub struct CoveredLine {
312    /// The class.
313    pub class: CoverClass,
314    /// How many regions.
315    pub count: u32,
316    /// "1 face", "3 personal text", "2 fields your schema marks personal".
317    pub text: String,
318    /// Which images, when the call sends several and not all of them: "in image 3".
319    #[serde(default, skip_serializing_if = "Option::is_none")]
320    pub note: Option<String>,
321}
322
323/// An evidence image that is no longer kept (board choice A13).
324#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
325#[serde(rename_all = "camelCase")]
326pub struct PurgedView {
327    /// "This image was deleted on 18 Dec".
328    pub title: String,
329    /// "Evidence is kept for 30 days. What it was, …".
330    pub text: String,
331    /// The day it went, "18 Dec", when its retention ran out.
332    #[serde(default, skip_serializing_if = "Option::is_none")]
333    pub day: Option<String>,
334    /// The shorter line a small picture shows: "Image deleted 18 Dec".
335    pub short: String,
336}
337
338/// One image a held call would send, as its card shows it.
339#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
340#[serde(rename_all = "camelCase")]
341pub struct EvidenceImage {
342    /// Its place in the call's evidence: what the image route takes.
343    pub index: u32,
344    /// `sha256:<hex>` of the image's bytes, in full: the exact call and the terminal show it.
345    pub digest: String,
346    /// The digest in short, `sha256:c52ca5…ce7550` (board choice S4).
347    pub digest_short: String,
348    /// `image/png`.
349    pub mime_type: String,
350    /// Width in pixels.
351    pub width: u32,
352    /// Height in pixels.
353    pub height: u32,
354    /// "1012 × 638 PNG".
355    pub size_text: String,
356    /// Where the surface loads the image with the viewer's own authorisation; absent when it
357    /// is deleted.
358    #[serde(default, skip_serializing_if = "Option::is_none")]
359    pub href: Option<String>,
360    /// The regions over it, covered before it leaves.
361    pub regions: Vec<EvidenceRegion>,
362    /// Every pixel of it is covered.
363    pub covered_all: bool,
364    /// What was covered of it, in one line: "1 field your schema marks personal", "nothing
365    /// covered".
366    pub covered_text: String,
367    /// The feature's one-line description of it.
368    #[serde(default, skip_serializing_if = "Option::is_none")]
369    pub caption: Option<String>,
370    /// The field it shows: "PO number".
371    #[serde(default, skip_serializing_if = "Option::is_none")]
372    pub field: Option<String>,
373    /// Why it is sent rather than read here: "Handwriting".
374    #[serde(default, skip_serializing_if = "Option::is_none")]
375    pub why: Option<String>,
376    /// It is no longer kept.
377    #[serde(default, skip_serializing_if = "Option::is_none")]
378    pub purged: Option<PurgedView>,
379}
380
381/// A notice on the card about its images: why nothing can be sent.
382#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
383#[serde(rename_all = "camelCase")]
384pub struct MediaNotice {
385    /// Why it says so.
386    pub kind: MediaNoticeKind,
387    /// The lead words, in bold: "Nothing to send."
388    pub title: String,
389    /// The rest.
390    pub text: String,
391}
392
393/// Why a card's images cannot be sent.
394#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
395#[serde(rename_all = "camelCase")]
396pub enum MediaNoticeKind {
397    /// The image was deleted (board choice A13).
398    Purged,
399    /// Every pixel is covered (board choice A15).
400    AllCovered,
401}
402
403/// Where the images go, in words.
404#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
405#[serde(rename_all = "camelCase")]
406pub struct GoesTo {
407    /// Who receives them: "Claude".
408    #[serde(default, skip_serializing_if = "Option::is_none")]
409    pub provider: Option<String>,
410    /// The model: `claude-sonnet-5-5`.
411    #[serde(default, skip_serializing_if = "Option::is_none")]
412    pub model: Option<String>,
413    /// The hosts, joined: `api.anthropic.com`.
414    pub host: String,
415}
416
417/// A held call's images on its card (spec 3.7 §8.2, X11): what would leave, after redaction,
418/// with what was covered, where it goes, what it costs, how long it is kept and why nothing
419/// can be sent when that is so.
420#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
421#[serde(rename_all = "camelCase")]
422pub struct CardMedia {
423    /// "The exact image that would leave", "The 3 images that would leave", "The image that
424    /// left" when a feature says where the images go ([`MediaFacts::to`]); otherwise
425    /// "Attached image", "3 attached images".
426    pub title: String,
427    /// The images, in the order of the call's evidence.
428    pub images: Vec<EvidenceImage>,
429    /// Where they go.
430    #[serde(default, skip_serializing_if = "Option::is_none")]
431    pub goes_to: Option<GoesTo>,
432    /// What they are: "Document crop", "3 document crops".
433    #[serde(default, skip_serializing_if = "Option::is_none")]
434    pub what: Option<String>,
435    /// What qualifies `what`: "never the page".
436    #[serde(default, skip_serializing_if = "Option::is_none")]
437    pub what_note: Option<String>,
438    /// What was covered before they leave, by class.
439    pub covered: Vec<CoveredLine>,
440    /// Every pixel of every image is covered.
441    pub covered_all: bool,
442    /// "100% of the image", when so.
443    #[serde(default, skip_serializing_if = "Option::is_none")]
444    pub covered_all_text: Option<String>,
445    /// "Up to $0.0044" while waiting; "$0.0024" once it ran.
446    #[serde(default, skip_serializing_if = "Option::is_none")]
447    pub cost_text: Option<String>,
448    /// What the cost counts: "851 image tokens".
449    #[serde(default, skip_serializing_if = "Option::is_none")]
450    pub cost_detail: Option<String>,
451    /// What they were cut from: "Page 2 of claim-0412.pdf".
452    #[serde(default, skip_serializing_if = "Option::is_none")]
453    pub cut_from: Option<String>,
454    /// How: "nothing resized".
455    #[serde(default, skip_serializing_if = "Option::is_none")]
456    pub cut_note: Option<String>,
457    /// "Kept as evidence until 18 Dec".
458    #[serde(default, skip_serializing_if = "Option::is_none")]
459    pub kept_text: Option<String>,
460    /// Where an authorised viewer opens the source image (board choice A9).
461    #[serde(default, skip_serializing_if = "Option::is_none")]
462    pub source_href: Option<String>,
463    /// Why nothing can be sent, when that is so.
464    #[serde(default, skip_serializing_if = "Option::is_none")]
465    pub notice: Option<MediaNotice>,
466    /// This surface may tighten the crop or add a redaction, which holds the call again with
467    /// the new image (board choices A7, A8).
468    pub can_change: bool,
469    /// The digest of the image a changed image replaced, when this call was held again with
470    /// a changed image.
471    #[serde(default, skip_serializing_if = "Option::is_none")]
472    pub replaces: Option<String>,
473    /// The fixed line under the card (board choice A21).
474    pub fixed_line: String,
475}
476
477impl CardMedia {
478    /// Something on the card can be sent: every image is kept and not wholly covered.
479    pub fn sendable(&self) -> bool {
480        self.notice.is_none()
481    }
482}
483
484/// A change to an evidence image before it leaves (board choices A7, A8): the crop can only
485/// shrink and covering can only grow, so a change never shows more than the image it changes.
486///
487/// # Example
488///
489/// ```rust
490/// use adk_surface::ImageChange;
491///
492/// let change = ImageChange { image: 0, crop: Some([0, 0, 1012, 450]), cover: vec![[592, 476, 760, 506]] };
493/// assert!(change.check(1012, 638).is_ok());
494/// let wider = ImageChange { image: 0, crop: Some([0, 0, 1100, 450]), cover: Vec::new() };
495/// assert!(wider.check(1012, 638).is_err());
496/// ```
497#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
498#[serde(rename_all = "camelCase")]
499pub struct ImageChange {
500    /// The image's place in the call's evidence.
501    pub image: u32,
502    /// The new edges `[x0, y0, x1, y1]` in the image's pixels, inside the image.
503    #[serde(default, skip_serializing_if = "Option::is_none")]
504    pub crop: Option<[u32; 4]>,
505    /// Boxes `[x0, y0, x1, y1]` in the image's pixels to fill solid black.
506    #[serde(default, skip_serializing_if = "Vec::is_empty")]
507    pub cover: Vec<[u32; 4]>,
508}
509
510impl ImageChange {
511    /// Checks the change against an image of `width` × `height`: the crop lies inside it and
512    /// leaves something, each box lies inside it, and the change changes something.
513    ///
514    /// # Errors
515    ///
516    /// A sentence saying what is wrong, for the person.
517    pub fn check(&self, width: u32, height: u32) -> std::result::Result<(), String> {
518        let inside = |[x0, y0, x1, y1]: [u32; 4]| x0 < x1 && y0 < y1 && x1 <= width && y1 <= height;
519        if let Some(crop) = self.crop {
520            if !inside(crop) {
521                return Err(format!(
522                    "the crop must lie inside the {width} × {height} image and keep some of it; \
523                     it can only cut the image smaller"
524                ));
525            }
526            if crop == [0, 0, width, height] && self.cover.is_empty() {
527                return Err("the crop keeps the whole image, so nothing changes".into());
528            }
529        }
530        if let Some(bad) = self.cover.iter().find(|bbox| !inside(**bbox)) {
531            return Err(format!(
532                "the box {bad:?} must lie inside the {width} × {height} image and cover something"
533            ));
534        }
535        if self.crop.is_none() && self.cover.is_empty() {
536            return Err("cut the image smaller or cover part of it; nothing changes".into());
537        }
538        Ok(())
539    }
540}
541
542/// What a change made: the image it replaces and the new one.
543#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
544#[serde(rename_all = "camelCase")]
545pub struct ImageChanged {
546    /// The digest of the image the change replaces.
547    pub from: String,
548    /// The digest of the new image, held again for the person's decision.
549    pub to: String,
550    /// The new image's width.
551    pub width: u32,
552    /// The new image's height.
553    pub height: u32,
554}
555
556/// An image a surface loads for a card, after the source checked its digest.
557#[derive(Debug, Clone, PartialEq, Eq)]
558pub struct EvidenceBytes {
559    /// `image/png`.
560    pub mime_type: String,
561    /// The image's bytes, whose SHA-256 is the evidence's digest.
562    pub bytes: Vec<u8>,
563}
564
565// ---------------------------------------------------------------------------
566// Projection
567// ---------------------------------------------------------------------------
568
569/// The images of an inbox entry that its card shows: image evidence, in order.
570pub(crate) fn images(request: &adk_core::ApprovalRequest) -> Vec<&adk_core::ImageEvidence> {
571    request
572        .evidence
573        .iter()
574        .filter_map(|item| match item {
575            adk_core::Evidence::Image(image) => Some(image),
576            _ => None,
577        })
578        .collect()
579}
580
581/// What the projection needs beyond the inbox entry.
582pub(crate) struct MediaInput<'a> {
583    pub(crate) facts: Option<&'a MediaFacts>,
584    pub(crate) kept: &'a [EvidenceKept],
585    /// The answer, when decided: whether the images left.
586    pub(crate) decided: Option<crate::model::DecidedAnswer>,
587    /// The asking agent's name, as the card shows it.
588    pub(crate) agent: String,
589    /// The time the card is drawn and the zone its dates read in.
590    pub(crate) now: DateTime<Utc>,
591    pub(crate) offset: FixedOffset,
592    /// The source holds a call again with a changed image.
593    pub(crate) can_change: bool,
594    /// The digest a changed image replaced.
595    pub(crate) replaces: Option<String>,
596}
597
598/// The card's media for `request`, or `None` when it holds no image.
599pub(crate) fn project(
600    request: &adk_core::ApprovalRequest,
601    input: &MediaInput<'_>,
602) -> Option<CardMedia> {
603    let evidence = images(request);
604    if evidence.is_empty() {
605        return None;
606    }
607    let facts = input.facts.cloned().unwrap_or_default();
608    let retention = facts.retention_days.unwrap_or(EVIDENCE_RETENTION_DAYS);
609    let kept_until = request.created_at + Duration::days(i64::from(retention));
610    let kept_day = day(kept_until, input.offset);
611    let several = evidence.len() > 1;
612
613    let mut shown = Vec::with_capacity(evidence.len());
614    for (index, image) in evidence.iter().enumerate() {
615        let kept = input.kept.get(index).copied().unwrap_or(EvidenceKept::Unknown);
616        let regions = regions_of(image);
617        let covered_all = coverage(&regions, image.width, image.height) >= ALL_COVERED;
618        let purged = (kept == EvidenceKept::Deleted).then(|| {
619            if input.now >= kept_until {
620                PurgedView {
621                    title: words::image_deleted_on(&kept_day),
622                    text: words::evidence_kept_for(retention),
623                    day: Some(kept_day.clone()),
624                    short: words::image_deleted_short(&kept_day),
625                }
626            } else {
627                PurgedView {
628                    title: words::IMAGE_DELETED.to_string(),
629                    text: words::IMAGE_DELETED_EARLY.to_string(),
630                    day: None,
631                    short: words::IMAGE_DELETED.to_string(),
632                }
633            }
634        });
635        let image_facts = facts.images.get(index).cloned().unwrap_or_default();
636        let covered_text = covered_words(&count_classes(&regions), ", ");
637        shown.push(EvidenceImage {
638            index: index as u32,
639            digest: image.digest.clone(),
640            digest_short: short_digest(&image.digest),
641            mime_type: image.mime_type.clone(),
642            width: image.width,
643            height: image.height,
644            size_text: words::image_size(image.width, image.height, &image.mime_type),
645            href: purged.is_none().then(|| evidence_href(&request.id, index)),
646            regions,
647            covered_all,
648            covered_text: if covered_text.is_empty() {
649                words::NOTHING_COVERED.to_string()
650            } else {
651                covered_text
652            },
653            caption: image.caption.clone(),
654            field: image_facts.field,
655            why: image_facts.why,
656            purged,
657        });
658    }
659
660    // What was covered, by class across every image; with several images, which ones.
661    let mut covered: Vec<CoveredLine> = Vec::new();
662    for class in [
663        CoverClass::Face,
664        CoverClass::PersonalText,
665        CoverClass::SchemaField,
666        CoverClass::Marked,
667        CoverClass::Other,
668    ] {
669        let per_image: Vec<u32> = shown
670            .iter()
671            .map(|image| image.regions.iter().filter(|region| region.class == class).count() as u32)
672            .collect();
673        let count: u32 = per_image.iter().sum();
674        if count == 0 {
675            continue;
676        }
677        let which: Vec<usize> =
678            per_image.iter().enumerate().filter(|(_, n)| **n > 0).map(|(i, _)| i + 1).collect();
679        let note = (several && which.len() < shown.len()).then(|| words::in_images(&which));
680        covered.push(CoveredLine { class, count, text: words::covered_class(class, count), note });
681    }
682
683    let covered_all = shown.iter().all(|image| image.covered_all);
684    let purged = shown.iter().any(|image| image.purged.is_some());
685    let left = matches!(
686        input.decided,
687        Some(crate::model::DecidedAnswer::Yes | crate::model::DecidedAnswer::Edited)
688    );
689    let decided = input.decided.is_some();
690    let notice = if decided {
691        None
692    } else if purged {
693        Some(MediaNotice {
694            kind: MediaNoticeKind::Purged,
695            title: words::NOTHING_TO_SEND.to_string(),
696            text: words::nothing_to_send_purged(&input.agent),
697        })
698    } else if covered_all {
699        Some(MediaNotice {
700            kind: MediaNoticeKind::AllCovered,
701            title: words::EVERYTHING_IS_COVERED.to_string(),
702            text: words::everything_covered(facts.provider.as_deref()),
703        })
704    } else {
705        None
706    };
707    // The images leave only where a feature says where they go: other evidence is what the
708    // call keeps or acts on, such as a claim photo held with an estimate.
709    let egress = !facts.hosts.is_empty();
710    let title = match (egress, left, purged, several) {
711        (false, _, _, false) => words::ATTACHED_IMAGE.to_string(),
712        (false, _, _, true) => words::attached_images(shown.len()),
713        (true, true, _, false) => words::THE_IMAGE_THAT_LEFT.to_string(),
714        (true, true, _, true) => words::the_images_that_left(shown.len()),
715        (true, false, true, false) => words::THE_IMAGE_THAT_WOULD_HAVE_LEFT.to_string(),
716        (true, false, true, true) => words::the_images_that_would_have_left(shown.len()),
717        (true, false, false, false) => words::THE_EXACT_IMAGE_THAT_WOULD_LEAVE.to_string(),
718        (true, false, false, true) => words::the_images_that_would_leave(shown.len()),
719    };
720    let goes_to = (!facts.hosts.is_empty()).then(|| GoesTo {
721        provider: facts.provider.clone(),
722        model: facts.model.clone(),
723        host: facts.hosts.join(", "),
724    });
725    let (what, what_note) = match &facts.data_class {
726        Some(class) if several => {
727            (Some(words::data_class_many(class, shown.len())), words::data_class_note(class))
728        }
729        Some(class) => (Some(words::data_class(class)), None),
730        None => (None, None),
731    };
732    let (cost_text, cost_detail) = match facts.actual_cost_micro_usd {
733        Some(actual) if decided && left => {
734            (Some(words::money(actual)), facts.actual_detail.clone())
735        }
736        _ => match facts.estimated_cost_micro_usd {
737            Some(estimate) if covered_all && !decided => {
738                (Some(words::up_to_if_sent(estimate)), None)
739            }
740            Some(estimate) => (Some(words::up_to(estimate)), facts.estimate_detail.clone()),
741            None => (None, None),
742        },
743    };
744    let kept_text = if purged {
745        None
746    } else if decided {
747        Some(words::as_evidence_until(&kept_day))
748    } else {
749        Some(words::kept_as_evidence_until(&kept_day))
750    };
751    let can_change = input.can_change && !decided && !purged && !covered_all && !several;
752    Some(CardMedia {
753        title,
754        images: shown,
755        goes_to,
756        what,
757        what_note,
758        covered,
759        covered_all,
760        covered_all_text: covered_all.then(|| words::ALL_OF_THE_IMAGE.to_string()),
761        cost_text,
762        cost_detail,
763        cut_from: facts.cut_from.clone(),
764        cut_note: facts.cut_note.clone(),
765        kept_text,
766        source_href: facts.source_href.clone().filter(|href| local_path(href)),
767        notice,
768        can_change,
769        replaces: input.replaces.clone(),
770        fixed_line: words::IMAGES_LEAVE_ONLY_COVERED.to_string(),
771    })
772}
773
774/// The web home's route for the `index`th image of decision `id`, under `/api/surface`.
775pub(crate) fn evidence_href(id: &str, index: usize) -> String {
776    format!("/api/surface/decisions/{}/evidence/{index}", percent_segment(id))
777}
778
779/// Where decision `id` opens in the web home: `/ui/decisions/<id>`.
780#[cfg(feature = "tui")]
781pub(crate) fn decision_path(id: &str) -> String {
782    format!("/ui/decisions/{}", percent_segment(id))
783}
784
785/// A path on this server: one slash, no scheme.
786fn local_path(href: &str) -> bool {
787    href.starts_with('/') && !href.starts_with("//")
788}
789
790/// `id` as one path segment.
791pub(crate) fn percent_segment(id: &str) -> String {
792    let mut out = String::with_capacity(id.len());
793    for byte in id.bytes() {
794        match byte {
795            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
796                out.push(byte as char);
797            }
798            other => out.push_str(&format!("%{other:02X}")),
799        }
800    }
801    out
802}
803
804/// `sha256:c52ca5…ce7550`: the scheme, the first six and the last six hex digits
805/// (board choice S4).
806///
807/// # Example
808///
809/// ```rust
810/// let digest = "sha256:c52ca5e48473595c3e5f3a67166abffb47bf1833af9c61b28f56dc769ece7550";
811/// assert_eq!(adk_surface::short_digest(digest), "sha256:c52ca5…ce7550");
812/// ```
813pub fn short_digest(digest: &str) -> String {
814    let (scheme, hex) = digest.split_once(':').unwrap_or(("", digest));
815    let chars: Vec<char> = hex.chars().collect();
816    if chars.len() <= 14 {
817        return digest.to_string();
818    }
819    let head: String = chars[..6].iter().collect();
820    let tail: String = chars[chars.len() - 6..].iter().collect();
821    if scheme.is_empty() { format!("{head}…{tail}") } else { format!("{scheme}:{head}…{tail}") }
822}
823
824/// `when` as "18 Dec" at `offset`.
825fn day(when: DateTime<Utc>, offset: FixedOffset) -> String {
826    when.with_timezone(&offset).format("%-d %b").to_string()
827}
828
829/// The class a region's label names.
830fn class_of(label: &str) -> CoverClass {
831    match label {
832        "faces" | "face" | "person" | "people" => CoverClass::Face,
833        "personal_text" => CoverClass::PersonalText,
834        "schema_personal_fields" | "schema_field" | "schema_fields" => CoverClass::SchemaField,
835        "marked" => CoverClass::Marked,
836        _ => CoverClass::Other,
837    }
838}
839
840/// The regions of an image's `RegionSet` overlay, as boxes in its pixels: a box as it is, a
841/// polygon by its bounds. Points and masks are not drawn on a card.
842fn regions_of(image: &adk_core::ImageEvidence) -> Vec<EvidenceRegion> {
843    let Some(set) = &image.regions else { return Vec::new() };
844    let Some(regions) = set.get("regions").and_then(Value::as_array) else {
845        return Vec::new();
846    };
847    let (width, height) = (f64::from(image.width), f64::from(image.height));
848    regions
849        .iter()
850        .filter_map(|region| {
851            let shape = region.get("shape")?;
852            let number = |key: &str| shape.get(key).and_then(Value::as_f64);
853            let (x0, y0, x1, y1) = match shape.get("kind").and_then(Value::as_str)? {
854                "box" => (number("x0")?, number("y0")?, number("x1")?, number("y1")?),
855                "polygon" => {
856                    let pairs: Vec<(f64, f64)> = shape
857                        .get("points")?
858                        .as_array()?
859                        .iter()
860                        .filter_map(|point| {
861                            let pair = point.as_array()?;
862                            Some((pair.first()?.as_f64()?, pair.get(1)?.as_f64()?))
863                        })
864                        .collect();
865                    if pairs.is_empty() {
866                        return None;
867                    }
868                    let fold =
869                        |pick: fn(&(f64, f64)) -> f64, start: f64, f: fn(f64, f64) -> f64| {
870                            pairs.iter().map(pick).fold(start, f)
871                        };
872                    (
873                        fold(|p| p.0, f64::INFINITY, f64::min),
874                        fold(|p| p.1, f64::INFINITY, f64::min),
875                        fold(|p| p.0, f64::NEG_INFINITY, f64::max),
876                        fold(|p| p.1, f64::NEG_INFINITY, f64::max),
877                    )
878                }
879                _ => return None,
880            };
881            if ![x0, y0, x1, y1].iter().all(|v| v.is_finite()) {
882                return None;
883            }
884            let (x0, y0) = (x0.clamp(0.0, width), y0.clamp(0.0, height));
885            let (x1, y1) = (x1.clamp(0.0, width), y1.clamp(0.0, height));
886            if x1 <= x0 || y1 <= y0 {
887                return None;
888            }
889            let label = region.get("label").and_then(Value::as_str).unwrap_or_default();
890            let class = class_of(label);
891            Some(EvidenceRegion {
892                class,
893                tag: words::region_tag(class, label),
894                short_tag: words::region_short_tag(class, label),
895                x0,
896                y0,
897                x1,
898                y1,
899            })
900        })
901        .collect()
902}
903
904/// How many regions of each class, in the order of [`CoverClass`].
905fn count_classes(regions: &[EvidenceRegion]) -> Vec<(CoverClass, u32)> {
906    let mut counts: Vec<(CoverClass, u32)> = Vec::new();
907    for region in regions {
908        match counts.iter_mut().find(|(class, _)| *class == region.class) {
909            Some((_, count)) => *count += 1,
910            None => counts.push((region.class, 1)),
911        }
912    }
913    counts.sort_by_key(|(class, _)| *class as u8);
914    counts
915}
916
917/// "1 face, 3 personal text", joined by `separator`; empty when nothing was covered.
918pub(crate) fn covered_words(counts: &[(CoverClass, u32)], separator: &str) -> String {
919    counts
920        .iter()
921        .map(|(class, count)| words::covered_class(*class, *count))
922        .collect::<Vec<_>>()
923        .join(separator)
924}
925
926/// The share of a `width` × `height` image the regions cover, from 0 to 1: the exact area of
927/// their union over the image's.
928pub(crate) fn coverage(regions: &[EvidenceRegion], width: u32, height: u32) -> f64 {
929    let area = f64::from(width) * f64::from(height);
930    if area <= 0.0 || regions.is_empty() {
931        return 0.0;
932    }
933    let mut xs: Vec<f64> = regions.iter().flat_map(|r| [r.x0, r.x1]).collect();
934    xs.sort_by(f64::total_cmp);
935    xs.dedup();
936    let mut union = 0.0;
937    for pair in xs.windows(2) {
938        let (left, right) = (pair[0], pair[1]);
939        let mut spans: Vec<(f64, f64)> = regions
940            .iter()
941            .filter(|r| r.x0 <= left && r.x1 >= right)
942            .map(|r| (r.y0, r.y1))
943            .collect();
944        spans.sort_by(|a, b| a.0.total_cmp(&b.0));
945        let mut covered = 0.0;
946        let mut current: Option<(f64, f64)> = None;
947        for (top, bottom) in spans {
948            current = match current {
949                Some((start, end)) if top <= end => Some((start, end.max(bottom))),
950                Some((start, end)) => {
951                    covered += end - start;
952                    Some((top, bottom))
953                }
954                None => Some((top, bottom)),
955            };
956        }
957        if let Some((start, end)) = current {
958            covered += end - start;
959        }
960        union += covered * (right - left);
961    }
962    (union / area).clamp(0.0, 1.0)
963}
964
965/// The bytes of an evidence image from `artifacts`, read at its exact version and checked
966/// against its digest; `None` when it is no longer kept.
967///
968/// # Errors
969///
970/// `surface.invalid` when the stored bytes are not an image or do not match the digest, or
971/// the artifact service's error.
972pub(crate) async fn load_image(
973    artifacts: &dyn adk_artifact::ArtifactService,
974    image: &adk_core::ImageEvidence,
975) -> crate::Result<Option<Vec<u8>>> {
976    let at = &image.artifact;
977    let loaded = artifacts
978        .load(adk_artifact::LoadRequest {
979            app_name: at.app_name.clone(),
980            user_id: at.user_id.clone(),
981            session_id: at.session_id.clone(),
982            file_name: at.file_name.clone(),
983            version: Some(at.version),
984        })
985        .await;
986    let part = match loaded {
987        Ok(loaded) => loaded.part,
988        Err(error) if error.is_not_found() => return Ok(None),
989        Err(error) => return Err(error.into()),
990    };
991    let adk_core::Part::InlineData { data, .. } = part else {
992        return Err(crate::SurfaceError::Invalid(
993            "an evidence artifact holds no image bytes".into(),
994        ));
995    };
996    if digest_of(&data) != image.digest {
997        tracing::warn!(evidence.digest = %image.digest, "an evidence image does not match its digest; it is not shown");
998        return Err(crate::SurfaceError::Invalid(
999            "the stored image does not match the digest the decision names; it is not shown".into(),
1000        ));
1001    }
1002    Ok(Some(data))
1003}
1004
1005/// `sha256:<hex>` of `bytes`, as evidence digests are written.
1006pub(crate) fn digest_of(bytes: &[u8]) -> String {
1007    use sha2::Digest as _;
1008    format!("sha256:{:x}", sha2::Sha256::digest(bytes))
1009}
1010
1011/// The most pixels [`changed_png`] decodes: above an 8K frame, and 160 MB as 8-bit RGBA.
1012#[cfg(feature = "web")]
1013const MAX_CHANGED_PIXELS: u64 = 40_000_000;
1014
1015/// The PNG `change` makes of the PNG `bytes`: cut to its crop, then its boxes filled solid
1016/// black (spec 3.7 §7.8 step 3: a fill, since blur and pixelation of text can be reversed),
1017/// as 8-bit RGBA, with its size.
1018///
1019/// # Errors
1020///
1021/// A sentence for the person when the image is not a PNG this can read, has more than
1022/// [`MAX_CHANGED_PIXELS`] pixels, or the change does not fit it.
1023#[cfg(feature = "web")]
1024pub(crate) fn changed_png(
1025    bytes: &[u8],
1026    change: &ImageChange,
1027) -> std::result::Result<(Vec<u8>, u32, u32), String> {
1028    let unreadable =
1029        |error: &dyn std::fmt::Display| format!("the image could not be read as a PNG: {error}");
1030    let mut decoder = png::Decoder::new(std::io::Cursor::new(bytes));
1031    decoder.set_transformations(
1032        png::Transformations::EXPAND | png::Transformations::STRIP_16 | png::Transformations::ALPHA,
1033    );
1034    let mut reader = decoder.read_info().map_err(|error| unreadable(&error))?;
1035    // The header states the size, so a small file cannot make this allocate a huge frame.
1036    let declared = u64::from(reader.info().width) * u64::from(reader.info().height);
1037    if declared > MAX_CHANGED_PIXELS {
1038        return Err(format!(
1039            "the image has {declared} pixels; one of more than {MAX_CHANGED_PIXELS} cannot be \
1040             cropped or covered here"
1041        ));
1042    }
1043    let size = reader.output_buffer_size().ok_or_else(|| unreadable(&"it is too large"))?;
1044    let mut buffer = vec![0; size];
1045    let frame = reader.next_frame(&mut buffer).map_err(|error| unreadable(&error))?;
1046    let (width, height) = (frame.width, frame.height);
1047    change.check(width, height)?;
1048    let pixels: Vec<u8> = match frame.color_type {
1049        png::ColorType::Rgba => buffer[..frame.buffer_size()].to_vec(),
1050        png::ColorType::GrayscaleAlpha => buffer[..frame.buffer_size()]
1051            .chunks_exact(2)
1052            .flat_map(|ga| [ga[0], ga[0], ga[0], ga[1]])
1053            .collect(),
1054        other => return Err(unreadable(&format!("{other:?} pixels"))),
1055    };
1056    let [x0, y0, x1, y1] = change.crop.unwrap_or([0, 0, width, height]);
1057    let (out_width, out_height) = (x1 - x0, y1 - y0);
1058    // Offsets are counted in `usize`: a product of two `u32` sides can pass `u32::MAX`.
1059    let (stride, out_stride) = (width as usize * 4, out_width as usize * 4);
1060    let mut out = Vec::with_capacity(out_stride * out_height as usize);
1061    for row in y0..y1 {
1062        let start = row as usize * stride + x0 as usize * 4;
1063        out.extend_from_slice(&pixels[start..start + out_stride]);
1064    }
1065    for [bx0, by0, bx1, by1] in &change.cover {
1066        // A box in the image's pixels, clipped to the crop and moved with it.
1067        let (cx0, cy0) = ((*bx0).max(x0) - x0, (*by0).max(y0) - y0);
1068        let (cx1, cy1) = ((*bx1).min(x1).saturating_sub(x0), (*by1).min(y1).saturating_sub(y0));
1069        for row in cy0..cy1 {
1070            for column in cx0..cx1 {
1071                let at = row as usize * out_stride + column as usize * 4;
1072                out[at..at + 4].copy_from_slice(&[0, 0, 0, 255]);
1073            }
1074        }
1075    }
1076    let mut encoded = Vec::new();
1077    {
1078        let mut encoder = png::Encoder::new(&mut encoded, out_width, out_height);
1079        encoder.set_color(png::ColorType::Rgba);
1080        encoder.set_depth(png::BitDepth::Eight);
1081        let mut writer = encoder.write_header().map_err(|error| error.to_string())?;
1082        writer.write_image_data(&out).map_err(|error| error.to_string())?;
1083    }
1084    Ok((encoded, out_width, out_height))
1085}
1086
1087#[cfg(test)]
1088mod tests {
1089    use adk_core::{
1090        ApprovalPolicy, ApprovalRequest, ApprovalScope, ApproverSelector, ArtifactLocator,
1091        Evidence, ImageEvidence, ToolConfirmationRequest,
1092    };
1093    use proptest::prelude::*;
1094    use serde_json::json;
1095
1096    use super::*;
1097
1098    const DIGEST: &str = "sha256:c52ca5e48473595c3e5f3a67166abffb47bf1833af9c61b28f56dc769ece7550";
1099
1100    fn boxed(label: &str, [x0, y0, x1, y1]: [f64; 4]) -> Value {
1101        json!({ "image": DIGEST, "label": label, "shape": { "kind": "box", "x0": x0, "y0": y0, "x1": x1, "y1": y1 }, "origin": {} })
1102    }
1103
1104    fn card_image(regions: Vec<Value>) -> ImageEvidence {
1105        ImageEvidence::new(
1106            DIGEST,
1107            ArtifactLocator::new("desk", "ana", "s1", "vision-c52ca5.png", 1),
1108            "image/png",
1109            1012,
1110            638,
1111        )
1112        .with_regions(json!({ "image": DIGEST, "width": 1012, "height": 638, "regions": regions }))
1113    }
1114
1115    fn request(images: Vec<ImageEvidence>) -> ApprovalRequest {
1116        let call = ToolConfirmationRequest::new(
1117            "vision_describe",
1118            json!({ "image": DIGEST, "backend": "claude", "prompt": "What kind of document is this?" }),
1119        )
1120        .with_evidence(images.into_iter().map(Evidence::from));
1121        ApprovalRequest::new(
1122            "dec-7c41e0",
1123            ApprovalScope::new("desk", "ana", "s1"),
1124            &call,
1125            ApprovalPolicy::new([ApproverSelector::group("owner")]),
1126        )
1127    }
1128
1129    fn input(kept: &[EvidenceKept]) -> MediaInput<'_> {
1130        MediaInput {
1131            facts: None,
1132            kept,
1133            decided: None,
1134            agent: "Document desk".into(),
1135            now: Utc::now(),
1136            offset: FixedOffset::east_opt(0).unwrap(),
1137            can_change: true,
1138            replaces: None,
1139        }
1140    }
1141
1142    /// Facts that say where the images go: the call is an egress.
1143    fn to_claude() -> MediaFacts {
1144        MediaFacts::new().to("Claude", "claude-sonnet-5-5", ["api.anthropic.com"])
1145    }
1146
1147    fn the_card() -> ApprovalRequest {
1148        request(vec![card_image(vec![
1149            boxed("faces", [48.0, 150.0, 300.0, 468.0]),
1150            boxed("personal_text", [344.0, 176.0, 700.0, 214.0]),
1151            boxed("personal_text", [344.0, 250.0, 760.0, 288.0]),
1152            boxed("personal_text", [344.0, 324.0, 560.0, 362.0]),
1153            boxed("schema_personal_fields", [620.0, 324.0, 940.0, 362.0]),
1154            boxed("schema_personal_fields", [40.0, 520.0, 972.0, 600.0]),
1155        ])])
1156    }
1157
1158    #[test]
1159    fn the_identity_card_shows_what_was_covered_by_class() {
1160        let request = the_card();
1161        let facts = to_claude();
1162        let mut given = input(&[EvidenceKept::Kept]);
1163        given.facts = Some(&facts);
1164        let media = project(&request, &given).unwrap();
1165        let lines: Vec<&str> = media.covered.iter().map(|line| line.text.as_str()).collect();
1166        assert_eq!(lines, ["1 face", "3 personal text", "2 fields your schema marks personal"]);
1167        assert_eq!(media.title, "The exact image that would leave");
1168        let image = &media.images[0];
1169        assert_eq!(image.digest_short, "sha256:c52ca5…ce7550");
1170        assert_eq!(image.size_text, "1012 × 638 PNG");
1171        assert_eq!(image.href.as_deref(), Some("/api/surface/decisions/dec-7c41e0/evidence/0"));
1172        assert_eq!(image.regions[0].tag, "face");
1173        assert_eq!(image.regions[0].short_tag, "face");
1174        assert!(!media.covered_all);
1175        assert!(media.sendable());
1176        assert!(media.can_change);
1177        assert_eq!(media.fixed_line, words::IMAGES_LEAVE_ONLY_COVERED);
1178    }
1179
1180    #[test]
1181    fn images_no_feature_sends_are_attached_not_leaving() {
1182        let card = the_card();
1183        let media = project(&card, &input(&[EvidenceKept::Kept])).unwrap();
1184        assert_eq!(media.title, "Attached image");
1185        assert!(media.goes_to.is_none());
1186        let mut given = input(&[EvidenceKept::Kept]);
1187        given.decided = Some(crate::model::DecidedAnswer::Yes);
1188        assert_eq!(project(&card, &given).unwrap().title, "Attached image");
1189        let two = request(vec![card_image(Vec::new()), card_image(Vec::new())]);
1190        let media = project(&two, &input(&[EvidenceKept::Kept; 2])).unwrap();
1191        assert_eq!(media.title, "2 attached images");
1192    }
1193
1194    #[test]
1195    fn a_face_reads_face_and_a_person_covered_whole_reads_whole_person() {
1196        let request = request(vec![card_image(vec![
1197            boxed("faces", [48.0, 150.0, 300.0, 468.0]),
1198            boxed("people", [600.0, 100.0, 900.0, 630.0]),
1199        ])]);
1200        let media = project(&request, &input(&[EvidenceKept::Kept])).unwrap();
1201        let face = |tag: &str, [x0, y0, x1, y1]: [f64; 4]| EvidenceRegion {
1202            class: CoverClass::Face,
1203            tag: tag.into(),
1204            short_tag: "face".into(),
1205            x0,
1206            y0,
1207            x1,
1208            y1,
1209        };
1210        assert_eq!(
1211            media.images[0].regions,
1212            [
1213                face("face", [48.0, 150.0, 300.0, 468.0]),
1214                face("face · whole person", [600.0, 100.0, 900.0, 630.0]),
1215            ]
1216        );
1217        assert_eq!(media.covered[0].text, "2 faces");
1218    }
1219
1220    #[test]
1221    fn a_deleted_image_leaves_nothing_to_send() {
1222        let request = the_card();
1223        let facts = to_claude();
1224        let mut later = input(&[EvidenceKept::Deleted]);
1225        later.facts = Some(&facts);
1226        later.now = request.created_at + Duration::days(31);
1227        let media = project(&request, &later).unwrap();
1228        let notice = media.notice.as_ref().unwrap();
1229        assert_eq!(notice.kind, MediaNoticeKind::Purged);
1230        assert!(notice.text.contains("ask Document desk again"));
1231        assert!(media.images[0].href.is_none());
1232        let purged = media.images[0].purged.as_ref().unwrap();
1233        assert!(purged.title.starts_with("This image was deleted on"));
1234        assert!(!media.can_change);
1235        assert!(media.kept_text.is_none());
1236        assert_eq!(media.title, "The image that would have left");
1237    }
1238
1239    #[test]
1240    fn a_crop_covered_in_full_leaves_nothing_to_send() {
1241        let request = request(vec![
1242            ImageEvidence::new(
1243                DIGEST,
1244                ArtifactLocator::new("desk", "ana", "s1", "vision-9cb6f7.png", 1),
1245                "image/png",
1246                422,
1247                160,
1248            )
1249            .with_regions(json!({ "regions": [
1250                boxed("schema_personal_fields", [0.0, 0.0, 422.0, 64.0]),
1251                boxed("schema_personal_fields", [0.0, 64.0, 422.0, 160.0]),
1252            ] })),
1253        ]);
1254        let media = project(&request, &input(&[EvidenceKept::Kept])).unwrap();
1255        assert!(media.covered_all);
1256        assert_eq!(media.covered_all_text.as_deref(), Some("100% of the image"));
1257        assert_eq!(media.notice.as_ref().unwrap().kind, MediaNoticeKind::AllCovered);
1258        assert!(!media.can_change);
1259    }
1260
1261    #[test]
1262    fn several_images_name_which_ones_were_covered() {
1263        let plain = || card_image(Vec::new());
1264        let request = request(vec![
1265            plain(),
1266            plain(),
1267            card_image(vec![boxed("schema_field", [80.0, 10.0, 120.0, 40.0])]),
1268        ]);
1269        let mut facts = to_claude().with_data_class("document_crop");
1270        facts.images = vec![
1271            ImageFacts::new().with_field("PO number").with_why("Handwriting"),
1272            ImageFacts::new().with_field("Invoice date"),
1273            ImageFacts::new().with_field("Approved by"),
1274        ];
1275        let mut given = input(&[EvidenceKept::Kept; 3]);
1276        given.facts = Some(&facts);
1277        let media = project(&request, &given).unwrap();
1278        assert_eq!(media.title, "The 3 images that would leave");
1279        assert_eq!(media.what.as_deref(), Some("3 document crops"));
1280        assert_eq!(media.what_note.as_deref(), Some("never the page"));
1281        assert_eq!(media.covered[0].text, "1 field your schema marks personal");
1282        assert_eq!(media.covered[0].note.as_deref(), Some("in image 3"));
1283        assert_eq!(media.images[0].covered_text, "nothing covered");
1284        assert_eq!(media.images[0].field.as_deref(), Some("PO number"));
1285        assert!(!media.can_change, "one image of several is not changed on the card");
1286    }
1287
1288    #[test]
1289    fn a_decided_card_shows_what_left_and_its_cost() {
1290        let request = the_card();
1291        let facts = MediaFacts::new()
1292            .to("Claude", "claude-sonnet-5-5", ["api.anthropic.com"])
1293            .with_estimated_cost(4_400, Some("851 image tokens".into()))
1294            .with_actual_cost(2_400, Some("851 image tokens, 63 answer tokens".into()));
1295        let mut given = input(&[EvidenceKept::Kept]);
1296        given.facts = Some(&facts);
1297        let waiting = project(&request, &given).unwrap();
1298        assert_eq!(waiting.cost_text.as_deref(), Some("Up to $0.0044"));
1299        given.decided = Some(crate::model::DecidedAnswer::Yes);
1300        let decided = project(&request, &given).unwrap();
1301        assert_eq!(decided.title, "The image that left");
1302        assert_eq!(decided.cost_text.as_deref(), Some("$0.0024"));
1303        assert!(decided.kept_text.unwrap().starts_with("As evidence until"));
1304        assert!(!decided.can_change);
1305    }
1306
1307    #[test]
1308    fn a_change_can_only_shrink_the_crop_and_grow_the_covering() {
1309        let shrink = ImageChange { image: 0, crop: Some([0, 0, 1012, 450]), cover: Vec::new() };
1310        assert!(shrink.check(1012, 638).is_ok());
1311        let none = ImageChange { image: 0, crop: None, cover: Vec::new() };
1312        assert!(none.check(1012, 638).is_err());
1313        let whole = ImageChange { image: 0, crop: Some([0, 0, 1012, 638]), cover: Vec::new() };
1314        assert!(whole.check(1012, 638).is_err());
1315        let outside = ImageChange { image: 0, crop: None, cover: vec![[900, 600, 1100, 700]] };
1316        assert!(outside.check(1012, 638).is_err());
1317        let empty = ImageChange { image: 0, crop: Some([10, 10, 10, 50]), cover: Vec::new() };
1318        assert!(empty.check(1012, 638).is_err());
1319    }
1320
1321    #[cfg(feature = "web")]
1322    #[test]
1323    fn an_image_declaring_more_pixels_than_the_limit_is_refused_before_it_is_decoded() {
1324        // A 60,000 × 60,000 header and an empty zlib stream: 65 bytes for 14 GB of pixels.
1325        fn chunk(kind: &[u8; 4], data: &[u8]) -> Vec<u8> {
1326            let mut crc = u32::MAX;
1327            for byte in kind.iter().chain(data) {
1328                crc ^= u32::from(*byte);
1329                for _ in 0..8 {
1330                    crc = (crc >> 1) ^ (0xEDB8_8320 & 0u32.wrapping_sub(crc & 1));
1331                }
1332            }
1333            let mut out = (data.len() as u32).to_be_bytes().to_vec();
1334            out.extend_from_slice(kind);
1335            out.extend_from_slice(data);
1336            out.extend_from_slice(&(!crc).to_be_bytes());
1337            out
1338        }
1339        let mut header = Vec::new();
1340        header.extend_from_slice(&60_000u32.to_be_bytes());
1341        header.extend_from_slice(&60_000u32.to_be_bytes());
1342        header.extend_from_slice(&[8, 6, 0, 0, 0]);
1343        let mut source = b"\x89PNG\r\n\x1a\n".to_vec();
1344        source.extend(chunk(b"IHDR", &header));
1345        source.extend(chunk(b"IDAT", &[0x78, 0x9c, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01]));
1346        source.extend(chunk(b"IEND", &[]));
1347        let change = ImageChange { image: 0, crop: Some([0, 0, 10, 10]), cover: Vec::new() };
1348
1349        let error = changed_png(&source, &change).unwrap_err();
1350
1351        assert!(error.contains("3600000000 pixels"), "{error}");
1352    }
1353
1354    #[cfg(feature = "web")]
1355    #[test]
1356    fn a_change_cuts_the_image_and_fills_its_boxes_black() {
1357        let (width, height) = (8u32, 6u32);
1358        let white = vec![255u8; (width * height * 4) as usize];
1359        let mut source = Vec::new();
1360        {
1361            let mut encoder = png::Encoder::new(&mut source, width, height);
1362            encoder.set_color(png::ColorType::Rgba);
1363            encoder.set_depth(png::BitDepth::Eight);
1364            encoder.write_header().unwrap().write_image_data(&white).unwrap();
1365        }
1366        let change = ImageChange { image: 0, crop: Some([2, 1, 8, 5]), cover: vec![[0, 0, 4, 2]] };
1367        let (bytes, out_width, out_height) = changed_png(&source, &change).unwrap();
1368        assert_eq!((out_width, out_height), (6, 4));
1369        let mut decoder = png::Decoder::new(std::io::Cursor::new(&bytes));
1370        decoder.set_transformations(png::Transformations::ALPHA);
1371        let mut reader = decoder.read_info().unwrap();
1372        let mut pixels = vec![0; reader.output_buffer_size().unwrap()];
1373        reader.next_frame(&mut pixels).unwrap();
1374        let at = |x: usize, y: usize| pixels[(y * 6 + x) * 4..(y * 6 + x) * 4 + 4].to_vec();
1375        // The box [0, 0, 4, 2] in the image is [0, 0, 2, 1] in the crop.
1376        assert_eq!(at(0, 0), [0, 0, 0, 255]);
1377        assert_eq!(at(1, 0), [0, 0, 0, 255]);
1378        assert_eq!(at(2, 0), [255, 255, 255, 255]);
1379        assert_eq!(at(0, 1), [255, 255, 255, 255]);
1380        assert_ne!(digest_of(&bytes), digest_of(&source));
1381        let wider = ImageChange { image: 0, crop: Some([0, 0, 9, 6]), cover: Vec::new() };
1382        assert!(changed_png(&source, &wider).is_err());
1383    }
1384
1385    proptest! {
1386        #![proptest_config(ProptestConfig::with_cases(128))]
1387
1388        /// The union of boxes never covers more than the image, never less than the largest
1389        /// box, and a box over the whole image covers all of it.
1390        #[test]
1391        fn coverage_is_the_area_of_the_union(
1392            boxes in proptest::collection::vec((0u32..400, 0u32..300, 1u32..400, 1u32..300), 0..8),
1393            whole in any::<bool>(),
1394        ) {
1395            let region = |x0: f64, y0: f64, x1: f64, y1: f64| EvidenceRegion {
1396                class: CoverClass::Marked,
1397                tag: String::new(),
1398                short_tag: String::new(),
1399                x0,
1400                y0,
1401                x1,
1402                y1,
1403            };
1404            let mut regions: Vec<EvidenceRegion> = boxes
1405                .iter()
1406                .map(|(x, y, w, h)| {
1407                    region(f64::from(*x), f64::from(*y), f64::from((x + w).min(400)), f64::from((y + h).min(300)))
1408                })
1409                .filter(|r| r.x1 > r.x0 && r.y1 > r.y0)
1410                .collect();
1411            if whole {
1412                regions.push(region(0.0, 0.0, 400.0, 300.0));
1413            }
1414            let share = coverage(&regions, 400, 300);
1415            prop_assert!((0.0..=1.0).contains(&share));
1416            let largest = regions
1417                .iter()
1418                .map(|r| (r.x1 - r.x0) * (r.y1 - r.y0))
1419                .fold(0.0, f64::max)
1420                / 120_000.0;
1421            prop_assert!(share + 1e-9 >= largest);
1422            if whole {
1423                prop_assert!((share - 1.0).abs() < 1e-9);
1424            }
1425        }
1426    }
1427}