synaps 0.1.4

Terminal-native AI agent runtime — parallel orchestration, reactive subagents, MCP, autonomous supervision
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
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
use ratatui::Frame;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, BorderType, Borders, Clear, Gauge, Paragraph, Wrap};
use super::PluginsModalState;
use super::progress::{ClonePhase, InstallProgressHandle};
use super::state::{Focus, LeftRow, RightMode, RightRow};
use super::super::theme::THEME;

const OVERLAY_MAX_WIDTH: u16 = 70;
const OVERLAY_HEIGHT: u16 = 7;

/// Width of the centered overlay rect for a given outer area.
/// Single source of truth — used by both the rect builder and the
/// content-aware height estimators so wrapping can be computed against
/// the same width that will actually be rendered.
fn overlay_outer_width(area: Rect) -> u16 {
    area.width.saturating_sub(4).clamp(24, OVERLAY_MAX_WIDTH)
}

/// Inner content width = outer width minus 2 for the rounded box borders.
fn overlay_inner_width(area: Rect) -> u16 {
    overlay_outer_width(area).saturating_sub(2)
}

/// Estimate how many rows `line` will occupy when rendered into a column of
/// `content_width` cells with `Wrap { trim: false }`. Counts characters as
/// a 1:1 proxy for display width — fine for ASCII, slightly over-tall for
/// wide-char content (we'd rather waste a row than clip the y/n footer).
fn estimate_wrapped_rows(line: &str, content_width: u16) -> u16 {
    if content_width == 0 {
        return 1;
    }
    let cw = content_width as usize;
    let chars = line.chars().count().max(1);
    (chars.div_ceil(cw)) as u16
}

/// Estimate total rows for a summary block. Each summary line is prefixed
/// with two spaces of indent (`"  {line}"`), so usable width per line is
/// `inner_width - 2`.
fn estimate_summary_rows(summary: &[String], inner_width: u16) -> u16 {
    let usable = inner_width.saturating_sub(2);
    summary
        .iter()
        .map(|s| estimate_wrapped_rows(s, usable))
        .sum()
}

pub(crate) fn render(frame: &mut Frame, area: Rect, state: &PluginsModalState) {
    let w = (area.width.saturating_mul(8) / 10).max(60).min(area.width);
    let h = (area.height.saturating_mul(7) / 10).max(20).min(area.height);
    let x = area.x + (area.width.saturating_sub(w)) / 2;
    let y = area.y + (area.height.saturating_sub(h)) / 2;
    let modal = Rect { x, y, width: w, height: h };

    frame.render_widget(Clear, modal);
    let block = Block::default()
        .title(" Plugins ")
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(THEME.load().border_active))
        .style(Style::default().bg(THEME.load().bg));
    let inner = block.inner(modal);
    frame.render_widget(block, modal);

    let outer = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Min(1), Constraint::Length(1)])
        .split(inner);
    let panes = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([Constraint::Length(20), Constraint::Min(1)])
        .split(outer[0]);

    render_left(frame, panes[0], state);
    render_right(frame, panes[1], state);
    render_footer(frame, outer[1], state);
}

fn render_left(frame: &mut Frame, area: Rect, state: &PluginsModalState) {
    let rows = state.left_rows();
    let installed_count = state.file.installed.len();
    let mut lines = Vec::with_capacity(rows.len());
    for (i, row) in rows.iter().enumerate() {
        let selected = i == state.selected_left;
        let marker = if selected { "" } else { "  " };
        let style = if selected && matches!(state.focus, Focus::Left) {
            Style::default().fg(THEME.load().claude_label)
        } else if selected {
            Style::default().fg(THEME.load().claude_text)
        } else {
            Style::default().fg(THEME.load().help_fg)
        };
        let label = match row {
            LeftRow::Installed => {
                if installed_count > 0 {
                    format!("Installed ({})", installed_count)
                } else {
                    "Installed".to_string()
                }
            }
            LeftRow::Marketplace(name) => {
                let count = state.file.marketplaces.iter()
                    .find(|m| &m.name == name)
                    .map(|m| m.cached_plugins.len())
                    .unwrap_or(0);
                if count > 0 {
                    format!("{} ({})", name, count)
                } else {
                    name.clone()
                }
            }
            LeftRow::AddMarketplace => "+ Add Marketplace…".to_string(),
        };
        lines.push(Line::from(vec![Span::styled(format!("{}{}", marker, label), style)]));
    }
    frame.render_widget(Paragraph::new(lines), area);
}

