par-term 0.48.0

Cross-platform GPU-accelerated terminal emulator with inline graphics support (Sixel, iTerm2, Kitty)
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
//! Agent-usage popup panel.
//!
//! Detail view over the usage store's snapshot, modeled on the command
//! palette's overlay skeleton (`crate::command_palette`): an egui `Window`
//! anchored center, an action-enum return for the one thing the caller must
//! do (refresh). Every panel key — Escape, `r`, `h`/`l` — is read here on
//! the egui side: the panel is a guarding Popup in the overlay stack (UX.md
//! OV2), so the stack consumes each key before terminal key dispatch and
//! feeds it to egui, where `show()` is the only reader.

use crate::agent_usage::records::ModelUsage;
use crate::agent_usage::store::UsageSnapshot;
use chrono::{DateTime, Utc};
use egui::{Context, Frame, Key, Window, epaint::Shadow};

/// Days drawn in the tokens-by-day chart.
const CHART_DAYS: usize = 7;

/// What the panel asked its caller to do this frame.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum PanelAction {
    /// User pressed `r` — rescan the records directory now.
    RefreshRequested,
}

/// Popup detail panel over the usage snapshot.
pub(crate) struct AgentUsagePanel {
    /// Whether the panel is currently on screen.
    pub(crate) visible: bool,
    /// Index into the snapshot's records; `h`/`l` move it.
    selected_agent: usize,
}

impl Default for AgentUsagePanel {
    fn default() -> Self {
        Self::new()
    }
}

impl AgentUsagePanel {
    /// Build the panel, hidden.
    pub(crate) fn new() -> Self {
        Self {
            visible: false,
            selected_agent: 0,
        }
    }

    /// Show the panel, starting from the first agent.
    pub(crate) fn open(&mut self) {
        self.visible = true;
        self.selected_agent = 0;
    }

    /// Hide the panel. Idempotent — the stack's Escape close and the
    /// egui-side Escape can both call it in one frame without harm.
    pub(crate) fn close(&mut self) {
        self.visible = false;
    }

    /// Flip visibility, resetting the agent selection when opening.
    pub(crate) fn toggle(&mut self) {
        if self.visible {
            self.close();
        } else {
            self.open();
        }
    }

    /// Move the agent selection within `agent_count` records (`h`/`l`).
    pub(crate) fn cycle_agent(&mut self, forward: bool, agent_count: usize) {
        if agent_count == 0 {
            self.selected_agent = 0;
            return;
        }
        let idx = self.selected_agent % agent_count;
        self.selected_agent = if forward {
            (idx + 1) % agent_count
        } else {
            (idx + agent_count - 1) % agent_count
        };
    }

