chromewright 0.8.0

Browser automation MCP server via Chrome DevTools Protocol (CDP)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
//! Revision-keyed markdown and snapshot caches plus managed screenshot artifact storage.
//!
//! Markdown hits require matching document id, revision, and URL so SPA
//! `pushState` without a revision bump still forces re-extraction. Snapshot
//! entries baseline delta mode. Screenshots stay in a private per-session
//! directory with a fixed retention cap; callers never choose output paths.

use super::BrowserSession;
use crate::browser::backend::{
    ScreenshotCapture, ScreenshotClip, ScreenshotFormat, ScreenshotMode,
};
use crate::dom::{DocumentMetadata, SnapshotNode};
use crate::error::{BrowserError, Result};
use crate::tools::limits::validate_screenshot_png_bytes;
use std::collections::VecDeque;
use std::fs::OpenOptions;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};

const SCREENSHOT_ARTIFACT_LIMIT: usize = 8;
static SCREENSHOT_ARTIFACT_COUNTER: AtomicU64 = AtomicU64::new(1);
const MARKDOWN_PAGINATION_CHECKPOINT_INTERVAL: usize = 4_096;

#[derive(Debug, Clone)]
struct MarkdownPaginationMetadata {
    total_chars: usize,
    checkpoint_interval: usize,
    checkpoint_byte_offsets: Arc<[usize]>,
}

impl MarkdownPaginationMetadata {
    fn build(content: &str) -> Self {
        let mut checkpoint_byte_offsets = vec![0];
        let mut total_chars = 0;

        for (char_index, (byte_offset, _)) in content.char_indices().enumerate() {
            if char_index > 0 && char_index % MARKDOWN_PAGINATION_CHECKPOINT_INTERVAL == 0 {
                checkpoint_byte_offsets.push(byte_offset);
            }
            total_chars = char_index + 1;
        }

        Self {
            total_chars,
            checkpoint_interval: MARKDOWN_PAGINATION_CHECKPOINT_INTERVAL,
            checkpoint_byte_offsets: checkpoint_byte_offsets.into(),
        }
    }
}

/// Identity and reader metadata used to construct a revision-keyed markdown cache entry.
#[derive(Debug, Clone)]
pub(crate) struct MarkdownCacheMetadata {
    /// Stable document identity at extraction time.
    pub document_id: String,
    /// Document revision token at extraction time.
    pub revision: String,
    /// Page title retained for reader metadata responses.
    pub title: String,
    /// Page URL required for cache hits (detects SPA `pushState` without revision bump).
    pub url: String,
    /// Optional author byline from Readability extraction.
    pub byline: String,
    /// Optional short excerpt from Readability extraction.
    pub excerpt: String,
    /// Optional site name from Readability extraction.
    pub site_name: String,
}

/// Cached full-document markdown keyed by document id, revision, and URL.
///
/// Hits require all three keys so SPA `pushState` navigations without a revision bump still
/// force re-extraction. Pagination checkpoints enable efficient char-offset slicing.
#[derive(Debug, Clone)]
pub(crate) struct MarkdownCacheEntry {
    /// Stable document identity at extraction time.
    pub document_id: String,
    /// Document revision token at extraction time.
    pub revision: String,
    /// Page title retained for reader metadata responses.
    pub title: String,
    /// Page URL required for cache hits.
    pub url: String,
    /// Optional author byline from Readability extraction.
    pub byline: String,
    /// Optional short excerpt from Readability extraction.
    pub excerpt: String,
    /// Optional site name from Readability extraction.
    pub site_name: String,
    /// Full markdown body shared via `Arc` for cheap cloning into tool results.
    pub full_markdown: Arc<str>,
    pagination: MarkdownPaginationMetadata,
}