fn render_right(frame: &mut Frame, area: Rect, state: &PluginsModalState) {
    // Always render the list behind overlays so users see context.
    render_right_list(frame, area, state);
    match &state.mode {
        RightMode::List => {}
        RightMode::Installing { progress } => render_installing(frame, area, progress),
        RightMode::Detail { row_idx } => render_right_detail(frame, area, state, *row_idx),
        RightMode::AddMarketplaceEditor { buffer, error } => {
            render_add_editor(frame, area, buffer, error.as_deref())
        }
        RightMode::TrustPrompt { plugin_name, host, summary, .. } => {
            render_trust_prompt(frame, area, plugin_name, host, summary)
        }
        RightMode::Confirm { prompt, summary, .. } => render_confirm(frame, area, prompt, summary),
        RightMode::PendingInstallConfirm { plugin_name, summary, .. } => {
            render_confirm(frame, area, &format!("Install executable plugin '{}' ?", plugin_name).replace("' ?", "'?"), summary)
        }
        RightMode::PendingUpdateConfirm { plugin_name, summary, .. } => {
            render_confirm(frame, area, &format!("Update plugin '{}' ?", plugin_name).replace("' ?", "'?"), summary)
        }
    }
}

fn installed_row_up_to_date(latest_commit: Option<&String>, installed_commit: &str, checksum_value: Option<&String>) -> bool {
    match (latest_commit, checksum_value) {
        (Some(latest), _) if latest == installed_commit => true,
        (None, Some(_)) => true,
        _ => false,
    }
}

fn render_right_list(frame: &mut Frame, area: Rect, state: &PluginsModalState) {
    let rows = state.right_rows();
    if rows.is_empty() {
        let hint = match state.left_rows().get(state.selected_left) {
            Some(LeftRow::AddMarketplace) => "  Press Enter to add a marketplace.",
            Some(LeftRow::Installed) => "  No plugins installed.",
            Some(LeftRow::Marketplace(_)) => "  No cached plugins. Press r to refresh.",
            None => "",
        };
        frame.render_widget(
            Paragraph::new(Line::from(Span::styled(
                hint,
                Style::default().fg(THEME.load().help_fg),
            ))),
            area,
        );
        return;
    }

    let mut lines = Vec::with_capacity(rows.len());
    for (i, row) in rows.iter().enumerate() {
        let selected = i == state.selected_right && matches!(state.focus, Focus::Right);
        let style = if selected {
            Style::default().fg(THEME.load().claude_label)
        } else if i == state.selected_right {
            Style::default().fg(THEME.load().claude_text)
        } else {
            Style::default().fg(THEME.load().help_fg)
        };
        let (name, status) = match row {
            RightRow::Installed(ip) => {
                let mut s = String::from("installed");
                let up_to_date = installed_row_up_to_date(
                    ip.latest_commit.as_ref(),
                    &ip.installed_commit,
                    ip.checksum_value.as_ref(),
                );
                if !up_to_date {
                    s.push_str(" (update)");
                }
                (ip.name.clone(), s)
            }
            RightRow::Browseable { plugin, installed } => {
                let status = if *installed { "installed" } else { "available" };
                (plugin.name.clone(), status.to_string())
            }
        };
        lines.push(Line::from(vec![Span::styled(
            format!("  {:<20} {}", name, status),
            style,
        )]));
    }
    frame.render_widget(Paragraph::new(lines), area);
}