    /// Draw the panel. Returns the action the caller must take, if any.
    pub(crate) fn show(&mut self, ctx: &Context, snap: &UsageSnapshot) -> Option<PanelAction> {
        if !self.visible {
            return None;
        }

        let mut action: Option<PanelAction> = None;

        // Escape closes here, on the egui side, mirroring the palette;
        // close() is idempotent, and consume_key keeps Escape away from
        // other widgets.
        if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape)) {
            self.close();
        }
        // `r` refreshes: a manual rescan is instant (local dir read), so it
        // runs inline rather than through the update-command runner.
        if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::R)) {
            action = Some(PanelAction::RefreshRequested);
        }
        let (next, previous) = ctx.input_mut(|i| {
            (
                i.count_and_consume_key(egui::Modifiers::NONE, Key::L),
                i.count_and_consume_key(egui::Modifiers::NONE, Key::H),
            )
        });
        for _ in 0..next {
            self.cycle_agent(true, snap.records.len());
        }
        for _ in 0..previous {
            self.cycle_agent(false, snap.records.len());
        }

        let record = snap.records.get(self.selected_agent);
        self.selected_agent = self
            .selected_agent
            .min(snap.records.len().saturating_sub(1));

        Window::new("Agent Usage")
            .title_bar(false)
            .resizable(false)
            .collapsible(false)
            .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
            .frame(Frame::popup(&ctx.global_style()).shadow(Shadow::default()))
            .show(ctx, |ui| {
                ui.set_min_width(420.0);
                ui.set_max_width(520.0);

                match record {
                    Some(record) => {
                        // ── Hero ─────────────────────────────────────────
                        ui.horizontal(|ui| {
                            ui.heading(&record.name);
                            if let Some(tier) = &record.tier_label {
                                ui.weak(tier);
                            }
                        });
                        if let Some(status) = &record.usage_status_text
                            && !status.is_empty()
                        {
                            ui.label(status);
                        }

                        ui.add_space(6.0);

                        // ── Limits ───────────────────────────────────────
                        for limit in &record.limits {
                            let label = limit.label.as_deref().unwrap_or("Limit");
                            ui.horizontal(|ui| {
                                ui.label(label);
                                if let Some(percent) = limit.percent {
                                    ui.with_layout(
                                        egui::Layout::right_to_left(egui::Align::Center),
                                        |ui| {
                                            ui.weak(format!("{percent:.0}%"));
                                            if let Some(countdown) =
                                                reset_countdown(limit.resets_at.as_deref())
                                            {
                                                ui.weak(countdown);
                                            }
                                        },
                                    );
                                }
                            });
                            if let Some(percent) = limit.percent {
                                draw_meter(ui, (percent / 100.0).clamp(0.0, 1.0));
                            }
                            ui.add_space(4.0);
                        }

                        // ── Prepaid balance ──────────────────────────────
                        if let Some(balance) = &record.balance {
                            ui.label(format!(
                                "Balance: {:.2} {} of {:.2}{} spent",
                                balance.remaining,
                                balance.currency,
                                balance.spent,
                                if balance.estimated { " (est.)" } else { "" }
                            ));
                            let funded = balance.funded;
                            let remaining = balance.remaining;
                            let fraction = if funded > 0.0 {
                                (remaining / funded).clamp(0.0, 1.0)
                            } else {
                                0.0
                            };
                            draw_meter(ui, fraction);
                            ui.add_space(4.0);
                        }

                        // ── Tokens by day ────────────────────────────────
                        if !record.recent_days.is_empty() {
                            ui.weak("Tokens, last days");
                            draw_day_chart(
                                ui,
                                &record.recent_days[..CHART_DAYS.min(record.recent_days.len())],
                            );
                            ui.add_space(4.0);
                        }

                        // ── Tokens by model ──────────────────────────────
                        if !record.model_usage.is_empty() {
                            ui.weak("Tokens by model");
                            let mut rows: Vec<_> = record.model_usage.iter().collect();
                            let total = |u: &ModelUsage| {
                                u.input_tokens
                                    + u.output_tokens
                                    + u.cache_read_input_tokens
                                    + u.cache_creation_input_tokens
                            };
                            rows.sort_by(|a, b| total(b.1).total_cmp(&total(a.1)));
                            for (model, usage) in rows {
                                ui.horizontal(|ui| {
                                    ui.label(model.as_str());
                                    ui.with_layout(
                                        egui::Layout::right_to_left(egui::Align::Center),
                                        |ui| {
                                            ui.weak(format_tokens(
                                                usage.input_tokens
                                                    + usage.output_tokens
                                                    + usage.cache_read_input_tokens
                                                    + usage.cache_creation_input_tokens,
                                            ));
                                        },
                                    );
                                });
                            }
                        }

                        // ── Footer ───────────────────────────────────────
                        ui.add_space(6.0);
                        ui.horizontal(|ui| {
                            ui.weak(format!("updated {}", record.updated_at));
                            ui.with_layout(
                                egui::Layout::right_to_left(egui::Align::Center),
                                |ui| ui.weak("h/l agent · r refresh · Esc close"),
                            );
                        });
                    }
                    None => {
                        ui.heading("Agent Usage");
                        ui.label("No usage records found.");
                        ui.weak(
                            "Collectors write <agent-id>.json into the records directory; \
                             the panel renders whatever appears there.",
                        );
                    }
                }

                for error in &snap.errors {
                    ui.weak(
                        egui::RichText::new(error).color(egui::Color32::from_rgb(220, 120, 90)),
                    );
                }
            });

        action
    }
}

/// Human reset countdown ("3h12m") from an RFC3339 timestamp.
fn reset_countdown(resets_at: Option<&str>) -> Option<String> {
    let raw = resets_at?;
    let parsed = DateTime::parse_from_rfc3339(raw).ok()?;
    let remaining = parsed.signed_duration_since(Utc::now());
    if remaining <= chrono::Duration::zero() {
        return None;
    }
    let mins = remaining.num_minutes();
    Some(if mins >= 60 {
        format!("resets in {}h{}m", mins / 60, mins % 60)
    } else {
        format!("resets in {mins}m")
    })
}

