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
//! Terminal browser state: lifecycle, interaction modes, viewport, and chrome fields.
//!
//! [`TuiState`] is the local UI mirror of page readiness and interaction mode.
//! Shared companion coordination lives in [`crate::tui::shared::SharedTuiState`];
//! both use the same Loading → Ready | Error lifecycle vocabulary so neither
//! can claim Ready while the other still owns a page action.

use crate::semantic::{SemanticDocument, SemanticRef};
use crate::tui::content::ContentProjection;
use std::collections::{HashMap, HashSet};

/// Page lifecycle: Ready → Loading → Ready | Error (atomic publish on success).
///
/// Shared by the terminal controller and companion tools. Loading blocks normal
/// key actions. Error retains the last published page and blocks normal keys
/// until Escape dismisses it back to Ready (without requiring a new capture).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Lifecycle {
    /// Settled document is published; normal commands and scrolling apply.
    Ready,
    /// Page-changing work is in flight; normal key actions are ignored.
    Loading { action: String },
    /// Last action failed; previous page (if any) is retained for recovery.
    Error { action: String, message: String },
}

impl Lifecycle {
    /// True while a page-changing action owns the UI (blocks Normal keys).
    pub fn is_loading(&self) -> bool {
        matches!(self, Self::Loading { .. })
    }

    /// True when the published page is settled and Normal commands may run.
    pub fn is_ready(&self) -> bool {
        matches!(self, Self::Ready)
    }

    /// Short chrome/status label for the lifecycle state (not a key legend).
    pub fn status_label(&self) -> &str {
        match self {
            Self::Ready => "Ready",
            Self::Loading { .. } => "Loading",
            Self::Error { .. } => "Error",
        }
    }
}

/// Interaction mode while lifecycle is Ready (or Error, until Escape dismisses it).
///
/// The dispatcher routes keys by mode so Normal action maps never fire during
/// URL/search/form editing or two-key hint selection.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InteractionMode {
    /// Keymap-driven action dispatch (Vimari-style).
    Normal,
    /// URL bar, forward search, or form-control editing.
    Input(InputKind),
    /// Two-key link hint selection (chained until Escape).
    Hint(HintMode),
}

/// Kind of text-input overlay active while [`InteractionMode::Input`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InputKind {
    /// Navigate-to URL prompt (`o` / OpenUrl).
    Url { buffer: String },
    /// Forward search by content (`/` / Search); matches bind exact `semantic_ref`s.
    Search { buffer: String },
    /// Form control value editing bound to an exact `semantic_ref`.
    Form {
        semantic_ref: SemanticRef,
        buffer: String,
    },
}

/// Whether a resolved link hint opens in the current tab or a new tab.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HintMode {
    /// Follow link in the current tab (`f`).
    Follow,
    /// Open link in a new tab (`F`).
    NewTab,
}

/// Snapshot published only after wait/settle + capture + reconciliation.
///
/// Chrome fields (url/title/revision) are copied from the SemanticDocument so
/// the UI never shows metadata from a different capture than the body.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PublishedPage {
    /// Semantic capture body (source of truth for content).
    pub document: SemanticDocument,
    /// Chrome URL copied from the document at publish time.
    pub url: String,
    /// Chrome title copied from the document at publish time.
    pub title: String,
    /// Chrome revision token copied from the document at publish time.
    pub revision: String,
}

impl PublishedPage {
    /// Derive chrome fields from a complete semantic capture.
    pub fn from_document(document: SemanticDocument) -> Self {
        let url = document.document.url.clone();
        let title = document.document.title.clone();
        let revision = document.document.revision.clone();
        Self {
            document,
            url,
            title,
            revision,
        }
    }
}

