daat-locus 0.4.0

A long-running local agent runtime with memory, workflows, apps, and sleep-time self-improvement.
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
use std::{str::FromStr, time::Duration};

use miette::{IntoDiagnostic, Result, miette};
use ratatui::{Terminal, backend::TestBackend};
use serde::Serialize;

use super::{
    DashboardActivityEvent, DashboardState, LiveActivityEvent, SessionActivityEvent,
    apply_activity_event, assistant_activity_cell,
    command_panels::{CommandPanel, SkillsListPanel, SkillsTogglePanel},
    render_tui_dashboard_frame, terminal_activity_event_from_terminal_data, thinking_activity_cell,
    view_state::TuiViewState,
};
use crate::{
    activity_event::{
        BrowserActivityAction, BrowserActivityDescriptor, ExploredActivityDescriptor,
        ExploredCallActivityAction, ExploredCallActivityDescriptor,
        PatchDiffLineActivityDescriptor, PatchDiffLineKind, PatchFileActivityDescriptor,
        PatchFileOperation, ReplyActivityDescriptor, ReplyDisposition, ReplySubject,
        TerminalActivityAction, TerminalActivityDescriptor,
    },
    openskills::OpenSkillDashboardSummary,
};

#[derive(Clone, Debug)]
pub struct TuiPerfCommand {
    pub(crate) scenario: String,
    pub(crate) frames: usize,
    pub(crate) warmup: usize,
    pub(crate) width: u16,
    pub(crate) height: u16,
    pub(crate) json: bool,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum TuiPerfScenario {
    Mixed,
    LongHistory,
    Scrolling,
    LiveActivity,
    CommandPanels,
}

impl TuiPerfScenario {
    const fn as_str(self) -> &'static str {
        match self {
            Self::Mixed => "mixed",
            Self::LongHistory => "long-history",
            Self::Scrolling => "scrolling",
            Self::LiveActivity => "live-activity",
            Self::CommandPanels => "command-panels",
        }
    }

    const fn valid_values() -> &'static str {
        "mixed, long-history, scrolling, live-activity, command-panels"
    }
}

impl FromStr for TuiPerfScenario {
    type Err = miette::Report;

    fn from_str(value: &str) -> Result<Self> {
        match value.trim() {
            "mixed" => Ok(Self::Mixed),
            "long-history" => Ok(Self::LongHistory),
            "scrolling" => Ok(Self::Scrolling),
            "live-activity" => Ok(Self::LiveActivity),
            "command-panels" => Ok(Self::CommandPanels),
            other => Err(miette!(
                "unknown TUI perf scenario `{other}`; expected one of {}",
                Self::valid_values()
            )),
        }
    }
}

#[derive(Debug, Serialize)]
struct TuiPerfReport {
    scenario: String,
    frames: usize,
    warmup_frames: usize,
    width: u16,
    height: u16,
    committed_cells: usize,
    live_cells: usize,
    scroll_steps: usize,
    final_scroll_offset: u16,
    final_auto_scroll: bool,
    nonblank_cells: usize,
    frame_ms: TuiPerfTimingSummary,
    prep_ms: TuiPerfTimingSummary,
    draw_ms: TuiPerfTimingSummary,
    activity_ms: TuiPerfTimingSummary,
    command_ms: TuiPerfTimingSummary,
    cache: TuiPerfCacheReport,
}

#[derive(Debug, Default, Serialize)]
struct TuiPerfTimingSummary {
    avg: f64,
    max: f64,
}

#[derive(Debug, Serialize)]
struct TuiPerfCacheReport {
    entries: usize,
    occupied_entries: usize,
    hits: u64,
    misses: u64,
    hit_rate: f64,
}

#[derive(Default)]
struct TuiPerfTimingAccumulator {
    frame: Duration,
    max_frame: Duration,
    prep: Duration,
    max_prep: Duration,
    draw: Duration,
    max_draw: Duration,
    activity: Duration,
    max_activity: Duration,
    command: Duration,
    max_command: Duration,
    committed_cells: usize,
    live_cells: usize,
}

pub fn run_tui_perf_command(command: &TuiPerfCommand) -> Result<()> {
    let report = run_tui_perf(&command.clone())?;
    if command.json {
        println!(
            "{}",
            serde_json::to_string_pretty(&report)
                .map_err(|err| miette!("serialize TUI perf report failed: {err}"))?
        );
    } else {
        print_text_report(&report);
    }
    Ok(())
}

