Skip to main content

ftui_web/
runtime_options.rs

1//! Runtime option and theming mutation API with atomic validation (bd-2vr05.13.5).
2//!
3//! # Why this exists
4//!
5//! Production embedders of the FrankenTermJS web surface need to reconfigure a
6//! live terminal **without re-instantiating it** — exactly the `term.options`
7//! mutation surface that real `xterm.js` integrators depend on (cursor style,
8//! scrollback depth, screen-reader mode, renderer backend, theme palette, …).
9//!
10//! This module is the **single host-agnostic source of truth** for that option
11//! schema and its mutation semantics. It is pure and deterministic: identical
12//! `(current options, patch, capability profile)` inputs always produce an
13//! identical [`RuntimeOptionUpdate`] outcome and an identical structured-log
14//! serialisation, so a fixed capability profile yields reproducible behaviour
15//! across the rendering backends introduced by `bd-2vr05.8.1`.
16//!
17//! ```text
18//!  JSON patch ──parse──> RuntimeOptionPatch ─┐
19//!  (or typed builder) ───────────────────────┤
20//!                                            ├─ apply_patch(caps) ─┬─ Applied  ─> field diffs + repaint/reinit flags
21//!  OptionCapabilityProfile ──────────────────┘  (atomic: all or    └─ Rejected ─> per-field errors, options UNCHANGED
22//!                                                 nothing commits)
23//! ```
24//!
25//! ## Atomicity & rollback
26//!
27//! [`RuntimeOptions::apply_patch`] validates the **entire** candidate state
28//! (schema range checks + capability gating) before committing anything. If any
29//! field is invalid it returns a [`RuntimeOptionUpdate`] carrying *every*
30//! offending field's error and leaves `self` byte-for-byte unchanged — there is
31//! no partial application. On success it commits atomically and reports the
32//! exact set of changed fields plus the renderer/engine synchronisation that the
33//! host must perform ([`RuntimeOptionUpdate::requires_repaint`] /
34//! [`RuntimeOptionUpdate::requires_renderer_reinit`]).
35//!
36//! ## Capability / profile gating
37//!
38//! A value can be *schema-valid* yet *unsupported by the active engine*: e.g. a
39//! `WebGpu` renderer request when the host only advertises Canvas, or a
40//! scrollback depth beyond the host's memory budget. Those are reported as
41//! gating errors distinct from out-of-range schema errors, so a host can tell
42//! "you asked for something impossible here" apart from "you asked for nonsense".
43//!
44//! The colour swaps themselves stay host-side (browser CSS / canvas), keeping
45//! this module free of any dependency on `ftui-style` — the same layering rule
46//! the accessibility preference policies follow.
47
48use core::fmt;
49use ftui_core::terminal_capabilities::ColorDepth;
50
51/// Hard ceiling on scrollback retention, independent of the host's advertised
52/// budget. Guards against absurd payloads even when a host reports a very large
53/// `max_scrollback_lines`.
54pub const SCROLLBACK_HARD_MAX: u32 = 1_000_000;
55
56/// Minimum WCAG contrast ratio expressible by the option, ×100 (`1.0:1`).
57pub const MIN_CONTRAST_RATIO_X100: u16 = 100;
58/// Maximum WCAG contrast ratio expressible by the option, ×100 (`21:1`, the
59/// largest ratio achievable between sRGB black and white).
60pub const MAX_CONTRAST_RATIO_X100: u16 = 2100;
61
62/// Minimum supported tab stop width, in columns.
63pub const MIN_TAB_WIDTH: u8 = 1;
64/// Maximum supported tab stop width, in columns.
65pub const MAX_TAB_WIDTH: u8 = 16;
66
67/// Terminal cursor presentation style (parity with `xterm.js` `cursorStyle`).
68#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
69pub enum CursorStyle {
70    /// Full-cell block cursor.
71    Block,
72    /// Underline cursor.
73    Underline,
74    /// Vertical bar cursor.
75    Bar,
76}
77
78impl CursorStyle {
79    /// Stable lowercase token used in serialisation and JSON parsing.
80    #[must_use]
81    pub const fn as_token(self) -> &'static str {
82        match self {
83            Self::Block => "block",
84            Self::Underline => "underline",
85            Self::Bar => "bar",
86        }
87    }
88
89    /// Parse from a stable token; `None` for an unknown style.
90    #[must_use]
91    pub fn from_token(token: &str) -> Option<Self> {
92        match token {
93            "block" => Some(Self::Block),
94            "underline" => Some(Self::Underline),
95            "bar" => Some(Self::Bar),
96            _ => None,
97        }
98    }
99}
100
101impl fmt::Display for CursorStyle {
102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103        f.write_str(self.as_token())
104    }
105}
106
107/// Rendering backend selection (parity with `xterm.js` renderer addons, plus the
108/// WebGPU-primary backend introduced by `bd-2vr05.8.1`).
109#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
110pub enum RendererType {
111    /// DOM-cell renderer (most compatible, slowest).
112    Dom,
113    /// 2D canvas renderer.
114    Canvas,
115    /// WebGL renderer.
116    WebGl,
117    /// WebGPU renderer (primary high-performance backend).
118    WebGpu,
119}
120
121impl RendererType {
122    /// Stable lowercase token used in serialisation and JSON parsing.
123    #[must_use]
124    pub const fn as_token(self) -> &'static str {
125        match self {
126            Self::Dom => "dom",
127            Self::Canvas => "canvas",
128            Self::WebGl => "webgl",
129            Self::WebGpu => "webgpu",
130        }
131    }
132
133    /// Parse from a stable token; `None` for an unknown renderer.
134    #[must_use]
135    pub fn from_token(token: &str) -> Option<Self> {
136        match token {
137            "dom" => Some(Self::Dom),
138            "canvas" => Some(Self::Canvas),
139            "webgl" => Some(Self::WebGl),
140            "webgpu" => Some(Self::WebGpu),
141            _ => None,
142        }
143    }
144}
145
146impl fmt::Display for RendererType {
147    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148        f.write_str(self.as_token())
149    }
150}
151
152/// A packed `0xRRGGBBAA` theme colour. Host-agnostic: the actual swap is applied
153/// by the browser/canvas, this is pure intent.
154#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
155pub struct ThemeColor(pub u32);
156
157impl ThemeColor {
158    /// Construct from individual sRGB channels and alpha.
159    #[must_use]
160    pub const fn rgba(r: u8, g: u8, b: u8, a: u8) -> Self {
161        Self(((r as u32) << 24) | ((g as u32) << 16) | ((b as u32) << 8) | (a as u32))
162    }
163
164    /// Construct an opaque colour from sRGB channels.
165    #[must_use]
166    pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
167        Self::rgba(r, g, b, 0xFF)
168    }
169
170    /// Red channel.
171    #[must_use]
172    pub const fn r(self) -> u8 {
173        (self.0 >> 24) as u8
174    }
175    /// Green channel.
176    #[must_use]
177    pub const fn g(self) -> u8 {
178        (self.0 >> 16) as u8
179    }
180    /// Blue channel.
181    #[must_use]
182    pub const fn b(self) -> u8 {
183        (self.0 >> 8) as u8
184    }
185    /// Alpha channel (`0xFF` = fully opaque).
186    #[must_use]
187    pub const fn a(self) -> u8 {
188        self.0 as u8
189    }
190
191    /// `true` when the colour is fully opaque.
192    #[must_use]
193    pub const fn is_opaque(self) -> bool {
194        self.a() == 0xFF
195    }
196
197    /// Stable `#rrggbbaa` lowercase hex token used in serialisation.
198    #[must_use]
199    pub fn as_hex(self) -> String {
200        format!("#{:08x}", self.0)
201    }
202
203    /// Parse a `#rrggbb` (opaque) or `#rrggbbaa` hex token.
204    #[must_use]
205    pub fn from_hex(token: &str) -> Option<Self> {
206        let body = token.strip_prefix('#')?;
207        match body.len() {
208            6 => {
209                let rgb = u32::from_str_radix(body, 16).ok()?;
210                Some(Self((rgb << 8) | 0xFF))
211            }
212            8 => Some(Self(u32::from_str_radix(body, 16).ok()?)),
213            _ => None,
214        }
215    }
216}
217
218/// The full theme palette: anchor colours plus the 16 ANSI entries.
219#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
220pub struct ThemePalette {
221    /// Default foreground colour.
222    pub foreground: ThemeColor,
223    /// Default background colour.
224    pub background: ThemeColor,
225    /// Cursor colour.
226    pub cursor: ThemeColor,
227    /// Cursor glyph (accent) colour.
228    pub cursor_accent: ThemeColor,
229    /// Selection highlight background.
230    pub selection_background: ThemeColor,
231    /// The 16 ANSI palette entries (`0..=7` normal, `8..=15` bright).
232    pub ansi: [ThemeColor; 16],
233}
234
235impl ThemePalette {
236    /// The default dark palette (parity with `xterm.js` defaults).
237    #[must_use]
238    pub const fn dark() -> Self {
239        Self {
240            foreground: ThemeColor::rgb(0xD0, 0xD0, 0xD0),
241            background: ThemeColor::rgb(0x00, 0x00, 0x00),
242            cursor: ThemeColor::rgb(0xFF, 0xFF, 0xFF),
243            cursor_accent: ThemeColor::rgb(0x00, 0x00, 0x00),
244            selection_background: ThemeColor::rgba(0xFF, 0xFF, 0xFF, 0x4D),
245            ansi: [
246                ThemeColor::rgb(0x2E, 0x34, 0x36), // black
247                ThemeColor::rgb(0xCC, 0x00, 0x00), // red
248                ThemeColor::rgb(0x4E, 0x9A, 0x06), // green
249                ThemeColor::rgb(0xC4, 0xA0, 0x00), // yellow
250                ThemeColor::rgb(0x34, 0x65, 0xA4), // blue
251                ThemeColor::rgb(0x75, 0x50, 0x7B), // magenta
252                ThemeColor::rgb(0x06, 0x98, 0x9A), // cyan
253                ThemeColor::rgb(0xD3, 0xD7, 0xCF), // white
254                ThemeColor::rgb(0x55, 0x57, 0x53), // bright black
255                ThemeColor::rgb(0xEF, 0x29, 0x29), // bright red
256                ThemeColor::rgb(0x8A, 0xE2, 0x34), // bright green
257                ThemeColor::rgb(0xFC, 0xE9, 0x4F), // bright yellow
258                ThemeColor::rgb(0x72, 0x9F, 0xCF), // bright blue
259                ThemeColor::rgb(0xAD, 0x7F, 0xA8), // bright magenta
260                ThemeColor::rgb(0x34, 0xE2, 0xE2), // bright cyan
261                ThemeColor::rgb(0xEE, 0xEE, 0xEC), // bright white
262            ],
263        }
264    }
265
266    /// The anchor colours that must remain fully opaque (a transparent default
267    /// foreground/background is meaningless for a terminal grid).
268    const fn anchors(self) -> [(&'static str, ThemeColor); 2] {
269        [
270            ("foreground", self.foreground),
271            ("background", self.background),
272        ]
273    }
274}
275
276impl Default for ThemePalette {
277    fn default() -> Self {
278        Self::dark()
279    }
280}
281
282/// The complete, validated runtime option state.
283///
284/// Construct with [`RuntimeOptions::default`] (safe defaults) and mutate via
285/// [`RuntimeOptions::apply_patch`]. Direct field assignment is allowed for
286/// host-side initialisation but bypasses validation — prefer the patch API for
287/// any host-driven mutation.
288#[derive(Debug, Clone, Copy, PartialEq, Eq)]
289pub struct RuntimeOptions {
290    /// Cursor presentation style.
291    pub cursor_style: CursorStyle,
292    /// Whether the cursor blinks.
293    pub cursor_blink: bool,
294    /// Scrollback retention in lines (`0` = no scrollback).
295    pub scrollback_lines: u32,
296    /// Tab stop width in columns (`1..=16`).
297    pub tab_width: u8,
298    /// Whether bare LF is treated as CRLF on output (`convertEol`).
299    pub convert_eol: bool,
300    /// Whether screen-reader assistive output mode is active.
301    pub screen_reader_mode: bool,
302    /// Whether bracketed paste is enabled.
303    pub bracketed_paste: bool,
304    /// Minimum enforced foreground/background contrast ratio, ×100
305    /// (`100..=2100`). `100` (1.0:1) disables enforcement.
306    pub minimum_contrast_ratio_x100: u16,
307    /// Active rendering backend.
308    pub renderer: RendererType,
309    /// Theme palette.
310    pub theme: ThemePalette,
311}
312
313impl Default for RuntimeOptions {
314    fn default() -> Self {
315        Self {
316            cursor_style: CursorStyle::Block,
317            cursor_blink: false,
318            scrollback_lines: 1_000,
319            tab_width: 8,
320            convert_eol: false,
321            screen_reader_mode: false,
322            bracketed_paste: true,
323            minimum_contrast_ratio_x100: MIN_CONTRAST_RATIO_X100,
324            // DOM is the most compatible backend and is advertised by every
325            // capability profile, so a freshly-defaulted terminal validates and
326            // boots on any engine; the host upgrades to Canvas/WebGL/WebGPU via
327            // an explicit option patch once it knows what the engine supports.
328            renderer: RendererType::Dom,
329            theme: ThemePalette::dark(),
330        }
331    }
332}
333
334impl RuntimeOptions {
335    /// Apply a (sparse) patch atomically against the given capability profile.
336    ///
337    /// Returns a [`RuntimeOptionUpdate`] describing the outcome. On any
338    /// validation or gating failure the update is *rejected*, every offending
339    /// field's error is reported, and `self` is left unchanged. On success the
340    /// patch is committed atomically and the changed fields plus required
341    /// renderer/engine synchronisation are reported.
342    ///
343    /// `correlation_id` is recorded for structured-log triage only; it does not
344    /// affect the decision.
345    #[must_use]
346    pub fn apply_patch(
347        &mut self,
348        patch: &RuntimeOptionPatch,
349        caps: &OptionCapabilityProfile,
350        correlation_id: &str,
351    ) -> RuntimeOptionUpdate {
352        // Build the candidate by overlaying the patch onto the current state.
353        let mut candidate = *self;
354        if let Some(v) = patch.cursor_style {
355            candidate.cursor_style = v;
356        }
357        if let Some(v) = patch.cursor_blink {
358            candidate.cursor_blink = v;
359        }
360        if let Some(v) = patch.scrollback_lines {
361            candidate.scrollback_lines = v;
362        }
363        if let Some(v) = patch.tab_width {
364            candidate.tab_width = v;
365        }
366        if let Some(v) = patch.convert_eol {
367            candidate.convert_eol = v;
368        }
369        if let Some(v) = patch.screen_reader_mode {
370            candidate.screen_reader_mode = v;
371        }
372        if let Some(v) = patch.bracketed_paste {
373            candidate.bracketed_paste = v;
374        }
375        if let Some(v) = patch.minimum_contrast_ratio_x100 {
376            candidate.minimum_contrast_ratio_x100 = v;
377        }
378        if let Some(v) = patch.renderer {
379            candidate.renderer = v;
380        }
381        if let Some(v) = patch.theme {
382            candidate.theme = v;
383        }
384
385        // Validate the whole candidate, collecting EVERY error (deterministic,
386        // complete diagnostics) before deciding.
387        let errors = candidate.validate(caps);
388        if !errors.is_empty() {
389            return RuntimeOptionUpdate {
390                correlation_id: correlation_id.to_owned(),
391                applied: false,
392                changes: Vec::new(),
393                errors,
394                requires_repaint: false,
395                requires_renderer_reinit: false,
396            };
397        }
398
399        // Compute the field-level diff against the (still-current) state.
400        let changes = self.diff(&candidate);
401        let requires_renderer_reinit = changes.iter().any(|c| c.field == FIELD_RENDERER);
402        let requires_repaint = changes.iter().any(|c| {
403            matches!(
404                c.field,
405                FIELD_RENDERER
406                    | FIELD_THEME
407                    | FIELD_SCROLLBACK
408                    | FIELD_TAB_WIDTH
409                    | FIELD_CURSOR_STYLE
410                    | FIELD_MIN_CONTRAST
411            )
412        });
413
414        // Commit atomically.
415        *self = candidate;
416
417        RuntimeOptionUpdate {
418            correlation_id: correlation_id.to_owned(),
419            applied: true,
420            changes,
421            errors: Vec::new(),
422            requires_repaint,
423            requires_renderer_reinit,
424        }
425    }
426
427    /// Validate this option state against a capability profile, returning every
428    /// violation. An empty vector means fully valid and supported.
429    #[must_use]
430    pub fn validate(&self, caps: &OptionCapabilityProfile) -> Vec<RuntimeOptionError> {
431        let mut errors = Vec::new();
432
433        // ── Schema range checks ────────────────────────────────────────────
434        if self.scrollback_lines > SCROLLBACK_HARD_MAX {
435            errors.push(RuntimeOptionError::OutOfRange {
436                field: FIELD_SCROLLBACK,
437                value: u64::from(self.scrollback_lines),
438                min: 0,
439                max: u64::from(SCROLLBACK_HARD_MAX),
440            });
441        }
442        if self.tab_width < MIN_TAB_WIDTH || self.tab_width > MAX_TAB_WIDTH {
443            errors.push(RuntimeOptionError::OutOfRange {
444                field: FIELD_TAB_WIDTH,
445                value: u64::from(self.tab_width),
446                min: u64::from(MIN_TAB_WIDTH),
447                max: u64::from(MAX_TAB_WIDTH),
448            });
449        }
450        if self.minimum_contrast_ratio_x100 < MIN_CONTRAST_RATIO_X100
451            || self.minimum_contrast_ratio_x100 > MAX_CONTRAST_RATIO_X100
452        {
453            errors.push(RuntimeOptionError::OutOfRange {
454                field: FIELD_MIN_CONTRAST,
455                value: u64::from(self.minimum_contrast_ratio_x100),
456                min: u64::from(MIN_CONTRAST_RATIO_X100),
457                max: u64::from(MAX_CONTRAST_RATIO_X100),
458            });
459        }
460
461        // Theme anchors must be opaque.
462        for (slot, color) in self.theme.anchors() {
463            if !color.is_opaque() {
464                errors.push(RuntimeOptionError::TransparentAnchorColor {
465                    field: FIELD_THEME,
466                    slot,
467                    alpha: color.a(),
468                });
469            }
470        }
471
472        // ── Capability / profile gating ────────────────────────────────────
473        // Gating only applies to otherwise schema-valid values, so a single
474        // field never reports both an out-of-range and a gating error (an
475        // over-hard-max scrollback is nonsense, not merely unsupported here).
476        if self.scrollback_lines <= SCROLLBACK_HARD_MAX
477            && self.scrollback_lines > caps.max_scrollback_lines
478        {
479            errors.push(RuntimeOptionError::CapabilityGated {
480                field: FIELD_SCROLLBACK,
481                detail: GatingDetail::ScrollbackBudgetExceeded {
482                    requested: self.scrollback_lines,
483                    budget: caps.max_scrollback_lines,
484                },
485            });
486        }
487        if !caps.supports_renderer(self.renderer) {
488            errors.push(RuntimeOptionError::CapabilityGated {
489                field: FIELD_RENDERER,
490                detail: GatingDetail::RendererUnsupported {
491                    requested: self.renderer,
492                },
493            });
494        }
495
496        errors
497    }
498
499    /// Compute the ordered field-level diff between `self` and `next`.
500    fn diff(&self, next: &Self) -> Vec<OptionFieldChange> {
501        let mut changes = Vec::new();
502        if self.cursor_style != next.cursor_style {
503            changes.push(OptionFieldChange::new(
504                FIELD_CURSOR_STYLE,
505                self.cursor_style.to_string(),
506                next.cursor_style.to_string(),
507            ));
508        }
509        if self.cursor_blink != next.cursor_blink {
510            changes.push(OptionFieldChange::new(
511                FIELD_CURSOR_BLINK,
512                self.cursor_blink.to_string(),
513                next.cursor_blink.to_string(),
514            ));
515        }
516        if self.scrollback_lines != next.scrollback_lines {
517            changes.push(OptionFieldChange::new(
518                FIELD_SCROLLBACK,
519                self.scrollback_lines.to_string(),
520                next.scrollback_lines.to_string(),
521            ));
522        }
523        if self.tab_width != next.tab_width {
524            changes.push(OptionFieldChange::new(
525                FIELD_TAB_WIDTH,
526                self.tab_width.to_string(),
527                next.tab_width.to_string(),
528            ));
529        }
530        if self.convert_eol != next.convert_eol {
531            changes.push(OptionFieldChange::new(
532                FIELD_CONVERT_EOL,
533                self.convert_eol.to_string(),
534                next.convert_eol.to_string(),
535            ));
536        }
537        if self.screen_reader_mode != next.screen_reader_mode {
538            changes.push(OptionFieldChange::new(
539                FIELD_SCREEN_READER,
540                self.screen_reader_mode.to_string(),
541                next.screen_reader_mode.to_string(),
542            ));
543        }
544        if self.bracketed_paste != next.bracketed_paste {
545            changes.push(OptionFieldChange::new(
546                FIELD_BRACKETED_PASTE,
547                self.bracketed_paste.to_string(),
548                next.bracketed_paste.to_string(),
549            ));
550        }
551        if self.minimum_contrast_ratio_x100 != next.minimum_contrast_ratio_x100 {
552            changes.push(OptionFieldChange::new(
553                FIELD_MIN_CONTRAST,
554                self.minimum_contrast_ratio_x100.to_string(),
555                next.minimum_contrast_ratio_x100.to_string(),
556            ));
557        }
558        if self.renderer != next.renderer {
559            changes.push(OptionFieldChange::new(
560                FIELD_RENDERER,
561                self.renderer.to_string(),
562                next.renderer.to_string(),
563            ));
564        }
565        if self.theme != next.theme {
566            changes.push(OptionFieldChange::new(
567                FIELD_THEME,
568                self.theme.foreground.as_hex(),
569                next.theme.foreground.as_hex(),
570            ));
571        }
572        changes
573    }
574
575    /// Stable, ordered CSS data-attribute pairs for the browser host. Mirrors
576    /// the accessibility surface's `web_dataset()` convention so generated DOM
577    /// markup is byte-for-byte reproducible.
578    #[must_use]
579    pub fn web_dataset(&self) -> [(&'static str, String); 3] {
580        [
581            ("data-ftui-cursor-style", self.cursor_style.to_string()),
582            ("data-ftui-renderer", self.renderer.to_string()),
583            (
584                "data-ftui-screen-reader",
585                self.screen_reader_mode.to_string(),
586            ),
587        ]
588    }
589
590    /// Serialise the full option snapshot to a single deterministic JSON line.
591    #[must_use]
592    pub fn to_jsonl(&self, correlation_id: &str) -> String {
593        format!(
594            concat!(
595                "{{\"event\":\"runtime_options_snapshot\",\"correlation_id\":\"{cid}\",",
596                "\"cursor_style\":\"{cs}\",\"cursor_blink\":{cb},\"scrollback_lines\":{sb},",
597                "\"tab_width\":{tw},\"convert_eol\":{ce},\"screen_reader_mode\":{srm},",
598                "\"bracketed_paste\":{bp},\"minimum_contrast_ratio_x100\":{mcr},",
599                "\"renderer\":\"{rt}\",\"theme_foreground\":\"{fg}\",\"theme_background\":\"{bg}\"}}"
600            ),
601            cid = escape_json(correlation_id),
602            cs = self.cursor_style,
603            cb = self.cursor_blink,
604            sb = self.scrollback_lines,
605            tw = self.tab_width,
606            ce = self.convert_eol,
607            srm = self.screen_reader_mode,
608            bp = self.bracketed_paste,
609            mcr = self.minimum_contrast_ratio_x100,
610            rt = self.renderer,
611            fg = self.theme.foreground.as_hex(),
612            bg = self.theme.background.as_hex(),
613        )
614    }
615}
616
617// Canonical field identifiers — single source of truth for diffs, errors, and
618// serialisation so the strings never drift between producers.
619const FIELD_CURSOR_STYLE: &str = "cursor_style";
620const FIELD_CURSOR_BLINK: &str = "cursor_blink";
621const FIELD_SCROLLBACK: &str = "scrollback_lines";
622const FIELD_TAB_WIDTH: &str = "tab_width";
623const FIELD_CONVERT_EOL: &str = "convert_eol";
624const FIELD_SCREEN_READER: &str = "screen_reader_mode";
625const FIELD_BRACKETED_PASTE: &str = "bracketed_paste";
626const FIELD_MIN_CONTRAST: &str = "minimum_contrast_ratio_x100";
627const FIELD_RENDERER: &str = "renderer";
628const FIELD_THEME: &str = "theme";
629
630/// A sparse patch: every field is independently `Some(_)` to mutate or `None` to
631/// leave untouched. Mirrors assigning to a subset of `xterm.js` `term.options`.
632#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
633pub struct RuntimeOptionPatch {
634    /// See [`RuntimeOptions::cursor_style`].
635    pub cursor_style: Option<CursorStyle>,
636    /// See [`RuntimeOptions::cursor_blink`].
637    pub cursor_blink: Option<bool>,
638    /// See [`RuntimeOptions::scrollback_lines`].
639    pub scrollback_lines: Option<u32>,
640    /// See [`RuntimeOptions::tab_width`].
641    pub tab_width: Option<u8>,
642    /// See [`RuntimeOptions::convert_eol`].
643    pub convert_eol: Option<bool>,
644    /// See [`RuntimeOptions::screen_reader_mode`].
645    pub screen_reader_mode: Option<bool>,
646    /// See [`RuntimeOptions::bracketed_paste`].
647    pub bracketed_paste: Option<bool>,
648    /// See [`RuntimeOptions::minimum_contrast_ratio_x100`].
649    pub minimum_contrast_ratio_x100: Option<u16>,
650    /// See [`RuntimeOptions::renderer`].
651    pub renderer: Option<RendererType>,
652    /// See [`RuntimeOptions::theme`].
653    pub theme: Option<ThemePalette>,
654}
655
656impl RuntimeOptionPatch {
657    /// An empty patch (no-op).
658    #[must_use]
659    pub const fn new() -> Self {
660        Self {
661            cursor_style: None,
662            cursor_blink: None,
663            scrollback_lines: None,
664            tab_width: None,
665            convert_eol: None,
666            screen_reader_mode: None,
667            bracketed_paste: None,
668            minimum_contrast_ratio_x100: None,
669            renderer: None,
670            theme: None,
671        }
672    }
673
674    /// `true` when the patch mutates nothing.
675    #[must_use]
676    pub const fn is_empty(&self) -> bool {
677        self.cursor_style.is_none()
678            && self.cursor_blink.is_none()
679            && self.scrollback_lines.is_none()
680            && self.tab_width.is_none()
681            && self.convert_eol.is_none()
682            && self.screen_reader_mode.is_none()
683            && self.bracketed_paste.is_none()
684            && self.minimum_contrast_ratio_x100.is_none()
685            && self.renderer.is_none()
686            && self.theme.is_none()
687    }
688
689    /// Builder: set cursor style.
690    #[must_use]
691    pub const fn with_cursor_style(mut self, v: CursorStyle) -> Self {
692        self.cursor_style = Some(v);
693        self
694    }
695    /// Builder: set scrollback retention.
696    #[must_use]
697    pub const fn with_scrollback_lines(mut self, v: u32) -> Self {
698        self.scrollback_lines = Some(v);
699        self
700    }
701    /// Builder: set tab width.
702    #[must_use]
703    pub const fn with_tab_width(mut self, v: u8) -> Self {
704        self.tab_width = Some(v);
705        self
706    }
707    /// Builder: set screen-reader mode.
708    #[must_use]
709    pub const fn with_screen_reader_mode(mut self, v: bool) -> Self {
710        self.screen_reader_mode = Some(v);
711        self
712    }
713    /// Builder: set minimum contrast ratio ×100.
714    #[must_use]
715    pub const fn with_minimum_contrast_ratio_x100(mut self, v: u16) -> Self {
716        self.minimum_contrast_ratio_x100 = Some(v);
717        self
718    }
719    /// Builder: set renderer backend.
720    #[must_use]
721    pub const fn with_renderer(mut self, v: RendererType) -> Self {
722        self.renderer = Some(v);
723        self
724    }
725    /// Builder: set theme palette.
726    #[must_use]
727    pub const fn with_theme(mut self, v: ThemePalette) -> Self {
728        self.theme = Some(v);
729        self
730    }
731}
732
733/// What the active rendering engine / host advertises as supported. A
734/// schema-valid option can still be gated against this profile.
735#[derive(Debug, Clone, Copy, PartialEq, Eq)]
736pub struct OptionCapabilityProfile {
737    /// Whether the DOM renderer is available (effectively always true).
738    pub dom: bool,
739    /// Whether the 2D canvas renderer is available.
740    pub canvas: bool,
741    /// Whether the WebGL renderer is available.
742    pub webgl: bool,
743    /// Whether the WebGPU renderer is available.
744    pub webgpu: bool,
745    /// Maximum color fidelity (informational; theme colors stay host-downgraded
746    /// rather than gated).
747    pub color_depth: ColorDepth,
748    /// Maximum scrollback the host will retain in memory.
749    pub max_scrollback_lines: u32,
750}
751
752impl OptionCapabilityProfile {
753    /// A conservative default profile: DOM + Canvas only, modest scrollback.
754    #[must_use]
755    pub const fn minimal() -> Self {
756        Self {
757            dom: true,
758            canvas: true,
759            webgl: false,
760            webgpu: false,
761            color_depth: ColorDepth::Ansi16,
762            max_scrollback_lines: 10_000,
763        }
764    }
765
766    /// A fully-featured profile: every renderer, generous scrollback.
767    #[must_use]
768    pub const fn full() -> Self {
769        Self {
770            dom: true,
771            canvas: true,
772            webgl: true,
773            webgpu: true,
774            color_depth: ColorDepth::TrueColor,
775            max_scrollback_lines: SCROLLBACK_HARD_MAX,
776        }
777    }
778
779    /// Whether the requested renderer backend is available.
780    #[must_use]
781    pub const fn supports_renderer(&self, renderer: RendererType) -> bool {
782        match renderer {
783            RendererType::Dom => self.dom,
784            RendererType::Canvas => self.canvas,
785            RendererType::WebGl => self.webgl,
786            RendererType::WebGpu => self.webgpu,
787        }
788    }
789}
790
791impl Default for OptionCapabilityProfile {
792    fn default() -> Self {
793        Self::minimal()
794    }
795}
796
797/// A single field that changed in a committed update.
798#[derive(Debug, Clone, PartialEq, Eq)]
799pub struct OptionFieldChange {
800    /// Canonical field identifier.
801    pub field: &'static str,
802    /// Previous value, rendered as a stable token.
803    pub old: String,
804    /// New value, rendered as a stable token.
805    pub new: String,
806}
807
808impl OptionFieldChange {
809    fn new(field: &'static str, old: String, new: String) -> Self {
810        Self { field, old, new }
811    }
812}
813
814/// Detail for a capability-gating rejection.
815#[derive(Debug, Clone, Copy, PartialEq, Eq)]
816pub enum GatingDetail {
817    /// The requested renderer is not advertised by the host.
818    RendererUnsupported {
819        /// The renderer that was requested.
820        requested: RendererType,
821    },
822    /// The requested scrollback exceeds the host's memory budget.
823    ScrollbackBudgetExceeded {
824        /// Requested scrollback retention.
825        requested: u32,
826        /// The host's advertised budget.
827        budget: u32,
828    },
829}
830
831/// A single, explicit option validation/gating failure.
832#[derive(Debug, Clone, PartialEq, Eq)]
833pub enum RuntimeOptionError {
834    /// A numeric field is outside its allowed schema range.
835    OutOfRange {
836        /// Canonical field identifier.
837        field: &'static str,
838        /// The offending value.
839        value: u64,
840        /// Inclusive minimum.
841        min: u64,
842        /// Inclusive maximum.
843        max: u64,
844    },
845    /// A theme anchor colour (foreground/background) was not fully opaque.
846    TransparentAnchorColor {
847        /// Canonical field identifier (`theme`).
848        field: &'static str,
849        /// The offending palette slot.
850        slot: &'static str,
851        /// The non-opaque alpha value.
852        alpha: u8,
853    },
854    /// The value is schema-valid but unsupported by the active capability
855    /// profile.
856    CapabilityGated {
857        /// Canonical field identifier.
858        field: &'static str,
859        /// Specific gating reason.
860        detail: GatingDetail,
861    },
862}
863
864impl RuntimeOptionError {
865    /// The canonical field identifier this error concerns.
866    #[must_use]
867    pub const fn field(&self) -> &'static str {
868        match self {
869            Self::OutOfRange { field, .. }
870            | Self::TransparentAnchorColor { field, .. }
871            | Self::CapabilityGated { field, .. } => field,
872        }
873    }
874
875    /// A stable machine token for the error kind (used in structured logs).
876    #[must_use]
877    pub const fn kind(&self) -> &'static str {
878        match self {
879            Self::OutOfRange { .. } => "out_of_range",
880            Self::TransparentAnchorColor { .. } => "transparent_anchor_color",
881            Self::CapabilityGated { .. } => "capability_gated",
882        }
883    }
884}
885
886impl fmt::Display for RuntimeOptionError {
887    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
888        match self {
889            Self::OutOfRange {
890                field,
891                value,
892                min,
893                max,
894            } => write!(
895                f,
896                "option `{field}` value {value} is out of range [{min}, {max}]"
897            ),
898            Self::TransparentAnchorColor { field, slot, alpha } => write!(
899                f,
900                "option `{field}` anchor colour `{slot}` must be opaque (alpha {alpha} != 255)"
901            ),
902            Self::CapabilityGated { field, detail } => match detail {
903                GatingDetail::RendererUnsupported { requested } => write!(
904                    f,
905                    "option `{field}` renderer `{requested}` is not supported by the active host"
906                ),
907                GatingDetail::ScrollbackBudgetExceeded { requested, budget } => write!(
908                    f,
909                    "option `{field}` scrollback {requested} exceeds host budget {budget}"
910                ),
911            },
912        }
913    }
914}
915
916impl std::error::Error for RuntimeOptionError {}
917
918/// The outcome of an [`RuntimeOptions::apply_patch`] call.
919#[derive(Debug, Clone, PartialEq, Eq)]
920pub struct RuntimeOptionUpdate {
921    /// Correlation id carried through for structured-log triage.
922    pub correlation_id: String,
923    /// `true` when the patch was committed; `false` means rejected and rolled
924    /// back (options unchanged).
925    pub applied: bool,
926    /// The fields that actually changed (empty when rejected or a no-op).
927    pub changes: Vec<OptionFieldChange>,
928    /// Every validation/gating error (empty when applied).
929    pub errors: Vec<RuntimeOptionError>,
930    /// Whether the host must repaint the grid to reflect the change.
931    pub requires_repaint: bool,
932    /// Whether the host must tear down and re-create the renderer backend.
933    pub requires_renderer_reinit: bool,
934}
935
936impl RuntimeOptionUpdate {
937    /// `true` when applied but nothing actually changed (idempotent patch).
938    #[must_use]
939    pub fn is_noop(&self) -> bool {
940        self.applied && self.changes.is_empty()
941    }
942
943    /// Serialise the outcome to a single deterministic JSON line, including the
944    /// full change set and (on rejection) every error. This is the canonical
945    /// applied/rejected audit artifact.
946    #[must_use]
947    pub fn to_jsonl(&self) -> String {
948        let mut changes_json = String::from("[");
949        for (i, c) in self.changes.iter().enumerate() {
950            if i > 0 {
951                changes_json.push(',');
952            }
953            changes_json.push_str(&format!(
954                "{{\"field\":\"{}\",\"old\":\"{}\",\"new\":\"{}\"}}",
955                c.field,
956                escape_json(&c.old),
957                escape_json(&c.new),
958            ));
959        }
960        changes_json.push(']');
961
962        let mut errors_json = String::from("[");
963        for (i, e) in self.errors.iter().enumerate() {
964            if i > 0 {
965                errors_json.push(',');
966            }
967            errors_json.push_str(&format!(
968                "{{\"field\":\"{}\",\"kind\":\"{}\",\"detail\":\"{}\"}}",
969                e.field(),
970                e.kind(),
971                escape_json(&e.to_string()),
972            ));
973        }
974        errors_json.push(']');
975
976        format!(
977            concat!(
978                "{{\"event\":\"runtime_option_update\",\"correlation_id\":\"{cid}\",",
979                "\"applied\":{applied},\"requires_repaint\":{rp},",
980                "\"requires_renderer_reinit\":{rr},\"change_count\":{cc},",
981                "\"error_count\":{ec},\"changes\":{changes},\"errors\":{errors}}}"
982            ),
983            cid = escape_json(&self.correlation_id),
984            applied = self.applied,
985            rp = self.requires_repaint,
986            rr = self.requires_renderer_reinit,
987            cc = self.changes.len(),
988            ec = self.errors.len(),
989            changes = changes_json,
990            errors = errors_json,
991        )
992    }
993}
994
995/// Errors from parsing a JSON option patch (shape/syntax), distinct from
996/// validation/gating errors which are surfaced by [`RuntimeOptions::apply_patch`].
997#[cfg(feature = "input-parser")]
998#[derive(Debug, Clone, PartialEq, Eq)]
999pub enum OptionPatchParseError {
1000    /// The payload was not valid JSON or not a JSON object.
1001    MalformedJson(String),
1002    /// An unknown option key was present (strict parsing rejects typos).
1003    UnknownKey(String),
1004    /// A key held a value of the wrong JSON type.
1005    TypeMismatch {
1006        /// The offending key.
1007        key: String,
1008        /// The JSON type that was expected.
1009        expected: &'static str,
1010    },
1011    /// An enum-valued field held an unrecognised token.
1012    InvalidToken {
1013        /// The offending key.
1014        key: String,
1015        /// The unrecognised token.
1016        token: String,
1017    },
1018}
1019
1020#[cfg(feature = "input-parser")]
1021impl fmt::Display for OptionPatchParseError {
1022    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1023        match self {
1024            Self::MalformedJson(msg) => write!(f, "malformed option patch JSON: {msg}"),
1025            Self::UnknownKey(key) => write!(f, "unknown option key `{key}`"),
1026            Self::TypeMismatch { key, expected } => {
1027                write!(f, "option key `{key}` expected a {expected}")
1028            }
1029            Self::InvalidToken { key, token } => {
1030                write!(f, "option key `{key}` has invalid token `{token}`")
1031            }
1032        }
1033    }
1034}
1035
1036#[cfg(feature = "input-parser")]
1037impl std::error::Error for OptionPatchParseError {}
1038
1039#[cfg(feature = "input-parser")]
1040impl RuntimeOptionPatch {
1041    /// Parse a sparse option patch from a JSON object (the exact shape a JS host
1042    /// produces from a `term.options = {...}` assignment).
1043    ///
1044    /// Strict: unknown keys, wrong JSON types, and unrecognised enum tokens are
1045    /// rejected with an actionable [`OptionPatchParseError`] rather than silently
1046    /// ignored. Numeric *range* checks are intentionally deferred to
1047    /// [`RuntimeOptions::apply_patch`] so that parse errors (shape) stay distinct
1048    /// from validation errors (semantics).
1049    ///
1050    /// # Errors
1051    ///
1052    /// Returns [`OptionPatchParseError`] when the payload is not a JSON object,
1053    /// contains an unknown key, has a type mismatch, or carries an invalid enum
1054    /// token.
1055    pub fn parse_json(input: &str) -> Result<Self, OptionPatchParseError> {
1056        use serde_json::Value;
1057
1058        let value: Value = serde_json::from_str(input)
1059            .map_err(|e| OptionPatchParseError::MalformedJson(e.to_string()))?;
1060        let obj = value.as_object().ok_or_else(|| {
1061            OptionPatchParseError::MalformedJson("top-level value must be an object".to_owned())
1062        })?;
1063
1064        let mut patch = Self::new();
1065
1066        for (key, val) in obj {
1067            match key.as_str() {
1068                "cursorStyle" => {
1069                    let token = expect_str(key, val)?;
1070                    patch.cursor_style = Some(CursorStyle::from_token(token).ok_or_else(|| {
1071                        OptionPatchParseError::InvalidToken {
1072                            key: key.clone(),
1073                            token: token.to_owned(),
1074                        }
1075                    })?);
1076                }
1077                "cursorBlink" => patch.cursor_blink = Some(expect_bool(key, val)?),
1078                "scrollback" => patch.scrollback_lines = Some(expect_u32(key, val)?),
1079                "tabStopWidth" => patch.tab_width = Some(expect_u8(key, val)?),
1080                "convertEol" => patch.convert_eol = Some(expect_bool(key, val)?),
1081                "screenReaderMode" => patch.screen_reader_mode = Some(expect_bool(key, val)?),
1082                "bracketedPaste" => patch.bracketed_paste = Some(expect_bool(key, val)?),
1083                "minimumContrastRatioX100" => {
1084                    patch.minimum_contrast_ratio_x100 = Some(expect_u16(key, val)?);
1085                }
1086                "rendererType" => {
1087                    let token = expect_str(key, val)?;
1088                    patch.renderer = Some(RendererType::from_token(token).ok_or_else(|| {
1089                        OptionPatchParseError::InvalidToken {
1090                            key: key.clone(),
1091                            token: token.to_owned(),
1092                        }
1093                    })?);
1094                }
1095                "theme" => patch.theme = Some(parse_theme(key, val)?),
1096                other => return Err(OptionPatchParseError::UnknownKey(other.to_owned())),
1097            }
1098        }
1099
1100        Ok(patch)
1101    }
1102}
1103
1104#[cfg(feature = "input-parser")]
1105fn expect_str<'a>(key: &str, val: &'a serde_json::Value) -> Result<&'a str, OptionPatchParseError> {
1106    val.as_str()
1107        .ok_or_else(|| OptionPatchParseError::TypeMismatch {
1108            key: key.to_owned(),
1109            expected: "string",
1110        })
1111}
1112
1113#[cfg(feature = "input-parser")]
1114fn expect_bool(key: &str, val: &serde_json::Value) -> Result<bool, OptionPatchParseError> {
1115    val.as_bool()
1116        .ok_or_else(|| OptionPatchParseError::TypeMismatch {
1117            key: key.to_owned(),
1118            expected: "boolean",
1119        })
1120}
1121
1122#[cfg(feature = "input-parser")]
1123fn expect_u64(key: &str, val: &serde_json::Value) -> Result<u64, OptionPatchParseError> {
1124    val.as_u64()
1125        .ok_or_else(|| OptionPatchParseError::TypeMismatch {
1126            key: key.to_owned(),
1127            expected: "non-negative integer",
1128        })
1129}
1130
1131#[cfg(feature = "input-parser")]
1132fn expect_u32(key: &str, val: &serde_json::Value) -> Result<u32, OptionPatchParseError> {
1133    // Saturate at u32::MAX so an absurd payload becomes a clean range rejection
1134    // at apply time rather than a parse-time overflow.
1135    Ok(u32::try_from(expect_u64(key, val)?).unwrap_or(u32::MAX))
1136}
1137
1138#[cfg(feature = "input-parser")]
1139fn expect_u16(key: &str, val: &serde_json::Value) -> Result<u16, OptionPatchParseError> {
1140    Ok(u16::try_from(expect_u64(key, val)?).unwrap_or(u16::MAX))
1141}
1142
1143#[cfg(feature = "input-parser")]
1144fn expect_u8(key: &str, val: &serde_json::Value) -> Result<u8, OptionPatchParseError> {
1145    Ok(u8::try_from(expect_u64(key, val)?).unwrap_or(u8::MAX))
1146}
1147
1148#[cfg(feature = "input-parser")]
1149fn parse_color(key: &str, val: &serde_json::Value) -> Result<ThemeColor, OptionPatchParseError> {
1150    let token = expect_str(key, val)?;
1151    ThemeColor::from_hex(token).ok_or_else(|| OptionPatchParseError::InvalidToken {
1152        key: key.to_owned(),
1153        token: token.to_owned(),
1154    })
1155}
1156
1157#[cfg(feature = "input-parser")]
1158fn parse_theme(key: &str, val: &serde_json::Value) -> Result<ThemePalette, OptionPatchParseError> {
1159    let obj = val
1160        .as_object()
1161        .ok_or_else(|| OptionPatchParseError::TypeMismatch {
1162            key: key.to_owned(),
1163            expected: "object",
1164        })?;
1165    // Start from the default palette; the theme object overlays named slots.
1166    let mut palette = ThemePalette::dark();
1167    for (slot, color_val) in obj {
1168        match slot.as_str() {
1169            "foreground" => palette.foreground = parse_color(slot, color_val)?,
1170            "background" => palette.background = parse_color(slot, color_val)?,
1171            "cursor" => palette.cursor = parse_color(slot, color_val)?,
1172            "cursorAccent" => palette.cursor_accent = parse_color(slot, color_val)?,
1173            "selectionBackground" => {
1174                palette.selection_background = parse_color(slot, color_val)?;
1175            }
1176            other => {
1177                // Accept ansi0..=ansi15; reject anything else.
1178                if let Some(idx) = other
1179                    .strip_prefix("ansi")
1180                    .and_then(|n| n.parse::<usize>().ok())
1181                    .filter(|i| *i < 16)
1182                {
1183                    palette.ansi[idx] = parse_color(other, color_val)?;
1184                } else {
1185                    return Err(OptionPatchParseError::UnknownKey(format!("theme.{other}")));
1186                }
1187            }
1188        }
1189    }
1190    Ok(palette)
1191}
1192
1193/// Escape a string for embedding inside a JSON double-quoted value.
1194fn escape_json(input: &str) -> String {
1195    let mut out = String::with_capacity(input.len() + 2);
1196    for ch in input.chars() {
1197        match ch {
1198            '"' => out.push_str("\\\""),
1199            '\\' => out.push_str("\\\\"),
1200            '\n' => out.push_str("\\n"),
1201            '\r' => out.push_str("\\r"),
1202            '\t' => out.push_str("\\t"),
1203            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
1204            c => out.push(c),
1205        }
1206    }
1207    out
1208}
1209
1210#[cfg(test)]
1211mod tests {
1212    use super::*;
1213
1214    // ── Defaults & schema construction ──────────────────────────────────────
1215
1216    #[test]
1217    fn defaults_are_valid_under_full_caps() {
1218        let opts = RuntimeOptions::default();
1219        assert!(opts.validate(&OptionCapabilityProfile::full()).is_empty());
1220    }
1221
1222    #[test]
1223    fn default_renderer_is_valid_under_minimal_caps() {
1224        // The default renderer (DOM) must be supported by the minimal profile
1225        // so a fresh terminal always boots.
1226        let opts = RuntimeOptions::default();
1227        assert!(
1228            opts.validate(&OptionCapabilityProfile::minimal())
1229                .is_empty()
1230        );
1231    }
1232
1233    #[test]
1234    fn empty_patch_is_noop() {
1235        let mut opts = RuntimeOptions::default();
1236        let before = opts;
1237        let patch = RuntimeOptionPatch::new();
1238        assert!(patch.is_empty());
1239        let update = opts.apply_patch(&patch, &OptionCapabilityProfile::full(), "noop");
1240        assert!(update.applied);
1241        assert!(update.is_noop());
1242        assert!(update.changes.is_empty());
1243        assert_eq!(opts, before);
1244    }
1245
1246    // ── Successful atomic apply ─────────────────────────────────────────────
1247
1248    #[test]
1249    fn apply_commits_and_reports_changed_fields() {
1250        let mut opts = RuntimeOptions::default();
1251        let patch = RuntimeOptionPatch::new()
1252            .with_cursor_style(CursorStyle::Bar)
1253            .with_scrollback_lines(5_000)
1254            .with_screen_reader_mode(true);
1255        let update = opts.apply_patch(&patch, &OptionCapabilityProfile::full(), "c1");
1256        assert!(update.applied);
1257        assert_eq!(update.changes.len(), 3);
1258        assert_eq!(opts.cursor_style, CursorStyle::Bar);
1259        assert_eq!(opts.scrollback_lines, 5_000);
1260        assert!(opts.screen_reader_mode);
1261        // cursor_style + scrollback both demand a repaint; no renderer change.
1262        assert!(update.requires_repaint);
1263        assert!(!update.requires_renderer_reinit);
1264    }
1265
1266    #[test]
1267    fn idempotent_apply_changes_nothing() {
1268        let mut opts = RuntimeOptions::default();
1269        let patch = RuntimeOptionPatch::new().with_cursor_style(opts.cursor_style);
1270        let update = opts.apply_patch(&patch, &OptionCapabilityProfile::full(), "id");
1271        assert!(update.applied);
1272        assert!(update.is_noop());
1273        assert!(!update.requires_repaint);
1274    }
1275
1276    #[test]
1277    fn renderer_change_requires_reinit_and_repaint() {
1278        let mut opts = RuntimeOptions::default();
1279        let patch = RuntimeOptionPatch::new().with_renderer(RendererType::WebGpu);
1280        let update = opts.apply_patch(&patch, &OptionCapabilityProfile::full(), "r1");
1281        assert!(update.applied);
1282        assert!(update.requires_renderer_reinit);
1283        assert!(update.requires_repaint);
1284        assert_eq!(opts.renderer, RendererType::WebGpu);
1285    }
1286
1287    // ── Atomic rollback on invalid payloads ─────────────────────────────────
1288
1289    #[test]
1290    fn out_of_range_rejects_and_rolls_back_entire_patch() {
1291        let mut opts = RuntimeOptions::default();
1292        let before = opts;
1293        // tab_width is valid, but minimum_contrast is absurd → whole patch fails.
1294        let patch = RuntimeOptionPatch::new()
1295            .with_tab_width(4)
1296            .with_minimum_contrast_ratio_x100(9_999);
1297        let update = opts.apply_patch(&patch, &OptionCapabilityProfile::full(), "bad");
1298        assert!(!update.applied);
1299        assert_eq!(update.changes.len(), 0);
1300        assert_eq!(update.errors.len(), 1);
1301        assert_eq!(update.errors[0].field(), FIELD_MIN_CONTRAST);
1302        // Rollback: even the *valid* tab_width must NOT have been applied.
1303        assert_eq!(opts, before);
1304    }
1305
1306    #[test]
1307    fn all_errors_collected_not_just_first() {
1308        let mut opts = RuntimeOptions::default();
1309        let patch = RuntimeOptionPatch::new()
1310            .with_tab_width(0) // below MIN_TAB_WIDTH
1311            .with_minimum_contrast_ratio_x100(5) // below MIN_CONTRAST
1312            .with_scrollback_lines(SCROLLBACK_HARD_MAX + 1); // above hard max
1313        let update = opts.apply_patch(&patch, &OptionCapabilityProfile::full(), "multi");
1314        assert!(!update.applied);
1315        assert_eq!(update.errors.len(), 3);
1316        let fields: Vec<&str> = update
1317            .errors
1318            .iter()
1319            .map(RuntimeOptionError::field)
1320            .collect();
1321        assert!(fields.contains(&FIELD_TAB_WIDTH));
1322        assert!(fields.contains(&FIELD_MIN_CONTRAST));
1323        assert!(fields.contains(&FIELD_SCROLLBACK));
1324    }
1325
1326    #[test]
1327    fn transparent_anchor_color_is_rejected() {
1328        let mut opts = RuntimeOptions::default();
1329        let mut theme = ThemePalette::dark();
1330        theme.background = ThemeColor::rgba(0x10, 0x10, 0x10, 0x80); // semi-transparent
1331        let patch = RuntimeOptionPatch::new().with_theme(theme);
1332        let update = opts.apply_patch(&patch, &OptionCapabilityProfile::full(), "tc");
1333        assert!(!update.applied);
1334        assert!(matches!(
1335            update.errors[0],
1336            RuntimeOptionError::TransparentAnchorColor { .. }
1337        ));
1338    }
1339
1340    #[test]
1341    fn transparent_selection_is_allowed() {
1342        // Only foreground/background anchors must be opaque; selection may be
1343        // translucent (that is its whole purpose).
1344        let mut opts = RuntimeOptions::default();
1345        let mut theme = ThemePalette::dark();
1346        theme.selection_background = ThemeColor::rgba(0x80, 0x80, 0xFF, 0x40);
1347        let patch = RuntimeOptionPatch::new().with_theme(theme);
1348        let update = opts.apply_patch(&patch, &OptionCapabilityProfile::full(), "sel");
1349        assert!(update.applied);
1350    }
1351
1352    // ── Capability / profile gating ─────────────────────────────────────────
1353
1354    #[test]
1355    fn renderer_gated_when_unsupported() {
1356        let mut opts = RuntimeOptions::default();
1357        let before = opts;
1358        let patch = RuntimeOptionPatch::new().with_renderer(RendererType::WebGpu);
1359        let update = opts.apply_patch(&patch, &OptionCapabilityProfile::minimal(), "g1");
1360        assert!(!update.applied);
1361        assert!(matches!(
1362            update.errors[0],
1363            RuntimeOptionError::CapabilityGated {
1364                detail: GatingDetail::RendererUnsupported { .. },
1365                ..
1366            }
1367        ));
1368        assert_eq!(opts, before);
1369    }
1370
1371    #[test]
1372    fn scrollback_gated_by_host_budget() {
1373        let mut opts = RuntimeOptions::default();
1374        let caps = OptionCapabilityProfile::minimal(); // budget 10_000
1375        let patch = RuntimeOptionPatch::new().with_scrollback_lines(50_000);
1376        let update = opts.apply_patch(&patch, &caps, "g2");
1377        assert!(!update.applied);
1378        assert!(matches!(
1379            update.errors[0],
1380            RuntimeOptionError::CapabilityGated {
1381                detail: GatingDetail::ScrollbackBudgetExceeded { .. },
1382                ..
1383            }
1384        ));
1385    }
1386
1387    #[test]
1388    fn same_renderer_under_minimal_caps_is_ok() {
1389        let mut opts = RuntimeOptions::default();
1390        let patch = RuntimeOptionPatch::new().with_renderer(RendererType::Dom);
1391        let update = opts.apply_patch(&patch, &OptionCapabilityProfile::minimal(), "g3");
1392        assert!(update.applied);
1393    }
1394
1395    // ── Determinism & serialisation ─────────────────────────────────────────
1396
1397    #[test]
1398    fn apply_is_deterministic() {
1399        let patch = RuntimeOptionPatch::new()
1400            .with_cursor_style(CursorStyle::Underline)
1401            .with_renderer(RendererType::WebGl);
1402        let caps = OptionCapabilityProfile::full();
1403        let mut a = RuntimeOptions::default();
1404        let mut b = RuntimeOptions::default();
1405        let ua = a.apply_patch(&patch, &caps, "det");
1406        let ub = b.apply_patch(&patch, &caps, "det");
1407        assert_eq!(ua, ub);
1408        assert_eq!(a, b);
1409        assert_eq!(ua.to_jsonl(), ub.to_jsonl());
1410    }
1411
1412    #[test]
1413    fn update_jsonl_is_single_line_and_complete() {
1414        let mut opts = RuntimeOptions::default();
1415        let patch = RuntimeOptionPatch::new().with_cursor_style(CursorStyle::Bar);
1416        let line = opts
1417            .apply_patch(&patch, &OptionCapabilityProfile::full(), "j1")
1418            .to_jsonl();
1419        assert!(line.starts_with('{') && line.ends_with('}'));
1420        assert!(!line.contains('\n'));
1421        assert!(line.contains("\"event\":\"runtime_option_update\""));
1422        assert!(line.contains("\"correlation_id\":\"j1\""));
1423        assert!(line.contains("\"applied\":true"));
1424        assert!(line.contains("\"field\":\"cursor_style\""));
1425        assert!(line.contains("\"old\":\"block\""));
1426        assert!(line.contains("\"new\":\"bar\""));
1427    }
1428
1429    #[test]
1430    fn rejected_update_jsonl_carries_errors() {
1431        let mut opts = RuntimeOptions::default();
1432        let patch = RuntimeOptionPatch::new().with_renderer(RendererType::WebGpu);
1433        let line = opts
1434            .apply_patch(&patch, &OptionCapabilityProfile::minimal(), "j2")
1435            .to_jsonl();
1436        assert!(line.contains("\"applied\":false"));
1437        assert!(line.contains("\"error_count\":1"));
1438        assert!(line.contains("\"kind\":\"capability_gated\""));
1439        assert!(line.contains("\"field\":\"renderer\""));
1440    }
1441
1442    #[test]
1443    fn snapshot_jsonl_round_trips_key_fields() {
1444        let opts = RuntimeOptions::default();
1445        let line = opts.to_jsonl("snap");
1446        assert!(line.contains("\"cursor_style\":\"block\""));
1447        assert!(line.contains("\"renderer\":\"dom\""));
1448        assert!(line.contains("\"scrollback_lines\":1000"));
1449        assert!(line.contains("\"theme_background\":\"#000000ff\""));
1450    }
1451
1452    #[test]
1453    fn web_dataset_keys_are_stable() {
1454        let opts = RuntimeOptions::default();
1455        let ds = opts.web_dataset();
1456        assert_eq!(
1457            ds.clone().map(|(k, _)| k),
1458            [
1459                "data-ftui-cursor-style",
1460                "data-ftui-renderer",
1461                "data-ftui-screen-reader",
1462            ]
1463        );
1464        assert_eq!(ds[0].1, "block");
1465    }
1466
1467    // ── Token & colour helpers ──────────────────────────────────────────────
1468
1469    #[test]
1470    fn cursor_and_renderer_token_round_trip() {
1471        for s in [CursorStyle::Block, CursorStyle::Underline, CursorStyle::Bar] {
1472            assert_eq!(CursorStyle::from_token(s.as_token()), Some(s));
1473        }
1474        for r in [
1475            RendererType::Dom,
1476            RendererType::Canvas,
1477            RendererType::WebGl,
1478            RendererType::WebGpu,
1479        ] {
1480            assert_eq!(RendererType::from_token(r.as_token()), Some(r));
1481        }
1482        assert_eq!(CursorStyle::from_token("nope"), None);
1483        assert_eq!(RendererType::from_token("nope"), None);
1484    }
1485
1486    #[test]
1487    fn theme_color_hex_round_trips() {
1488        let c = ThemeColor::rgba(0x12, 0x34, 0x56, 0x78);
1489        assert_eq!(c.as_hex(), "#12345678");
1490        assert_eq!(ThemeColor::from_hex("#12345678"), Some(c));
1491        // 6-digit form implies opaque.
1492        assert_eq!(
1493            ThemeColor::from_hex("#abcdef"),
1494            Some(ThemeColor::rgb(0xAB, 0xCD, 0xEF))
1495        );
1496        assert_eq!(ThemeColor::from_hex("zzz"), None);
1497        assert_eq!(ThemeColor::from_hex("#12"), None);
1498    }
1499
1500    #[test]
1501    fn jsonl_escapes_correlation_id() {
1502        let mut opts = RuntimeOptions::default();
1503        let update = opts.apply_patch(
1504            &RuntimeOptionPatch::new(),
1505            &OptionCapabilityProfile::full(),
1506            "a\"b\\c",
1507        );
1508        let line = update.to_jsonl();
1509        assert!(line.contains(r#""correlation_id":"a\"b\\c""#));
1510    }
1511
1512    // ── JSON patch parsing (feature-gated) ──────────────────────────────────
1513
1514    #[cfg(feature = "input-parser")]
1515    mod json {
1516        use super::*;
1517
1518        #[test]
1519        fn parses_full_patch() {
1520            let json = r##"{
1521                "cursorStyle":"bar","cursorBlink":true,"scrollback":5000,
1522                "tabStopWidth":4,"convertEol":true,"screenReaderMode":true,
1523                "bracketedPaste":false,"minimumContrastRatioX100":450,
1524                "rendererType":"webgpu",
1525                "theme":{"foreground":"#c0c0c0","background":"#101010","ansi3":"#ffcc00"}
1526            }"##;
1527            let patch = RuntimeOptionPatch::parse_json(json).expect("valid patch");
1528            assert_eq!(patch.cursor_style, Some(CursorStyle::Bar));
1529            assert_eq!(patch.scrollback_lines, Some(5000));
1530            assert_eq!(patch.tab_width, Some(4));
1531            assert_eq!(patch.renderer, Some(RendererType::WebGpu));
1532            let theme = patch.theme.expect("theme present");
1533            assert_eq!(theme.background, ThemeColor::rgb(0x10, 0x10, 0x10));
1534            assert_eq!(theme.ansi[3], ThemeColor::rgb(0xFF, 0xCC, 0x00));
1535        }
1536
1537        #[test]
1538        fn parse_then_apply_end_to_end() {
1539            let mut opts = RuntimeOptions::default();
1540            let patch = RuntimeOptionPatch::parse_json(r#"{"cursorStyle":"underline"}"#).unwrap();
1541            let update = opts.apply_patch(&patch, &OptionCapabilityProfile::full(), "e2e");
1542            assert!(update.applied);
1543            assert_eq!(opts.cursor_style, CursorStyle::Underline);
1544        }
1545
1546        #[test]
1547        fn malformed_json_is_actionable() {
1548            let err = RuntimeOptionPatch::parse_json(r#"{"cursorStyle":"#).unwrap_err();
1549            assert!(matches!(err, OptionPatchParseError::MalformedJson(_)));
1550            assert!(err.to_string().contains("malformed"));
1551        }
1552
1553        #[test]
1554        fn unknown_key_rejected() {
1555            let err = RuntimeOptionPatch::parse_json(r#"{"bogusKey":1}"#).unwrap_err();
1556            assert_eq!(
1557                err,
1558                OptionPatchParseError::UnknownKey("bogusKey".to_owned())
1559            );
1560        }
1561
1562        #[test]
1563        fn type_mismatch_rejected() {
1564            let err = RuntimeOptionPatch::parse_json(r#"{"scrollback":"lots"}"#).unwrap_err();
1565            assert!(matches!(err, OptionPatchParseError::TypeMismatch { .. }));
1566        }
1567
1568        #[test]
1569        fn invalid_enum_token_rejected() {
1570            let err = RuntimeOptionPatch::parse_json(r#"{"rendererType":"crayon"}"#).unwrap_err();
1571            assert!(matches!(
1572                err,
1573                OptionPatchParseError::InvalidToken { ref token, .. } if token == "crayon"
1574            ));
1575        }
1576
1577        #[test]
1578        fn unknown_theme_slot_rejected() {
1579            let err =
1580                RuntimeOptionPatch::parse_json(r##"{"theme":{"sparkle":"#fff"}}"##).unwrap_err();
1581            assert!(
1582                matches!(err, OptionPatchParseError::UnknownKey(ref k) if k == "theme.sparkle")
1583            );
1584        }
1585
1586        #[test]
1587        fn absurd_scrollback_saturates_then_range_rejects() {
1588            // 9e18 overflows u32 → saturates to u32::MAX at parse, then the
1589            // hard-max range check rejects it at apply time (not a parse panic).
1590            let patch =
1591                RuntimeOptionPatch::parse_json(r#"{"scrollback":9000000000000000000}"#).unwrap();
1592            assert_eq!(patch.scrollback_lines, Some(u32::MAX));
1593            let mut opts = RuntimeOptions::default();
1594            let update = opts.apply_patch(&patch, &OptionCapabilityProfile::full(), "sat");
1595            assert!(!update.applied);
1596            assert_eq!(update.errors[0].field(), FIELD_SCROLLBACK);
1597        }
1598    }
1599}