fn render_right_detail(frame: &mut Frame, area: Rect, state: &PluginsModalState, row_idx: usize) {
    // Inset overlay panel for detail content.
    let rect = inset_rect(area, 2, 1);
    frame.render_widget(Clear, rect);
    let block = Block::default()
        .title(" Detail ")
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(THEME.load().border_active))
        .style(Style::default().bg(THEME.load().bg));
    let inner = block.inner(rect);
    frame.render_widget(block, rect);

    let rows = state.right_rows();
    let Some(row) = rows.get(row_idx) else {
        frame.render_widget(
            Paragraph::new("(no selection)")
                .style(Style::default().fg(THEME.load().help_fg)),
            inner,
        );
        return;
    };

    let label_style = Style::default().fg(THEME.load().help_fg);
    let value_style = Style::default().fg(THEME.load().claude_text);
    let mut lines: Vec<Line> = Vec::new();
    match row {
        RightRow::Installed(ip) => {
            lines.push(Line::from(vec![
                Span::styled("name:        ", label_style),
                Span::styled(ip.name.clone(), value_style),
            ]));
            lines.push(Line::from(vec![
                Span::styled("source:      ", label_style),
                Span::styled(ip.source_url.clone(), value_style),
            ]));
            lines.push(Line::from(vec![
                Span::styled("marketplace: ", label_style),
                Span::styled(
                    ip.marketplace.clone().unwrap_or_else(|| "(direct)".to_string()),
                    value_style,
                ),
            ]));
            lines.push(Line::from(vec![
                Span::styled("commit:      ", label_style),
                Span::styled(ip.installed_commit.clone(), value_style),
            ]));
            let latest = ip.latest_commit.clone().unwrap_or_else(|| {
                if ip.checksum_value.is_some() {
                    "index-verified".to_string()
                } else {
                    "?".to_string()
                }
            });
            let up_to_date = installed_row_up_to_date(
                ip.latest_commit.as_ref(),
                &ip.installed_commit,
                ip.checksum_value.as_ref(),
            );
            let mut latest_line = latest;
            if !up_to_date {
                latest_line.push_str("  (update available)");
            }
            lines.push(Line::from(vec![
                Span::styled("latest:      ", label_style),
                Span::styled(latest_line, value_style),
            ]));
            lines.push(Line::from(vec![
                Span::styled("installed:   ", label_style),
                Span::styled(ip.installed_at.clone(), value_style),
            ]));
            if let Some(value) = &ip.checksum_value {
                lines.push(Line::from(vec![
                    Span::styled("checksum:    ", label_style),
                    Span::styled(
                        format!("{}:{}", ip.checksum_algorithm.clone().unwrap_or_else(|| "sha256".to_string()), value),
                        value_style,
                    ),
                ]));
            }
        }
        RightRow::Browseable { plugin, installed } => {
            lines.push(Line::from(vec![
                Span::styled("name:        ", label_style),
                Span::styled(plugin.name.clone(), value_style),
            ]));
            lines.push(Line::from(vec![
                Span::styled("source:      ", label_style),
                Span::styled(plugin.source.clone(), value_style),
            ]));
            lines.push(Line::from(vec![
                Span::styled("version:     ", label_style),
                Span::styled(
                    plugin.version.clone().unwrap_or_else(|| "?".to_string()),
                    value_style,
                ),
            ]));
            lines.push(Line::from(vec![
                Span::styled("description: ", label_style),
                Span::styled(
                    plugin.description.clone().unwrap_or_else(|| "no description".to_string()),
                    value_style,
                ),
            ]));
            lines.push(Line::from(vec![
                Span::styled("status:      ", label_style),
                Span::styled(
                    if *installed { "installed" } else { "available" }.to_string(),
                    value_style,
                ),
            ]));
            if let Some(index) = &plugin.index {
                lines.push(Line::from(vec![
                    Span::styled("repository:  ", label_style),
                    Span::styled(index.repository.clone(), value_style),
                ]));
                lines.push(Line::from(vec![
                    Span::styled("checksum:    ", label_style),
                    Span::styled(format!("{}:{}", index.checksum_algorithm, index.checksum_value), value_style),
                ]));
                lines.push(Line::from(vec![
                    Span::styled("compatible:  ", label_style),
                    Span::styled(format!(
                        "Synaps {}, extension protocol {}",
                        index.compatibility_synaps.clone().unwrap_or_else(|| "unspecified".to_string()),
                        index.compatibility_extension_protocol.clone().unwrap_or_else(|| "unspecified".to_string())
                    ), value_style),
                ]));
                lines.push(Line::from(vec![
                    Span::styled("executable:  ", label_style),
                    Span::styled(if index.has_extension { "yes" } else { "no" }, value_style),
                ]));
                lines.push(Line::from(vec![
                    Span::styled("permissions: ", label_style),
                    Span::styled(if index.permissions.is_empty() { "none".to_string() } else { index.permissions.join(", ") }, value_style),
                ]));
                lines.push(Line::from(vec![
                    Span::styled("hooks:       ", label_style),
                    Span::styled(if index.hooks.is_empty() { "none".to_string() } else { index.hooks.join(", ") }, value_style),
                ]));
                lines.push(Line::from(vec![
                    Span::styled("commands:    ", label_style),
                    Span::styled(if index.commands.is_empty() { "none".to_string() } else { index.commands.join(", ") }, value_style),
                ]));
                if !index.providers.is_empty() {
                    lines.push(Line::from(vec![
                        Span::styled("providers:   ", label_style),
                        Span::styled(index.providers.iter().map(|p| format!("{} ({})", p.id, p.models.join(", "))).collect::<Vec<_>>().join("; "), value_style),
                    ]));
                }
                if index.permissions.iter().any(|permission| permission == "providers.register") {
                    lines.push(Line::from(vec![
                        Span::styled("provider UX: ", label_style),
                        Span::styled("high impact — selected provider models receive conversation content", Style::default().fg(THEME.load().error_color)),
                    ]));
                }
                if let Some(publisher) = &index.trust_publisher {
                    lines.push(Line::from(vec![
                        Span::styled("publisher:   ", label_style),
                        Span::styled(publisher.clone(), value_style),
                    ]));
                }
                if let Some(homepage) = &index.trust_homepage {
                    lines.push(Line::from(vec![
                        Span::styled("homepage:    ", label_style),
                        Span::styled(homepage.clone(), value_style),
                    ]));
                }
                lines.push(Line::from(vec![
                    Span::styled("install:     ", label_style),
                    Span::styled("fetched manifest is re-inspected before final install", value_style),
                ]));
            }
        }
    }
    frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), inner);
}

