eguidev 0.1.0

AI-assisted development tooling and in-process instrumentation for egui apps
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
//! DevMCP instrumentation helpers and public API.
#![allow(missing_docs)]

use std::{
    any::Any,
    fmt,
    sync::{Arc, Mutex, atomic::Ordering},
    time::Duration,
};

use egui::Context;

use crate::{
    actions::InputAction,
    diagnostics::{DevMcpConfigError, DiagnosticRegistry, DiagnosticResult},
    fixtures::{FixtureHandler, RuntimeFixtureHandler, UiFixtureHandler},
    idle::IdleRegistry,
    instrument::{ACTIVE, container, swallow_panic},
    registry::Inner,
    script_prelude::{ScriptPrelude, ScriptPreludeRegistry},
    types::{FixtureCall, FixtureResult, FixtureSpec},
};

const KEEP_ALIVE_INTERVAL: Duration = Duration::from_millis(250);

#[derive(Clone, Debug, Default)]
enum DevMcpState {
    #[default]
    Inactive,
    Active(Arc<Inner>),
}

pub trait RuntimeHooks: Send + Sync {
    fn as_any(&self) -> &(dyn Any + Send + Sync);

    fn on_raw_input(&self, _inner: &Inner, _events: &[egui::Event]) {}

    fn on_frame_end(&self, _inner: &Inner, _ctx: &Context) {}
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AutomationOptions {
    pub keep_alive: bool,
    pub animations: bool,
}

impl Default for AutomationOptions {
    fn default() -> Self {
        Self {
            keep_alive: true,
            animations: false,
        }
    }
}

/// Egui plugin that injects DevMCP-queued input into every pass of every
/// viewport.
///
/// Registered automatically on the first instrumented frame (see
/// [`DevMcp::begin_frame`]), so apps do not need to wire anything up
/// themselves. Because `egui::Plugin::input_hook` runs inside the public
/// `Context::begin_pass` for root, deferred, and immediate viewports alike,
/// this makes injected input reach immediate viewports, which the old
/// app-side `raw_input_hook` override could never do (by the time an
/// immediate viewport's render callback ran, `begin_pass` had already
/// consumed that pass's `RawInput`).
///
/// Holding a `DevMcp` here (which transitively remembers `Context`s through
/// `Inner::remember_context`) creates a reference cycle with the `Context`
/// that owns this plugin. That cycle is benign: both live for the process
/// lifetime and are torn down together at process exit.
struct InputInjectionPlugin {
    /// The DevMCP handle whose queued actions should be drained into raw
    /// input for every pass.
    devmcp: DevMcp,
}

impl egui::Plugin for InputInjectionPlugin {
    fn debug_name(&self) -> &'static str {
        "eguidev_input_injection"
    }

    fn input_hook(&mut self, ctx: &Context, raw_input: &mut egui::RawInput) {
        let Some(inner) = self.devmcp.inner() else {
            return;
        };
        swallow_panic("input_injection_plugin", || {
            inner.remember_context(raw_input.viewport_id, ctx);
            self.devmcp
                .drain_actions_into_raw_input(inner, raw_input.viewport_id, raw_input);
        });
    }
}

/// DevMCP handle stored in app state.
#[derive(Clone, Default)]
pub struct DevMcp {
    state: DevMcpState,
    fixtures: Vec<FixtureSpec>,
    diagnostics: DiagnosticRegistry,
    idle: IdleRegistry,
    script_preludes: ScriptPreludeRegistry,
    verbose_logging: bool,
    fixture_handler: Option<FixtureHandler>,
    automation_options: AutomationOptions,
}

impl fmt::Debug for DevMcp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("DevMcp")
            .field("state", &self.state)
            .field("fixtures", &self.fixtures)
            .field("diagnostics", &self.diagnostics)
            .field("idle", &self.idle)
            .field("script_preludes", &self.script_preludes)
            .field("verbose_logging", &self.verbose_logging)
            .field("automation_options", &self.automation_options)
            .finish()
    }
}