/// Format a token count with k/M/B suffixes.
fn format_tokens(tokens: f64) -> String {
    if tokens >= 1e9 {
        format!("{:.1}B", tokens / 1e9)
    } else if tokens >= 1e6 {
        format!("{:.1}M", tokens / 1e6)
    } else if tokens >= 1e3 {
        format!("{:.1}k", tokens / 1e3)
    } else {
        format!("{tokens:.0}")
    }
}

/// One full-width meter bar drawn with the painter — no plot dependency.
fn draw_meter(ui: &mut egui::Ui, fraction: f64) {
    use egui::{Sense, Vec2};
    let width = ui.available_width();
    let (rect, _) = ui.allocate_exact_size(Vec2::new(width, 6.0), Sense::hover());
    let track = rect;
    ui.painter()
        .rect_filled(track, 3.0, egui::Color32::from_gray(70));
    let fill_width = track.width() as f64 * fraction.clamp(0.0, 1.0);
    let mut fill = track;
    fill.set_width(fill_width as f32);
    let color = if fraction >= 0.9 {
        egui::Color32::from_rgb(220, 100, 90)
    } else if fraction >= 0.7 {
        egui::Color32::from_rgb(235, 180, 70)
    } else {
        egui::Color32::from_rgb(110, 190, 120)
    };
    ui.painter().rect_filled(fill, 3.0, color);
}

