clauth 0.5.0

Simple Claude Code account switcher and usage monitor
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
//! Fallback tab — master-detail, mirroring the Config layout. Left: the ordered
//! chain (plus a trailing `+ add` row), cursor = `❯`, color = active. Right: the
//! selected member's rotation card (position, a 5h gauge with a threshold tick,
//! headroom, next hop) plus inline rows — a threshold stepper and a remove row —
//! or, on `+ add`, a candidate picker. Editing happens in place: ⏎ on the left
//! drops focus into the right pane, `+` / `-` step the threshold (or ⏎ on it to
//! type a value), ⏎ on remove arms then confirms. No popups.

use ratatui::Frame;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::Paragraph;

use super::super::app::{
    App, ChainItemKind, FALLBACK_ROWS, FallbackFocus, FallbackRow, InputState, chain_candidates,
    chain_items,
};
use super::super::theme;
use super::panes::{
    SELECTOR_WIDTH, draw_selector_list, highlight_row, name_color, section_box, select_line,
};
use crate::fallback::{DEFAULT_THRESHOLD, threshold_for};
use crate::profile::AppConfig;

/// Cells in the detail-pane gauges. Wide enough to read a threshold tick.
const GAUGE_W: usize = 22;
/// Padded key column width for the detail rows, matching the Config tab.
const KEY_W: usize = 11;

pub(super) fn draw(frame: &mut Frame<'_>, area: Rect, app: &App) {
    let cols = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([Constraint::Length(SELECTOR_WIDTH), Constraint::Min(20)])
        .split(area);

    let chain_focused = app.fallback_focus == FallbackFocus::Chain;
    draw_chain_selector(frame, cols[0], app, chain_focused);
    draw_chain_detail(frame, cols[1], app);
}

/// Left pane: the ordered chain members plus a trailing `+ add` row. Color marks
/// the active account; the cursor rides on `❯` only while this pane has focus.
fn draw_chain_selector(frame: &mut Frame<'_>, area: Rect, app: &App, focused: bool) {
    let items = chain_items(app);
    let cfg = app.config();
    let sel = app.chain_cursor.min(items.len().saturating_sub(1));
    draw_selector_list(frame, area, "chain", focused, sel, |w| {
        items
            .iter()
            .enumerate()
            .map(|(row, item)| {
                let selected = row == sel;
                let line = match item {
                    ChainItemKind::Member(i) => {
                        let name = cfg
                            .state
                            .fallback_chain
                            .get(*i)
                            .cloned()
                            .unwrap_or_default();
                        let style = name_color(cfg.is_active(&name));
                        // Cursor + ordinal share the leading span so the name
                        // lands at spans[1] — the item `highlight_row` bolds.
                        let rail = if selected {
                            Span::styled(format!("{:>2}  ", i + 1), theme::accent())
                        } else {
                            Span::styled(format!("  {:>2}  ", i + 1), theme::faint())
                        };
                        Line::from(vec![rail, Span::styled(name, style)])
                    }
                    ChainItemKind::Add => {
                        let arrow = if selected {
                            Span::styled("", theme::accent())
                        } else {
                            Span::raw("  ")
                        };
                        Line::from(vec![arrow, Span::styled("    + add", theme::accent())])
                    }
                };
                select_line(line, selected, focused, w)
            })
            .collect()
    });
}