impl DevMcp {
    /// Create a new inert DevMCP handle.
    pub fn new() -> Self {
        Self::default()
    }

    /// Enable or disable verbose internal logging for DevMCP operations.
    pub fn verbose_logging(mut self, verbose_logging: bool) -> Self {
        self.verbose_logging = verbose_logging;
        if let Some(inner) = self.inner() {
            inner.set_verbose_logging(verbose_logging);
        }
        self
    }

    /// Configure runtime-owned automation behavior.
    pub fn automation_options(mut self, options: AutomationOptions) -> Self {
        self.automation_options = options;
        if let Some(inner) = self.inner() {
            inner.set_automation_options(options);
        }
        self
    }

    /// Enable or disable runtime repaint keep-alive while automation is attached.
    pub fn keep_alive(mut self, keep_alive: bool) -> Self {
        self.automation_options.keep_alive = keep_alive;
        if let Some(inner) = self.inner() {
            inner.set_automation_options(self.automation_options);
        }
        self
    }

    /// Enable or disable egui animations while automation is attached.
    pub fn animations(mut self, animations: bool) -> Self {
        self.automation_options.animations = animations;
        if let Some(inner) = self.inner() {
            inner.set_automation_options(self.automation_options);
        }
        self
    }

    /// Register fixture metadata for discovery and validation.
    pub fn fixtures(mut self, fixtures: impl IntoIterator<Item = FixtureSpec>) -> Self {
        self.fixtures = fixtures.into_iter().collect();
        if let Some(inner) = self.inner() {
            inner.fixtures.set_fixtures(self.fixtures.clone());
        }
        self
    }

    /// Register a runtime-thread fixture handler.
    pub fn on_fixture_runtime<F>(mut self, handler: F) -> Result<Self, DevMcpConfigError>
    where
        F: Fn(&FixtureCall) -> FixtureResult + Send + Sync + 'static,
    {
        self.ensure_no_fixture_handler()?;
        let handler: RuntimeFixtureHandler = Arc::new(handler);
        let handler = FixtureHandler::Runtime(handler);
        if let Some(inner) = self.inner() {
            inner.fixtures.set_handler(handler.clone())?;
        }
        self.fixture_handler = Some(handler);
        Ok(self)
    }

    /// Register a UI-thread fixture handler.
    pub fn on_fixture_ui<F>(mut self, handler: F) -> Result<Self, DevMcpConfigError>
    where
        F: FnMut(&Context, &FixtureCall) -> FixtureResult + Send + 'static,
    {
        self.ensure_no_fixture_handler()?;
        let handler: UiFixtureHandler = Arc::new(Mutex::new(Box::new(handler)));
        let handler = FixtureHandler::Ui(handler);
        if let Some(inner) = self.inner() {
            inner.fixtures.set_handler(handler.clone())?;
        }
        self.fixture_handler = Some(handler);
        Ok(self)
    }

    /// Register a named diagnostic provider that runs on the automation runtime thread.
    pub fn diagnostic<F>(
        self,
        name: impl Into<String>,
        provider: F,
    ) -> Result<Self, DevMcpConfigError>
    where
        F: Fn() -> DiagnosticResult + Send + Sync + 'static,
    {
        self.diagnostics.insert_runtime(name.into(), provider)?;
        if let Some(inner) = self.inner() {
            inner.diagnostics.set_providers_from(&self.diagnostics);
        }
        Ok(self)
    }

    /// Register a named diagnostic provider that runs on the UI thread.
    pub fn diagnostic_ui<F>(
        self,
        name: impl Into<String>,
        provider: F,
    ) -> Result<Self, DevMcpConfigError>
    where
        F: FnMut(&Context) -> DiagnosticResult + Send + 'static,
    {
        self.diagnostics.insert_ui(name.into(), provider)?;
        if let Some(inner) = self.inner() {
            inner.diagnostics.set_providers_from(&self.diagnostics);
        }
        Ok(self)
    }

