Skip to main content

adk_surface/camera/
desk.rs

1//! The live camera surface on the engine (spec 3.7 §8.2): reads authorised as the inbox is —
2//! a camera belongs to its agent's session, and only that session's owner sees or acts on it
3//! (spec 3.3 §11 S-I8) — and every act recorded.
4
5use chrono::Duration;
6use serde_json::json;
7
8use super::facts::{CameraFacts, ZoneFacts};
9use super::hub::Cameras;
10use super::hub::{DropReason, Offered};
11use super::project::{self, Camera, Ctx, Place};
12use super::view::{
13    CameraAgent, CameraView, CamerasView, CardRaised, FrameDropped, FrameTaken, RaiseCard,
14    StageView, ZoneChange, ZoneSaved,
15};
16use super::{
17    SURFACE_AUDIT_CAMERA_CARD, SURFACE_AUDIT_CAMERA_RETRY, SURFACE_AUDIT_CAMERA_STOP,
18    SURFACE_AUDIT_CAMERA_SWITCH, SURFACE_AUDIT_CAMERA_ZONE,
19};
20use crate::engine::SurfaceEngine;
21use crate::error::{Result, SurfaceError};
22use crate::evidence::{EVIDENCE_RETENTION_DAYS, EvidenceBytes};
23use crate::origin::{Caller, Origin};
24
25/// The words "Nothing is waiting for you." under Decisions.
26const NOTHING_WAITING: &str = "Nothing is waiting for you.";
27
28/// The largest frame a screen may send a camera: a 1280 × 720 JPEG is about a tenth of it.
29pub const MAX_SENT_FRAME_BYTES: usize = 2 * 1024 * 1024;
30
31impl SurfaceEngine {
32    fn hub(&self) -> Result<&Cameras> {
33        self.camera_hub().ok_or_else(|| SurfaceError::unsupported("the live camera surface"))
34    }
35
36    /// The cameras `caller` may see: those of their own sessions.
37    async fn visible_cameras(&self, caller: &Caller) -> Result<Vec<CameraFacts>> {
38        let mut visible = Vec::new();
39        for facts in self.hub()?.facts().await? {
40            if self.owns_session(caller, &facts.session).await.is_ok() {
41                visible.push(facts);
42            }
43        }
44        Ok(visible)
45    }
46
47    /// One camera of `caller`'s, `surface.not_found` for any other.
48    async fn owned_camera(&self, caller: &Caller, camera: &str) -> Result<CameraFacts> {
49        self.visible_cameras(caller)
50            .await?
51            .into_iter()
52            .find(|facts| facts.id == camera)
53            .ok_or_else(|| SurfaceError::not_found(format!("camera '{camera}'")))
54    }
55
56    fn camera_ctx<'a>(&self, caller: &'a Caller, agent: &str) -> Ctx<'a> {
57        Ctx {
58            offset: self.projector().offset,
59            now: self.clock_now(),
60            user: caller.user_id(),
61            agent_name: self.projector().agent(agent).display_name,
62        }
63    }
64
65    async fn with_gates<'a>(&self, facts: &'a [CameraFacts]) -> Result<Vec<Camera<'a>>> {
66        let hub = self.hub()?;
67        let mut cameras = Vec::with_capacity(facts.len());
68        for camera in facts {
69            let gate = hub.gate(&camera.id).await.unwrap_or(super::hub::Gate {
70                on: camera.on,
71                switched: None,
72                stopped: None,
73                frozen: hub.is_frozen(),
74            });
75            cameras.push(Camera {
76                facts: camera,
77                gate,
78                recent: hub.recent(&camera.id).await,
79                takes_frames: hub.takes_frames(&camera.id),
80            });
81        }
82        Ok(cameras)
83    }
84
85    fn camera_agent(&self, camera: &Camera<'_>) -> CameraAgent {
86        let (line, tone) = project::agent_line(camera);
87        CameraAgent {
88            agent: self.projector().agent(&camera.facts.agent),
89            line,
90            tone,
91            session_id: camera.facts.session.clone(),
92        }
93    }
94
95    /// Every camera `caller` may see, as the grid shows them (spec 3.7 §8.2, board choice C8).
96    ///
97    /// # Errors
98    ///
99    /// `surface.unsupported` when the engine serves no cameras; the source's error.
100    pub async fn cameras_view(&self, caller: &Caller) -> Result<CamerasView> {
101        let facts = self.visible_cameras(caller).await?;
102        let cameras = self.with_gates(&facts).await?;
103        let first = cameras.first();
104        let agent = first.map(|camera| {
105            let mut agent = self.camera_agent(camera);
106            let watched = cameras
107                .iter()
108                .filter(|other| {
109                    other.facts.agent == camera.facts.agent && !other.facts.watches.is_empty()
110                })
111                .count();
112            if watched > 1 {
113                agent.line = format!("{} · {watched} cameras", agent.line);
114            }
115            agent
116        });
117        let agent_name = first.map_or_else(String::new, |camera| camera.facts.agent.clone());
118        let ctx = self.camera_ctx(caller, &agent_name);
119        let on =
120            cameras.iter().filter(|camera| camera.gate.on && camera.gate.stopped.is_none()).count();
121        let mut decisions = Vec::new();
122        let mut sessions: Vec<&str> = facts.iter().map(|facts| facts.session.as_str()).collect();
123        sessions.dedup();
124        for session in sessions {
125            decisions.extend(self.session_decisions(caller, session).await?);
126        }
127        let selected_line = first.map(|camera| {
128            let state = camera.state();
129            let mut line = format!(
130                "{} · {}",
131                camera.facts.name,
132                project::state_text(state, camera.facts, ctx.offset)
133            );
134            if matches!(
135                state,
136                super::view::CameraState::Live | super::view::CameraState::SavingFrames
137            ) {
138                line.push_str(&format!(" · {} a second", rate_text(camera.facts.governor.rate)));
139            }
140            line
141        });
142        Ok(CamerasView {
143            title: "Cameras".into(),
144            count_text: format!("{} sources · {on} on", cameras.len()),
145            count_short: format!("{} · {on} on", cameras.len()),
146            agent,
147            selected: first.map(|camera| camera.facts.id.clone()),
148            selected_line,
149            tiles: cameras
150                .iter()
151                .enumerate()
152                .map(|(index, camera)| project::camera_tile(camera, index == 0, &ctx))
153                .collect(),
154            note: "Each source has its own frame budget. Stop all pauses every one of them.".into(),
155            short_note: "Each camera has its own frame budget. People are blurred before any frame is shown or kept.".into(),
156            footer: "Select a camera to watch it large. People are blurred before any frame is shown or kept.".into(),
157            decisions,
158            nothing_waiting: NOTHING_WAITING.into(),
159            budget: cameras.iter().filter_map(|camera| project::tile_meter(camera, &ctx)).collect(),
160        })
161    }
162
163    /// Camera `camera`, watched large (spec 3.7 §8.2, board choice C1): the picture with its
164    /// overlays, the agent's decisions, what it watches for, the frame budget, the tracks and
165    /// every source.
166    ///
167    /// # Errors
168    ///
169    /// `surface.not_found` when the camera is not one of `caller`'s; `surface.unsupported` when
170    /// the engine serves no cameras; the source's error.
171    pub async fn camera_view(&self, caller: &Caller, camera: &str) -> Result<CameraView> {
172        let facts = self.visible_cameras(caller).await?;
173        if !facts.iter().any(|facts| facts.id == camera) {
174            return Err(SurfaceError::not_found(format!("camera '{camera}'")));
175        }
176        let cameras = self.with_gates(&facts).await?;
177        let Some(shown) = cameras.iter().find(|candidate| candidate.facts.id == camera) else {
178            return Err(SurfaceError::not_found(format!("camera '{camera}'")));
179        };
180        let ctx = self.camera_ctx(caller, &shown.facts.agent);
181        let state = shown.state();
182        let (tracks, tracks_note, tracks_short_note) = project::tracks(shown);
183        Ok(CameraView {
184            id: shown.facts.id.clone(),
185            name: shown.facts.name.clone(),
186            ingest: project::ingest(shown.facts),
187            state,
188            state_text: project::state_text(state, shown.facts, ctx.offset),
189            tone: project::tone(state),
190            // The person's switch: Stop all pauses a camera without switching it off.
191            on: shown.gate.on && shown.gate.stopped.is_none(),
192            agent: self.camera_agent(shown),
193            stage: project::stage(shown, Place::Main, &ctx),
194            notice: project::notice(shown, &ctx),
195            actions: project::actions(shown),
196            decisions: self.session_decisions(caller, &shown.facts.session).await?,
197            nothing_waiting: NOTHING_WAITING.into(),
198            watches: project::watches(shown, &ctx),
199            budget: project::budget(shown, &ctx),
200            tracks,
201            tracks_note,
202            tracks_short_note,
203            zones: project::zones(shown.facts),
204            sources: cameras
205                .iter()
206                .map(|other| project::source_tile(other, other.facts.id == camera, &ctx))
207                .collect(),
208        })
209    }
210
211    /// Camera `camera`'s picture alone, as its feed sends it after each frame.
212    ///
213    /// # Errors
214    ///
215    /// As [`camera_view`](Self::camera_view).
216    pub async fn camera_stage(&self, caller: &Caller, camera: &str) -> Result<StageView> {
217        let facts = self.owned_camera(caller, camera).await?;
218        self.stage_of(caller, facts).await
219    }
220
221    /// Camera `camera`'s picture for a feed that already checked the caller may see it: the
222    /// sessions are not read again for every frame.
223    #[cfg(feature = "web")]
224    pub(crate) async fn camera_stage_after_check(
225        &self,
226        caller: &Caller,
227        camera: &str,
228    ) -> Result<StageView> {
229        let facts = self
230            .hub()?
231            .facts()
232            .await?
233            .into_iter()
234            .find(|facts| facts.id == camera)
235            .ok_or_else(|| SurfaceError::not_found(format!("camera '{camera}'")))?;
236        self.stage_of(caller, facts).await
237    }
238
239    async fn stage_of(&self, caller: &Caller, facts: CameraFacts) -> Result<StageView> {
240        let shown = self.with_gates(std::slice::from_ref(&facts)).await?;
241        let ctx = self.camera_ctx(caller, &facts.agent);
242        Ok(project::stage(&shown[0], Place::Main, &ctx))
243    }
244
245    /// Freezes frame `frame` of `camera` for a card (board choice C11): the hub holds it in
246    /// memory while the person writes what the agent should look at. Returns the picture of that
247    /// frame with what was found on it. Nothing is written.
248    ///
249    /// # Errors
250    ///
251    /// `surface.not_found` when the camera is not `caller`'s or the frame is no longer held;
252    /// `surface.not_here` from anything but a person at a screen.
253    pub async fn freeze_camera_frame(
254        &self,
255        caller: &Caller,
256        camera: &str,
257        frame: &str,
258    ) -> Result<StageView> {
259        at_a_screen(caller)?;
260        let facts = self.owned_camera(caller, camera).await?;
261        let recent = self.hub()?.freeze(camera, frame, self.clock_now()).await.ok_or_else(|| {
262            SurfaceError::not_found(format!(
263                "frame '{frame}' of camera '{camera}': it is no longer held; freeze the picture again"
264            ))
265        })?;
266        let mut shown = self.with_gates(std::slice::from_ref(&facts)).await?;
267        shown[0].recent = recent;
268        let ctx = self.camera_ctx(caller, &facts.agent);
269        Ok(project::stage(&shown[0], Place::Main, &ctx))
270    }
271
272    /// The frame of `camera` with `digest`, while the hub holds it in memory, its bytes checked
273    /// against the digest (spec 3.7 §8.3). A camera that is off holds none.
274    ///
275    /// # Errors
276    ///
277    /// `surface.not_found` when the camera is not `caller`'s or the frame is no longer held.
278    pub async fn camera_frame(
279        &self,
280        caller: &Caller,
281        camera: &str,
282        digest: &str,
283    ) -> Result<EvidenceBytes> {
284        self.owned_camera(caller, camera).await?;
285        let held = self
286            .hub()?
287            .held(camera, digest)
288            .await
289            .filter(|held| crate::evidence::digest_of(&held.frame.bytes) == digest)
290            .ok_or_else(|| {
291                SurfaceError::not_found(format!("frame '{digest}' of camera '{camera}'"))
292            })?;
293        Ok(EvidenceBytes { mime_type: held.frame.mime_type, bytes: held.frame.bytes })
294    }
295
296    /// Switches `camera` on or off for `caller` (board choice C2). Off closes the hub's gate
297    /// before anything else, so the server drops every frame from then on, and forgets the
298    /// frames it held; then it is recorded and the source told. On is recorded first.
299    ///
300    /// # Errors
301    ///
302    /// `surface.not_found` when the camera is not `caller`'s; `surface.not_here` from anything
303    /// but a person at a screen; the source's error.
304    pub async fn switch_camera(
305        &self,
306        caller: &Caller,
307        camera: &str,
308        on: bool,
309    ) -> Result<CameraView> {
310        at_a_screen(caller)?;
311        let facts = self.owned_camera(caller, camera).await?;
312        let hub = self.hub()?;
313        let fields = json!({ "camera": camera, "sessionId": facts.session, "on": on });
314        if on {
315            self.record(caller, SURFACE_AUDIT_CAMERA_SWITCH, fields).await?;
316            hub.switch(camera, true, caller.user_id(), self.clock_now()).await?;
317        } else {
318            let switched = hub.switch(camera, false, caller.user_id(), self.clock_now()).await;
319            self.record(caller, SURFACE_AUDIT_CAMERA_SWITCH, fields).await?;
320            switched?;
321        }
322        self.camera_view(caller, camera).await
323    }
324
325    /// Ends `camera`'s stream for `caller` (board choice C2): the gate closes for good, then it
326    /// is recorded and the source told.
327    ///
328    /// # Errors
329    ///
330    /// As [`switch_camera`](Self::switch_camera).
331    pub async fn stop_camera(&self, caller: &Caller, camera: &str) -> Result<CameraView> {
332        at_a_screen(caller)?;
333        let facts = self.owned_camera(caller, camera).await?;
334        let stopped = self.hub()?.stop(camera, caller.user_id(), self.clock_now()).await;
335        self.record(
336            caller,
337            SURFACE_AUDIT_CAMERA_STOP,
338            json!({ "camera": camera, "sessionId": facts.session }),
339        )
340        .await?;
341        stopped?;
342        self.camera_view(caller, camera).await
343    }
344
345    /// Takes one frame `caller`'s screen captured for `camera` — the web home's or the phone's
346    /// own camera — and hands it to the camera's frame pipeline through the hub's gate
347    /// ([`Cameras::ingest`]): while the camera is off, stopped or paused by Stop all the frame is
348    /// dropped and the answer says why, so the screen stops capturing. A camera switched off
349    /// sends nothing. Nothing is held or written here; the pipeline shows what it makes of the
350    /// frame. Frames are not recorded one by one: switching the camera is.
351    ///
352    /// # Errors
353    ///
354    /// `surface.not_found` when the camera is not `caller`'s; `surface.not_here` from anything
355    /// but a person at a screen; `surface.invalid` for an empty frame, one over
356    /// [`MAX_SENT_FRAME_BYTES`], or one that is not the JPEG, PNG or WebP `mime_type` says;
357    /// `surface.unsupported` for a camera that reads its own source; `surface.rate_limited`
358    /// for a frame sooner than [`MAX_SCREEN_FPS`](super::MAX_SCREEN_FPS) allows.
359    pub async fn send_camera_frame(
360        &self,
361        caller: &Caller,
362        camera: &str,
363        mime_type: &str,
364        bytes: Vec<u8>,
365    ) -> Result<FrameTaken> {
366        at_a_screen(caller)?;
367        if bytes.is_empty() || bytes.len() > MAX_SENT_FRAME_BYTES {
368            return Err(SurfaceError::Invalid(format!(
369                "a camera frame is 1 byte to {} MiB; this one is {} bytes",
370                MAX_SENT_FRAME_BYTES / (1024 * 1024),
371                bytes.len()
372            )));
373        }
374        let mime = mime_type.split(';').next().unwrap_or_default().trim().to_ascii_lowercase();
375        let matches = match mime.as_str() {
376            "image/jpeg" => bytes.starts_with(&[0xFF, 0xD8, 0xFF]),
377            "image/png" => bytes.starts_with(b"\x89PNG\r\n\x1a\n"),
378            "image/webp" => bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP",
379            _ => {
380                return Err(SurfaceError::Invalid(format!(
381                    "a camera frame is image/jpeg, image/png or image/webp, not '{mime_type}'"
382                )));
383            }
384        };
385        if !matches {
386            return Err(SurfaceError::Invalid(format!(
387                "the frame's bytes are not the {mime} its content type says"
388            )));
389        }
390        self.owned_camera(caller, camera).await?;
391        let hub = self.hub()?;
392        if !hub.takes_frames(camera) {
393            return Err(SurfaceError::unsupported(format!(
394                "sending frames to camera '{camera}', which reads its own source"
395            )));
396        }
397        let dropped = match hub.ingest(camera, bytes, self.clock_now()).await {
398            Offered::Forwarded | Offered::Shown { .. } => None,
399            Offered::Dropped(DropReason::Off) => Some(FrameDropped::Off),
400            Offered::Dropped(DropReason::Stopped) => Some(FrameDropped::Stopped),
401            Offered::Dropped(DropReason::Frozen) => Some(FrameDropped::Frozen),
402            Offered::Dropped(DropReason::Unknown) => Some(FrameDropped::NotReading),
403            Offered::Dropped(DropReason::TooSoon) => {
404                return Err(SurfaceError::Source(adk_core::AdkError::new(
405                    adk_core::ErrorComponent::Server,
406                    adk_core::ErrorCategory::RateLimited,
407                    "surface.rate_limited",
408                    format!(
409                        "camera '{camera}' takes at most {} frames a second from a screen; send them further apart",
410                        super::MAX_SCREEN_FPS
411                    ),
412                )));
413            }
414        };
415        Ok(FrameTaken { taken: dropped.is_none(), dropped })
416    }
417
418    /// Tries a lost `camera` again now (board choice C6).
419    ///
420    /// # Errors
421    ///
422    /// As [`switch_camera`](Self::switch_camera); `surface.unsupported` when the source cannot.
423    pub async fn retry_camera(&self, caller: &Caller, camera: &str) -> Result<CameraView> {
424        at_a_screen(caller)?;
425        let facts = self.owned_camera(caller, camera).await?;
426        self.record(
427            caller,
428            SURFACE_AUDIT_CAMERA_RETRY,
429            json!({ "camera": camera, "sessionId": facts.session }),
430        )
431        .await?;
432        self.hub()?.source().retry(camera).await?;
433        self.hub()?.changed(camera);
434        self.camera_view(caller, camera).await
435    }
436
437    /// Changes zone `zone` of `camera` (board choice C12): every watch that uses it reads the
438    /// new corners from its next frame. A zone changed since the person started is refused,
439    /// never overwritten. Recorded before it is saved.
440    ///
441    /// # Errors
442    ///
443    /// `surface.not_found` for another's camera or an unknown zone; `surface.invalid` for corners
444    /// outside the frame, an empty name, or a zone that changed; `surface.not_here` from a
445    /// paired device or anything but a person at a screen; the source's error.
446    pub async fn save_camera_zone(
447        &self,
448        caller: &Caller,
449        camera: &str,
450        zone: &str,
451        change: &ZoneChange,
452    ) -> Result<ZoneSaved> {
453        at_a_screen(caller)?;
454        if caller.device.is_some() {
455            return Err(SurfaceError::NotHere(
456                "edit a zone in the web home; a phone shows the zone and opens it there".into(),
457            ));
458        }
459        let facts = self.owned_camera(caller, camera).await?;
460        let current =
461            facts.zones.iter().find(|candidate| candidate.id == zone).ok_or_else(|| {
462                SurfaceError::not_found(format!("zone '{zone}' of camera '{camera}'"))
463            })?;
464        let name = change.name.trim();
465        if name.is_empty() || name.chars().count() > 60 {
466            return Err(SurfaceError::Invalid("a zone needs a name of 1 to 60 characters".into()));
467        }
468        let [x0, y0, x1, y1] = change.corners;
469        let (width, height) = (f64::from(facts.ingest.width), f64::from(facts.ingest.height));
470        let inside = change.corners.iter().all(|value| value.is_finite())
471            && x0 >= 0.0
472            && y0 >= 0.0
473            && x1 <= width
474            && y1 <= height
475            && x1 - x0 >= 8.0
476            && y1 - y0 >= 8.0;
477        if !inside {
478            return Err(SurfaceError::Invalid(format!(
479                "a zone's corners must lie inside the camera's {} × {} pixels, top left before bottom right",
480                facts.ingest.width, facts.ingest.height
481            )));
482        }
483        if change.was.iter().zip(current.corners).any(|(was, now)| (was - now).abs() > 0.5) {
484            return Err(SurfaceError::Invalid(
485                "the zone changed since you started editing it; open it again to see it as it is now"
486                    .into(),
487            ));
488        }
489        let corners = change.corners.map(f64::round);
490        self.record(
491            caller,
492            SURFACE_AUDIT_CAMERA_ZONE,
493            json!({
494                "camera": camera,
495                "sessionId": facts.session,
496                "zone": zone,
497                "name": name,
498                "corners": corners,
499                "was": current.corners,
500            }),
501        )
502        .await?;
503        let saved = ZoneFacts { id: zone.to_string(), name: name.to_string(), corners };
504        self.hub()?.source().save_zone(camera, &saved).await?;
505        self.hub()?.changed(camera);
506        let mut facts = facts;
507        if let Some(entry) = facts.zones.iter_mut().find(|candidate| candidate.id == zone) {
508            *entry = saved;
509        }
510        let view = project::zones(&facts).into_iter().find(|candidate| candidate.id == zone);
511        let view = view.ok_or_else(|| SurfaceError::not_found(format!("zone '{zone}'")))?;
512        let text = match view.used_by.as_slice() {
513            [] => "Saved.".to_string(),
514            [one] => format!("Saved. The {} uses it from the next frame.", one.to_lowercase()),
515            several => format!("Saved. {} use it from the next frame.", several.join(", ")),
516        };
517        Ok(ZoneSaved { zone: view, text })
518    }
519
520    /// Raises a card from a frozen frame of `camera` (board choice C11): that one frame is kept
521    /// as evidence — blurred first by the source, kept
522    /// [`EVIDENCE_RETENTION_DAYS`] days — with the regions on it, and the card goes to the
523    /// watching agent as `caller`'s message, naming the evidence by digest and artifact, never
524    /// carrying pixels (spec 3.7 V-I15). Nothing else is stored. Recorded before the frame is
525    /// kept.
526    ///
527    /// # Errors
528    ///
529    /// `surface.not_found` when the camera is not `caller`'s or the hub no longer holds the
530    /// frame; `surface.invalid` for an empty note; `surface.not_here` from anything but a person
531    /// at a screen; the source's error, and nothing is kept then.
532    pub async fn raise_camera_card(
533        &self,
534        caller: &Caller,
535        camera: &str,
536        card: &RaiseCard,
537    ) -> Result<CardRaised> {
538        at_a_screen(caller)?;
539        let note = card.note.trim();
540        if note.is_empty() {
541            return Err(SurfaceError::Invalid(
542                "say what the agent should look at on the frame".into(),
543            ));
544        }
545        let facts = self.owned_camera(caller, camera).await?;
546        let held = self.hub()?.held(camera, &card.frame).await.ok_or_else(|| {
547            SurfaceError::not_found(format!(
548                "frame '{}' of camera '{camera}': it is no longer held; freeze the picture again",
549                card.frame
550            ))
551        })?;
552        let regions: Vec<_> =
553            held.frame.overlays.iter().filter(|overlay| overlay.bbox.is_some()).collect();
554        self.record(
555            caller,
556            SURFACE_AUDIT_CAMERA_CARD,
557            json!({
558                "camera": camera,
559                "sessionId": facts.session,
560                "frame": held.digest,
561                "regions": regions.len(),
562                "noteDigest": crate::evidence::digest_of(note.as_bytes()),
563            }),
564        )
565        .await?;
566        let evidence = self.hub()?.source().keep_frame(&facts, &held).await?;
567        let offset = self.projector().offset;
568        let kept_until = (self.clock_now() + Duration::days(i64::from(EVIDENCE_RETENTION_DAYS)))
569            .with_timezone(&offset)
570            .format("%-d %b")
571            .to_string();
572        let lines: Vec<String> = regions
573            .iter()
574            .filter_map(|overlay| {
575                let [x0, y0, x1, y1] = overlay.bbox?.map(|value| value.round() as i64);
576                let mut name = overlay.label.clone();
577                if let Some(track) = overlay.track {
578                    name.push_str(&format!(" T{track}"));
579                }
580                if let Some(score) = overlay.score {
581                    name.push_str(&format!(" {score:.2}"));
582                }
583                Some(format!("- {name}: {x0}, {y0} → {x1}, {y1}"))
584            })
585            .collect();
586        let at = held.frame.at.with_timezone(&offset).format("%H:%M:%S");
587        let text = format!(
588            "Card from the {place} camera, frame of {at}: {note}\n\nThe frame is kept as evidence until {kept_until}: {digest} (artifact {file} v{version}, {width} × {height}, anyone in it blurred). {count} regions on it, in the camera's pixels:\n{lines}",
589            place = facts.place,
590            digest = evidence.digest,
591            file = evidence.artifact.file_name,
592            version = evidence.artifact.version,
593            width = evidence.width,
594            height = evidence.height,
595            count = lines.len(),
596            lines = lines.join("\n"),
597        );
598        let outcome = self.send_message(caller, &facts.session, text).await?;
599        let agent = self.projector().agent(&facts.agent).display_name;
600        // Behind an open decision or a running turn the card waits its turn, as a typed message
601        // does (spec 3.3 S-I4).
602        let when = match &outcome {
603            crate::engine::CommandOutcome::Queued { .. } => {
604                format!(
605                    "Raised to the {agent}, who reads it once the open decision or turn is done."
606                )
607            }
608            _ => format!("Raised to the {agent}."),
609        };
610        Ok(CardRaised {
611            short_digest: crate::evidence::short_digest(&evidence.digest),
612            href: crate::viewer::viewer_path(&facts.session, &evidence.artifact.file_name),
613            digest: evidence.digest,
614            regions: lines.len(),
615            text: format!("{when} This one frame is kept as evidence until {kept_until}."),
616            kept_until: format!("Kept as evidence until {kept_until}"),
617            outcome,
618        })
619    }
620}
621
622/// Cameras are switched, stopped, edited and carded by a person at a screen; voice and chat
623/// have no camera controls (spec 3.7 §8.2: web home and phone).
624fn at_a_screen(caller: &Caller) -> Result<()> {
625    match caller.origin {
626        Origin::Keyboard | Origin::Pointer | Origin::Touch => Ok(()),
627        Origin::Voice | Origin::Chat { .. } | Origin::Agent { .. } => Err(SurfaceError::NotHere(
628            "cameras are switched and edited from the web home or the phone".into(),
629        )),
630    }
631}
632
633fn rate_text(rate: f64) -> String {
634    if (rate - rate.round()).abs() < 1e-6 {
635        format!("{}", rate.round() as i64)
636    } else {
637        format!("{rate:.1}")
638    }
639}