Skip to main content

orch/engine/runner/
screenshots.rs

1//! Screenshots on the PR. The agent lists image paths in its final JSON, orch pushes the images
2//! to a branch that never merges and comments on the PR with links pinned to that commit
3
4use std::fmt::Write as _;
5use std::fs::{self, File};
6use std::io::Read;
7use std::path::{Path, PathBuf};
8use std::process;
9
10use anyhow::{Context, bail};
11use tokio::process::Command;
12
13use super::git_ops;
14use crate::cmd::CommandErrorContext;
15use crate::parser::Screenshot;
16
17/// Branch that holds the images, used as no PR base or head, and cleanup deletes task branches only
18pub const SCREENSHOTS_BRANCH: &str = "orch/screenshots";
19
20const MAX_IMAGES: usize = 12;
21const MAX_IMAGE_BYTES: u64 = 10 * 1024 * 1024;
22const IMAGE_EXTENSIONS: &[&str] = &["png", "jpg", "jpeg", "gif", "webp"];
23const LOCAL_REF: &str = "refs/orch/screenshots";
24
25/// An image checked and placed at its path on the screenshots branch
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct Prepared {
28    pub source: PathBuf,
29    pub branch_path: String,
30    pub caption: String,
31}
32
33/// Keep the file name safe for a URL and a git tree
34fn safe_name(name: &str) -> String {
35    let cleaned: String = name
36        .chars()
37        .map(|c| {
38            if c.is_ascii_alphanumeric() || c == '.' || c == '-' || c == '_' {
39                c
40            } else {
41                '-'
42            }
43        })
44        .collect();
45    cleaned.trim_start_matches('.').to_string()
46}
47
48/// Check each listed image, and skip a bad entry with a reason so it does not drop the others
49pub fn prepare(
50    shots: &[Screenshot],
51    base: &Path,
52    roots: &[PathBuf],
53    pr_number: u64,
54) -> (Vec<Prepared>, Vec<String>) {
55    let mut prepared = Vec::new();
56    let mut skipped = Vec::new();
57
58    for shot in shots {
59        if prepared.len() >= MAX_IMAGES {
60            skipped.push(format!("{}: more than {MAX_IMAGES} screenshots", shot.path));
61            continue;
62        }
63        match check_image(&shot.path, base, roots) {
64            Ok(source) => {
65                let name = source
66                    .file_name()
67                    .map(|n| safe_name(&n.to_string_lossy()))
68                    .unwrap_or_default();
69                prepared.push(Prepared {
70                    branch_path: format!("pr-{pr_number}/{}-{name}", prepared.len() + 1),
71                    source,
72                    caption: shot.caption.clone(),
73                });
74            }
75            Err(e) => skipped.push(format!("{}: {e}", shot.path)),
76        }
77    }
78    (prepared, skipped)
79}
80
81fn check_image(path: &str, base: &Path, roots: &[PathBuf]) -> anyhow::Result<PathBuf> {
82    let joined = base.join(path.trim());
83    let source = fs::canonicalize(&joined).context("file not found")?;
84    if !roots.iter().any(|root| source.starts_with(root)) {
85        bail!("outside the worktree");
86    }
87    let is_image = source
88        .extension()
89        .and_then(|e| e.to_str())
90        .is_some_and(|e| IMAGE_EXTENSIONS.contains(&e.to_ascii_lowercase().as_str()));
91    if !is_image {
92        bail!("not an image file");
93    }
94    let meta = fs::metadata(&source).context("unreadable")?;
95    if !meta.is_file() || meta.len() == 0 || meta.len() > MAX_IMAGE_BYTES {
96        bail!("empty or larger than {} MB", MAX_IMAGE_BYTES / 1024 / 1024);
97    }
98    let mut head = [0u8; 12];
99    let read = File::open(&source)
100        .and_then(|mut f| f.read(&mut head))
101        .context("unreadable")?;
102    if !has_image_header(&head[..read]) {
103        bail!("not an image file");
104    }
105    Ok(source)
106}
107
108fn has_image_header(head: &[u8]) -> bool {
109    head.starts_with(b"\x89PNG\r\n\x1a\n")
110        || head.starts_with(&[0xFF, 0xD8, 0xFF])
111        || head.starts_with(b"GIF8")
112        || (head.starts_with(b"RIFF") && head.get(8..12) == Some(b"WEBP"))
113}
114
115fn one_line(text: &str) -> String {
116    text.split_whitespace()
117        .collect::<Vec<_>>()
118        .join(" ")
119        .replace(['[', ']'], "")
120}
121
122/// The PR comment, with links pinned to `commit` so they render in a private repository
123pub fn build_comment(
124    repo: &str,
125    commit: &str,
126    images: &[Prepared],
127    note: Option<&str>,
128    skipped: &[String],
129) -> String {
130    let mut body = String::from("## Screenshots\n");
131    for (i, image) in images.iter().enumerate() {
132        let caption = one_line(&image.caption);
133        let alt = if caption.is_empty() {
134            format!("Screenshot {}", i + 1)
135        } else {
136            caption.clone()
137        };
138        let url = format!(
139            "https://github.com/{repo}/blob/{commit}/{}?raw=true",
140            image.branch_path
141        );
142        body.push('\n');
143        if !caption.is_empty() {
144            let _ = writeln!(body, "**{caption}**\n");
145        }
146        let _ = writeln!(body, "![{alt}]({url})");
147    }
148    if !skipped.is_empty() {
149        body.push_str("\nSkipped:\n");
150        for reason in skipped {
151            let _ = writeln!(body, "- {}", one_line(reason));
152        }
153    }
154    if let Some(note) = note.map(str::trim).filter(|n| !n.is_empty()) {
155        let _ = write!(body, "\n> {}\n", one_line(note));
156    }
157    body
158}
159
160async fn git_out(dir: &Path, index: Option<&Path>, args: &[&str]) -> anyhow::Result<String> {
161    let mut cmd: Command = git_ops::git().await;
162    cmd.arg("-C").arg(dir).args(args);
163    if let Some(index) = index {
164        cmd.env("GIT_INDEX_FILE", index);
165    }
166    cmd.env("GIT_AUTHOR_NAME", "orch")
167        .env("GIT_AUTHOR_EMAIL", "orch@localhost")
168        .env("GIT_COMMITTER_NAME", "orch")
169        .env("GIT_COMMITTER_EMAIL", "orch@localhost");
170    let out = cmd.output_with_context().await?;
171    if !out.status.success() {
172        bail!(
173            "git {} failed: {}",
174            args.first().copied().unwrap_or(""),
175            String::from_utf8_lossy(&out.stderr).trim()
176        );
177    }
178    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
179}
180
181/// Roots an image may live in: the worktree and its git dir, which stays out of the PR commit
182pub async fn allowed_roots(worktree: &Path) -> Vec<PathBuf> {
183    let mut roots = Vec::new();
184    if let Ok(root) = fs::canonicalize(worktree) {
185        roots.push(root);
186    }
187    if let Ok(dir) = git_out(worktree, None, &["rev-parse", "--absolute-git-dir"]).await
188        && let Ok(dir) = fs::canonicalize(dir)
189    {
190        roots.push(dir);
191    }
192    roots
193}
194
195/// Push the images on top of the screenshots branch, with a throwaway index so the worktree stays
196/// untouched, and return the commit the links point at
197pub async fn publish(
198    worktree: &Path,
199    images: &[Prepared],
200    pr_number: u64,
201) -> anyhow::Result<String> {
202    if images.is_empty() {
203        bail!("no images to publish");
204    }
205    let git_dir = git_out(worktree, None, &["rev-parse", "--absolute-git-dir"]).await?;
206    let index = PathBuf::from(git_dir).join(format!("orch-screenshots-index-{}", process::id()));
207    let result = push_images(worktree, &index, images, pr_number).await;
208    let _ = fs::remove_file(&index);
209    result
210}
211
212async fn push_images(
213    worktree: &Path,
214    index: &Path,
215    images: &[Prepared],
216    pr_number: u64,
217) -> anyhow::Result<String> {
218    let fetch_spec = format!("+refs/heads/{SCREENSHOTS_BRANCH}:{LOCAL_REF}");
219    let parent = match git_out(worktree, None, &["fetch", "origin", &fetch_spec]).await {
220        Ok(_) => git_out(worktree, None, &["rev-parse", "--verify", LOCAL_REF])
221            .await
222            .ok(),
223        Err(_) => None,
224    };
225
226    if let Some(parent) = &parent {
227        git_out(worktree, Some(index), &["read-tree", parent]).await?;
228    }
229    for image in images {
230        let source = image.source.to_string_lossy();
231        let blob = git_out(worktree, None, &["hash-object", "-w", "--", &source]).await?;
232        let entry = format!("100644,{blob},{}", image.branch_path);
233        git_out(
234            worktree,
235            Some(index),
236            &["update-index", "--add", "--cacheinfo", &entry],
237        )
238        .await?;
239    }
240    let tree = git_out(worktree, Some(index), &["write-tree"]).await?;
241    let message = format!("Screenshots for PR #{pr_number}");
242    let mut args = vec!["commit-tree", &tree, "-m", &message];
243    if let Some(parent) = &parent {
244        args.extend(["-p", parent]);
245    }
246    let commit = git_out(worktree, None, &args).await?;
247
248    let refspec = format!("{commit}:refs/heads/{SCREENSHOTS_BRANCH}");
249    git_out(worktree, None, &["push", "origin", &refspec]).await?;
250    Ok(commit)
251}
252
253#[cfg(test)]
254mod tests {
255    use std::process::Command as StdCommand;
256    use std::slice;
257
258    use super::*;
259
260    const PNG_HEADER: &[u8] = b"\x89PNG\r\n\x1a\n";
261
262    fn shot(path: &str, caption: &str) -> Screenshot {
263        Screenshot {
264            path: path.into(),
265            caption: caption.into(),
266        }
267    }
268
269    fn git_run(dir: &Path, args: &[&str]) -> String {
270        let out = StdCommand::new("git")
271            .arg("-C")
272            .arg(dir)
273            .args(args)
274            .env("GIT_CONFIG_GLOBAL", "/dev/null")
275            .output()
276            .unwrap();
277        assert!(out.status.success(), "git {args:?}: {out:?}");
278        String::from_utf8_lossy(&out.stdout).trim().to_string()
279    }
280
281    #[test]
282    fn comment_links_images_to_the_commit() {
283        let images = vec![
284            Prepared {
285                source: PathBuf::from("/x/home.png"),
286                branch_path: "pr-7/1-home.png".into(),
287                caption: "Home, desktop".into(),
288            },
289            Prepared {
290                source: PathBuf::from("/x/phone.png"),
291                branch_path: "pr-7/2-phone.png".into(),
292                caption: String::new(),
293            },
294        ];
295        let body = build_comment(
296            "owner/repo",
297            "abc123",
298            &images,
299            Some("ui-screenshot skill missing"),
300            &[],
301        );
302        assert!(body.starts_with("## Screenshots"));
303        assert!(body.contains("**Home, desktop**"));
304        assert!(body.contains(
305            "![Home, desktop](https://github.com/owner/repo/blob/abc123/pr-7/1-home.png?raw=true)"
306        ));
307        assert!(body.contains(
308            "![Screenshot 2](https://github.com/owner/repo/blob/abc123/pr-7/2-phone.png?raw=true)"
309        ));
310        assert!(body.contains("> ui-screenshot skill missing"));
311    }
312
313    #[test]
314    fn note_comment_has_no_images() {
315        let body = build_comment(
316            "owner/repo",
317            "",
318            &[],
319            Some("no browser, the screenshot could not be taken"),
320            &[],
321        );
322        assert!(!body.contains("!["));
323        assert!(body.contains("> no browser"));
324    }
325
326    #[test]
327    fn prepare_keeps_images_inside_the_roots_only() {
328        let tmp = tempfile::tempdir().unwrap();
329        let root = fs::canonicalize(tmp.path()).unwrap();
330        fs::write(root.join("a b.png"), PNG_HEADER).unwrap();
331        fs::write(root.join("notes.txt"), b"text").unwrap();
332        fs::write(root.join("fake.png"), b"not an image at all").unwrap();
333        let outside = tempfile::tempdir().unwrap();
334        fs::write(outside.path().join("secret.png"), PNG_HEADER).unwrap();
335
336        let shots = vec![
337            shot("a b.png", "A"),
338            shot("notes.txt", "B"),
339            shot("fake.png", "F"),
340            shot("missing.png", "C"),
341            shot(&outside.path().join("secret.png").to_string_lossy(), "D"),
342            shot("../secret.png", "E"),
343        ];
344        let (prepared, skipped) = prepare(&shots, &root, slice::from_ref(&root), 9);
345
346        assert_eq!(prepared.len(), 1);
347        assert_eq!(prepared[0].branch_path, "pr-9/1-a-b.png");
348        assert_eq!(skipped.len(), 5);
349    }
350
351    #[tokio::test]
352    async fn publish_pushes_a_branch_the_worktree_never_sees() {
353        let tmp = tempfile::tempdir().unwrap();
354        let origin = tmp.path().join("origin.git");
355        let clone = tmp.path().join("clone");
356        git_run(tmp.path(), &["init", "--bare", "-q", "origin.git"]);
357        git_run(tmp.path(), &["init", "-q", "-b", "main", "clone"]);
358        git_run(&clone, &["config", "user.email", "t@t"]);
359        git_run(&clone, &["config", "user.name", "t"]);
360        git_run(
361            &clone,
362            &["remote", "add", "origin", &origin.to_string_lossy()],
363        );
364        fs::write(clone.join("f"), "x").unwrap();
365        git_run(&clone, &["add", "f"]);
366        git_run(&clone, &["commit", "-qm", "init"]);
367        let head_before = git_run(&clone, &["rev-parse", "HEAD"]);
368
369        let shot_path = clone.join("home.png");
370        fs::write(&shot_path, PNG_HEADER).unwrap();
371        let roots = vec![fs::canonicalize(&clone).unwrap()];
372        let (images, _) = prepare(&[shot("home.png", "Home")], &clone, &roots, 3);
373        let first = publish(&clone, &images, 3).await.unwrap();
374
375        fs::write(&shot_path, b"\x89PNG\r\n\x1a\nsecond").unwrap();
376        let (images, _) = prepare(&[shot("home.png", "Home")], &clone, &roots, 4);
377        let second = publish(&clone, &images, 4).await.unwrap();
378
379        assert_ne!(first, second);
380        let tip = format!("refs/heads/{SCREENSHOTS_BRANCH}");
381        assert_eq!(git_run(&origin, &["rev-parse", &tip]), second);
382        assert_eq!(
383            git_run(&origin, &["rev-parse", &format!("{second}^")]),
384            first
385        );
386        let files = git_run(&origin, &["ls-tree", "-r", "--name-only", &second]);
387        assert!(files.contains("pr-3/1-home.png"), "{files}");
388        assert!(files.contains("pr-4/1-home.png"), "{files}");
389        assert_eq!(git_run(&clone, &["rev-parse", "HEAD"]), head_before);
390        assert_eq!(
391            git_run(&clone, &["branch", "--list", SCREENSHOTS_BRANCH]),
392            ""
393        );
394    }
395}