1pub mod launch;
27pub mod patchset;
28pub mod session;
29pub mod tree;
30
31use std::cell::RefCell;
32use std::collections::BTreeMap;
33use std::sync::atomic::{AtomicBool, Ordering};
34use std::sync::OnceLock;
35
36use serde_json::Value;
37use termwright_protocol::client::{ENV_ENDPOINT, ENV_TOKEN};
38use termwright_protocol::{
39 ProbeIdentityKind, ProbeInfo, ProbeInjectionTier, ProbeInstrumentation, ProbeSemanticClass,
40};
41
42pub use termwright_protocol::{Action, Role};
43
44#[derive(Debug, Clone, Default, PartialEq, Eq)]
53pub struct Annotation {
54 pub role: Option<Role>,
56 pub name: Option<String>,
58 pub description: Option<String>,
60 pub test_id: Option<String>,
62 pub extended: BTreeMap<String, Value>,
64 pub actions: Vec<Action>,
66 pub labelled_by: Vec<String>,
68 pub described_by: Vec<String>,
70 pub semantic_key: Option<String>,
72}
73
74impl Annotation {
75 #[must_use]
77 pub fn new() -> Self {
78 Self::default()
79 }
80
81 #[must_use]
83 pub fn role(mut self, role: Role) -> Self {
84 self.role = Some(role);
85 self
86 }
87
88 #[must_use]
90 pub fn name(mut self, name: impl Into<String>) -> Self {
91 self.name = Some(name.into());
92 self
93 }
94
95 #[must_use]
97 pub fn description(mut self, description: impl Into<String>) -> Self {
98 self.description = Some(description.into());
99 self
100 }
101
102 #[must_use]
108 pub fn test_id(mut self, test_id: impl Into<String>) -> Self {
109 self.test_id = Some(test_id.into());
110 self
111 }
112
113 #[must_use]
115 pub fn domain(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
116 self.extended.insert(key.into(), value.into());
117 self
118 }
119
120 #[must_use]
122 pub fn extended(mut self, extended: BTreeMap<String, Value>) -> Self {
123 self.extended = extended;
124 self
125 }
126
127 #[must_use]
132 pub fn action(mut self, action: Action) -> Self {
133 if !self.actions.contains(&action) {
134 self.actions.push(action);
135 }
136 self
137 }
138
139 #[must_use]
141 pub fn labelled_by(mut self, semantic_key: impl Into<String>) -> Self {
142 self.labelled_by.push(semantic_key.into());
143 self
144 }
145
146 #[must_use]
148 pub fn described_by(mut self, semantic_key: impl Into<String>) -> Self {
149 self.described_by.push(semantic_key.into());
150 self
151 }
152
153 #[must_use]
159 pub fn semantic_key(mut self, semantic_key: impl Into<String>) -> Self {
160 self.semantic_key = Some(semantic_key.into());
161 self
162 }
163}
164
165#[derive(Debug, Clone, PartialEq, Eq, Default)]
173pub struct Collection {
174 pub selected: Option<usize>,
176 pub offset: usize,
178 pub item_count: usize,
180 pub items: Vec<String>,
182}
183
184pub const MAX_ITEMS: usize = 200;
191
192#[derive(Debug, Clone, PartialEq, Eq)]
198pub struct RenderCall {
199 pub ordinal: u32,
201 pub parent_ordinal: Option<u32>,
203 pub type_name: &'static str,
204 pub x: u16,
205 pub y: u16,
206 pub width: u16,
207 pub height: u16,
208 pub collection: Option<Collection>,
210 pub annotation: Option<Annotation>,
213}
214
215#[derive(Debug, Default)]
217pub struct FrameBuffer {
218 calls: Vec<RenderCall>,
219}
220
221impl FrameBuffer {
222 #[must_use]
224 pub fn calls(&self) -> &[RenderCall] {
225 &self.calls
226 }
227
228 pub fn clear(&mut self) {
230 self.calls.clear();
231 }
232}
233
234fn instrumented() -> bool {
240 static STATE: OnceLock<bool> = OnceLock::new();
241 *STATE.get_or_init(|| {
242 let named = |key: &str| std::env::var(key).map(|v| !v.is_empty()).unwrap_or(false);
243 named(ENV_ENDPOINT) && named(ENV_TOKEN)
244 })
245}
246
247static DISABLED: AtomicBool = AtomicBool::new(false);
249
250#[derive(Debug, Default)]
251struct FrameContext {
252 buffer: FrameBuffer,
253 annotated_stack: Vec<u32>,
254}
255
256thread_local! {
257 static FRAME_STACK: RefCell<Vec<FrameContext>> = const { RefCell::new(Vec::new()) };
262}
263
264fn with_current_frame<R>(operation: impl FnOnce(&mut FrameContext) -> R) -> Option<R> {
265 FRAME_STACK.with(|stack| {
266 let Ok(mut stack) = stack.try_borrow_mut() else {
267 DISABLED.store(true, Ordering::Release);
268 return None;
269 };
270 stack.last_mut().map(operation)
271 })
272}
273
274pub struct FrameGuard {
276 active: bool,
277}
278
279#[must_use]
281pub fn begin_frame() -> FrameGuard {
282 if !instrumented() || DISABLED.load(Ordering::Relaxed) {
283 return FrameGuard { active: false };
284 }
285 let active = FRAME_STACK.with(|stack| match stack.try_borrow_mut() {
286 Ok(mut stack) => {
287 stack.push(FrameContext::default());
288 true
289 }
290 Err(_) => {
291 DISABLED.store(true, Ordering::Release);
292 false
293 }
294 });
295 FrameGuard { active }
296}
297
298impl Drop for FrameGuard {
299 fn drop(&mut self) {
300 if !self.active {
301 return;
302 }
303 FRAME_STACK.with(|stack| match stack.try_borrow_mut() {
304 Ok(mut stack) => {
305 if stack.pop().is_none() {
306 DISABLED.store(true, Ordering::Release);
307 }
308 }
309 Err(_) => DISABLED.store(true, Ordering::Release),
310 });
311 }
312}
313
314pub fn frame_guard_active() -> bool {
316 FRAME_STACK.with(|stack| {
317 stack
318 .try_borrow()
319 .map(|stack| !stack.is_empty())
320 .unwrap_or(false)
321 })
322}
323
324pub struct AnnotatedRenderGuard {
326 ordinal: Option<u32>,
327}
328
329impl Drop for AnnotatedRenderGuard {
330 fn drop(&mut self) {
331 let Some(expected) = self.ordinal else { return };
332 if with_current_frame(|frame| frame.annotated_stack.pop()) != Some(Some(expected)) {
333 DISABLED.store(true, Ordering::Relaxed);
334 }
335 }
336}
337
338pub fn on_render(type_name: &'static str, x: u16, y: u16, width: u16, height: u16) {
346 if !instrumented() || DISABLED.load(Ordering::Relaxed) {
347 return;
348 }
349 if !frame_guard_active() {
350 return;
351 }
352 let _ = with_current_frame(|frame| {
353 let ordinal = frame.buffer.calls.len() as u32;
354 frame.buffer.calls.push(RenderCall {
355 ordinal,
356 parent_ordinal: None,
357 type_name,
358 x,
359 y,
360 width,
361 height,
362 collection: None,
363 annotation: None,
364 });
365 });
366}
367
368#[must_use]
373pub fn begin_annotated_render(
374 wrapper_type_name: &'static str,
375 widget_type_name: &'static str,
376 annotation: Annotation,
377 x: u16,
378 y: u16,
379 width: u16,
380 height: u16,
381) -> AnnotatedRenderGuard {
382 if !instrumented() || DISABLED.load(Ordering::Relaxed) {
383 return AnnotatedRenderGuard { ordinal: None };
384 }
385 if !frame_guard_active() {
386 return AnnotatedRenderGuard { ordinal: None };
387 }
388 let Some(ordinal) = with_current_frame(|frame| {
389 let parent_ordinal = frame.annotated_stack.last().copied();
390 let ordinal = record_annotated_call(
391 &mut frame.buffer,
392 parent_ordinal,
393 wrapper_type_name,
394 widget_type_name,
395 annotation,
396 x,
397 y,
398 width,
399 height,
400 );
401 frame.annotated_stack.push(ordinal);
402 ordinal
403 }) else {
404 return AnnotatedRenderGuard { ordinal: None };
405 };
406 AnnotatedRenderGuard {
407 ordinal: Some(ordinal),
408 }
409}
410
411#[allow(clippy::too_many_arguments)]
412fn record_annotated_call(
413 frame: &mut FrameBuffer,
414 parent_ordinal: Option<u32>,
415 wrapper_type_name: &'static str,
416 widget_type_name: &'static str,
417 annotation: Annotation,
418 x: u16,
419 y: u16,
420 width: u16,
421 height: u16,
422) -> u32 {
423 let existing = frame.calls.last_mut().filter(|call| {
424 call.type_name == wrapper_type_name
425 && call.annotation.is_none()
426 && call.x == x
427 && call.y == y
428 && call.width == width
429 && call.height == height
430 });
431 if let Some(call) = existing {
432 call.type_name = widget_type_name;
433 call.annotation = Some(annotation);
434 call.parent_ordinal = parent_ordinal;
435 call.ordinal
436 } else {
437 let ordinal = frame.calls.len() as u32;
438 frame.calls.push(RenderCall {
439 ordinal,
440 parent_ordinal,
441 type_name: widget_type_name,
442 x,
443 y,
444 width,
445 height,
446 collection: None,
447 annotation: Some(annotation),
448 });
449 ordinal
450 }
451}
452
453pub fn on_collection(selected: Option<usize>, offset: usize, item_count: usize, items: &[String]) {
463 if !instrumented() || DISABLED.load(Ordering::Relaxed) {
464 return;
465 }
466 if !frame_guard_active() {
467 return;
468 }
469 let _ = with_current_frame(|frame| {
470 let Some(call) = frame.buffer.calls.last_mut() else {
471 return;
475 };
476 call.collection = Some(Collection {
477 selected,
478 offset,
479 item_count,
480 items: items.iter().take(MAX_ITEMS).cloned().collect(),
481 });
482 });
483}
484
485#[must_use]
490pub fn take_frame() -> Vec<RenderCall> {
491 if !instrumented() || DISABLED.load(Ordering::Relaxed) {
492 return Vec::new();
493 }
494 with_current_frame(|frame| std::mem::take(&mut frame.buffer.calls)).unwrap_or_default()
495}
496
497#[must_use]
499pub fn active() -> bool {
500 instrumented() && !DISABLED.load(Ordering::Relaxed)
501}
502
503#[cfg(test)]
504mod tests {
505 use super::*;
506
507 #[test]
510 fn dormant_without_the_environment() {
511 assert!(!active());
514 on_render("Fixture", 0, 0, 1, 1);
515 assert!(take_frame().is_empty());
516 }
517
518 #[test]
519 fn a_render_call_carries_what_the_framework_reported() {
520 let call = RenderCall {
521 ordinal: 0,
522 parent_ordinal: None,
523 type_name: "ratatui_widgets::paragraph::Paragraph<'_>",
524 x: 1,
525 y: 2,
526 width: 3,
527 height: 4,
528 collection: None,
529 annotation: None,
530 };
531 assert_eq!(call.ordinal, 0);
533 assert!(call.type_name.contains("Paragraph"));
534 }
535
536 #[test]
537 fn direct_and_frame_announced_annotations_have_one_truthful_call() {
538 let mut frame = FrameBuffer {
539 calls: vec![RenderCall {
540 ordinal: 0,
541 parent_ordinal: None,
542 type_name: "my_app::Outer",
543 x: 1,
544 y: 2,
545 width: 3,
546 height: 4,
547 collection: None,
548 annotation: None,
549 }],
550 };
551
552 let direct = record_annotated_call(
553 &mut frame,
554 Some(0),
555 "termwright_ratatui::Annotated<my_app::Inner>",
556 "my_app::Inner",
557 Annotation::new().name("nested"),
558 5,
559 6,
560 7,
561 8,
562 );
563 assert_eq!(frame.calls[0].type_name, "my_app::Outer");
564 assert!(frame.calls[0].annotation.is_none());
565 assert_eq!(direct, 1);
566 assert_eq!(frame.calls[1].parent_ordinal, Some(0));
567
568 frame.calls.push(RenderCall {
569 ordinal: 2,
570 parent_ordinal: None,
571 type_name: "termwright_ratatui::Annotated<my_app::Button>",
572 x: 9,
573 y: 10,
574 width: 11,
575 height: 12,
576 collection: None,
577 annotation: None,
578 });
579 let claimed = record_annotated_call(
580 &mut frame,
581 Some(1),
582 "termwright_ratatui::Annotated<my_app::Button>",
583 "my_app::Button",
584 Annotation::new().name("claimed"),
585 9,
586 10,
587 11,
588 12,
589 );
590 assert_eq!(claimed, 2);
591 assert_eq!(frame.calls.len(), 3);
592 assert_eq!(frame.calls[2].type_name, "my_app::Button");
593 assert_eq!(frame.calls[2].parent_ordinal, Some(1));
594 assert_eq!(
595 frame.calls[2]
596 .annotation
597 .as_ref()
598 .and_then(|annotation| annotation.name.as_deref()),
599 Some("claimed")
600 );
601 }
602
603 #[test]
604 fn nested_frame_contexts_suspend_and_restore_the_outer_frame() {
605 FRAME_STACK.with(|stack| {
606 let mut stack = stack.borrow_mut();
607 assert!(stack.is_empty());
608 stack.push(FrameContext::default());
609 });
610 with_current_frame(|frame| {
611 frame.buffer.calls.push(RenderCall {
612 ordinal: 0,
613 parent_ordinal: None,
614 type_name: "Outer",
615 x: 0,
616 y: 0,
617 width: 10,
618 height: 2,
619 collection: None,
620 annotation: None,
621 });
622 });
623 FRAME_STACK.with(|stack| stack.borrow_mut().push(FrameContext::default()));
624 with_current_frame(|frame| {
625 frame.buffer.calls.push(RenderCall {
626 ordinal: 0,
627 parent_ordinal: None,
628 type_name: "Inner",
629 x: 1,
630 y: 1,
631 width: 4,
632 height: 1,
633 collection: None,
634 annotation: None,
635 });
636 });
637
638 let inner = with_current_frame(|frame| std::mem::take(&mut frame.buffer.calls))
639 .expect("inner frame");
640 assert_eq!(inner.len(), 1);
641 assert_eq!(inner[0].type_name, "Inner");
642 FRAME_STACK.with(|stack| {
643 stack.borrow_mut().pop().expect("inner context");
644 });
645 let outer = with_current_frame(|frame| std::mem::take(&mut frame.buffer.calls))
646 .expect("restored outer frame");
647 assert_eq!(outer.len(), 1);
648 assert_eq!(outer[0].type_name, "Outer");
649 FRAME_STACK.with(|stack| {
650 stack.borrow_mut().pop().expect("outer context");
651 assert!(stack.borrow().is_empty());
652 });
653 }
654}
655
656#[must_use]
669pub fn probe_info(framework_version: Option<&str>) -> ProbeInfo {
670 ProbeInfo {
671 framework: "ratatui".to_owned(),
672 framework_version: framework_version.map(str::to_owned),
673 probe_version: env!("CARGO_PKG_VERSION").to_owned(),
674 identity_kind: ProbeIdentityKind::FrameLocal,
675 capabilities: vec![
676 "intended-rect".to_owned(),
677 "operations".to_owned(),
678 "annotations".to_owned(),
679 ],
680 instrumentation: Some(ProbeInstrumentation {
681 highest_tier: ProbeInjectionTier::T3,
682 semantic_class: ProbeSemanticClass::A,
683 degraded_capabilities: vec![],
684 }),
685 }
686}
687
688#[cfg(test)]
689mod handshake_tests {
690 use super::*;
691
692 #[test]
698 fn it_claims_only_what_ratatui_gives() {
699 let declared = serde_json::to_string(&probe_info(Some("0.30.2"))).expect("serialises");
700 assert!(
701 declared.contains("\"identityKind\":\"frame-local\""),
702 "{declared}"
703 );
704 for absent in [
705 "stable-identity",
706 "visible-rect",
707 "paint-order",
708 "frame-begin",
709 ] {
710 assert!(
711 !declared.contains(absent),
712 "claimed {absent}, which Ratatui does not provide: {declared}"
713 );
714 }
715 assert!(declared.contains("\"operations\""), "{declared}");
716 assert!(declared.contains("\"annotations\""), "{declared}");
717 assert!(declared.contains("\"highestTier\":\"T3\""), "{declared}");
718 assert!(declared.contains("\"semanticClass\":\"A\""), "{declared}");
719 assert!(declared.contains("0.30.2"), "{declared}");
720 }
721
722 #[test]
723 fn the_framework_version_is_optional() {
724 let declared = serde_json::to_string(&probe_info(None)).expect("serialises");
725 assert!(!declared.contains("frameworkVersion"), "{declared}");
726 }
727}