fn run_tui_perf(command: &TuiPerfCommand) -> Result<TuiPerfReport> {
    let scenario = TuiPerfScenario::from_str(&command.scenario)?;
    if command.frames == 0 {
        return Err(miette!("--frames must be greater than zero"));
    }
    if command.width < 40 || command.height < 12 {
        return Err(miette!("--width must be >= 40 and --height must be >= 12"));
    }

    let (state, mut view) = mock_dashboard_state(scenario);
    let backend = TestBackend::new(command.width, command.height);
    let mut terminal = Terminal::new(backend).into_diagnostic()?;

    for frame in 0..command.warmup {
        prepare_view_for_frame(&state, &mut view);
        apply_perf_scroll_step(scenario, frame, &mut view);
        render_tui_dashboard_frame(&mut terminal, &mut view, &state).into_diagnostic()?;
    }

    view.cached_activity_lines.reset_stats();
    let mut timings = TuiPerfTimingAccumulator::default();
    let mut scroll_steps = 0;
    for frame in 0..command.frames {
        prepare_view_for_frame(&state, &mut view);
        if apply_perf_scroll_step(scenario, command.warmup + frame, &mut view) {
            scroll_steps += 1;
        }
        let frame_render =
            render_tui_dashboard_frame(&mut terminal, &mut view, &state).into_diagnostic()?;
        timings.record(&frame_render.timing);
    }
    let cache_stats = view.cached_activity_lines.stats();
    let last_buffer = terminal.backend().buffer();
    let nonblank_cells = last_buffer
        .content()
        .iter()
        .filter(|cell| cell.symbol() != " ")
        .count();
    std::hint::black_box(nonblank_cells);

    Ok(TuiPerfReport {
        scenario: scenario.as_str().to_string(),
        frames: command.frames,
        warmup_frames: command.warmup,
        width: command.width,
        height: command.height,
        committed_cells: timings.committed_cells,
        live_cells: timings.live_cells,
        scroll_steps,
        final_scroll_offset: view.activity_scroll.scroll,
        final_auto_scroll: view.activity_scroll.follow_bottom,
        nonblank_cells,
        frame_ms: TuiPerfTimingAccumulator::summary(
            timings.frame,
            timings.max_frame,
            command.frames,
        ),
        prep_ms: TuiPerfTimingAccumulator::summary(timings.prep, timings.max_prep, command.frames),
        draw_ms: TuiPerfTimingAccumulator::summary(timings.draw, timings.max_draw, command.frames),
        activity_ms: TuiPerfTimingAccumulator::summary(
            timings.activity,
            timings.max_activity,
            command.frames,
        ),
        command_ms: TuiPerfTimingAccumulator::summary(
            timings.command,
            timings.max_command,
            command.frames,
        ),
        cache: TuiPerfCacheReport {
            entries: cache_stats.entries,
            occupied_entries: cache_stats.occupied_entries,
            hits: cache_stats.hits,
            misses: cache_stats.misses,
            hit_rate: hit_rate(cache_stats.hits, cache_stats.misses),
        },
    })
}

fn print_text_report(report: &TuiPerfReport) {
    println!(
        "tui-perf scenario={} frames={} warmup={} size={}x{}",
        report.scenario, report.frames, report.warmup_frames, report.width, report.height
    );
    println!(
        "cells committed={} live={} nonblank={}",
        report.committed_cells, report.live_cells, report.nonblank_cells
    );
    println!(
        "scroll steps={} final_offset={} auto_scroll={}",
        report.scroll_steps, report.final_scroll_offset, report.final_auto_scroll
    );
    println!(
        "frame_ms avg={:.3} max={:.3}  prep avg={:.3} max={:.3}  draw avg={:.3} max={:.3}",
        report.frame_ms.avg,
        report.frame_ms.max,
        report.prep_ms.avg,
        report.prep_ms.max,
        report.draw_ms.avg,
        report.draw_ms.max
    );
    println!(
        "activity_ms avg={:.3} max={:.3}  command_ms avg={:.3} max={:.3}",
        report.activity_ms.avg,
        report.activity_ms.max,
        report.command_ms.avg,
        report.command_ms.max
    );
    println!(
        "cache entries={} occupied={} hits={} misses={} hit_rate={:.3}",
        report.cache.entries,
        report.cache.occupied_entries,
        report.cache.hits,
        report.cache.misses,
        report.cache.hit_rate
    );
}

impl TuiPerfTimingAccumulator {
    fn record(&mut self, timing: &super::frame_profiler::TuiFrameTiming) {
        self.committed_cells = timing.committed_cells;
        self.live_cells = timing.live_cells;
        self.frame += timing.frame;
        self.max_frame = self.max_frame.max(timing.frame);
        self.prep += timing.prep;
        self.max_prep = self.max_prep.max(timing.prep);
        self.draw += timing.draw;
        self.max_draw = self.max_draw.max(timing.draw);
        self.activity += timing.activity;
        self.max_activity = self.max_activity.max(timing.activity);
        self.command += timing.command;
        self.max_command = self.max_command.max(timing.command);
    }