/// Viewport and selection state keyed by exact `semantic_ref`.
///
/// Human selection and agent attention are independent exact refs. Collapse and
/// search match lists also store exact refs so recapture can rebind survivors
/// without fuzzy identity.
#[derive(Debug, Clone)]
pub struct ViewState {
    /// Vertical scroll offset in content lines.
    pub scroll_y: usize,
    /// Horizontal scroll offset in columns (ignored while word-wrap is on).
    pub scroll_x: usize,
    /// Viewport height in lines (content area).
    pub viewport_height: usize,
    /// Viewport width in columns.
    pub viewport_width: usize,
    /// Soft-wrap long content lines to the viewport width (on by default).
    pub wrap: bool,
    /// When true, ignore `content_max_width` and use the full padded content pane.
    /// Default false (use the configured column cap, default 100). Toggle with `w`.
    pub full_width: bool,
    /// Content projection: prose (default) hides structural chrome; structure shows it.
    pub projection: ContentProjection,
    /// Currently selected addressable component (exact ref).
    pub selection: Option<SemanticRef>,
    /// Agent attention spotlight (exact ref), independent of human selection.
    pub attention: Option<SemanticRef>,
    /// Refs painted for the current attention (root + descendants). Empty when clear.
    ///
    /// Lets prose-hidden containers (landmarks) still show a spotlight on their
    /// visible children without retargeting human selection.
    pub attention_paint: HashSet<SemanticRef>,
    /// Collapsed component refs (exact).
    pub collapsed: HashSet<SemanticRef>,
    /// Forward-search matches (exact refs, document order).
    pub search_matches: Vec<SemanticRef>,
    /// Index into `search_matches` for the current hit (wraps with n/N).
    pub search_index: usize,
    /// Last search query (for status).
    pub search_query: String,
    /// Inspection overlay body (no key legends).
    pub inspect_text: Option<String>,
    /// Inspection panel title: full DOM path (`main > form#x > input#email`).
    pub inspect_title: Option<String>,
    /// When true, inspect stays open and refreshes as selection moves (j/k, tab, …).
    pub inspect_follow: bool,
    /// Transient status (anchor changed, clipboard fallback, etc.).
    pub status_message: Option<String>,
    /// Pending two-key hint buffer.
    pub hint_buffer: String,
    /// Values typed into form controls this capture, not yet written/submitted.
    ///
    /// Tabbing away from a field stashes here so multi-field forms can be filled
    /// like Chrome before Enter on a submit button sends the form.
    pub pending_form_values: HashMap<SemanticRef, String>,
}

impl Default for ViewState {
    fn default() -> Self {
        Self {
            scroll_y: 0,
            scroll_x: 0,
            viewport_height: 0,
            viewport_width: 0,
            wrap: true,
            full_width: false,
            projection: ContentProjection::default(),
            selection: None,
            attention: None,
            attention_paint: HashSet::new(),
            collapsed: HashSet::new(),
            search_matches: Vec::new(),
            search_index: 0,
            search_query: String::new(),
            inspect_text: None,
            inspect_title: None,
            inspect_follow: false,
            status_message: None,
            hint_buffer: String::new(),
            pending_form_values: HashMap::new(),
        }
    }
}

impl ViewState {
    /// Set the transient footer/status line (search feedback, action messages).
    pub fn set_status(&mut self, msg: impl Into<String>) {
        self.status_message = Some(msg.into());
    }

    /// Clear the transient footer/status line.
    pub fn clear_status(&mut self) {
        self.status_message = None;
    }

    /// Drop staged form edits (escape, navigation, new capture).
    pub fn clear_pending_form_values(&mut self) {
        self.pending_form_values.clear();
    }

    /// Clear sticky `/search` state (footer `/{query}  n/m` and match list).
    ///
    /// Returns `true` when a search was active. Used by Escape in Normal mode.
    pub fn clear_search(&mut self) -> bool {
        let had = !self.search_query.is_empty() || !self.search_matches.is_empty();
        self.search_query.clear();
        self.search_matches.clear();
        self.search_index = 0;
        if had {
            // Drop stale "pattern not found" / search: status once the cmdline is gone.
            if self
                .status_message
                .as_deref()
                .is_some_and(|m| m.starts_with("search:") || m == "pattern not found")
            {
                self.clear_status();
            }
        }
        had
    }
}