fn centered_overlay_with_height(frame: &mut Frame, area: Rect, title: &str, height: u16) -> Rect {
    let w = overlay_outer_width(area);
    let h = height;
    let x = area.x + area.width.saturating_sub(w) / 2;
    let y = area.y + area.height.saturating_sub(h) / 2;
    let rect = Rect { x, y, width: w, height: h.min(area.height) };
    frame.render_widget(Clear, rect);
    let block = Block::default()
        .title(title.to_string())
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(THEME.load().border_active))
        .style(Style::default().bg(THEME.load().bg));
    let inner = block.inner(rect);
    frame.render_widget(block, rect);
    inner
}

fn centered_overlay(frame: &mut Frame, area: Rect, title: &str) -> Rect {
    centered_overlay_with_height(frame, area, title, OVERLAY_HEIGHT)
}

fn render_add_editor(frame: &mut Frame, area: Rect, buffer: &str, error: Option<&str>) {
    let inner = centered_overlay(frame, area, " Add Marketplace ");

    let mut lines: Vec<Line> = Vec::new();
    lines.push(Line::from(Span::styled(
        "Enter marketplace URL:",
        Style::default().fg(THEME.load().help_fg),
    )));
    lines.push(Line::from(Span::styled(
        format!("[{}_]", buffer),
        Style::default().fg(THEME.load().claude_label),
    )));
    if let Some(err) = error {
        lines.push(Line::from(Span::raw("")));
        lines.push(Line::from(Span::styled(
            format!("! {}", err),
            Style::default().fg(THEME.load().error_color),
        )));
    }
    frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), inner);
}