    fn summary(total: Duration, max: Duration, frames: usize) -> TuiPerfTimingSummary {
        let frame_count = u32::try_from(frames.max(1)).unwrap_or(u32::MAX);
        let frame_count = f64::from(frame_count);
        TuiPerfTimingSummary {
            avg: duration_ms(total) / frame_count,
            max: duration_ms(max),
        }
    }
}

fn duration_ms(duration: Duration) -> f64 {
    duration.as_secs_f64() * 1000.0
}

fn hit_rate(hits: u64, misses: u64) -> f64 {
    let total = hits.saturating_add(misses);
    if total == 0 {
        0.0
    } else {
        let hits = u32::try_from(hits).unwrap_or(u32::MAX);
        let total = u32::try_from(total).unwrap_or(u32::MAX);
        f64::from(hits) / f64::from(total)
    }
}

fn prepare_view_for_frame(state: &DashboardState, view: &mut TuiViewState) {
    view.sync_visible_clear_from_state(state);
    view.sync_transcript_overlay(state);
    view.sync_workflow_inspector(state);
    if let Some(panel) = view.command_panel.as_mut() {
        panel.sync_state(state);
    }
    view.tick_history_load_cooldown();
    view.sync_history_cursor_from_state(state);
}

fn apply_perf_scroll_step(
    scenario: TuiPerfScenario,
    frame_index: usize,
    view: &mut TuiViewState,
) -> bool {
    if scenario != TuiPerfScenario::Scrolling {
        return false;
    }

    let rows = if (frame_index / 18).is_multiple_of(2) {
        4
    } else {
        -4
    };
    view.handle_activity_scroll_rows(rows)
}

fn mock_dashboard_state(scenario: TuiPerfScenario) -> (DashboardState, TuiViewState) {
    let mut state = DashboardState {
        activity_events: mock_activity_cells(match scenario {
            TuiPerfScenario::LongHistory | TuiPerfScenario::Scrolling => 260,
            TuiPerfScenario::LiveActivity => 45,
            TuiPerfScenario::CommandPanels => 55,
            TuiPerfScenario::Mixed => 140,
        }),
        skills: mock_skills(),
        status_output: "runtime: active\nsessions: 4\ntransport: local".to_string(),
        sleep_status_output: "sleep: idle\nlast run: 12m ago".to_string(),
        inspect_telegram_output: "telegram: polling\nverification: token-based".to_string(),
        app_status_outputs: vec![
            (
                "coding".to_string(),
                "project_root=/Users/example/project\nlsp=ready\npending_reviews=0".to_string(),
            ),
            (
                "terminal".to_string(),
                "cwd=/Users/example/project\nsessions=2\nactive=main".to_string(),
            ),
        ],
        runtime_status: Some(if scenario == TuiPerfScenario::LiveActivity {
            "Working".to_string()
        } else {
            "Idle".to_string()
        }),
        footer_context: "gpt-5.5 · 126.5k/258.4k used".to_string(),
        footer_estimated_input_tokens: Some(126_500),
        ..DashboardState::default()
    };
    if matches!(
        scenario,
        TuiPerfScenario::Mixed | TuiPerfScenario::LiveActivity
    ) {
        add_live_cells(&mut state, 5);
    }

    let mut view = TuiViewState::new();
    match scenario {
        TuiPerfScenario::LongHistory => {
            view.activity_scroll.follow_bottom = false;
            view.activity_scroll.scroll = 80;
        }
        TuiPerfScenario::Scrolling => {
            view.activity_scroll.follow_bottom = false;
            view.activity_scroll.scroll = 80;
            view.activity_scroll.max_scroll = u16::MAX;
        }
        TuiPerfScenario::LiveActivity => {
            view.command_input.set_text("/status".to_string());
        }
        TuiPerfScenario::CommandPanels => {
            view.command_panel = Some(CommandPanel::SkillsList(SkillsListPanel::from_state(
                &state,
            )));
            view.command_input.set_text("/skills".to_string());
        }
        TuiPerfScenario::Mixed => {
            view.command_panel = Some(CommandPanel::SkillsToggle(SkillsTogglePanel::from_state(
                &state,
            )));
            view.command_input.set_text("/skills".to_string());
        }
    }
    (state, view)
}