    /// Register an app-level idle check that runs on the automation runtime thread.
    pub fn on_idle<F>(self, is_idle: F) -> Result<Self, DevMcpConfigError>
    where
        F: Fn() -> bool + Send + Sync + 'static,
    {
        self.idle.insert_runtime(is_idle)?;
        if let Some(inner) = self.inner() {
            inner.idle.set_from(&self.idle);
        }
        Ok(self)
    }

    /// Register an app-level idle check that runs on the UI thread at root frame end.
    pub fn on_idle_ui<F>(self, is_idle: F) -> Result<Self, DevMcpConfigError>
    where
        F: FnMut(&Context) -> bool + Send + 'static,
    {
        self.idle.insert_ui(is_idle)?;
        if let Some(inner) = self.inner() {
            inner.idle.set_from(&self.idle);
        }
        Ok(self)
    }

    /// Register app-owned Luau helpers under a required namespace.
    pub fn script_prelude(self, prelude: ScriptPrelude) -> Result<Self, DevMcpConfigError> {
        self.script_preludes.insert(prelude)?;
        if let Some(inner) = self.inner() {
            inner.script_preludes.set_from(&self.script_preludes);
        }
        Ok(self)
    }

    /// Returns true if DevMCP automation is attached.
    pub fn is_enabled(&self) -> bool {
        matches!(self.state, DevMcpState::Active(_))
    }

    #[doc(hidden)]
    pub fn inner_arc(&self) -> Option<Arc<Inner>> {
        self.inner().map(Arc::clone)
    }

    #[doc(hidden)]
    pub fn runtime_hooks(&self) -> Option<Arc<dyn RuntimeHooks>> {
        self.inner().and_then(|inner| inner.runtime_hooks())
    }

    fn verbose_logging_enabled(&self) -> bool {
        self.inner()
            .map_or(self.verbose_logging, |inner| inner.verbose_logging())
    }

    fn ensure_no_fixture_handler(&self) -> Result<(), DevMcpConfigError> {
        if self.fixture_handler.is_some() {
            return Err(DevMcpConfigError::new(
                "duplicate_fixture_handler",
                "fixture handler is already registered",
            ));
        }
        Ok(())
    }

    #[cfg(test)]
    fn context_for(&self, viewport_id: egui::ViewportId) -> Option<Context> {
        self.inner()
            .and_then(|inner| inner.context_for(viewport_id))
    }

    #[doc(hidden)]
    pub fn activate_runtime(mut self, inner: Arc<Inner>, hooks: Arc<dyn RuntimeHooks>) -> Self {
        inner.set_runtime_hooks(hooks);
        inner.set_verbose_logging(self.verbose_logging);
        inner.set_automation_options(self.automation_options);
        if !self.fixtures.is_empty() {
            inner.fixtures.set_fixtures(self.fixtures.clone());
        }
        if let Some(handler) = &self.fixture_handler {
            inner
                .fixtures
                .set_handler(handler.clone())
                .expect("fixture handler was validated before runtime activation");
        }
        inner.diagnostics.set_providers_from(&self.diagnostics);
        inner.idle.set_from(&self.idle);
        inner.script_preludes.set_from(&self.script_preludes);
        self.state = DevMcpState::Active(inner);
        self
    }

    pub(crate) fn inner(&self) -> Option<&Arc<Inner>> {
        match &self.state {
            DevMcpState::Inactive => None,
            DevMcpState::Active(inner) => Some(inner),
        }
    }

