Skip to main content

vtcode_desktop_protocol/
preview.rs

1//! Ephemeral computer-use screenshot preview DTOs.
2//!
3//! Transcript rows carry a `computer-preview://` reference (row id plus byte
4//! metadata, no pixels); the client resolves it through `computer/preview/read`
5//! while the service still retains the bytes. Retention is memory-only and
6//! bounded, so reads answer either the PNG body or an explicit expiry —
7//! never an error the client should retry.
8
9use serde::{Deserialize, Serialize};
10
11/// URI scheme for computer-preview references. The remainder is the outer
12/// tool row id verbatim; no filesystem or network resource is named.
13pub const COMPUTER_PREVIEW_URI_SCHEME: &str = "computer-preview://";
14
15/// Longest accepted reference. Row ids are short harness handles; anything
16/// longer is rejected before the lookup.
17pub const MAX_COMPUTER_PREVIEW_URI_BYTES: usize = 512;
18
19/// Parse and validate a preview reference, returning the row id. Rejects
20/// foreign schemes, empty ids, whitespace, and overlong input before any
21/// lookup; a well-formed but unknown id is a lookup miss (expired), not a
22/// validation failure.
23pub fn parse_preview_uri(uri: &str) -> Option<&str> {
24    let id = uri.strip_prefix(COMPUTER_PREVIEW_URI_SCHEME)?;
25    if id.is_empty() || id.len() > MAX_COMPUTER_PREVIEW_URI_BYTES || id.chars().any(char::is_whitespace) {
26        return None;
27    }
28    Some(id)
29}
30
31/// Reference URI for a row's screenshot.
32pub fn preview_uri(item_id: &str) -> String {
33    format!("{COMPUTER_PREVIEW_URI_SCHEME}{item_id}")
34}
35
36/// Request one retained screenshot body.
37#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
38#[serde(rename_all = "camelCase")]
39pub struct ComputerPreviewReadParams {
40    /// `computer-preview://` URI to read.
41    pub uri: String,
42    /// Opaque client identity used to reject superseded reads.
43    pub request_id: String,
44}
45
46/// One retained screenshot body, or its expiry.
47#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
48#[serde(rename_all = "camelCase")]
49pub struct ComputerPreviewReadResult {
50    /// URI that was read.
51    pub uri: String,
52    /// Echoed request identity.
53    pub request_id: String,
54    /// MIME type of the retained bytes.
55    pub mime_type: Option<String>,
56    /// Base64 PNG body; absent when the bytes expired.
57    #[serde(default, skip_serializing_if = "Option::is_none")]
58    pub data: Option<String>,
59    /// Served PNG bytes (post-scaling).
60    pub total_bytes: u64,
61    /// True when the served body was downscaled to fit the frame budget.
62    #[serde(default)]
63    pub downscaled: bool,
64    /// True when the bytes are gone (evicted, cleared, or unknown): the
65    /// client renders the expired state and never retries.
66    pub expired: bool,
67}
68
69#[cfg(test)]
70mod tests {
71    use super::*;
72
73    #[test]
74    fn preview_uris_round_trip_and_reject_foreign_shapes() {
75        assert_eq!(preview_uri("row-1"), "computer-preview://row-1");
76        assert_eq!(parse_preview_uri("computer-preview://row-1"), Some("row-1"));
77        assert_eq!(parse_preview_uri("computer-preview://call_1:ab12"), Some("call_1:ab12"));
78        for bad in [
79            String::new(),
80            "row-1".to_string(),
81            "ui://row-1".to_string(),
82            "computer-preview://".to_string(),
83            "computer-preview://has space".to_string(),
84            "computer-preview://has\nnewline".to_string(),
85            format!("computer-preview://{}", "x".repeat(MAX_COMPUTER_PREVIEW_URI_BYTES + 1)),
86        ] {
87            assert!(parse_preview_uri(&bad).is_none(), "must reject {bad:?}");
88        }
89    }
90
91    #[test]
92    fn preview_result_marks_expiry_without_a_body() {
93        let expired = ComputerPreviewReadResult {
94            uri: preview_uri("gone"),
95            request_id: "req-1".to_string(),
96            mime_type: None,
97            data: None,
98            total_bytes: 0,
99            downscaled: false,
100            expired: true,
101        };
102        let json = serde_json::to_value(&expired).unwrap();
103        assert_eq!(json["expired"], serde_json::json!(true));
104        assert!(json.get("data").is_none(), "expired reads carry no body: {json}");
105        assert_eq!(serde_json::from_value::<ComputerPreviewReadResult>(json).unwrap(), expired);
106    }
107}