fn render_trust_prompt(frame: &mut Frame, area: Rect, plugin_name: &str, host: &str, summary: &[String]) {
    let inner_w = overlay_inner_width(area);
    let prompt = format!("Trust source {} and install {}?", host, plugin_name);
    let prompt_rows = estimate_wrapped_rows(&prompt, inner_w);
    let summary_rows = estimate_summary_rows(summary, inner_w);
    // Layout (content): prompt + blank + summary + blank + y/n
    // Plus 2 rows for the rounded box borders.
    let needed = 2 + prompt_rows + 1 + summary_rows + 1 + 1;
    let height = needed.max(OVERLAY_HEIGHT).min(area.height.max(1));
    let inner = centered_overlay_with_height(frame, area, " Trust Plugin ", height);

    let mut lines = vec![
        Line::from(Span::styled(
            prompt,
            Style::default().fg(THEME.load().claude_text),
        )),
        Line::from(Span::raw("")),
    ];
    for line in summary {
        lines.push(Line::from(Span::styled(
            format!("  {}", line),
            Style::default().fg(THEME.load().help_fg),
        )));
    }
    lines.push(Line::from(Span::raw("")));
    lines.push(Line::from(Span::styled(
        "  [y]es  [n]o",
        Style::default().fg(THEME.load().help_fg),
    )));
    frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), inner);
}

fn render_confirm(frame: &mut Frame, area: Rect, prompt: &str, summary: &[String]) {
    let inner_w = overlay_inner_width(area);
    let prompt_rows = estimate_wrapped_rows(prompt, inner_w);
    let summary_rows = estimate_summary_rows(summary, inner_w);
    // Layout (content): prompt + blank + summary + blank + y/n
    // Plus 2 rows for the rounded box borders.
    let needed = 2 + prompt_rows + 1 + summary_rows + 1 + 1;
    let height = needed.max(OVERLAY_HEIGHT).min(area.height.max(1));
    let inner = centered_overlay_with_height(frame, area, " Confirm ", height);

    let mut lines = vec![
        Line::from(Span::styled(
            prompt.to_string(),
            Style::default().fg(THEME.load().claude_text),
        )),
        Line::from(Span::raw("")),
    ];
    for line in summary {
        lines.push(Line::from(Span::styled(
            format!("  {}", line),
            Style::default().fg(THEME.load().help_fg),
        )));
    }
    lines.push(Line::from(Span::raw("")));
    lines.push(Line::from(Span::styled(
        "  [y]es  [n]o",
        Style::default().fg(THEME.load().help_fg),
    )));
    frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), inner);
}

/// Animated frames for the spinner shown next to "Downloading…" while the
/// background `git clone` is in flight. Braille frames give a smooth feel
/// at 60fps without competing with the gauge for attention.
const SPINNER_FRAMES: &[char] = &['', '', '', '', '', '', '', '', '', ''];