    /// Begin a frame, enabling widget tracking for this thread.
    ///
    /// Prefer [`FrameGuard`] over calling this directly.
    pub(crate) fn begin_frame(&self, ctx: &Context) {
        let Some(inner) = self.inner() else {
            return;
        };
        if inner.try_install_input_plugin() {
            ctx.add_plugin(InputInjectionPlugin {
                devmcp: self.clone(),
            });
        }
        swallow_panic("begin_frame", || {
            let viewport_id = ctx.viewport_id();
            inner.begin_frame(viewport_id);
            inner.capture_context(viewport_id, ctx);
            if viewport_id == egui::ViewportId::ROOT {
                inner.fixtures.drain_ui(ctx);
                inner.diagnostics.drain_ui(ctx);
            }
            if let Some(hooks) = inner.runtime_hooks() {
                let events = ctx.input(|input| input.events.clone());
                hooks.on_raw_input(inner, &events);
            }
            inner.widgets.clear_registry(viewport_id);
            ACTIVE.with(|active| {
                if let Ok(mut active) = active.try_borrow_mut() {
                    *active = Some(Arc::clone(inner));
                } else {
                    eprintln!("eguidev: begin_frame skipped; active already borrowed");
                }
            });
        });
    }

    /// End a frame, finalizing widget registry and handling automation state.
    ///
    /// Prefer [`FrameGuard`] over calling this directly.
    pub(crate) fn end_frame(&self, ctx: &Context) {
        let Some(inner) = self.inner() else {
            return;
        };
        swallow_panic("end_frame", || {
            self.finish_frame(inner, ctx);
            ACTIVE.with(|active| {
                if let Ok(mut active) = active.try_borrow_mut() {
                    *active = None;
                } else {
                    eprintln!("eguidev: end_frame skipped; active already borrowed");
                }
            });
        });
    }

    fn finish_frame(&self, inner: &Arc<Inner>, ctx: &Context) {
        let viewport_id = ctx.viewport_id();
        inner.widgets.finalize_registry(viewport_id);
        let next_frame = inner.frame_count() + 1;
        let fixture_epoch = inner
            .finish_frame_fixture_epoch(viewport_id)
            .unwrap_or_else(|| inner.fixture_epoch());
        inner
            .viewports
            .capture_input_snapshot(ctx, fixture_epoch, next_frame);
        if viewport_id == egui::ViewportId::ROOT {
            inner.idle.update_ui(ctx, next_frame);
        }
        inner.advance_frame();
        if let Some(hooks) = inner.runtime_hooks() {
            hooks.on_frame_end(inner, ctx);
            if inner.automation_options().keep_alive {
                ctx.request_repaint_after(KEEP_ALIVE_INTERVAL);
            }
        }
    }

    /// Clear script-visible widgets for a viewport that the app has hidden.
    pub fn clear_viewport(&self, viewport_id: egui::ViewportId) {
        let Some(inner) = self.inner() else {
            return;
        };
        inner.widgets.clear_registry(viewport_id);
        inner.widgets.finalize_registry(viewport_id);
    }

    fn drain_actions_into_raw_input(
        &self,
        inner: &Arc<Inner>,
        viewport_id: egui::ViewportId,
        raw_input: &mut egui::RawInput,
    ) {
        let actions = inner
            .actions
            .drain_actions(viewport_id, inner.frame_count());
        if !actions.is_empty() {
            inner
                .last_action_frame
                .store(inner.frame_count(), Ordering::Relaxed);
            if self.verbose_logging_enabled() {
                eprintln!(
                    "eguidev: input_hook viewport={:?} actions={}",
                    viewport_id,
                    actions.len()
                );
            }
        }
        let base_modifiers = raw_input.modifiers;
        let mut current_modifiers = base_modifiers;
        let mut force_focus = false;
        for action in &actions {
            if let InputAction::Key {
                pressed, modifiers, ..
            } = action
            {
                current_modifiers = if *pressed {
                    base_modifiers.plus((*modifiers).into())
                } else {
                    base_modifiers
                };
            }
            if matches!(
                action,
                InputAction::Key { .. } | InputAction::Text { .. } | InputAction::Paste { .. }
            ) {
                force_focus = true;
            }
        }
        raw_input.modifiers = current_modifiers;
        if force_focus {
            raw_input.focused = true;
        }
        for action in actions {
            action.apply(raw_input);
        }
    }
}