impl MarkdownCacheEntry {
    /// Build a revision-keyed entry and precompute pagination checkpoints for char-offset slices.
    pub(crate) fn new(metadata: MarkdownCacheMetadata, full_markdown: Arc<str>) -> Self {
        Self {
            document_id: metadata.document_id,
            revision: metadata.revision,
            title: metadata.title,
            url: metadata.url,
            byline: metadata.byline,
            excerpt: metadata.excerpt,
            site_name: metadata.site_name,
            pagination: MarkdownPaginationMetadata::build(&full_markdown),
            full_markdown,
        }
    }

    /// Total Unicode scalar count of the cached markdown body.
    pub(crate) fn pagination_total_chars(&self) -> usize {
        self.pagination.total_chars
    }

    /// Nearest pagination checkpoint at or before `char_offset` as `(char_offset, byte_offset)`.
    pub(crate) fn pagination_checkpoint(&self, char_offset: usize) -> (usize, usize) {
        let checkpoint_index = (char_offset / self.pagination.checkpoint_interval).min(
            self.pagination
                .checkpoint_byte_offsets
                .len()
                .saturating_sub(1),
        );
        let checkpoint_char_offset = checkpoint_index * self.pagination.checkpoint_interval;
        let checkpoint_byte_offset = self.pagination.checkpoint_byte_offsets[checkpoint_index];
        (checkpoint_char_offset, checkpoint_byte_offset)
    }
}

/// Scope summary retained with a snapshot cache entry for delta and locality decisions.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct SnapshotCacheScope {
    /// Snapshot mode string used when the entry was produced (for example `viewport`).
    pub mode: String,
    /// Fallback mode if locality degraded during capture.
    pub fallback_mode: Option<String>,
    /// Whether the capture preferred viewport-local interactive nodes.
    pub viewport_biased: bool,
    /// Interactive nodes returned in this capture (after locality filtering).
    pub returned_node_count: usize,
    /// Frames that could not be traversed (for example cross-origin).
    pub unavailable_frame_count: usize,
    /// Total interactive count in the document when known.
    pub global_interactive_count: Option<usize>,
}

/// Revision-keyed snapshot base: YAML text, interactive nodes, and capture scope.
///
/// Lookup reuses a prior revision for the same `document_id` so delta snapshots can compare
/// against a stable base; a different document identity evicts the entry on read.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct SnapshotCacheEntry {
    /// Document identity for the cached snapshot revision.
    pub document: DocumentMetadata,
    /// YAML accessibility tree text used as the delta base.
    pub snapshot: Arc<str>,
    /// Interactive nodes with cursors corresponding to the snapshot.
    pub nodes: Arc<[SnapshotNode]>,
    /// How the base snapshot was scoped (mode, locality, frame failures).
    pub scope: SnapshotCacheScope,
}

/// Managed PNG artifact written under the session-private screenshot root.
///
/// Files are mode `0o600` on Unix, retained up to a small ring limit, and removed on session
/// close. `uri` is a `file://` URL suitable for tool responses.
#[derive(Debug, Clone)]
pub struct ScreenshotArtifact {
    /// Session-unique artifact id (not a filesystem path).
    pub id: String,
    /// Percent-encoded `file://` URI pointing at [`Self::path`].
    pub uri: String,
    /// Absolute filesystem path of the stored PNG.
    pub path: PathBuf,
    /// Encoded image format for this artifact.
    pub format: ScreenshotFormat,
    /// MIME type for tool responses (`image/png`).
    pub mime_type: &'static str,
    /// On-disk byte length of the PNG.
    pub byte_count: usize,
    /// Intrinsic PNG width in device pixels.
    pub width: u32,
    /// Intrinsic PNG height in device pixels.
    pub height: u32,
    /// Capture surface used when the artifact was created.
    pub mode: ScreenshotMode,
    /// Tab id that produced the capture.
    pub tab_id: String,
    /// Applied clip region, when the capture was cropped.
    pub clip: Option<ScreenshotClip>,
}

impl ScreenshotArtifact {
    /// Read stored PNG bytes from the managed path (tests only; panics on IO failure).
    #[cfg(test)]
    pub(crate) fn bytes(&self) -> Arc<[u8]> {
        Arc::<[u8]>::from(
            std::fs::read(&self.path).expect("test screenshot artifact bytes should be readable"),
        )
    }
}