fn render_installing(frame: &mut Frame, area: Rect, progress: &InstallProgressHandle) {
    // Snapshot the shared state under a short-lived lock; never hold the
    // lock across rendering calls.
    let snap = match progress.lock() {
        Ok(p) => (
            p.plugin_name.clone(),
            p.phase,
            p.percent,
            p.counts,
            p.throughput.clone(),
            p.spinner_frame as usize,
            p.started_at,
            p.last_raw_line.clone(),
        ),
        Err(_) => return,
    };
    let (plugin_name, phase, percent, counts, throughput, spinner_frame, started_at, last_raw) =
        snap;

    let elapsed = started_at.elapsed();
    let elapsed_str = format!("{:>2}.{:02}s", elapsed.as_secs(), elapsed.subsec_millis() / 10);

    // Layout: title + blank + gauge (1 row) + status line + (optional error line)
    // Content rows fixed at 5 + optional error line; +2 borders.
    let has_error = matches!(phase, ClonePhase::Failed) && last_raw.is_some();
    let needed = 5 + if has_error { 1 } else { 0 } + 2;
    let height = (needed as u16).max(OVERLAY_HEIGHT).min(area.height.max(1));
    let inner = centered_overlay_with_height(frame, area, " Installing ", height);

    let layout = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1), // title
            Constraint::Length(1), // blank
            Constraint::Length(1), // gauge
            Constraint::Length(1), // status line
            Constraint::Min(0),    // error / spacer
        ])
        .split(inner);

    let spinner_ch = SPINNER_FRAMES[spinner_frame % SPINNER_FRAMES.len()];
    let title_line = Line::from(vec![
        Span::styled(
            format!("{} ", spinner_ch),
            Style::default()
                .fg(THEME.load().claude_label)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            format!("Downloading {}", plugin_name),
            Style::default().fg(THEME.load().claude_text),
        ),
        Span::styled(
            format!("   {}", elapsed_str),
            Style::default().fg(THEME.load().help_fg),
        ),
    ]);
    frame.render_widget(Paragraph::new(title_line), layout[0]);

    // Gauge — show indeterminate spinner-style fill while connecting,
    // real percentage once we have one.
    let pct = percent.unwrap_or(0).min(100);
    let pct_ratio = (pct as f64) / 100.0;
    let gauge_label = match (phase, counts) {
        (ClonePhase::Connecting, _) => "connecting…".to_string(),
        (ClonePhase::SetupRunning, _) => "running setup script…".to_string(),
        (ClonePhase::Done, _) => "complete".to_string(),
        (ClonePhase::Failed, _) => "failed".to_string(),
        (_, Some((a, b))) => format!("{:>3}%  ({}/{})", pct, a, b),
        (_, None) => format!("{:>3}%", pct),
    };
    let gauge = Gauge::default()
        .gauge_style(
            Style::default()
                .fg(if matches!(phase, ClonePhase::Failed) {
                    THEME.load().error_color
                } else {
                    THEME.load().claude_label
                })
                .bg(THEME.load().bg),
        )
        .ratio(pct_ratio)
        .label(gauge_label);
    frame.render_widget(gauge, layout[2]);

    // Status line: phase label + throughput
    let mut status_spans = vec![Span::styled(
        phase.label(),
        Style::default().fg(THEME.load().help_fg),
    )];
    if let Some(tp) = throughput {
        status_spans.push(Span::styled(
            format!("    {}", tp),
            Style::default().fg(THEME.load().help_fg),
        ));
    }
    frame.render_widget(Paragraph::new(Line::from(status_spans)), layout[3]);

    if has_error {
        if let Some(msg) = last_raw {
            frame.render_widget(
                Paragraph::new(Line::from(Span::styled(
                    format!("! {}", msg),
                    Style::default().fg(THEME.load().error_color),
                )))
                .wrap(Wrap { trim: false }),
                layout[4],
            );
        }
    }
}

fn render_footer(frame: &mut Frame, area: Rect, state: &PluginsModalState) {
    let hint = match (&state.focus, &state.mode) {
        (_, RightMode::Detail { .. }) => "Esc back  i install  u update  U uninstall",
        (_, RightMode::AddMarketplaceEditor { .. }) => "Type URL  Enter submit  Esc cancel",
        (_, RightMode::TrustPrompt { .. }) => "y trust  n cancel",
        (_, RightMode::Confirm { .. }) => "y yes  n no  Esc cancel",
        (_, RightMode::PendingInstallConfirm { .. }) => "y install  n cancel  Esc cancel",
        (_, RightMode::PendingUpdateConfirm { .. }) => "y update  n cancel  Esc cancel",
        (_, RightMode::Installing { .. }) => "downloading…  please wait",
        (Focus::Left, RightMode::List) => {
            "↑↓ nav  Tab switch  Enter select  r refresh  R remove  Esc close"
        }
        (Focus::Right, RightMode::List) => {
            "↑↓ nav  Tab  Enter detail  i install  e/d enable/disable  u update  U uninstall  r refresh  R remove mkt  Esc close"
        }
    };

    if let Some(err) = &state.row_error {
        let spans = vec![
            Span::styled(format!("! {}  ", err), Style::default().fg(THEME.load().error_color)),
            Span::styled(hint.to_string(), Style::default().fg(THEME.load().help_fg)),
        ];
        frame.render_widget(Paragraph::new(Line::from(spans)), area);
    } else {
        frame.render_widget(
            Paragraph::new(hint).style(Style::default().fg(THEME.load().help_fg)),
            area,
        );
    }
}

fn inset_rect(area: Rect, dx: u16, dy: u16) -> Rect {
    let w = area.width.saturating_sub(dx * 2);
    let h = area.height.saturating_sub(dy * 2);
    Rect {
        x: area.x + dx.min(area.width),
        y: area.y + dy.min(area.height),
        width: w,
        height: h,
    }
}