/// RAII guard that calls `begin_frame` and `end_frame` automatically.
#[must_use = "FrameGuard must be held for the duration of the frame"]
pub struct FrameGuard<'a> {
    /// DevMcp handle for the active frame.
    devmcp: &'a DevMcp,
    /// Egui context for the current frame.
    ctx: &'a egui::Context,
}

impl<'a> FrameGuard<'a> {
    /// Create a new frame guard for the provided DevMcp.
    pub fn new(devmcp: &'a DevMcp, ctx: &'a Context) -> Self {
        devmcp.begin_frame(ctx);
        Self { devmcp, ctx }
    }
}

impl Drop for FrameGuard<'_> {
    fn drop(&mut self) {
        self.devmcp.end_frame(self.ctx);
    }
}

/// Wrap one viewport frame and register `container_id` as its root container.
///
/// Call this once for each rendered viewport pass, and render all instrumented
/// widgets for that pass inside `add_contents`. If the viewport has a semantic
/// name, call `name_viewport` from inside `add_contents` so the active frame is
/// already installed.
pub fn frame_scope<R>(
    devmcp: &DevMcp,
    ui: &mut egui::Ui,
    container_id: impl Into<String>,
    add_contents: impl FnOnce(&mut egui::Ui) -> R,
) -> R {
    let ctx = ui.ctx().clone();
    let _guard = FrameGuard::new(devmcp, &ctx);
    container(ui, container_id, add_contents)
}

/// Clear script-visible widgets for a viewport that is no longer rendered.
pub fn clear_viewport(devmcp: &DevMcp, viewport_id: egui::ViewportId) {
    devmcp.clear_viewport(viewport_id);
}

#[cfg(test)]
#[allow(deprecated)]
#[allow(clippy::tests_outside_test_module)]
mod inactive_tests {
    use std::{
        any::Any,
        sync::{
            Arc, Mutex,
            atomic::{AtomicUsize, Ordering as AtomicOrdering},
        },
    };

    use egui::{Context, Plugin};

    use super::*;
    use crate::{actions::InputAction, instrument, registry::Inner, ui_ext::DevUiExt};

    #[derive(Default)]
    struct CountingRuntimeHooks {
        raw_input_calls: AtomicUsize,
        raw_input_events: AtomicUsize,
        frame_end_calls: AtomicUsize,
    }

    impl RuntimeHooks for CountingRuntimeHooks {
        fn as_any(&self) -> &(dyn Any + Send + Sync) {
            self
        }

        fn on_raw_input(&self, _inner: &Inner, events: &[egui::Event]) {
            self.raw_input_calls.fetch_add(1, AtomicOrdering::Relaxed);
            self.raw_input_events
                .fetch_add(events.len(), AtomicOrdering::Relaxed);
        }

        fn on_frame_end(&self, _inner: &Inner, _ctx: &Context) {
            self.frame_end_calls.fetch_add(1, AtomicOrdering::Relaxed);
        }
    }

    #[test]
    fn inactive_input_hook_plugin_is_a_noop() {
        let devmcp = DevMcp::new();
        let ctx = Context::default();
        let mut plugin = InputInjectionPlugin { devmcp };
        let mut raw_input = egui::RawInput {
            viewport_id: egui::ViewportId::ROOT,
            focused: false,
            ..Default::default()
        };

        plugin.input_hook(&ctx, &mut raw_input);

        assert!(!raw_input.focused);
        assert!(raw_input.events.is_empty());
    }

    #[test]
    fn input_hook_plugin_injects_queued_actions_for_viewport() {
        let inner = Arc::new(Inner::new());
        let hooks: Arc<dyn RuntimeHooks> = Arc::new(CountingRuntimeHooks::default());
        let viewport_id = egui::ViewportId::from_hash_of("secondary");
        inner.queue_action(
            viewport_id,
            InputAction::Text {
                text: "event".to_string(),
            },
        );
        let devmcp = DevMcp::new().activate_runtime(inner, hooks);
        let mut plugin = InputInjectionPlugin { devmcp };
        let ctx = Context::default();
        let mut raw_input = egui::RawInput {
            viewport_id,
            ..Default::default()
        };

        plugin.input_hook(&ctx, &mut raw_input);

        assert_eq!(
            raw_input.events,
            vec![egui::Event::Text("event".to_string())],
            "plugin should inject queued actions for the pass's viewport"
        );
    }