fn screenshot_artifact_id() -> String {
    let millis = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis();
    let ordinal = SCREENSHOT_ARTIFACT_COUNTER.fetch_add(1, Ordering::Relaxed);
    format!("{millis}-{ordinal}")
}

fn file_uri(path: &Path) -> String {
    let path = path.to_string_lossy().replace('\\', "/");
    let mut encoded = String::with_capacity(path.len());

    for byte in path.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' | b'/' | b':' => {
                encoded.push(byte as char)
            }
            _ => encoded.push_str(&format!("%{byte:02X}")),
        }
    }

    if encoded.starts_with('/') {
        format!("file://{encoded}")
    } else {
        format!("file:///{encoded}")
    }
}

fn screenshot_artifact_filename(id: &str, format: ScreenshotFormat) -> String {
    format!("chromewright-shot-{id}.{}", format.extension())
}

fn create_screenshot_artifact_file(path: &Path, bytes: &[u8]) -> Result<()> {
    let mut options = OpenOptions::new();
    options.write(true).create_new(true);

    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        options.mode(0o600);
    }

    let mut file = options.open(path).map_err(|e| {
        BrowserError::ScreenshotFailed(format!("Failed to store screenshot artifact: {}", e))
    })?;

    if let Err(err) = file.write_all(bytes) {
        let _ = std::fs::remove_file(path);
        return Err(BrowserError::ScreenshotFailed(format!(
            "Failed to store screenshot artifact: {}",
            err
        )));
    }

    Ok(())
}

impl BrowserSession {
    /// Look up the Markdown cache hit for `document` (requires matching id, revision, and URL).
    pub(crate) fn markdown_cache_entry(
        &self,
        document: &crate::dom::DocumentMetadata,
    ) -> Result<Option<Arc<MarkdownCacheEntry>>> {
        let guard = self
            .markdown_cache
            .lock()
            .map_err(|e| BrowserError::ToolExecutionFailed {
                tool: "get_markdown".to_string(),
                reason: format!("Failed to read markdown cache: {}", e),
            })?;

        // URL is part of the key so SPA pushState without a revision bump still misses.
        Ok(guard.as_ref().and_then(|entry| {
            (entry.document_id == document.document_id
                && entry.revision == document.revision
                && entry.url == document.url)
                .then_some(Arc::clone(entry))
        }))
    }

    /// Replace the single Markdown cache slot with a freshly extracted entry.
    pub(crate) fn store_markdown_cache(&self, entry: Arc<MarkdownCacheEntry>) -> Result<()> {
        *self
            .markdown_cache
            .lock()
            .map_err(|e| BrowserError::ToolExecutionFailed {
                tool: "get_markdown".to_string(),
                reason: format!("Failed to write markdown cache: {}", e),
            })? = Some(entry);
        Ok(())
    }

    /// Look up the Snapshot cache base for delta reads, keyed primarily by document identity.
    ///
    /// Same `document_id` reuses a prior revision as the delta base; a different document identity
    /// evicts the entry on read so stale cross-document bases cannot leak.
    pub(crate) fn snapshot_cache_entry(
        &self,
        document: &DocumentMetadata,
    ) -> Result<Option<Arc<SnapshotCacheEntry>>> {
        let mut guard =
            self.snapshot_cache
                .lock()
                .map_err(|e| BrowserError::ToolExecutionFailed {
                    tool: "snapshot".to_string(),
                    reason: format!("Failed to read snapshot cache: {}", e),
                })?;

        let Some(entry) = guard.as_ref() else {
            return Ok(None);
        };

        if entry.document.document_id == document.document_id {
            return Ok(Some(Arc::clone(entry)));
        }

        *guard = None;
        Ok(None)
    }