#[cfg(test)]
mod tests {
    use super::{
        estimate_summary_rows, estimate_wrapped_rows, installed_row_up_to_date,
        OVERLAY_HEIGHT,
    };

    #[test]
    fn index_verified_row_without_remote_head_is_current() {
        let checksum = "f".repeat(64);
        assert!(installed_row_up_to_date(None, "abc", Some(&checksum)));
    }

    #[test]
    fn legacy_row_without_remote_head_is_not_current() {
        assert!(!installed_row_up_to_date(None, "abc", None));
    }

    #[test]
    fn matching_remote_head_is_current() {
        let latest = "abc".to_string();
        assert!(installed_row_up_to_date(Some(&latest), "abc", None));
    }

    #[test]
    fn empty_line_estimates_one_row() {
        assert_eq!(estimate_wrapped_rows("", 40), 1);
    }

    #[test]
    fn short_line_estimates_one_row() {
        assert_eq!(estimate_wrapped_rows("hello", 40), 1);
    }

    #[test]
    fn line_at_exact_width_is_one_row() {
        let s: String = "x".repeat(40);
        assert_eq!(estimate_wrapped_rows(&s, 40), 1);
    }

    #[test]
    fn line_one_over_width_wraps_to_two() {
        let s: String = "x".repeat(41);
        assert_eq!(estimate_wrapped_rows(&s, 40), 2);
    }

    #[test]
    fn zero_width_falls_back_to_single_row() {
        assert_eq!(estimate_wrapped_rows("anything", 0), 1);
    }

    #[test]
    fn summary_rows_account_for_two_space_indent() {
        // Inner width 40 -> usable 38 after the "  " indent.
        // A 38-char line stays on one row; 39 wraps to two.
        let lines = vec!["x".repeat(38), "x".repeat(39)];
        assert_eq!(estimate_summary_rows(&lines, 40), 1 + 2);
    }

    #[test]
    fn summary_rows_for_typical_install_summary() {
        // Realistic permissions summary: 2-3 short lines, all fit.
        let lines: Vec<String> = vec![
            "executable extension: yes".into(),
            "permissions: tools.intercept, privacy.llm_content".into(),
            "hooks: 5".into(),
        ];
        assert_eq!(estimate_summary_rows(&lines, 60), 3);
    }

    /// Regression: previously `render_confirm` used `5 + N` for height which
    /// clipped the y/n footer when the summary had two or more lines on a
    /// terminal large enough that OVERLAY_HEIGHT (7) wasn't the floor.
    /// The corrected formula is `2 + prompt_rows + 1 + summary_rows + 1 + 1`
    /// (= 5 + summary_rows + prompt_rows). For a 1-row prompt and 3-row
    /// summary that's 9, and `.max(OVERLAY_HEIGHT)` keeps shorter cases at 7.
    #[test]
    fn confirm_height_fits_three_line_summary() {
        let summary = vec![
            "executable extension: yes".to_string(),
            "permissions: 3".to_string(),
            "hooks: 5".to_string(),
        ];
        let inner_w = 60;
        let prompt_rows = estimate_wrapped_rows("Install plugin 'x'?", inner_w);
        let summary_rows = estimate_summary_rows(&summary, inner_w);
        let needed = 2 + prompt_rows + 1 + summary_rows + 1 + 1;
        assert_eq!(needed, 9, "1-row prompt + 3-row summary needs 9 cells");
        let height = needed.max(OVERLAY_HEIGHT);
        assert!(
            height >= needed,
            "computed height {height} must accommodate content {needed}"
        );
    }

    #[test]
    fn confirm_height_floors_to_overlay_minimum_for_tiny_summary() {
        let summary: Vec<String> = vec![];
        let inner_w = 60;
        let prompt_rows = estimate_wrapped_rows("ok?", inner_w);
        let summary_rows = estimate_summary_rows(&summary, inner_w);
        let needed = 2 + prompt_rows + 1 + summary_rows + 1 + 1;
        assert_eq!(needed, 6);
        assert_eq!(needed.max(OVERLAY_HEIGHT), OVERLAY_HEIGHT);
    }
}