    #[test]
    fn frame_guard_forwards_input_events_to_runtime_hooks() {
        let inner = Arc::new(Inner::new());
        let hooks = Arc::new(CountingRuntimeHooks::default());
        let runtime_hooks: Arc<dyn RuntimeHooks> = hooks.clone();
        let devmcp = DevMcp::new().activate_runtime(inner, runtime_hooks);
        let ctx = Context::default();
        let raw_input = egui::RawInput {
            events: vec![egui::Event::Text("event".to_string())],
            ..Default::default()
        };

        let _output = ctx.run_ui(raw_input, |ui| {
            let _guard = FrameGuard::new(&devmcp, ui.ctx());
        });

        assert_eq!(
            hooks.raw_input_calls.load(AtomicOrdering::Relaxed),
            1,
            "frame guard should notify runtime hooks about input events"
        );
        assert_eq!(
            hooks.raw_input_events.load(AtomicOrdering::Relaxed),
            1,
            "frame guard should forward input events"
        );
    }

    #[test]
    fn frame_guard_requests_repaint_when_keep_alive_is_enabled() {
        let inner = Arc::new(Inner::new());
        let hooks: Arc<dyn RuntimeHooks> = Arc::new(CountingRuntimeHooks::default());
        let devmcp = DevMcp::new().activate_runtime(inner, hooks);
        let ctx = Context::default();
        let repaint_delays = Arc::new(Mutex::new(Vec::new()));
        let repaint_delays_for_callback = Arc::clone(&repaint_delays);
        ctx.set_request_repaint_callback(move |info| {
            repaint_delays_for_callback
                .lock()
                .expect("repaint delay lock")
                .push(info.delay);
        });

        {
            let _guard = FrameGuard::new(&devmcp, &ctx);
        }

        let repaint_delays = repaint_delays.lock().expect("repaint delay lock");
        assert_eq!(repaint_delays.len(), 1);
        assert!(repaint_delays[0] > Duration::from_millis(200));
        assert!(repaint_delays[0] <= KEEP_ALIVE_INTERVAL);
    }

    #[test]
    fn frame_guard_does_not_request_repaint_when_keep_alive_is_disabled() {
        let inner = Arc::new(Inner::new());
        let hooks = Arc::new(CountingRuntimeHooks::default());
        let runtime_hooks: Arc<dyn RuntimeHooks> = hooks.clone();
        let devmcp = DevMcp::new()
            .keep_alive(false)
            .activate_runtime(inner, runtime_hooks);
        let ctx = Context::default();
        let repaint_count = Arc::new(AtomicUsize::new(0));
        let repaint_count_for_callback = Arc::clone(&repaint_count);
        ctx.set_request_repaint_callback(move |_| {
            repaint_count_for_callback.fetch_add(1, AtomicOrdering::Relaxed);
        });

        {
            let _guard = FrameGuard::new(&devmcp, &ctx);
        }

        assert_eq!(hooks.frame_end_calls.load(AtomicOrdering::Relaxed), 1);
        assert_eq!(repaint_count.load(AtomicOrdering::Relaxed), 0);
    }

    #[test]
    fn inactive_frame_guard_does_not_capture_context() {
        let devmcp = DevMcp::new();
        let ctx = Context::default();
        instrument::reset_test_counters();

        let _output = ctx.run_ui(egui::RawInput::default(), |ui| {
            let ctx = ui.ctx().clone();
            let _guard = FrameGuard::new(&devmcp, &ctx);
            ui.dev_button("inactive.button", "Inactive");
        });

        assert!(devmcp.context_for(egui::ViewportId::ROOT).is_none());
        assert_eq!(instrument::test_layout_capture_count(), 0);
    }
}