/// Right pane: the member rotation card + inline rows, the add-candidate picker
/// on the `+ add` row, or an empty-chain explainer.
fn draw_chain_detail(frame: &mut Frame<'_>, area: Rect, app: &App) {
    let detail_focused = app.fallback_focus == FallbackFocus::Detail;
    let inner_w = section_box("", detail_focused).inner(area).width as usize;
    let items = chain_items(app);
    let selected = items
        .get(app.chain_cursor.min(items.len().saturating_sub(1)))
        .copied();

    // Each arm acquires the `config` guard only for as long as it needs it. The
    // `Add` arm must NOT hold it — `add_detail` re-locks `config` (via
    // `chain_candidates`), and the mutex is non-reentrant, so holding it here
    // would deadlock the whole render loop on the `+ add` row.
    let (title, lines): (String, Vec<Line<'static>>) = match selected {
        Some(ChainItemKind::Member(i)) => {
            let cfg = app.config();
            let chain_len = cfg.state.fallback_chain.len();
            let name = cfg.state.fallback_chain.get(i).cloned().unwrap_or_default();
            let lines = member_detail(
                &cfg,
                &name,
                i,
                chain_len,
                detail_focused,
                app.fallback_detail_cursor,
                app.fallback_armed_remove,
                app.fallback_threshold_draft.as_ref(),
                inner_w,
            );
            (name, lines)
        }
        Some(ChainItemKind::Add) => (
            "add to chain".to_string(),
            add_detail(app, detail_focused, inner_w),
        ),
        None => ("chain".to_string(), empty_detail()),
    };

    let block = section_box(&title, detail_focused);
    let inner = block.inner(area);
    frame.render_widget(block, area);
    frame.render_widget(Paragraph::new(lines).style(theme::base()), inner);
}

/// The member rotation card: position + active state, a 5h gauge with a
/// threshold tick, the headroom, the next hop, then the inline threshold
/// stepper / editor and remove rows. Caret + edit affordances appear only when
/// the right pane holds focus; keybind cues live in the footer.
#[allow(clippy::too_many_arguments)]
fn member_detail(
    cfg: &AppConfig,
    name: &str,
    index: usize,
    chain_len: usize,
    focused: bool,
    row_cursor: usize,
    armed_remove: bool,
    editing: Option<&InputState>,
    width: usize,
) -> Vec<Line<'static>> {
    let Some(profile) = cfg.find(name) else {
        return vec![Line::from(Span::styled(
            "account no longer exists — remove it from the chain",
            theme::danger(),
        ))];
    };

    let threshold = threshold_for(profile);
    let pct = profile
        .usage
        .as_ref()
        .and_then(|u| u.five_hour.as_ref())
        .map(|w| w.utilization);
    let active = cfg.is_active(name);
    let cursor = row_cursor.min(FALLBACK_ROWS.len() - 1);

    let mut lines: Vec<Line<'static>> = Vec::new();

    // Position + active state.
    lines.push(Line::from(vec![
        Span::styled(kv_key("position"), theme::faint()),
        Span::styled(format!("#{} of {chain_len}", index + 1), theme::muted()),
        if active {
            Span::styled("   ● active", theme::orange())
        } else {
            Span::raw("")
        },
    ]));
    lines.push(Line::from(""));

    // 5h gauge with a threshold tick.
    lines.push(Line::from(Span::styled("5h utilization", theme::label())));
    lines.push(Line::from(gauge_with_tick(pct, Some(threshold))));
    let (figure, figure_style) = match pct {
        Some(v) => {
            let headroom = (threshold - v).max(0.0);
            (
                format!("{v:.0}% used · {headroom:.0}% until rotate"),
                Style::default().fg(health_color(v, threshold)),
            )
        }
        None => ("no usage data yet".to_string(), theme::faint()),
    };
    lines.push(Line::from(Span::styled(figure, figure_style)));
    lines.push(Line::from(""));

    // Where rotation flows when this member crosses its threshold.
    if chain_len > 1 {
        let next = (index + 1) % chain_len;
        let next_name = cfg
            .state
            .fallback_chain
            .get(next)
            .cloned()
            .unwrap_or_default();
        let arrow = if next == 0 {
            Span::styled("↺ wraps to ", theme::orange())
        } else {
            Span::styled("→ next ", theme::accent())
        };
        lines.push(Line::from(vec![
            arrow,
            Span::styled(next_name, theme::dim()),
        ]));
    } else {
        lines.push(Line::from(Span::styled(
            "only member — rotation has nowhere to go",
            theme::faint(),
        )));
    }
    lines.push(Line::from(""));

    // Inline rows: threshold stepper / editor, the chain-global wrap-off toggle,
    // then remove. The caret + interactivity only render while the right pane
    // holds focus.
    let wrap_off = cfg.state.wrap_off;
    for (i, row) in FALLBACK_ROWS.iter().enumerate() {
        let selected = focused && i == cursor;
        let row_editing = if *row == FallbackRow::Threshold {
            editing
        } else {
            None
        };
        let line = detail_row(
            *row,
            selected,
            threshold,
            armed_remove,
            wrap_off,
            row_editing,
        );
        lines.push(if selected {
            highlight_row(line, width)
        } else {
            line
        });
        // Meaning tooltip under the focused row (keybind cues live in the footer).
        if selected && row_editing.is_none() {
            let tip = match row {
                FallbackRow::Threshold => Some("rotate to next account when 5h usage reaches this"),
                FallbackRow::WrapOff => Some("what to do once every member is over its threshold"),
                FallbackRow::Remove => None,
            };
            if let Some(tip) = tip {
                lines.push(Line::from(vec![
                    Span::styled("", theme::faint()),
                    Span::styled(tip, theme::faint()),
                ]));
            }
        }
    }
    lines
}