    /// Store a revision-scoped Snapshot cache base for later delta comparison.
    pub(crate) fn store_snapshot_cache(&self, entry: Arc<SnapshotCacheEntry>) -> Result<()> {
        *self
            .snapshot_cache
            .lock()
            .map_err(|e| BrowserError::ToolExecutionFailed {
                tool: "snapshot".to_string(),
                reason: format!("Failed to write snapshot cache: {}", e),
            })? = Some(entry);
        Ok(())
    }

    /// Drop the Snapshot cache after navigation, scroll, tab change, viewport, or DOM mutation.
    pub(crate) fn invalidate_snapshot_cache(&self) -> Result<()> {
        *self
            .snapshot_cache
            .lock()
            .map_err(|e| BrowserError::ToolExecutionFailed {
                tool: "snapshot".to_string(),
                reason: format!("Failed to invalidate snapshot cache: {}", e),
            })? = None;
        Ok(())
    }

    /// Persist a capture under the private session root and retain it in the artifact ring buffer.
    ///
    /// Enforces the PNG byte cap before write; oldest artifacts are pruned when the ring is full.
    /// Callers never choose output paths—storage is always session-managed.
    pub(crate) fn store_screenshot_artifact(
        &self,
        capture: ScreenshotCapture,
    ) -> Result<Arc<ScreenshotArtifact>> {
        validate_screenshot_png_bytes(capture.bytes.len())?;

        let artifact_id = screenshot_artifact_id();
        let path = self
            .screenshot_artifact_root
            .path()
            .join(screenshot_artifact_filename(&artifact_id, capture.format));
        create_screenshot_artifact_file(&path, &capture.bytes)?;
        let path = path.canonicalize().unwrap_or(path);

        let artifact = Arc::new(ScreenshotArtifact {
            id: artifact_id,
            uri: file_uri(&path),
            path,
            format: capture.format,
            mime_type: capture.mime_type,
            byte_count: capture.byte_count,
            width: capture.width,
            height: capture.height,
            mode: capture.mode,
            tab_id: capture.tab.id,
            clip: capture.clip,
        });

        let mut evicted = VecDeque::new();
        {
            let mut guard = self.screenshot_artifacts.lock().map_err(|e| {
                BrowserError::ScreenshotFailed(format!(
                    "Failed to write screenshot artifact state: {}",
                    e
                ))
            })?;

            guard.push_back(Arc::clone(&artifact));
            while guard.len() > SCREENSHOT_ARTIFACT_LIMIT {
                if let Some(stale) = guard.pop_front() {
                    evicted.push_back(stale);
                }
            }
        }

        for stale in evicted {
            remove_screenshot_file(&stale.path)?;
        }

        Ok(artifact)
    }

    /// Remove all retained screenshot files and clear the in-memory artifact ring.
    pub(crate) fn clear_screenshot_artifacts(&self) -> Result<()> {
        let drained = {
            let mut guard = self.screenshot_artifacts.lock().map_err(|e| {
                BrowserError::ScreenshotFailed(format!(
                    "Failed to clear screenshot artifact state: {}",
                    e
                ))
            })?;
            guard.drain(..).collect::<Vec<_>>()
        };

        let mut failures = Vec::new();
        for artifact in drained {
            if let Err(err) = remove_screenshot_file(&artifact.path) {
                failures.push(err.to_string());
            }
        }

        if failures.is_empty() {
            Ok(())
        } else {
            Err(BrowserError::ScreenshotFailed(format!(
                "Failed to clear screenshot artifacts: {}",
                failures.join("; ")
            )))
        }
    }

    #[cfg(test)]
    pub(crate) fn snapshot_cache_for_test(&self) -> Result<Option<Arc<SnapshotCacheEntry>>> {
        self.snapshot_cache
            .lock()
            .map(|guard| guard.clone())
            .map_err(|e| BrowserError::ToolExecutionFailed {
                tool: "snapshot".to_string(),
                reason: format!("Failed to inspect snapshot cache: {}", e),
            })
    }
}