/// Mini bar chart for recent days, drawn with the painter.
fn draw_day_chart(ui: &mut egui::Ui, days: &[crate::agent_usage::records::DayUsage]) {
    use egui::{Sense, Vec2};
    if days.is_empty() {
        return;
    }
    let max = days
        .iter()
        .map(|d| d.tokens)
        .fold(0.0_f64, f64::max)
        .max(1.0);
    let width = ui.available_width();
    let (rect, _) = ui.allocate_exact_size(Vec2::new(width, 40.0), Sense::hover());
    let n = days.len() as f32;
    let slot = rect.width() / n;
    for (i, day) in days.iter().enumerate() {
        let h = (rect.height() as f64 * (day.tokens / max)).clamp(2.0, rect.height() as f64) as f32;
        let x = rect.left() + slot * i as f32 + 2.0;
        let bar = egui::Rect::from_min_size(
            egui::pos2(x, rect.bottom() - h),
            Vec2::new((slot - 4.0).max(1.0), h),
        );
        ui.painter()
            .rect_filled(bar, 1.0, egui::Color32::from_rgb(110, 160, 220));
        ui.painter().text(
            egui::pos2(x + bar.width() / 2.0, rect.bottom() + 8.0),
            egui::Align2::CENTER_TOP,
            day.date
                .rsplit_once('-')
                .map(|(_, d)| d)
                .unwrap_or(&day.date),
            egui::TextStyle::Small.resolve(ui.style()),
            ui.visuals().weak_text_color(),
        );
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    /// One headless egui frame over `panel` with `keys` pressed; returns
    /// the action `show()` asked for.
    fn frame_with_keys(
        ctx: &Context,
        snap: &UsageSnapshot,
        panel: &mut AgentUsagePanel,
        keys: &[Key],
    ) -> Option<PanelAction> {
        let events = keys
            .iter()
            .map(|&key| egui::Event::Key {
                key,
                physical_key: None,
                pressed: true,
                repeat: false,
                modifiers: egui::Modifiers::NONE,
            })
            .collect();
        let mut action = None;
        let action_slot = &mut action;
        let mut out = ctx.run_ui(
            egui::RawInput {
                screen_rect: Some(egui::Rect::from_min_size(
                    egui::Pos2::ZERO,
                    egui::vec2(1200.0, 800.0),
                )),
                events,
                ..Default::default()
            },
            |ui| *action_slot = panel.show(ui.ctx(), snap),
        );
        out.textures_delta.clear();
        action
    }

    #[test]
    fn starts_hidden() {
        assert!(!AgentUsagePanel::new().visible);
    }

    #[test]
    fn toggle_flips_visibility_and_open_resets_selection() {
        let mut panel = AgentUsagePanel::new();
        panel.toggle();
        assert!(panel.visible);
        panel.selected_agent = 5;
        panel.close();
        panel.open();
        assert_eq!(panel.selected_agent, 0, "opening resets to the first agent");
        panel.toggle();
        assert!(!panel.visible);
    }

    #[test]
    fn cycle_agent_wraps_both_ways() {
        let mut panel = AgentUsagePanel::new();
        panel.cycle_agent(true, 3);
        assert_eq!(panel.selected_agent, 1);
        panel.cycle_agent(true, 3);
        panel.cycle_agent(true, 3);
        assert_eq!(panel.selected_agent, 0, "forward wraps to first");
        panel.cycle_agent(false, 3);
        assert_eq!(panel.selected_agent, 2, "backward wraps to last");
    }

    #[test]
    fn cycle_agent_with_no_records_is_a_noop() {
        let mut panel = AgentUsagePanel::new();
        panel.cycle_agent(true, 0);
        assert_eq!(panel.selected_agent, 0);
    }

    #[test]
    fn escape_closes_the_panel_on_the_egui_side() {
        // The stack resolves Escape itself (CloseTop, withheld from egui);
        // show() must still close when Escape does arrive here — ui-test
        // chord injection, or a delegated Escape from a mode above.
        let snap = UsageSnapshot {
            records: Vec::new(),
            errors: Vec::new(),
        };
        let ctx = Context::default();
        let mut panel = AgentUsagePanel::new();
        panel.open();
        frame_with_keys(&ctx, &snap, &mut panel, &[Key::Escape]);
        assert!(!panel.visible, "Escape closes the panel");
    }

    #[test]
    fn h_and_l_switch_agents_on_the_egui_side() {
        // The panel is a guarding Popup: the overlay stack consumes `h`/`l`
        // before terminal key dispatch, so show() is the only place they
        // can act. Before this, the winit key layer that owned them was
        // unreachable and agent switching did nothing.
        let record = |id: &str| {
            crate::agent_usage::records::parse_record(&format!(
                r#"{{"id":"{id}","name":"{id}","ready":true}}"#
            ))
            .expect("record parses")
        };
        let snap = UsageSnapshot {
            records: vec![record("a"), record("b"), record("c")],
            errors: Vec::new(),
        };
        let ctx = Context::default();
        let mut panel = AgentUsagePanel::new();
        panel.open();
        frame_with_keys(&ctx, &snap, &mut panel, &[Key::L]);
        assert_eq!(panel.selected_agent, 1, "l moves to the next agent");
        frame_with_keys(&ctx, &snap, &mut panel, &[Key::L, Key::L]);
        assert_eq!(panel.selected_agent, 0, "two coalesced presses both act");
        frame_with_keys(&ctx, &snap, &mut panel, &[Key::H]);
        assert_eq!(panel.selected_agent, 2, "h wraps back to the last agent");
    }

    #[test]
    fn r_requests_the_refresh_rescan() {
        // The footer advertises `r refresh`; the caller runs the rescan
        // when show() returns RefreshRequested (egui_submit).
        let snap = UsageSnapshot {
            records: Vec::new(),
            errors: Vec::new(),
        };
        let ctx = Context::default();
        let mut panel = AgentUsagePanel::new();
        panel.open();
        assert_eq!(
            frame_with_keys(&ctx, &snap, &mut panel, &[Key::R]),
            Some(PanelAction::RefreshRequested),
            "r is the advertised refresh key"
        );
        assert_eq!(
            frame_with_keys(&ctx, &snap, &mut panel, &[]),
            None,
            "the refresh fires once per press, not every frame"
        );
    }

    #[test]
    fn panel_is_registered_as_modal() {
        // The Phase 1 lesson, made structural: an overlay that does not
        // guard the terminal leaks keystrokes to the PTY. The live half —
        // the panel opened on a real WindowState raises the guard — is
        // `overlay::stack_tests::b61_dialogs_block_the_terminal`.
        assert!(crate::app::overlay::OverlayId::AgentUsage.guards_terminal());
    }

    #[test]
    fn reset_countdown_formats_hours_and_minutes() {
        // 2h5m out, so a minute-boundary race cannot round the hours down
        // between constructing the timestamp and reading the countdown.
        let in_2h = (Utc::now() + chrono::Duration::minutes(125)).to_rfc3339();
        let text = reset_countdown(Some(&in_2h)).expect("parses future timestamp");
        assert!(text.starts_with("resets in 2h"), "got: {text}");
    }

    #[test]
    fn reset_countdown_rejects_garbage_and_past() {
        assert_eq!(reset_countdown(None), None);
        assert_eq!(reset_countdown(Some("not a date")), None);
        let past = (Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
        assert_eq!(reset_countdown(Some(&past)), None);
    }

    #[test]
    fn format_tokens_picks_sensible_units() {
        assert_eq!(format_tokens(950.0), "950");
        assert_eq!(format_tokens(8_200_000.0), "8.2M");
        assert_eq!(format_tokens(1.4e9), "1.4B");
    }
}