/// One member detail row: the threshold stepper / editor, the chain-global
/// wrap-off toggle, or the danger remove row. `editing` is `Some` only for the
/// threshold row while it's typed into.
fn detail_row(
    row: FallbackRow,
    selected: bool,
    threshold: f64,
    armed_remove: bool,
    wrap_off: bool,
    editing: Option<&InputState>,
) -> Line<'static> {
    let arrow = if selected {
        Span::styled("", theme::accent())
    } else {
        Span::raw("  ")
    };
    match row {
        FallbackRow::WrapOff => {
            let pad = KEY_W.saturating_sub("when spent".len()).max(1);
            // Spell out the action, not a mode name: the chosen branch reads as
            // a sentence so "off" is never shown as a bare, confusing value.
            let (value, style) = if wrap_off {
                ("switch off all accounts", theme::orange())
            } else {
                ("stay on last account", theme::accent())
            };
            Line::from(vec![
                arrow,
                Span::styled(
                    format!("when spent{}", " ".repeat(pad)),
                    Style::default().fg(theme::TEXT),
                ),
                Span::styled(value.to_string(), style),
            ])
        }
        FallbackRow::Threshold => {
            let pad = KEY_W.saturating_sub("threshold".len()).max(1);
            let mut spans = vec![
                arrow,
                Span::styled(
                    format!("threshold{}", " ".repeat(pad)),
                    Style::default().fg(theme::TEXT),
                ),
            ];
            match editing {
                Some(input) => {
                    spans.extend(value_caret(input));
                    spans.push(Span::styled("%", theme::faint()));
                }
                None => {
                    spans.push(Span::styled(format!("{threshold:.0}%"), theme::accent()));
                    if (threshold - DEFAULT_THRESHOLD).abs() > f64::EPSILON {
                        spans.push(Span::styled(
                            format!("   default: {DEFAULT_THRESHOLD:.0}%"),
                            theme::faint(),
                        ));
                    }
                }
            }
            Line::from(spans)
        }
        FallbackRow::Remove => {
            let label = if armed_remove {
                "remove from chain — ⏎ again to confirm".to_string()
            } else {
                "remove from chain".to_string()
            };
            Line::from(vec![arrow, Span::styled(label, theme::danger())])
        }
    }
}

/// The typed threshold value with a block caret over a sunken input strip,
/// matching the Config tab's inline text edit.
fn value_caret(input: &InputState) -> Vec<Span<'static>> {
    let (head, tail) = input.value.split_at(input.cursor.min(input.value.len()));
    let caret_style = Style::default()
        .fg(theme::TEXT)
        .bg(theme::ACCENT)
        .add_modifier(Modifier::BOLD);
    let body = Style::default().fg(theme::TEXT).bg(theme::BG_SUNKEN);
    let mut tail_iter = tail.chars();
    let caret = tail_iter.next().unwrap_or(' ').to_string();
    let after: String = tail_iter.collect();
    vec![
        Span::styled(head.to_string(), body),
        Span::styled(caret, caret_style),
        Span::styled(after, body),
    ]
}