fn mock_activity_cells(count: usize) -> Vec<SessionActivityEvent> {
    (0..count)
        .filter_map(|idx| match idx % 7 {
            0 => assistant_activity_cell(&mock_markdown(idx)),
            1 => thinking_activity_cell(&mock_reasoning(idx)),
            2 => Some(SessionActivityEvent::Explored(mock_explored(idx).into())),
            3 => terminal_activity_event_from_terminal_data(mock_terminal(idx)),
            4 => Some(SessionActivityEvent::Browser(mock_browser(idx).into())),
            5 => Some(SessionActivityEvent::Patch(mock_patch(idx).into())),
            _ => Some(SessionActivityEvent::Reply(mock_reply(idx).into())),
        })
        .collect()
}

fn add_live_cells(state: &mut DashboardState, count: usize) {
    for idx in 0..count {
        let key = format!("live-exec-{idx}");
        apply_activity_event(
            state,
            DashboardActivityEvent::ExecBegin {
                key: key.clone(),
                title: format!("Running command {idx}"),
                call_lines: vec![
                    "cargo test dashboard::".to_string(),
                    "collecting deterministic render timings".to_string(),
                ],
            },
        );
        apply_activity_event(
            state,
            DashboardActivityEvent::ExecUpdate {
                key,
                meta: Some(format!("{}ms", 120 + idx)),
                output_lines: vec![
                    "Compiling daat-locus".to_string(),
                    "rendering test frame".to_string(),
                    "waiting for next event".to_string(),
                ],
            },
        );
    }
    state.live_activity_events.push(LiveActivityEvent {
        key: "live-browser".to_string(),
        event: SessionActivityEvent::LiveBrowser(
            BrowserActivityDescriptor {
                action: BrowserActivityAction::Snapshot,
                title: "Capturing dashboard docs".to_string(),
                body_lines: vec!["https://example.local/docs/dashboard".to_string()],
                url: Some("https://example.local/docs/dashboard".to_string()),
                line_count: Some(180),
                ref_count: Some(24),
            }
            .into(),
        ),
    });
}

fn mock_markdown(idx: usize) -> String {
    format!(
        "Assistant update {idx}\n\n- inspected dashboard frame path\n- kept render state local\n- measured cache reuse\n\n```rust\nfn frame_{idx}() {{\n    render_activity_feed_cached();\n}}\n```\n\n{}",
        "This paragraph is intentionally long enough to wrap across several terminal rows and exercise markdown rendering, syntax spans, and width-aware cached cell height computation."
    )
}

fn mock_reasoning(idx: usize) -> String {
    format!(
        "Frame {idx} reasoning\nThe dashboard should render from current state only.\nAnimation scheduling should happen after draw.\nCache invalidation should follow source cell identity."
    )
}

fn mock_explored(idx: usize) -> ExploredActivityDescriptor {
    ExploredActivityDescriptor {
        stable_id: format!("explored-{idx}"),
        title: "Explored".to_string(),
        calls: vec![
            ExploredCallActivityDescriptor {
                tool_name: "Read".to_string(),
                action: Some(ExploredCallActivityAction::Read),
                target: Some("src/dashboard/mod.rs".to_string()),
                secondary_target: None,
                summary: "Read mod.rs".to_string(),
                detail_lines: vec!["src/dashboard/mod.rs#L350-L590".to_string()],
            },
            ExploredCallActivityDescriptor {
                tool_name: "Search".to_string(),
                action: Some(ExploredCallActivityAction::Search),
                target: Some("schedule_frame|render_tui_dashboard_frame".to_string()),
                secondary_target: Some("dashboard".to_string()),
                summary: "Search schedule_frame|render_tui_dashboard_frame in dashboard"
                    .to_string(),
                detail_lines: vec!["src/dashboard/mod.rs".to_string()],
            },
        ],
    }
}

fn mock_terminal(idx: usize) -> TerminalActivityDescriptor {
    TerminalActivityDescriptor {
        action: TerminalActivityAction::Execute,
        origin: None,
        title: format!("cargo check #{idx}"),
        body_lines: vec![
            "0.42s".to_string(),
            "Checking daat-locus".to_string(),
            "Finished dev profile".to_string(),
            "No stale redraw loop found".to_string(),
        ],
    }
}

fn mock_browser(idx: usize) -> BrowserActivityDescriptor {
    BrowserActivityDescriptor {
        action: BrowserActivityAction::Snapshot,
        title: format!("Browser snapshot {idx}"),
        body_lines: vec![
            "Dashboard Architecture".to_string(),
            "TUI Event Loop".to_string(),
            "FrameRequester".to_string(),
            "Render Caches".to_string(),
        ],
        url: Some("https://example.local/architecture".to_string()),
        line_count: Some(240 + idx),
        ref_count: Some(18),
    }
}