/// Full terminal browser state shared by controller and renderer.
///
/// Local only: does not own the BrowserSession. History affordances come from
/// the active browser tab; page content is the last successfully published
/// SemanticDocument (retained across Error).
#[derive(Debug, Clone)]
pub struct TuiState {
    /// Page lifecycle shared with companion coordination vocabulary.
    pub lifecycle: Lifecycle,
    /// Normal / Input / Hint interaction mode while Ready (or Error until dismissed).
    pub mode: InteractionMode,
    /// Last successfully published page (retained on Error).
    pub page: Option<PublishedPage>,
    /// Viewport scroll, selection, collapse, search, and inspect overlays.
    pub view: ViewState,
    /// Whether Chrome history can go back on the active tab.
    pub can_go_back: bool,
    /// Whether Chrome history can go forward on the active tab.
    pub can_go_forward: bool,
    /// Active tab ordinal among open tabs as `(index_1based, count)`, when known.
    /// Shown in chrome as `2/5` left of the history arrows.
    pub tab_position: Option<(usize, usize)>,
    /// Set when the user requests quit; the event loop exits after the current frame.
    pub should_quit: bool,
    /// Clipboard fallback text when OSC 52 is unavailable.
    pub clipboard_fallback: Option<String>,
}

impl Default for TuiState {
    fn default() -> Self {
        Self {
            lifecycle: Lifecycle::Ready,
            mode: InteractionMode::Normal,
            page: None,
            view: ViewState::default(),
            can_go_back: false,
            can_go_forward: false,
            tab_position: None,
            should_quit: false,
            clipboard_fallback: None,
        }
    }
}

impl TuiState {
    /// Empty Ready state with no published page.
    pub fn new() -> Self {
        Self::default()
    }