/// The `+ add` detail: an explainer plus the candidate picker. The caret only
/// renders while the right pane holds focus.
fn add_detail(app: &App, focused: bool, width: usize) -> Vec<Line<'static>> {
    let candidates = chain_candidates(app);
    let mut lines: Vec<Line<'static>> = vec![
        Line::from(Span::styled(
            "add an account to the rotation",
            theme::muted(),
        )),
        Line::from(""),
        Line::from(Span::styled(
            "clauth auto-switches off a member when its 5h window crosses the",
            theme::dim(),
        )),
        Line::from(Span::styled(
            "member's threshold, moving to the next account in the chain.",
            theme::dim(),
        )),
        Line::from(""),
    ];

    if candidates.is_empty() {
        lines.push(Line::from(Span::styled(
            "every account is already in the chain",
            theme::faint(),
        )));
        return lines;
    }

    // Blurred: explainer only. The candidate rows (with caret) appear once the
    // right pane takes focus; the footer carries the keybind cue.
    if !focused {
        return lines;
    }

    let cursor = app
        .fallback_detail_cursor
        .min(candidates.len().saturating_sub(1));
    for (i, name) in candidates.iter().enumerate() {
        let selected = i == cursor;
        let arrow = if selected {
            Span::styled("", theme::accent())
        } else {
            Span::raw("  ")
        };
        let line = Line::from(vec![
            arrow,
            Span::styled(name.clone(), Style::default().fg(theme::TEXT)),
        ]);
        lines.push(if selected {
            highlight_row(line, width)
        } else {
            line
        });
    }
    lines
}

fn empty_detail() -> Vec<Line<'static>> {
    vec![
        Line::from(Span::styled("chain is empty", theme::muted())),
        Line::from(""),
        Line::from(Span::styled(
            "create an account first, then add it to the chain.",
            theme::dim(),
        )),
    ]
}

/// `GAUGE_W`-cell bar over 0..100 with the fill colored by headroom against the
/// threshold and a `┊` tick drawn at the threshold position.
fn gauge_with_tick(pct: Option<f64>, threshold: Option<f64>) -> Vec<Span<'static>> {
    let value = pct.unwrap_or(0.0).clamp(0.0, 100.0);
    let fill = ((value / 100.0) * GAUGE_W as f64).round() as usize;
    let fill = fill.min(GAUGE_W);
    let tick = threshold.map(|t| {
        (((t.clamp(0.0, 100.0) / 100.0) * GAUGE_W as f64).round() as usize).min(GAUGE_W - 1)
    });
    let fill_color = match (pct, threshold) {
        (Some(v), Some(t)) => health_color(v, t),
        (Some(_), None) => theme::ACCENT,
        _ => theme::TEXT_FAINT,
    };

    let mut spans = vec![Span::raw("[")];
    for i in 0..GAUGE_W {
        if Some(i) == tick {
            spans.push(Span::styled("", Style::default().fg(theme::TEXT)));
        } else if i < fill {
            spans.push(Span::styled("", Style::default().fg(fill_color)));
        } else {
            spans.push(Span::styled("", Style::default().fg(theme::LINE_STRONG)));
        }
    }
    spans.push(Span::raw("]"));
    spans
}

/// 5h headroom against the member's own threshold: green with room, yellow as
/// it nears, pink once it crosses — the point clauth rotates off it.
fn health_color(pct: f64, threshold: f64) -> Color {
    if pct >= threshold {
        theme::DANGER
    } else if pct >= threshold * 0.8 {
        theme::WARNING
    } else {
        theme::SUCCESS
    }
}

/// Pad a detail key to a fixed gutter so values line up.
fn kv_key(key: &str) -> String {
    let pad = KEY_W.saturating_sub(key.chars().count()).max(1);
    format!("{key}{}", " ".repeat(pad))
}