fn mock_patch(idx: usize) -> crate::activity_event::PatchActivityDescriptor {
    crate::activity_event::PatchActivityDescriptor {
        summary_line: format!("Edited dashboard perf harness {idx}"),
        files: vec![PatchFileActivityDescriptor {
            path: "src/dashboard/tui_perf.rs".to_string(),
            operation: PatchFileOperation::Update,
            added_lines: 12,
            removed_lines: 3,
            diff_lines: vec![
                PatchDiffLineActivityDescriptor {
                    kind: PatchDiffLineKind::Context,
                    old_lineno: Some(10),
                    new_lineno: Some(10),
                    text: "fn render_frame() {".to_string(),
                },
                PatchDiffLineActivityDescriptor {
                    kind: PatchDiffLineKind::Delete,
                    old_lineno: Some(11),
                    new_lineno: None,
                    text: "    old_render_loop();".to_string(),
                },
                PatchDiffLineActivityDescriptor {
                    kind: PatchDiffLineKind::Add,
                    old_lineno: None,
                    new_lineno: Some(11),
                    text: "    render_tui_dashboard_frame();".to_string(),
                },
            ],
        }],
    }
}

fn mock_reply(idx: usize) -> ReplyActivityDescriptor {
    ReplyActivityDescriptor {
        disposition: ReplyDisposition::Resolved,
        subject: if idx.is_multiple_of(2) {
            ReplySubject::Message
        } else {
            ReplySubject::Notice
        },
        message_lines: vec![
            format!("Resolved dashboard update {idx}."),
            "The render path is deterministic for this scenario.".to_string(),
        ],
        elapsed_seconds: None,
    }
}

fn mock_skills() -> Vec<OpenSkillDashboardSummary> {
    vec![
        OpenSkillDashboardSummary {
            name: "gpt-taste".to_string(),
            description: "Elite UX/UI and advanced motion review for frontend interface polish."
                .to_string(),
            path: "/Users/example/.agents/skills/gpt-taste/SKILL.md".to_string(),
            scope: "user".to_string(),
            allow_implicit_invocation: true,
            user_disabled: false,
            auto_use_enabled: true,
        },
        OpenSkillDashboardSummary {
            name: "shadcn".to_string(),
            description: "Use shadcn/ui components and preserve design-system conventions."
                .to_string(),
            path: "/Users/example/.agents/skills/shadcn/SKILL.md".to_string(),
            scope: "user".to_string(),
            allow_implicit_invocation: true,
            user_disabled: false,
            auto_use_enabled: true,
        },
        OpenSkillDashboardSummary {
            name: "release-notes".to_string(),
            description: "Manual-only release note drafting helper.".to_string(),
            path: "/Users/example/project/.agents/skills/release-notes/SKILL.md".to_string(),
            scope: "project".to_string(),
            allow_implicit_invocation: false,
            user_disabled: false,
            auto_use_enabled: false,
        },
    ]
}

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

    #[test]
    fn tui_perf_mixed_scenario_renders_measured_frames() {
        let report = run_tui_perf(&TuiPerfCommand {
            scenario: "mixed".to_string(),
            frames: 3,
            warmup: 1,
            width: 100,
            height: 32,
            json: false,
        })
        .expect("perf report");

        assert_eq!(report.scenario, "mixed");
        assert_eq!(report.frames, 3);
        assert!(report.committed_cells > 0);
        assert!(report.nonblank_cells > 0);
        assert!(report.cache.occupied_entries > 0);
        assert!(report.cache.hits > 0);
    }

    #[test]
    fn tui_perf_scrolling_scenario_exercises_scroll_frames() {
        let report = run_tui_perf(&TuiPerfCommand {
            scenario: "scrolling".to_string(),
            frames: 8,
            warmup: 1,
            width: 100,
            height: 32,
            json: false,
        })
        .expect("perf report");

        assert_eq!(report.scenario, "scrolling");
        assert_eq!(report.scroll_steps, 8);
        assert!(!report.final_auto_scroll);
        assert_ne!(report.final_scroll_offset, 80);
        assert!(report.cache.hits > 0);
    }

    #[test]
    fn tui_perf_rejects_unknown_scenario() {
        let err = run_tui_perf(&TuiPerfCommand {
            scenario: "unknown".to_string(),
            frames: 1,
            warmup: 0,
            width: 80,
            height: 24,
            json: false,
        })
        .expect_err("unknown scenario should fail");

        assert!(err.to_string().contains("unknown TUI perf scenario"));
    }
}