Skip to main content

ftui_widgets/
error_boundary.rs

1#![forbid(unsafe_code)]
2
3//! Widget error boundaries with panic recovery.
4//!
5//! Wraps any widget in a safety boundary that catches panics during rendering
6//! and displays a fallback error indicator instead of crashing the application.
7
8use std::panic::{AssertUnwindSafe, catch_unwind};
9use web_time::Instant;
10
11use ftui_core::geometry::Rect;
12use ftui_core::with_panic_cleanup_suppressed;
13use ftui_render::cell::{Cell, PackedRgba};
14use ftui_render::frame::Frame;
15use ftui_style::Style;
16use ftui_text::{display_width, grapheme_width};
17use unicode_segmentation::UnicodeSegmentation;
18
19use crate::{StatefulWidget, Widget, apply_style, draw_text_span, set_style_area};
20
21/// Captured error from a widget panic.
22#[derive(Debug, Clone)]
23pub struct CapturedError {
24    /// Error message extracted from the panic payload.
25    pub message: String,
26    /// Name of the widget that panicked.
27    pub widget_name: &'static str,
28    /// Area the widget was rendering into.
29    pub area: Rect,
30    /// When the error was captured.
31    pub timestamp: Instant,
32}
33
34impl CapturedError {
35    fn from_panic(
36        payload: Box<dyn std::any::Any + Send>,
37        widget_name: &'static str,
38        area: Rect,
39    ) -> Self {
40        let mut message = if let Some(s) = payload.downcast_ref::<&str>() {
41            (*s).to_string()
42        } else if let Some(s) = payload.downcast_ref::<String>() {
43            s.clone()
44        } else {
45            "unknown panic".to_string()
46        };
47        if let Some(stripped) = message.strip_prefix("internal error: entered unreachable code: ") {
48            message = stripped.to_string();
49        }
50
51        Self {
52            message,
53            widget_name,
54            area,
55            timestamp: Instant::now(),
56        }
57    }
58}
59
60/// State for an error boundary.
61///
62/// A panic moves `Healthy` to `Recovering`: the fallback is drawn and the
63/// boundary retries the widget on the next render. Each retry that panics
64/// again counts one attempt; once `max_recovery_attempts` retries have
65/// failed the state is `Failed`, which shows the fallback without calling
66/// the widget until [`reset`](Self::reset) or [`try_recover`](Self::try_recover).
67/// A retry that renders cleanly returns to `Healthy`.
68#[derive(Debug, Clone, Default)]
69pub enum ErrorBoundaryState {
70    /// Widget is rendering normally.
71    #[default]
72    Healthy,
73    /// Retries are exhausted (or disabled): the fallback is shown and the
74    /// widget is no longer called.
75    Failed(CapturedError),
76    /// The widget panicked; the fallback is shown and the next render
77    /// retries it.
78    Recovering {
79        /// Retries scheduled so far, including the pending one; never more
80        /// than the boundary's `max_recovery_attempts`.
81        attempts: u32,
82        /// The most recent panic.
83        last_error: CapturedError,
84    },
85}
86
87impl ErrorBoundaryState {
88    /// Returns the current error, if any.
89    #[must_use = "use the returned error for diagnostics"]
90    pub fn error(&self) -> Option<&CapturedError> {
91        match self {
92            Self::Healthy => None,
93            Self::Failed(e) => Some(e),
94            Self::Recovering { last_error, .. } => Some(last_error),
95        }
96    }
97
98    /// Returns true if in a failed or recovering state.
99    pub fn is_failed(&self) -> bool {
100        !matches!(self, Self::Healthy)
101    }
102
103    /// Reset to healthy state.
104    pub fn reset(&mut self) {
105        *self = Self::Healthy;
106    }
107
108    /// Attempt recovery. Returns true if recovery attempt was initiated.
109    pub fn try_recover(&mut self, max_attempts: u32) -> bool {
110        match self {
111            Self::Failed(error) => {
112                if max_attempts > 0 {
113                    *self = Self::Recovering {
114                        attempts: 1,
115                        last_error: error.clone(),
116                    };
117                    true
118                } else {
119                    false
120                }
121            }
122            Self::Recovering {
123                attempts,
124                last_error,
125            } => {
126                if *attempts < max_attempts {
127                    *attempts += 1;
128                    true
129                } else {
130                    *self = Self::Failed(last_error.clone());
131                    false
132                }
133            }
134            Self::Healthy => true,
135        }
136    }
137
138    /// The state after the wrapped widget panicked with `error`: schedule a
139    /// retry while fewer than `max_attempts` have been made, else give up.
140    fn after_panic(&self, error: CapturedError, max_attempts: u32) -> Self {
141        match *self {
142            Self::Healthy if max_attempts > 0 => Self::Recovering {
143                attempts: 1,
144                last_error: error,
145            },
146            Self::Recovering { attempts, .. } if attempts < max_attempts => Self::Recovering {
147                attempts: attempts + 1,
148                last_error: error,
149            },
150            _ => Self::Failed(error),
151        }
152    }
153}
154
155/// A widget wrapper that catches panics from an inner widget.
156///
157/// When the inner widget panics during rendering, the error boundary
158/// captures the panic and renders a fallback error indicator instead.
159///
160/// Uses `StatefulWidget` so the error state persists across renders.
161///
162/// # Example
163///
164/// ```ignore
165/// let boundary = ErrorBoundary::new(my_widget, "my_widget");
166/// let mut state = ErrorBoundaryState::default();
167/// boundary.render(area, &mut buf, &mut state);
168/// ```
169#[derive(Debug, Clone)]
170pub struct ErrorBoundary<W> {
171    inner: W,
172    widget_name: &'static str,
173    max_recovery_attempts: u32,
174}
175
176impl<W: Widget> ErrorBoundary<W> {
177    /// Create a new error boundary wrapping the given widget.
178    pub fn new(inner: W, widget_name: &'static str) -> Self {
179        Self {
180            inner,
181            widget_name,
182            max_recovery_attempts: 3,
183        }
184    }
185
186    /// Set how many times the boundary retries a panicking widget, one retry
187    /// per render, before showing the fallback permanently (default 3; 0
188    /// disables retries).
189    #[must_use]
190    pub fn max_recovery_attempts(mut self, max: u32) -> Self {
191        self.max_recovery_attempts = max;
192        self
193    }
194
195    /// The configured retry cap, for an app driving
196    /// [`ErrorBoundaryState::try_recover`] itself (e.g. a "Press R" handler).
197    #[must_use]
198    pub fn recovery_attempts_limit(&self) -> u32 {
199        self.max_recovery_attempts
200    }
201
202    /// Get the widget name.
203    pub fn widget_name(&self) -> &'static str {
204        self.widget_name
205    }
206}
207
208impl<W: Widget> StatefulWidget for ErrorBoundary<W> {
209    type State = ErrorBoundaryState;
210
211    fn render(&self, area: Rect, frame: &mut Frame, state: &mut ErrorBoundaryState) {
212        #[cfg(feature = "tracing")]
213        let _span = tracing::debug_span!(
214            "widget_render",
215            widget = "ErrorBoundary",
216            x = area.x,
217            y = area.y,
218            w = area.width,
219            h = area.height
220        )
221        .entered();
222
223        if area.is_empty() {
224            return;
225        }
226
227        match state {
228            ErrorBoundaryState::Healthy | ErrorBoundaryState::Recovering { .. } => {
229                let result = with_panic_cleanup_suppressed(|| {
230                    catch_unwind(AssertUnwindSafe(|| {
231                        self.inner.render(area, frame);
232                    }))
233                });
234
235                match result {
236                    Ok(()) => {
237                        if matches!(state, ErrorBoundaryState::Recovering { .. }) {
238                            *state = ErrorBoundaryState::Healthy;
239                        }
240                    }
241                    Err(payload) => {
242                        let error = CapturedError::from_panic(payload, self.widget_name, area);
243                        clear_area(frame, area);
244                        render_error_fallback(frame, area, &error);
245                        *state = state.after_panic(error, self.max_recovery_attempts);
246                    }
247                }
248            }
249            ErrorBoundaryState::Failed(error) => {
250                render_error_fallback(frame, area, error);
251            }
252        }
253    }
254}
255
256/// Clear an area of the buffer to spaces.
257fn clear_area(frame: &mut Frame, area: Rect) {
258    let blank = Cell::from_char(' ');
259    for y in area.y..area.y.saturating_add(area.height) {
260        for x in area.x..area.x.saturating_add(area.width) {
261            frame.buffer.set_fast(x, y, blank);
262        }
263    }
264}
265
266/// Render a fallback error indicator in the given area.
267fn render_error_fallback(frame: &mut Frame, area: Rect, error: &CapturedError) {
268    let error_fg = PackedRgba::rgb(255, 60, 60);
269    let error_bg = PackedRgba::rgb(40, 0, 0);
270    let error_style = Style::new().fg(error_fg).bg(error_bg);
271    let border_style = Style::new().fg(error_fg);
272
273    // The fallback owns the full area. Clear any stale glyphs first so the
274    // error panel fully replaces prior widget content on re-render.
275    clear_area(frame, area);
276    set_style_area(&mut frame.buffer, area, Style::new().bg(error_bg));
277
278    if area.width < 3 || area.height < 1 {
279        // Too small for border, just show "!"
280        if area.width >= 1 && area.height >= 1 {
281            let mut cell = Cell::from_char('!');
282            apply_style(&mut cell, error_style);
283            frame.buffer.set_fast(area.x, area.y, cell);
284        }
285        return;
286    }
287
288    let top = area.y;
289    let bottom = area.y.saturating_add(area.height).saturating_sub(1);
290    let left = area.x;
291    let right = area.x.saturating_add(area.width).saturating_sub(1);
292
293    // Top border
294    for x in left..=right {
295        let c = if x == left && area.height > 1 {
296            '┌'
297        } else if x == right && area.height > 1 {
298            '┐'
299        } else {
300            '─'
301        };
302        let mut cell = Cell::from_char(c);
303        apply_style(&mut cell, border_style);
304        frame.buffer.set_fast(x, top, cell);
305    }
306
307    // Bottom border
308    if area.height > 1 {
309        for x in left..=right {
310            let c = if x == left {
311                '└'
312            } else if x == right {
313                '┘'
314            } else {
315                '─'
316            };
317            let mut cell = Cell::from_char(c);
318            apply_style(&mut cell, border_style);
319            frame.buffer.set_fast(x, bottom, cell);
320        }
321    }
322
323    // Side borders
324    if area.height > 2 {
325        for y in (top + 1)..bottom {
326            let mut cell_l = Cell::from_char('│');
327            apply_style(&mut cell_l, border_style);
328            frame.buffer.set_fast(left, y, cell_l);
329
330            let mut cell_r = Cell::from_char('│');
331            apply_style(&mut cell_r, border_style);
332            frame.buffer.set_fast(right, y, cell_r);
333        }
334    }
335
336    // Title "[Error]" on top border
337    if area.width >= 9 {
338        let title_x = left.saturating_add(1);
339        draw_text_span(frame, title_x, top, "[Error]", border_style, right);
340    }
341
342    // Error message inside
343    if area.height >= 3 && area.width >= 5 {
344        let inner_left = left.saturating_add(2);
345        let inner_right = right;
346        let inner_y = top.saturating_add(1);
347        let max_chars = (inner_right.saturating_sub(inner_left)) as usize;
348
349        let msg: String = if display_width(error.message.as_str()) > max_chars.saturating_sub(2) {
350            let mut truncated = String::new();
351            let mut w = 0;
352            let limit = max_chars.saturating_sub(3);
353            for grapheme in error.message.graphemes(true) {
354                let gw = grapheme_width(grapheme);
355                if w + gw > limit {
356                    break;
357                }
358                truncated.push_str(grapheme);
359                w += gw;
360            }
361            format!("! {truncated}\u{2026}")
362        } else {
363            format!("! {}", error.message)
364        };
365
366        draw_text_span(frame, inner_left, inner_y, &msg, error_style, inner_right);
367
368        // Widget name on next line if space
369        if area.height >= 4 {
370            let name_msg = format!("  in: {}", error.widget_name);
371            let name_style = Style::new().fg(PackedRgba::rgb(180, 180, 180)).bg(error_bg);
372            draw_text_span(
373                frame,
374                inner_left,
375                inner_y.saturating_add(1),
376                &name_msg,
377                name_style,
378                inner_right,
379            );
380        }
381
382        // Retry hint on next available line
383        if area.height >= 5 {
384            let hint_style = Style::new().fg(PackedRgba::rgb(120, 120, 120)).bg(error_bg);
385            draw_text_span(
386                frame,
387                inner_left,
388                inner_y.saturating_add(2),
389                "  Press R to retry",
390                hint_style,
391                inner_right,
392            );
393        }
394    }
395}
396
397/// A standalone fallback widget for rendering error indicators.
398///
399/// Can be used independently of `ErrorBoundary` when you need to
400/// display an error state in a widget area.
401#[derive(Debug, Clone)]
402pub struct FallbackWidget {
403    error: CapturedError,
404    show_retry_hint: bool,
405}
406
407impl FallbackWidget {
408    /// Create a new fallback widget for the given error.
409    pub fn new(error: CapturedError) -> Self {
410        Self {
411            error,
412            show_retry_hint: true,
413        }
414    }
415
416    /// Create a fallback with a simple message and widget name.
417    pub fn from_message(message: impl Into<String>, widget_name: &'static str) -> Self {
418        Self::new(CapturedError {
419            message: message.into(),
420            widget_name,
421            area: Rect::default(),
422            timestamp: Instant::now(),
423        })
424    }
425
426    /// Disable the retry hint.
427    #[must_use]
428    pub fn without_retry_hint(mut self) -> Self {
429        self.show_retry_hint = false;
430        self
431    }
432}
433
434impl Widget for FallbackWidget {
435    fn render(&self, area: Rect, frame: &mut Frame) {
436        #[cfg(feature = "tracing")]
437        let _span = tracing::debug_span!(
438            "widget_render",
439            widget = "FallbackWidget",
440            x = area.x,
441            y = area.y,
442            w = area.width,
443            h = area.height
444        )
445        .entered();
446
447        if area.is_empty() {
448            return;
449        }
450        render_error_fallback(frame, area, &self.error);
451
452        // If retry hint is disabled, overwrite it with background
453        if !self.show_retry_hint && area.height >= 5 {
454            let error_bg = PackedRgba::rgb(40, 0, 0);
455            let bg_style = Style::new().bg(error_bg);
456            let inner_y = area.y.saturating_add(3);
457            let inner_left = area.x.saturating_add(2);
458            let inner_right = area.x.saturating_add(area.width).saturating_sub(1);
459            // Clear the retry hint line
460            for x in inner_left..inner_right {
461                let mut cell = Cell::new(ftui_render::cell::CellContent::from_char(' '));
462                crate::apply_style(&mut cell, bg_style);
463                frame.buffer.set_fast(x, inner_y, cell);
464            }
465        }
466    }
467}
468
469/// Type alias for custom fallback factory functions.
470pub type FallbackFactory = Box<dyn Fn(&CapturedError) -> FallbackWidget + Send + Sync>;
471
472/// A widget wrapper with custom fallback support.
473///
474/// Like `ErrorBoundary`, but accepts a custom factory for producing
475/// fallback widgets when the inner widget panics.
476pub struct CustomErrorBoundary<W> {
477    inner: W,
478    widget_name: &'static str,
479    max_recovery_attempts: u32,
480    fallback_factory: Option<FallbackFactory>,
481}
482
483impl<W: Widget> CustomErrorBoundary<W> {
484    /// Create with a custom fallback factory.
485    pub fn new(inner: W, widget_name: &'static str) -> Self {
486        Self {
487            inner,
488            widget_name,
489            max_recovery_attempts: 3,
490            fallback_factory: None,
491        }
492    }
493
494    /// Set the fallback factory.
495    #[must_use]
496    pub fn fallback_factory(
497        mut self,
498        factory: impl Fn(&CapturedError) -> FallbackWidget + Send + Sync + 'static,
499    ) -> Self {
500        self.fallback_factory = Some(Box::new(factory));
501        self
502    }
503
504    /// Set how many times the boundary retries a panicking widget before
505    /// showing the fallback permanently; see [`ErrorBoundary::max_recovery_attempts`].
506    #[must_use]
507    pub fn max_recovery_attempts(mut self, max: u32) -> Self {
508        self.max_recovery_attempts = max;
509        self
510    }
511
512    /// The configured retry cap; see [`ErrorBoundary::recovery_attempts_limit`].
513    #[must_use]
514    pub fn recovery_attempts_limit(&self) -> u32 {
515        self.max_recovery_attempts
516    }
517}
518
519impl<W: Widget> StatefulWidget for CustomErrorBoundary<W> {
520    type State = ErrorBoundaryState;
521
522    fn render(&self, area: Rect, frame: &mut Frame, state: &mut ErrorBoundaryState) {
523        #[cfg(feature = "tracing")]
524        let _span = tracing::debug_span!(
525            "widget_render",
526            widget = "CustomErrorBoundary",
527            x = area.x,
528            y = area.y,
529            w = area.width,
530            h = area.height
531        )
532        .entered();
533
534        if area.is_empty() {
535            return;
536        }
537
538        match state {
539            ErrorBoundaryState::Healthy | ErrorBoundaryState::Recovering { .. } => {
540                let result = with_panic_cleanup_suppressed(|| {
541                    catch_unwind(AssertUnwindSafe(|| {
542                        self.inner.render(area, frame);
543                    }))
544                });
545
546                match result {
547                    Ok(()) => {
548                        if matches!(state, ErrorBoundaryState::Recovering { .. }) {
549                            *state = ErrorBoundaryState::Healthy;
550                        }
551                    }
552                    Err(payload) => {
553                        let error = CapturedError::from_panic(payload, self.widget_name, area);
554                        clear_area(frame, area);
555                        if let Some(factory) = &self.fallback_factory {
556                            let fallback = factory(&error);
557                            fallback.render(area, frame);
558                        } else {
559                            render_error_fallback(frame, area, &error);
560                        }
561                        *state = state.after_panic(error, self.max_recovery_attempts);
562                    }
563                }
564            }
565            ErrorBoundaryState::Failed(error) => {
566                if let Some(factory) = &self.fallback_factory {
567                    let fallback = factory(error);
568                    fallback.render(area, frame);
569                } else {
570                    render_error_fallback(frame, area, error);
571                }
572            }
573        }
574    }
575}
576
577#[cfg(test)]
578mod tests {
579    use super::*;
580    use ftui_render::grapheme_pool::GraphemePool;
581
582    struct PanickingWidget;
583
584    impl Widget for PanickingWidget {
585        fn render(&self, _area: Rect, _frame: &mut Frame) {
586            unreachable!("widget exploded");
587        }
588    }
589
590    struct GoodWidget;
591
592    impl Widget for GoodWidget {
593        fn render(&self, area: Rect, frame: &mut Frame) {
594            if area.width > 0 && area.height > 0 {
595                frame.buffer.set(area.x, area.y, Cell::from_char('G'));
596            }
597        }
598    }
599
600    #[test]
601    fn healthy_widget_renders_normally() {
602        let boundary = ErrorBoundary::new(GoodWidget, "good");
603        let mut state = ErrorBoundaryState::default();
604        let area = Rect::new(0, 0, 10, 5);
605        let mut pool = GraphemePool::new();
606        let mut frame = Frame::new(10, 5, &mut pool);
607
608        boundary.render(area, &mut frame, &mut state);
609
610        assert!(!state.is_failed());
611        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('G'));
612    }
613
614    #[test]
615    fn catches_panic_without_propagating() {
616        let boundary = ErrorBoundary::new(PanickingWidget, "panicker");
617        let mut state = ErrorBoundaryState::default();
618        let area = Rect::new(0, 0, 30, 5);
619        let mut pool = GraphemePool::new();
620        let mut frame = Frame::new(30, 5, &mut pool);
621
622        boundary.render(area, &mut frame, &mut state);
623
624        assert!(state.is_failed());
625        let err = state.error().unwrap();
626        assert_eq!(err.message, "widget exploded");
627        assert_eq!(err.widget_name, "panicker");
628    }
629
630    #[test]
631    fn failed_state_shows_fallback_on_rerender() {
632        let boundary = ErrorBoundary::new(PanickingWidget, "panicker");
633        let mut state = ErrorBoundaryState::default();
634        let area = Rect::new(0, 0, 30, 5);
635        let mut pool = GraphemePool::new();
636        let mut frame = Frame::new(30, 5, &mut pool);
637
638        boundary.render(area, &mut frame, &mut state);
639
640        // Second render shows fallback without re-trying
641        let mut pool2 = GraphemePool::new();
642        let mut frame2 = Frame::new(30, 5, &mut pool2);
643        boundary.render(area, &mut frame2, &mut state);
644
645        assert!(state.is_failed());
646        assert_eq!(
647            frame2.buffer.get(0, 0).unwrap().content.as_char(),
648            Some('┌')
649        );
650    }
651
652    #[test]
653    fn recovery_resets_on_success() {
654        let good = ErrorBoundary::new(GoodWidget, "good");
655        let mut state = ErrorBoundaryState::Failed(CapturedError {
656            message: "old error".to_string(),
657            widget_name: "old",
658            area: Rect::new(0, 0, 10, 5),
659            timestamp: Instant::now(),
660        });
661
662        assert!(state.try_recover(3));
663        assert!(matches!(state, ErrorBoundaryState::Recovering { .. }));
664
665        let area = Rect::new(0, 0, 10, 5);
666        let mut pool = GraphemePool::new();
667        let mut frame = Frame::new(10, 5, &mut pool);
668        good.render(area, &mut frame, &mut state);
669
670        assert!(!state.is_failed());
671        assert!(matches!(state, ErrorBoundaryState::Healthy));
672    }
673
674    #[test]
675    fn recovery_respects_max_attempts() {
676        let mut state = ErrorBoundaryState::Failed(CapturedError {
677            message: "error".to_string(),
678            widget_name: "w",
679            area: Rect::new(0, 0, 1, 1),
680            timestamp: Instant::now(),
681        });
682
683        assert!(state.try_recover(2));
684        assert!(matches!(
685            state,
686            ErrorBoundaryState::Recovering { attempts: 1, .. }
687        ));
688
689        assert!(state.try_recover(2));
690        assert!(matches!(
691            state,
692            ErrorBoundaryState::Recovering { attempts: 2, .. }
693        ));
694
695        assert!(!state.try_recover(2));
696        assert!(matches!(state, ErrorBoundaryState::Failed(_)));
697    }
698
699    #[test]
700    fn zero_max_recovery_denies_immediately() {
701        let mut state = ErrorBoundaryState::Failed(CapturedError {
702            message: "error".to_string(),
703            widget_name: "w",
704            area: Rect::new(0, 0, 1, 1),
705            timestamp: Instant::now(),
706        });
707
708        assert!(!state.try_recover(0));
709        assert!(matches!(state, ErrorBoundaryState::Failed(_)));
710    }
711
712    #[test]
713    fn reset_clears_error() {
714        let mut state = ErrorBoundaryState::Failed(CapturedError {
715            message: "error".to_string(),
716            widget_name: "w",
717            area: Rect::new(0, 0, 1, 1),
718            timestamp: Instant::now(),
719        });
720
721        state.reset();
722        assert!(!state.is_failed());
723        assert!(matches!(state, ErrorBoundaryState::Healthy));
724    }
725
726    #[test]
727    fn empty_area_is_noop() {
728        let boundary = ErrorBoundary::new(PanickingWidget, "panicker");
729        let mut state = ErrorBoundaryState::default();
730        let area = Rect::new(0, 0, 0, 0);
731        let mut pool = GraphemePool::new();
732        let mut frame = Frame::new(1, 1, &mut pool);
733
734        boundary.render(area, &mut frame, &mut state);
735
736        assert!(!state.is_failed());
737    }
738
739    #[test]
740    fn small_area_shows_minimal_fallback() {
741        let boundary = ErrorBoundary::new(PanickingWidget, "panicker");
742        let mut state = ErrorBoundaryState::default();
743        let area = Rect::new(0, 0, 2, 1);
744        let mut pool = GraphemePool::new();
745        let mut frame = Frame::new(2, 1, &mut pool);
746
747        boundary.render(area, &mut frame, &mut state);
748
749        assert!(state.is_failed());
750        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('!'));
751    }
752
753    #[test]
754    fn captured_error_extracts_string_panic() {
755        let payload: Box<dyn std::any::Any + Send> = Box::new("test error".to_string());
756        let error = CapturedError::from_panic(payload, "test", Rect::new(0, 0, 1, 1));
757        assert_eq!(error.message, "test error");
758    }
759
760    #[test]
761    fn captured_error_extracts_str_panic() {
762        let payload: Box<dyn std::any::Any + Send> = Box::new("static error");
763        let error = CapturedError::from_panic(payload, "test", Rect::new(0, 0, 1, 1));
764        assert_eq!(error.message, "static error");
765    }
766
767    #[test]
768    fn captured_error_handles_unknown_panic() {
769        let payload: Box<dyn std::any::Any + Send> = Box::new(42u32);
770        let error = CapturedError::from_panic(payload, "test", Rect::new(0, 0, 1, 1));
771        assert_eq!(error.message, "unknown panic");
772    }
773
774    #[test]
775    fn failed_state_renders_fallback_directly() {
776        let boundary = ErrorBoundary::new(GoodWidget, "good");
777        let mut state = ErrorBoundaryState::Failed(CapturedError {
778            message: "previous error".to_string(),
779            widget_name: "other",
780            area: Rect::new(0, 0, 30, 5),
781            timestamp: Instant::now(),
782        });
783
784        let area = Rect::new(0, 0, 30, 5);
785        let mut pool = GraphemePool::new();
786        let mut frame = Frame::new(30, 5, &mut pool);
787        boundary.render(area, &mut frame, &mut state);
788
789        assert!(state.is_failed());
790        // Should see border, not 'G'
791        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('┌'));
792    }
793
794    #[test]
795    fn failed_state_rerender_clears_stale_content() {
796        let boundary = ErrorBoundary::new(GoodWidget, "good");
797        let mut state = ErrorBoundaryState::Failed(CapturedError {
798            message: "err".to_string(),
799            widget_name: "other",
800            area: Rect::new(0, 0, 30, 5),
801            timestamp: Instant::now(),
802        });
803
804        let area = Rect::new(0, 0, 30, 5);
805        let mut pool = GraphemePool::new();
806        let mut frame = Frame::new(30, 5, &mut pool);
807        for y in area.y..area.bottom() {
808            for x in area.x..area.right() {
809                frame.buffer.set(x, y, Cell::from_char('X'));
810            }
811        }
812
813        boundary.render(area, &mut frame, &mut state);
814
815        assert_eq!(
816            frame.buffer.get(20, 1).unwrap().content.as_char(),
817            Some(' ')
818        );
819    }
820
821    #[test]
822    fn fallback_widget_renders_standalone() {
823        let fallback = FallbackWidget::from_message("render failed", "my_widget");
824        let area = Rect::new(0, 0, 30, 5);
825        let mut pool = GraphemePool::new();
826        let mut frame = Frame::new(30, 5, &mut pool);
827        fallback.render(area, &mut frame);
828
829        // Should show error border
830        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('┌'));
831    }
832
833    #[test]
834    fn fallback_widget_clears_stale_content() {
835        let fallback = FallbackWidget::from_message("err", "w");
836        let area = Rect::new(0, 0, 30, 5);
837        let mut pool = GraphemePool::new();
838        let mut frame = Frame::new(30, 5, &mut pool);
839        for y in area.y..area.bottom() {
840            for x in area.x..area.right() {
841                frame.buffer.set(x, y, Cell::from_char('X'));
842            }
843        }
844
845        fallback.render(area, &mut frame);
846
847        assert_eq!(
848            frame.buffer.get(20, 1).unwrap().content.as_char(),
849            Some(' ')
850        );
851    }
852
853    #[test]
854    fn fallback_widget_without_retry_hint() {
855        let fallback = FallbackWidget::from_message("error", "w").without_retry_hint();
856        let area = Rect::new(0, 0, 30, 6);
857        let mut pool = GraphemePool::new();
858        let mut frame = Frame::new(30, 6, &mut pool);
859        fallback.render(area, &mut frame);
860
861        // Retry hint line (y=3) should be blank spaces, not text
862        // The hint would be at inner_y + 2 = area.y + 3 = 3
863        let hint_cell = frame.buffer.get(4, 3).unwrap();
864        assert_eq!(hint_cell.content.as_char(), Some(' '));
865    }
866
867    #[test]
868    fn fallback_widget_empty_area() {
869        let fallback = FallbackWidget::from_message("error", "w");
870        let area = Rect::new(0, 0, 0, 0);
871        let mut pool = GraphemePool::new();
872        let mut frame = Frame::new(1, 1, &mut pool);
873        fallback.render(area, &mut frame);
874        // Should not panic
875    }
876
877    #[test]
878    fn custom_error_boundary_uses_factory() {
879        let boundary =
880            CustomErrorBoundary::new(PanickingWidget, "panicker").fallback_factory(|error| {
881                FallbackWidget::from_message(
882                    format!("CUSTOM: {}", error.message),
883                    error.widget_name,
884                )
885                .without_retry_hint()
886            });
887        let mut state = ErrorBoundaryState::default();
888        let area = Rect::new(0, 0, 40, 5);
889        let mut pool = GraphemePool::new();
890        let mut frame = Frame::new(40, 5, &mut pool);
891        boundary.render(area, &mut frame, &mut state);
892
893        assert!(state.is_failed());
894        // Should show the custom error (border should still appear)
895        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('┌'));
896    }
897
898    #[test]
899    fn custom_error_boundary_default_fallback() {
900        let boundary = CustomErrorBoundary::new(PanickingWidget, "panicker");
901        let mut state = ErrorBoundaryState::default();
902        let area = Rect::new(0, 0, 30, 5);
903        let mut pool = GraphemePool::new();
904        let mut frame = Frame::new(30, 5, &mut pool);
905        boundary.render(area, &mut frame, &mut state);
906
907        assert!(state.is_failed());
908        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('┌'));
909    }
910
911    #[test]
912    fn retry_hint_shows_in_tall_area() {
913        let boundary = ErrorBoundary::new(PanickingWidget, "panicker");
914        let mut state = ErrorBoundaryState::default();
915        let area = Rect::new(0, 0, 30, 6);
916        let mut pool = GraphemePool::new();
917        let mut frame = Frame::new(30, 6, &mut pool);
918        boundary.render(area, &mut frame, &mut state);
919
920        assert!(state.is_failed());
921        // Retry hint at inner_y + 2 = 3
922        // The text "Press R to retry" starts at inner_left (x=2) + 2 spaces
923        // "  Press R to retry" -> 'P' at x=4
924        let p_cell = frame.buffer.get(4, 3).unwrap();
925        assert_eq!(p_cell.content.as_char(), Some('P'));
926    }
927
928    #[test]
929    fn error_in_sibling_does_not_affect_other() {
930        let bad = ErrorBoundary::new(PanickingWidget, "bad");
931        let good = ErrorBoundary::new(GoodWidget, "good");
932        let mut bad_state = ErrorBoundaryState::default();
933        let mut good_state = ErrorBoundaryState::default();
934
935        let mut pool = GraphemePool::new();
936        let mut frame = Frame::new(20, 5, &mut pool);
937        let area_a = Rect::new(0, 0, 10, 5);
938        let area_b = Rect::new(10, 0, 10, 5);
939
940        bad.render(area_a, &mut frame, &mut bad_state);
941        good.render(area_b, &mut frame, &mut good_state);
942
943        assert!(bad_state.is_failed());
944        assert!(!good_state.is_failed());
945        assert_eq!(
946            frame.buffer.get(10, 0).unwrap().content.as_char(),
947            Some('G')
948        );
949    }
950
951    #[test]
952    fn max_recovery_attempts_builder() {
953        let boundary = ErrorBoundary::new(GoodWidget, "good").max_recovery_attempts(5);
954        assert_eq!(boundary.max_recovery_attempts, 5);
955    }
956
957    #[test]
958    fn widget_name_accessor() {
959        let boundary = ErrorBoundary::new(GoodWidget, "my_widget");
960        assert_eq!(boundary.widget_name(), "my_widget");
961    }
962
963    #[test]
964    fn error_state_error_accessor_recovering() {
965        let err = CapturedError {
966            message: "fail".to_string(),
967            widget_name: "w",
968            area: Rect::new(0, 0, 1, 1),
969            timestamp: Instant::now(),
970        };
971        let state = ErrorBoundaryState::Recovering {
972            attempts: 2,
973            last_error: err,
974        };
975        assert!(state.is_failed());
976        assert_eq!(state.error().unwrap().message, "fail");
977    }
978
979    #[test]
980    fn try_recover_on_healthy_returns_true() {
981        let mut state = ErrorBoundaryState::Healthy;
982        assert!(state.try_recover(3));
983        assert!(matches!(state, ErrorBoundaryState::Healthy));
984    }
985
986    #[test]
987    fn captured_error_strips_unreachable_prefix() {
988        let msg = "internal error: entered unreachable code: widget exploded";
989        let payload: Box<dyn std::any::Any + Send> = Box::new(msg.to_string());
990        let error = CapturedError::from_panic(payload, "test", Rect::new(0, 0, 1, 1));
991        assert_eq!(error.message, "widget exploded");
992    }
993
994    #[test]
995    fn default_state_is_healthy() {
996        let state = ErrorBoundaryState::default();
997        assert!(!state.is_failed());
998        assert!(state.error().is_none());
999    }
1000
1001    #[test]
1002    fn custom_boundary_max_recovery_builder() {
1003        let boundary = CustomErrorBoundary::new(GoodWidget, "good").max_recovery_attempts(7);
1004        assert_eq!(boundary.max_recovery_attempts, 7);
1005    }
1006
1007    #[test]
1008    fn fallback_widget_new_directly() {
1009        let err = CapturedError {
1010            message: "direct error".to_string(),
1011            widget_name: "direct",
1012            area: Rect::new(0, 0, 10, 5),
1013            timestamp: Instant::now(),
1014        };
1015        let fallback = FallbackWidget::new(err);
1016        assert!(fallback.show_retry_hint);
1017        assert_eq!(fallback.error.message, "direct error");
1018    }
1019
1020    #[test]
1021    fn recovering_state_panics_revert_to_failed() {
1022        let boundary = ErrorBoundary::new(PanickingWidget, "bad");
1023        let err = CapturedError {
1024            message: "initial".to_string(),
1025            widget_name: "bad",
1026            area: Rect::new(0, 0, 30, 5),
1027            timestamp: Instant::now(),
1028        };
1029        let mut state = ErrorBoundaryState::Recovering {
1030            attempts: 1,
1031            last_error: err,
1032        };
1033
1034        let area = Rect::new(0, 0, 30, 5);
1035        let mut pool = GraphemePool::new();
1036        let mut frame = Frame::new(30, 5, &mut pool);
1037        boundary.render(area, &mut frame, &mut state);
1038
1039        // A retry that panics counts an attempt rather than giving up while
1040        // attempts remain (default cap 3).
1041        assert!(matches!(
1042            state,
1043            ErrorBoundaryState::Recovering { attempts: 2, .. }
1044        ));
1045
1046        // At the cap, a panicking retry is final.
1047        let mut state = ErrorBoundaryState::Recovering {
1048            attempts: 3,
1049            last_error: state.error().cloned().expect("error"),
1050        };
1051        boundary.render(area, &mut frame, &mut state);
1052        assert!(matches!(state, ErrorBoundaryState::Failed(_)));
1053    }
1054
1055    // --- bd-382z0: the recovery cap applies ---
1056
1057    /// Panics on every render and counts how often it was called.
1058    struct CountingPanicker(std::cell::Cell<u32>);
1059
1060    impl Widget for CountingPanicker {
1061        fn render(&self, _area: Rect, _frame: &mut Frame) {
1062            self.0.set(self.0.get() + 1);
1063            panic!("still broken");
1064        }
1065    }
1066
1067    fn render_n<B: StatefulWidget<State = ErrorBoundaryState>>(
1068        boundary: &B,
1069        state: &mut ErrorBoundaryState,
1070        n: usize,
1071    ) {
1072        let area = Rect::new(0, 0, 30, 5);
1073        let mut pool = GraphemePool::new();
1074        let mut frame = Frame::new(30, 5, &mut pool);
1075        for _ in 0..n {
1076            boundary.render(area, &mut frame, state);
1077        }
1078    }
1079
1080    #[test]
1081    fn always_panicking_widget_is_retried_max_times_then_given_up() {
1082        // The bead's measurement: with max_recovery_attempts(3) the count used
1083        // to reset on every failed retry, so the cap never applied.
1084        let boundary = ErrorBoundary::new(CountingPanicker(std::cell::Cell::new(0)), "bad")
1085            .max_recovery_attempts(3);
1086        let mut state = ErrorBoundaryState::default();
1087
1088        let mut seen = Vec::new();
1089        for _ in 0..6 {
1090            render_n(&boundary, &mut state, 1);
1091            seen.push(match state {
1092                ErrorBoundaryState::Healthy => "healthy".to_owned(),
1093                ErrorBoundaryState::Recovering { attempts, .. } => {
1094                    format!("recovering({attempts})")
1095                }
1096                ErrorBoundaryState::Failed(_) => "failed".to_owned(),
1097            });
1098        }
1099        assert_eq!(
1100            seen,
1101            [
1102                "recovering(1)",
1103                "recovering(2)",
1104                "recovering(3)",
1105                "failed",
1106                "failed",
1107                "failed"
1108            ]
1109        );
1110        // The original render plus three retries; never called once failed.
1111        assert_eq!(boundary.inner.0.get(), 4);
1112    }
1113
1114    #[test]
1115    fn zero_attempts_fails_on_the_first_panic() {
1116        let boundary = ErrorBoundary::new(CountingPanicker(std::cell::Cell::new(0)), "bad")
1117            .max_recovery_attempts(0);
1118        let mut state = ErrorBoundaryState::default();
1119        render_n(&boundary, &mut state, 3);
1120        assert!(matches!(state, ErrorBoundaryState::Failed(_)));
1121        assert_eq!(boundary.inner.0.get(), 1);
1122    }
1123
1124    #[test]
1125    fn alternating_render_and_try_recover_reaches_the_cap() {
1126        // The cycle the bead observed granting six retries with the count
1127        // stuck at 1: render, then try_recover with the configured cap.
1128        let boundary = ErrorBoundary::new(CountingPanicker(std::cell::Cell::new(0)), "bad")
1129            .max_recovery_attempts(3);
1130        let cap = boundary.recovery_attempts_limit();
1131        let mut state = ErrorBoundaryState::default();
1132        let mut granted = 0;
1133        for _ in 0..6 {
1134            render_n(&boundary, &mut state, 1);
1135            if !state.try_recover(cap) {
1136                break;
1137            }
1138            granted += 1;
1139        }
1140        assert!(matches!(state, ErrorBoundaryState::Failed(_)), "{state:?}");
1141        assert!(
1142            granted < 3,
1143            "the count survives failed retries: {granted} grants"
1144        );
1145        // An explicit try_recover after giving up starts a fresh budget: that
1146        // is the user pressing R, not the boundary retrying on its own.
1147        assert!(state.try_recover(cap));
1148    }
1149
1150    #[test]
1151    fn a_retry_that_renders_cleanly_recovers() {
1152        struct FailsOnce(std::cell::Cell<bool>);
1153        impl Widget for FailsOnce {
1154            fn render(&self, area: Rect, frame: &mut Frame) {
1155                if !self.0.replace(true) {
1156                    panic!("first frame only");
1157                }
1158                frame.buffer.set(area.x, area.y, Cell::from_char('G'));
1159            }
1160        }
1161        let boundary = ErrorBoundary::new(FailsOnce(std::cell::Cell::new(false)), "flaky");
1162        let mut state = ErrorBoundaryState::default();
1163        render_n(&boundary, &mut state, 1);
1164        assert!(matches!(
1165            state,
1166            ErrorBoundaryState::Recovering { attempts: 1, .. }
1167        ));
1168        render_n(&boundary, &mut state, 1);
1169        assert!(matches!(state, ErrorBoundaryState::Healthy));
1170    }
1171
1172    #[test]
1173    fn custom_boundary_applies_the_same_cap() {
1174        let boundary = CustomErrorBoundary::new(CountingPanicker(std::cell::Cell::new(0)), "bad")
1175            .max_recovery_attempts(2);
1176        assert_eq!(boundary.recovery_attempts_limit(), 2);
1177        let mut state = ErrorBoundaryState::default();
1178        render_n(&boundary, &mut state, 5);
1179        assert!(matches!(state, ErrorBoundaryState::Failed(_)));
1180        assert_eq!(boundary.inner.0.get(), 3);
1181    }
1182}