fn remove_screenshot_file(path: &Path) -> Result<()> {
    match std::fs::remove_file(path) {
        Ok(()) => Ok(()),
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(err) => Err(BrowserError::ScreenshotFailed(format!(
            "Failed to remove screenshot artifact {}: {}",
            path.display(),
            err
        ))),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::browser::BrowserSession;
    use crate::browser::backend::{
        FakeSessionBackend, ScreenshotRequest, ScreenshotScale, TabDescriptor,
    };
    use crate::dom::{Cursor, NodeRef};
    use crate::tools::limits::SCREENSHOT_MAX_PNG_BYTES;
    #[cfg(unix)]
    use std::os::unix::fs::PermissionsExt;

    fn sample_document(document_id: &str, revision: &str) -> DocumentMetadata {
        DocumentMetadata {
            document_id: document_id.to_string(),
            revision: revision.to_string(),
            url: format!("https://{}.example", document_id),
            title: format!("Document {}", document_id),
            ready_state: "complete".to_string(),
            frames: Vec::new(),
        }
    }

    fn sample_snapshot_entry(document: DocumentMetadata) -> Arc<SnapshotCacheEntry> {
        Arc::new(SnapshotCacheEntry {
            document: document.clone(),
            snapshot: Arc::<str>::from("button \"Save\""),
            nodes: Arc::<[SnapshotNode]>::from(vec![SnapshotNode {
                cursor: Cursor {
                    node_ref: NodeRef {
                        document_id: document.document_id.clone(),
                        revision: document.revision.clone(),
                        index: 0,
                    },
                    selector: "#save".to_string(),
                    index: 0,
                    role: "button".to_string(),
                    name: "Save".to_string(),
                },
                node_ref: NodeRef {
                    document_id: document.document_id.clone(),
                    revision: document.revision.clone(),
                    index: 0,
                },
                index: 0,
                role: "button".to_string(),
                name: "Save".to_string(),
            }]),
            scope: SnapshotCacheScope {
                mode: "viewport".to_string(),
                fallback_mode: None,
                viewport_biased: true,
                returned_node_count: 1,
                unavailable_frame_count: 0,
                global_interactive_count: Some(1),
            },
        })
    }

    fn markdown_document(document_id: &str, revision: &str, url: &str) -> DocumentMetadata {
        DocumentMetadata {
            document_id: document_id.to_string(),
            revision: revision.to_string(),
            url: url.to_string(),
            title: "Document".to_string(),
            ready_state: "complete".to_string(),
            frames: Vec::new(),
        }
    }

    fn sample_markdown_entry(document: &DocumentMetadata) -> Arc<MarkdownCacheEntry> {
        Arc::new(MarkdownCacheEntry::new(
            MarkdownCacheMetadata {
                document_id: document.document_id.clone(),
                revision: document.revision.clone(),
                title: document.title.clone(),
                url: document.url.clone(),
                byline: String::new(),
                excerpt: String::new(),
                site_name: String::new(),
            },
            Arc::<str>::from("body"),
        ))
    }

    #[test]
    fn markdown_cache_hits_for_matching_document_revision_and_url() {
        let session = BrowserSession::with_test_backend(FakeSessionBackend::new());
        let document = markdown_document("doc-1", "main:42", "https://app.example/list");
        session
            .store_markdown_cache(sample_markdown_entry(&document))
            .expect("markdown cache should store");

        let cached = session
            .markdown_cache_entry(&document)
            .expect("markdown cache lookup should succeed");
        assert!(cached.is_some(), "matching url should hit cache");
    }

    #[test]
    fn markdown_cache_misses_when_url_changes_without_revision_bump() {
        let session = BrowserSession::with_test_backend(FakeSessionBackend::new());
        let stored = markdown_document("doc-1", "main:42", "https://app.example/list");
        let after_pushstate = markdown_document("doc-1", "main:42", "https://app.example/item/99");

        session
            .store_markdown_cache(sample_markdown_entry(&stored))
            .expect("markdown cache should store");

        let cached = session
            .markdown_cache_entry(&after_pushstate)
            .expect("markdown cache lookup should succeed");
        assert!(
            cached.is_none(),
            "url change without revision bump must force re-extraction"
        );
    }

    #[test]
    fn snapshot_cache_round_trips_for_matching_document_revision() {
        let session = BrowserSession::with_test_backend(FakeSessionBackend::new());
        let document = sample_document("doc-1", "rev-1");
        let entry = sample_snapshot_entry(document.clone());

        session
            .store_snapshot_cache(Arc::clone(&entry))
            .expect("snapshot cache should store");

        let cached = session
            .snapshot_cache_entry(&document)
            .expect("snapshot cache should read")
            .expect("matching cache entry should exist");

        assert_eq!(cached.as_ref(), entry.as_ref());
    }

    #[test]
    fn snapshot_cache_reuses_prior_revision_for_matching_document_identity() {
        let session = BrowserSession::with_test_backend(FakeSessionBackend::new());
        let stored_document = sample_document("doc-1", "rev-1");
        let current_document = sample_document("doc-1", "rev-2");

        session
            .store_snapshot_cache(sample_snapshot_entry(stored_document))
            .expect("snapshot cache should store");

        let cached = session
            .snapshot_cache_entry(&current_document)
            .expect("snapshot cache lookup should succeed")
            .expect("matching document identity should keep prior revision base");

        assert_eq!(cached.document.document_id, "doc-1");
        assert_eq!(cached.document.revision, "rev-1");
        assert!(
            session
                .snapshot_cache_for_test()
                .expect("test helper should read cache")
                .is_some()
        );
    }

    #[test]
    fn snapshot_cache_evicts_mismatched_document_identity_on_read() {
        let session = BrowserSession::with_test_backend(FakeSessionBackend::new());
        let stored_document = sample_document("doc-1", "rev-1");
        let current_document = sample_document("doc-2", "rev-9");

        session
            .store_snapshot_cache(sample_snapshot_entry(stored_document))
            .expect("snapshot cache should store");

        let cached = session
            .snapshot_cache_entry(&current_document)
            .expect("snapshot cache lookup should succeed");

        assert!(cached.is_none());
        assert!(
            session
                .snapshot_cache_for_test()
                .expect("test helper should read cache")
                .is_none()
        );
    }

    #[test]
    fn screenshot_artifacts_use_private_per_session_roots() {
        let session_a = BrowserSession::with_test_backend(FakeSessionBackend::new());
        let session_b = BrowserSession::with_test_backend(FakeSessionBackend::new());
        let root_a = session_a.screenshot_artifact_root_for_test();
        let root_b = session_b.screenshot_artifact_root_for_test();

        assert_ne!(root_a, root_b);

        let artifact_a = session_a
            .capture_screenshot_artifact(ScreenshotRequest::default())
            .expect("session A screenshot should store");
        let artifact_b = session_b
            .capture_screenshot_artifact(ScreenshotRequest::default())
            .expect("session B screenshot should store");

        assert!(artifact_a.path.starts_with(&root_a));
        assert!(artifact_b.path.starts_with(&root_b));

        #[cfg(unix)]
        {
            let root_mode = std::fs::metadata(&root_a)
                .expect("root metadata should be readable")
                .permissions()
                .mode()
                & 0o777;
            assert_eq!(root_mode, 0o700);

            let file_mode = std::fs::metadata(&artifact_a.path)
                .expect("artifact metadata should be readable")
                .permissions()
                .mode()
                & 0o777;
            assert_eq!(file_mode, 0o600);
        }

        session_a
            .close()
            .expect("session A close should clean artifacts");
        session_b
            .close()
            .expect("session B close should clean artifacts");
    }

    #[test]
    fn screenshot_artifact_duplicate_path_creation_fails_without_truncating() {
        let root = tempfile::tempdir().expect("private tempdir should be created");
        let path = root.path().join("duplicate.png");

        create_screenshot_artifact_file(&path, b"first")
            .expect("first exclusive create should succeed");
        let err = create_screenshot_artifact_file(&path, b"second")
            .expect_err("second exclusive create should fail");

        assert!(matches!(err, BrowserError::ScreenshotFailed(_)));
        assert_eq!(
            std::fs::read(&path).expect("original artifact should remain readable"),
            b"first"
        );
    }

    #[test]
    fn screenshot_artifact_uri_percent_encodes_url_sensitive_paths() {
        let path = Path::new("/tmp/chromewright shots/shot #1?100%.png");

        assert_eq!(
            file_uri(path),
            "file:///tmp/chromewright%20shots/shot%20%231%3F100%25.png"
        );
    }

    #[test]
    fn screenshot_artifact_retention_prunes_old_entries() {
        let session = BrowserSession::with_test_backend(FakeSessionBackend::new());
        let mut first_path = None;

        for _ in 0..=SCREENSHOT_ARTIFACT_LIMIT {
            let artifact = session
                .capture_screenshot_artifact(ScreenshotRequest::default())
                .expect("screenshot artifact should store");
            if first_path.is_none() {
                first_path = Some(artifact.path.clone());
            }
        }

        let artifacts = session.screenshot_artifacts_for_test();
        assert_eq!(artifacts.len(), SCREENSHOT_ARTIFACT_LIMIT);
        assert!(
            !first_path.expect("first artifact should exist").exists(),
            "oldest artifact should be pruned from disk"
        );

        session
            .close()
            .expect("session close should clean artifacts");
    }

    #[test]
    fn clear_screenshot_artifacts_removes_retained_private_files() {
        let session = BrowserSession::with_test_backend(FakeSessionBackend::new());
        let artifact = session
            .capture_screenshot_artifact(ScreenshotRequest::default())
            .expect("screenshot artifact should store");
        let path = artifact.path.clone();
        let root = session.screenshot_artifact_root_for_test();

        assert!(path.exists());
        session
            .clear_screenshot_artifacts()
            .expect("clear should remove retained artifacts");

        assert!(session.screenshot_artifacts_for_test().is_empty());
        assert!(!path.exists());
        assert!(
            root.exists(),
            "session tempdir should stay alive until session drop"
        );
    }

    #[test]
    fn screenshot_artifact_tracks_png_metadata() {
        let session = BrowserSession::with_test_backend(FakeSessionBackend::new());
        let artifact = session
            .capture_screenshot_artifact(ScreenshotRequest::default())
            .expect("default screenshot artifact should store");

        assert_eq!(artifact.format, ScreenshotFormat::Png);
        assert_eq!(artifact.mime_type, "image/png");
        assert_eq!((artifact.width, artifact.height), (1600, 1200));
        assert_eq!(artifact.byte_count, artifact.bytes().len());
        assert!(artifact.uri.starts_with("file://"));
        assert!(artifact.path.exists());

        session
            .close()
            .expect("session close should clean artifacts");
    }

    #[test]
    fn screenshot_artifact_rejects_png_over_byte_cap_before_storage() {
        let session = BrowserSession::with_test_backend(FakeSessionBackend::new());
        let capture = ScreenshotCapture {
            mode: ScreenshotMode::Viewport,
            scale: ScreenshotScale::Device,
            tab: TabDescriptor {
                id: "tab-1".to_string(),
                title: "Test Tab".to_string(),
                url: "about:blank".to_string(),
            },
            format: ScreenshotFormat::Png,
            mime_type: ScreenshotFormat::Png.mime_type(),
            byte_count: SCREENSHOT_MAX_PNG_BYTES + 1,
            width: 1,
            height: 1,
            css_width: 1.0,
            css_height: 1.0,
            device_pixel_ratio: 1.0,
            pixel_scale: 1.0,
            clip: None,
            bytes: vec![0; SCREENSHOT_MAX_PNG_BYTES + 1],
        };

        let err = session
            .store_screenshot_artifact(capture)
            .expect_err("oversized PNG should be rejected before storage");

        let BrowserError::ResourceLimitExceeded(details) = err else {
            panic!("expected resource limit error");
        };
        assert_eq!(details.resource, "screenshot_png_bytes");
        assert!(session.screenshot_artifacts_for_test().is_empty());
    }
}