    /// Short mode name for diagnostics/tests (not shown in header chrome).
    #[allow(dead_code)]
    pub fn mode_label(&self) -> &'static str {
        match &self.mode {
            InteractionMode::Normal => "Normal",
            InteractionMode::Input(InputKind::Url { .. }) => "URL",
            InteractionMode::Input(InputKind::Search { .. }) => "Search",
            InteractionMode::Input(InputKind::Form { .. }) => "Input",
            InteractionMode::Hint(HintMode::Follow) => "Hint",
            InteractionMode::Hint(HintMode::NewTab) => "Hint+",
        }
    }

    /// True when URL, search, or form editing owns the keyboard.
    pub fn is_input_mode(&self) -> bool {
        matches!(self.mode, InteractionMode::Input(_))
    }

    /// True when two-key link/hint selection owns the keyboard.
    pub fn is_hint_mode(&self) -> bool {
        matches!(self.mode, InteractionMode::Hint(_))
    }

    /// Whether keymap-driven Normal actions may run.
    ///
    /// Requires both Normal mode and Ready lifecycle. Error retains the page
    /// for display; Escape dismisses Error back to Ready so scrolling and
    /// further page actions can resume. Quit remains available while Error.
    pub fn allows_normal_commands(&self) -> bool {
        matches!(self.mode, InteractionMode::Normal) && self.lifecycle.is_ready()
    }

    /// Published page URL, or empty when no page is available.
    pub fn url(&self) -> &str {
        self.page.as_ref().map(|p| p.url.as_str()).unwrap_or("")
    }

    /// Published page title, or empty when no page is available.
    pub fn title(&self) -> &str {
        self.page.as_ref().map(|p| p.title.as_str()).unwrap_or("")
    }

    /// Published document revision token, or empty when no page is available.
    pub fn revision(&self) -> &str {
        self.page
            .as_ref()
            .map(|p| p.revision.as_str())
            .unwrap_or("")
    }

    /// Active SemanticDocument when a page has been published.
    pub fn document(&self) -> Option<&SemanticDocument> {
        self.page.as_ref().map(|p| &p.document)
    }

    /// Atomically publish document + url + title + revision and mark Ready.
    pub fn publish_page(&mut self, document: SemanticDocument) {
        self.page = Some(PublishedPage::from_document(document));
        self.lifecycle = Lifecycle::Ready;
    }

    /// Enter Loading and leave transient Input/Hint modes so keys cannot race the capture.
    pub fn enter_loading(&mut self, action: impl Into<String>) {
        self.lifecycle = Lifecycle::Loading {
            action: action.into(),
        };
        // Leave transient input/hint modes during page-changing work.
        if !matches!(self.mode, InteractionMode::Normal) {
            self.mode = InteractionMode::Normal;
            self.view.hint_buffer.clear();
        }
    }

    /// Enter Error while retaining `page` for recovery; clear transient modes.
    pub fn enter_error(&mut self, action: impl Into<String>, message: impl Into<String>) {
        self.lifecycle = Lifecycle::Error {
            action: action.into(),
            message: message.into(),
        };
        self.mode = InteractionMode::Normal;
        self.view.hint_buffer.clear();
    }

    /// Clear the published page and view after the browser has no open tabs.
    pub fn clear_session(&mut self) {
        self.lifecycle = Lifecycle::Ready;
        self.mode = InteractionMode::Normal;
        self.page = None;
        self.view = ViewState {
            viewport_height: self.view.viewport_height,
            viewport_width: self.view.viewport_width,
            wrap: self.view.wrap,
            full_width: self.view.full_width,
            projection: self.view.projection,
            inspect_follow: false,
            ..ViewState::default()
        };
        self.can_go_back = false;
        self.can_go_forward = false;
        self.tab_position = None;
        self.clipboard_fallback = None;
        self.view
            .set_status("no open tabs — press t or o to continue");
    }

    /// Dismiss Error back to Ready while retaining the last published page.
    ///
    /// Returns `true` when an Error was cleared. Loading and Ready are left
    /// unchanged. The prior error message is kept as a transient status so the
    /// operator can still see why the last action failed after recovery.
    pub fn clear_error(&mut self) -> bool {
        match std::mem::replace(&mut self.lifecycle, Lifecycle::Ready) {
            Lifecycle::Error { message, .. } => {
                self.mode = InteractionMode::Normal;
                self.view.hint_buffer.clear();
                self.view.inspect_text = None;
                self.view.inspect_title = None;
                self.view.inspect_follow = false;
                self.view.set_status(format!("dismissed: {message}"));
                true
            }
            other => {
                self.lifecycle = other;
                false
            }
        }
    }

    /// Set chrome affordances from the active browser tab, never from a local
    /// approximation of global navigation history.
    pub fn set_history_availability(&mut self, can_go_back: bool, can_go_forward: bool) {
        self.can_go_back = can_go_back;
        self.can_go_forward = can_go_forward;
    }

    /// Set the chrome tab ordinal (`2/5`) from the live browser tab list.
    ///
    /// `index` is 1-based. Pass `None` when there are no open tabs or the
    /// driver cannot determine position.
    pub fn set_tab_position(&mut self, position: Option<(usize, usize)>) {
        self.tab_position = match position {
            Some((index, count)) if count > 0 && index >= 1 && index <= count => {
                Some((index, count))
            }
            _ => None,
        };
    }

    /// Reconcile selection/collapse/search by exact identity after recapture.
    ///
    /// Surviving selected anchor restores viewport-relative position; otherwise
    /// scroll is clamped and an identity-change status is set.
    pub fn reconcile_after_capture(
        &mut self,
        new_document: SemanticDocument,
        previous_selection: Option<SemanticRef>,
        previous_scroll_y: usize,
        anchor_offset_in_viewport: usize,
        content_line_of: impl Fn(&SemanticDocument, &SemanticRef) -> Option<usize>,
    ) {
        let mut collapsed = HashSet::new();
        for old in &self.view.collapsed {
            if let Ok(rebound) = new_document.rebind_surviving(old) {
                collapsed.insert(rebound);
            }
        }

        let mut search_matches = Vec::new();
        for old in &self.view.search_matches {
            if let Ok(rebound) = new_document.rebind_surviving(old) {
                search_matches.push(rebound);
            }
        }
        let search_index = self
            .view
            .search_index
            .min(search_matches.len().saturating_sub(1));

        // The anchor must be measured against the reconciled collapsed layout,
        // not the old or fully expanded projection.
        self.view.collapsed = collapsed;

        let mut selection = None;
        let mut scroll_y = previous_scroll_y;
        let mut status = None;

        if let Some(prev) = previous_selection {
            match new_document.rebind_surviving(&prev) {
                Ok(rebound) => {
                    selection = Some(rebound.clone());
                    if let Some(line) = content_line_of(&new_document, &rebound) {
                        // Restore at the same viewport-relative offset.
                        scroll_y = line.saturating_sub(anchor_offset_in_viewport);
                    }
                }
                Err(_) => {
                    status = Some("anchor changed".to_string());
                    // Clamp later once content height is known; keep absolute scroll for now.
                }
            }
        }

        self.view.search_matches = search_matches;
        self.view.search_index = search_index;
        self.view.selection = selection;
        self.view.scroll_y = scroll_y;
        if let Some(msg) = status {
            self.view.set_status(msg);
        } else {
            // Clear only anchor messages; keep clipboard notes until next action.
            if self.view.status_message.as_deref() == Some("anchor changed") {
                self.view.clear_status();
            }
        }

        self.publish_page(new_document);
    }

    /// Keep vertical scroll within the current content length and viewport height.
    pub fn clamp_scroll(&mut self, content_len: usize) {
        let max_scroll = content_len.saturating_sub(self.view.viewport_height.max(1));
        if self.view.scroll_y > max_scroll {
            self.view.scroll_y = max_scroll;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn normal_commands_blocked_in_input_and_loading() {
        let mut s = TuiState::new();
        assert!(s.allows_normal_commands());

        s.mode = InteractionMode::Input(InputKind::Url {
            buffer: String::new(),
        });
        assert!(!s.allows_normal_commands());

        s.mode = InteractionMode::Normal;
        s.enter_loading("reload");
        assert!(!s.allows_normal_commands());
    }

    #[test]
    fn error_retains_last_page() {
        use crate::dom::DocumentMetadata;
        use crate::semantic::SemanticDocument;

        let doc = SemanticDocument::empty(DocumentMetadata {
            document_id: "d".into(),
            revision: "1".into(),
            url: "https://example.com/".into(),
            title: "T".into(),
            ready_state: "complete".into(),
            frames: vec![],
        })
        .expect("empty");
        let mut s = TuiState::new();
        s.publish_page(doc);
        assert_eq!(s.url(), "https://example.com/");
        s.enter_error("navigate", "boom");
        assert_eq!(s.url(), "https://example.com/");
        assert!(matches!(s.lifecycle, Lifecycle::Error { .. }));
    }

    #[test]
    fn error_blocks_semantic_actions_until_dismissed() {
        let mut state = TuiState::new();
        state.enter_error("reload", "failed");
        assert!(!state.allows_normal_commands());
        assert!(state.clear_error());
        assert!(state.lifecycle.is_ready());
        assert!(state.allows_normal_commands());
        assert_eq!(
            state.view.status_message.as_deref(),
            Some("dismissed: failed")
        );
    }

    #[test]
    fn clear_error_is_noop_when_ready_or_loading() {
        let mut state = TuiState::new();
        assert!(!state.clear_error());
        state.enter_loading("navigate");
        assert!(!state.clear_error());
        assert!(state.lifecycle.is_loading());
    }
}