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
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
//! Root: mode stack, action dispatch, component tree (PLAN.md §6).
//! GitHub calls run on worker threads (blocking reqwest); results return
//! over an mpsc channel as `AppEvent`s, drained once per event-loop tick.
//!
//! `App::with` constructs an **offline** app for tests: no workers are
//! spawned; backend outcomes are injected via `handle_action`.
use crate::action::Action;
use crate::components::browser::Browser;
use crate::components::clone_wizard::CloneWizard;
use crate::components::command_line::CommandLine;
use crate::components::consent_popup::ConsentPopup;
use crate::components::global_search::{GlobalSearch, SearchKind};
use crate::components::keybinds_popup::KeybindsPopup;
use crate::components::modeline::Modeline;
use crate::components::pane::EntryKind;
use crate::components::refs_popup::RefsPopup;
use crate::components::search_popup::SearchPopup;
use crate::components::settings_popup::SettingsPopup;
use crate::components::vim_input::Outcome;
use crate::config::Config;
use crate::event::{AppEvent, AppTx};
use crate::highlight::Highlighter;
use crate::keymap;
use crate::mode::Mode;
use crate::provider::{self, Provider};
use crate::state::State;
use crate::theme::{BorderShape, Theme};
use ratatui::Frame;
use ratatui::crossterm::event::KeyEvent;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::widgets::Paragraph;
use std::sync::Arc;
mod workers;
pub struct App {
mode: Mode,
browser: Browser,
popup: Option<SearchPopup>,
/// Full-screen global search view (␣ f / ␣ g); replaces the
/// browser while open (plans/0002-v0.2).
search_view: Option<GlobalSearch>,
/// Overlays (plans/0003/0004): at most one at a time.
help: Option<KeybindsPopup>,
command_line: Option<CommandLine>,
settings: Option<SettingsPopup>,
wizard: Option<CloneWizard>,
/// Revision switcher overlay (plans/0016 M1a mock) and the
/// revision committed when it opened — Esc reverts the crumb.
refs_popup: Option<RefsPopup>,
refs_baseline: Option<String>,
/// 0019 M2: declared-but-missing provider — the consent popup
/// owns startup until answered (y installs, n degrades honestly).
consent: Option<ConsentPopup>,
/// 0019 M2: sticky degradation notice (declared provider
/// unavailable — the honest-channel surface). Transient statuses
/// overlay it; nothing clears it for the session.
degraded: Option<String>,
/// 0019 polish: last-commit memo for the preview band, keyed
/// (repo, path, ref). The band is ambient — re-selects never
/// refetch; the first preview of a file spawns one `log(limit=1)`.
last_commits: std::collections::HashMap<(String, String, String), crate::provider::LogEntry>,
/// closes (history from blame, find from preview).
history_return: Option<Mode>,
find_return: Option<Mode>,
/// A newer release tag when the startup check found one (0017 M3)
/// — the modeline's `↑ vX.Y.Z` chip.
update_tag: Option<String>,
modeline: Modeline,
theme: Theme,
config: Config,
state: State,
tx: AppTx,
provider: Arc<dyn Provider>,
highlighter: Highlighter,
/// The syntax roles the highlighter + blob cache are styled with
/// (restyle trigger on theme switch).
highlight_syntax: crate::theme::Syntax,
/// Generation counter on search submissions; stale results dropped.
search_gen: u64,
/// Same for the global search view (find/grep workers).
view_gen: u64,
/// sha of the lazy hit-context fetch in flight (plans/0006 §1) —
/// dedupes repeat selections and names the cancel target.
pending_context_sha: Option<String>,
/// Cursor-rest debounce generation (plans/0008 §3): bumped on
/// every context request; a timer thread fires only if its
/// generation is still current when the cursor rests.
context_debounce_gen: std::sync::Arc<std::sync::atomic::AtomicU64>,
/// One-line status shown in the modeline (searching/loading/error).
status: Option<String>,
/// Offline apps (tests) never spawn workers.
offline: bool,
pub should_quit: bool,
/// Reserved for the editor-resume path (milestone 6): the only
/// legitimate full `terminal.clear()` trigger (PLAN.md §9).
pub force_redraw: bool,
/// A prepared editor invocation; the main loop runs it while the
/// terminal is suspended, then forces a full redraw.
pending_editor: Option<crate::editor::EditorJob>,
/// Queued yank (␣ y): the main loop writes it to the clipboard
/// outside the draw path (plans/0003 §1).
pending_clipboard: Option<String>,
}
/// Render a provider error for the status line (plans/0008 §2):
/// auth gets a recovery hint, throttling gets its advertised backoff,
/// everything else is yesterday's plain message.
pub(crate) fn provider_status(error: &crate::provider::ProviderError) -> String {
use crate::provider::ErrorKind;
match error.kind {
ErrorKind::Auth => format!(
"auth failed: {} — refresh provider credentials",
error.message
),
ErrorKind::RateLimited => match error.retry_after {
Some(d) => format!("provider throttled — retry in {}s", d.as_secs()),
None => format!("provider throttled: {}", error.message),
},
_ => error.message.clone(),
}
}
/// Forge chip text for the modeline: `[provider] name` when set, else
/// the provider's self-reported name (`stdio:name` → `name`).
fn forge_name(config: &Config, provider: &dyn Provider) -> String {
config
.provider
.name
.clone()
.unwrap_or_else(|| provider.name().trim_start_matches("stdio:").to_owned())
}
impl App {
/// Fetch the open history lens' commits (v1.5): the previewed
/// file's log at the browsed revision.
fn open_history_fetch(&mut self) {
let target = self
.browser
.repo_coords()
.zip(self.browser.history_path().map(str::to_string));
if let Some(((owner, name), path)) = target {
let ref_ = self.browser.current_ref().map(str::to_string);
self.spawn_log(format!("{owner}/{name}"), path, ref_);
}
}
pub fn new(tx: AppTx, config: Config, theme: Theme) -> Self {
let (provider, outcome) = provider::build(&config);
let mut app = Self::build(State::load(), tx, provider, false, config, theme);
match outcome {
provider::BuildOutcome::Ready => {}
provider::BuildOutcome::Warn(warning) => app.status = Some(warning),
// 0019 M2: a declared provider is missing — ask, never
// silently download-and-run. github carries the session
// while the popup is up.
provider::BuildOutcome::Missing(decl) => {
app.consent = Some(ConsentPopup::new(decl));
}
}
// 0017 M3 / 0018 M2: the 24h-cached update notice — never
// offline, never blocking, silent on failure; CI, dumb
// terminals, and piped stdout never check at all.
if !app.offline && app.config.update.check && crate::update::check_allowed() {
app.spawn_update_check();
}
// Warm the repos level for the initially selected org.
if let Some(org) = app.browser.selected_org() {
app.handle_action(Action::LoadOrgRepos(org));
}
app
}
/// Offline, state-injectable constructor for tests.
pub fn with(state: State, tx: AppTx) -> Self {
Self::build(
state,
tx,
provider::offline(),
true,
Config::default(),
Theme::catppuccin_mocha(),
)
}
fn build(
state: State,
tx: AppTx,
provider: Arc<dyn Provider>,
offline: bool,
config: Config,
theme: Theme,
) -> Self {
// Launch flow: the repo search popup opens automatically only
// for a fresh install (no repos in state yet). With recents,
// the browser opens directly; ␣ s still offers resume via the
// prefilled last repo.
let forge = forge_name(&config, provider.as_ref());
let icon = config.provider.icon.clone().or_else(|| provider.icon());
let popup = if state.recent_repos.is_empty()
&& state.recent_orgs.is_empty()
&& state.last_repo.is_none()
{
let mut p = SearchPopup::with_prefill(state.last_repo.as_deref());
p.forge = forge.clone();
Some(p)
} else {
None
};
App {
mode: Mode::Browse,
browser: Browser::new(&state.recent_orgs, &provider.default_orgs()),
popup, // opens on launch only for a fresh state
search_view: None,
help: None,
command_line: None,
settings: None,
wizard: None,
refs_popup: None,
refs_baseline: None,
// 0019 M2: declared-but-missing provider — the consent
consent: None,
degraded: None,
last_commits: std::collections::HashMap::new(),
history_return: None,
find_return: None,
update_tag: None,
modeline: Modeline {
forge,
icon,
context: String::new(),
status: None,
update_tag: None,
},
theme,
config,
state,
tx,
provider,
highlighter: Highlighter::new(&theme),
// The syntax roles the highlighter + blob cache are styled
// with; compared against the effective theme to trigger
// restyle (settings live preview / commit).
highlight_syntax: theme.syntax,
search_gen: 0,
view_gen: 0,
pending_context_sha: None,
context_debounce_gen: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)),
status: None,
offline,
should_quit: false,
force_redraw: false,
pending_editor: None,
pending_clipboard: None,
}
}
fn effective_mode(&self) -> Mode {
if self.command_line.is_some() {
return Mode::Insert;
}
if let Some(settings) = &self.settings {
return settings.effective_mode();
}
if self.help.is_some() || self.wizard.is_some() {
return Mode::Browse;
}
if let Some(view) = &self.search_view {
// The leader layer can be raised over the view (␣ from the
// results) — it owns the keys and the modeline while up.
if self.mode == Mode::Leader {
return Mode::Leader;
}
return view.effective_mode();
}
match &self.popup {
Some(popup) => popup.effective_mode(),
None => self.mode,
}
}
pub fn handle_key(&mut self, key: KeyEvent) {
let action = self.dispatch(key);
self.handle_action(action);
}
/// Worker outcomes from the event channel.
pub fn handle_app_event(&mut self, event: AppEvent) {
match event {
AppEvent::SearchResults { gen_id, items } => {
if gen_id != self.search_gen {
return; // stale submission
}
self.status = None;
if let Some(popup) = &mut self.popup {
popup.update(&Action::SearchResults { items });
}
}
AppEvent::SearchFailed { gen_id, error } => {
if gen_id != self.search_gen {
return;
}
self.status = None;
if let Some(popup) = &mut self.popup {
popup.update(&Action::SearchFailed { error });
}
}
AppEvent::OrgReposLoaded { org, repos } => {
self.status = None;
self.browser.org_repos_loaded(&org, repos);
}
AppEvent::OrgReposFailed { org, error } => {
self.status = Some(format!("{org}: {}", provider_status(&error)));
}
AppEvent::TreeLoaded {
owner,
name,
entries,
truncated,
branch,
} => {
self.handle_action(Action::TreeLoaded {
owner,
name,
entries,
truncated,
branch,
});
}
AppEvent::BlobLoaded { sha, name, bytes } => {
self.handle_action(Action::BlobLoaded { sha, name, bytes });
}
AppEvent::BlobFailed { sha, error } => {
self.handle_action(Action::BlobFailed { sha, error });
}
AppEvent::TreeFailed { owner, name, error } => {
self.handle_action(Action::TreeFailed { owner, name, error });
}
AppEvent::GlobalSearchDelta { gen_id, hits } => {
if gen_id != self.view_gen {
return; // stale batch — a newer submission owns the view
}
let Some(view) = &self.search_view else {
return;
};
let (kind, query) = (view.kind(), view.query.value());
let hits = hits
.into_iter()
.map(crate::components::global_search::SearchHit::from_raw)
.collect();
let hits = self.finish_hits(hits, kind, &query);
if let Some(view) = &mut self.search_view {
view.update(&Action::GlobalSearchDelta { hits });
}
// Live count while the stream runs.
if let Some(view) = &self.search_view {
self.status = Some(format!(
"searching {}… {} hits",
self.modeline.forge,
view.hit_count()
));
}
}
AppEvent::GlobalSearchResults {
gen_id,
hits,
clipped,
index,
client_filtered,
unfiltered,
} => {
if gen_id != self.view_gen {
return; // stale submission
}
self.status = None;
let Some(view) = &self.search_view else {
return;
};
let (kind, query) = (view.kind(), view.query.value());
let hits = hits
.into_iter()
.map(crate::components::global_search::SearchHit::from_raw)
.collect();
let hits = self.finish_hits(hits, kind, &query);
if let Some(view) = &mut self.search_view {
view.update(&Action::GlobalSearchResults {
hits,
clipped,
index,
client_filtered,
unfiltered,
});
}
// Bare selected hit (beyond the eager preview cap): ask
// for its context lazily (plans/0006 §1).
let request = self
.search_view
.as_ref()
.and_then(|view| view.context_request());
if let Some(action) = request {
self.handle_action(action);
}
}
AppEvent::GlobalSearchFailed { gen_id, error } => {
if gen_id != self.view_gen {
return;
}
self.status = None;
if let Some(view) = &mut self.search_view {
view.update(&Action::GlobalSearchFailed { error });
}
}
AppEvent::HitContextDebounceFired {
timer_gen,
hit,
query,
} => {
self.handle_action(Action::HitContextDebounceFired {
timer_gen,
hit,
query,
});
}
AppEvent::HitContextMissing { gen_id, sha } => {
if gen_id != self.view_gen {
return; // view moved on
}
self.handle_action(Action::HitContextMissing { sha });
}
AppEvent::HitContextFailed { gen_id, sha, error } => {
if gen_id != self.view_gen {
return;
}
self.handle_action(Action::HitContextFailed { sha, error });
}
AppEvent::HitContextLoaded {
gen_id,
repo,
path,
sha,
line,
preview,
match_count,
query,
} => {
if gen_id != self.view_gen {
return; // view moved on
}
if self.pending_context_sha.as_deref() == Some(sha.as_str()) {
self.pending_context_sha = None;
}
let Some(view) = &self.search_view else {
return;
};
let kind = view.kind();
let mut hits = vec![crate::components::global_search::SearchHit::plain(
&repo,
&path,
line,
preview,
match_count,
String::new(),
)];
hits = self.finish_hits(hits, kind, &query);
let styled = hits.pop().expect("one hit");
let action = Action::HitContextLoaded {
repo,
path,
sha,
line,
preview: styled.preview,
match_count,
};
if let Some(view) = &mut self.search_view {
view.update(&action);
}
}
AppEvent::HitFileLoaded {
gen_id,
repo,
path,
sha,
bytes,
} => {
if gen_id != self.view_gen {
return; // view moved on — drop the stale blob
}
// 0019 polish: the expanded pane's band rides the same
// last-commit memo as the miller preview.
let band_ctx = {
let branch = self
.search_view
.as_ref()
.and_then(|v| v.expanded_branch())
.unwrap_or_default();
self.last_commits
.get(&(repo.clone(), path.clone(), branch))
.map(|e| crate::components::preview::BandContext {
sha: e.sha.clone(),
subject: e.subject.clone(),
author: e.author.clone(),
date: e.date.clone(),
})
};
// Sanitize + highlight at the boundary, on the UI
// thread (PLAN.md §9) — same rule as every blob.
let action = if crate::sanitize::is_binary(&bytes) {
Action::HitFileFailed {
error: crate::provider::ProviderError::other("binary file"),
sha,
}
} else {
let text = crate::sanitize::sanitize(&bytes);
let mut lines = self.highlighter.highlight(&path, &text);
let lang = self.highlighter.language(&path);
// 0019: the expanded pane wears the same match chips
// as the results list — a boundary-aware chip so a
// match straddling syntax spans (half in a comment)
// still shows.
if let Some(view) = &self.search_view
&& view.is_grep()
{
let needle = view.query_text().to_lowercase();
if !needle.is_empty() {
let (bg, fg) =
(self.theme.semantic.search_match, self.theme.semantic.crust);
for line in &mut lines {
crate::components::global_search::chip_line(line, &needle, bg, fg);
}
}
}
Action::HitFileLoaded {
repo: repo.clone(),
path: path.clone(),
sha,
lang,
lines,
}
};
// Memo miss on the expanded hit: spawn the one-shot
// fetch (log-capable providers only; ambient).
if band_ctx.is_none()
&& !self.offline
&& let Some(view) = &self.search_view
&& let Some(branch) = view.expanded_branch()
{
self.spawn_last_commit(repo.clone(), path.clone(), Some(branch.clone()));
}
if let Some(view) = &mut self.search_view {
view.expanded_set_band(&path, band_ctx);
view.update(&action);
}
}
AppEvent::HitFileFailed { gen_id, sha, error } => {
if gen_id != self.view_gen {
return;
}
// Auth/throttle surface a status line; other kinds
// stay quiet — the pane itself shows the error
// (same rule as the lazy context, plans/0008 §2).
use crate::provider::ErrorKind;
if matches!(error.kind, ErrorKind::Auth | ErrorKind::RateLimited) {
self.status = Some(provider_status(&error));
}
if let Some(view) = &mut self.search_view {
view.update(&Action::HitFileFailed { sha, error });
}
}
AppEvent::CloneExpanded { repos, errors } => {
if repos.is_empty() {
self.status = Some(if errors.is_empty() {
"nothing to clone".into()
} else {
format!("no repos: {}", errors.join("; "))
});
} else {
if !errors.is_empty() {
self.status = Some(format!("some orgs failed: {}", errors.join("; ")));
}
let cwd = std::env::current_dir().unwrap_or_default();
self.wizard = Some(CloneWizard::new(repos, cwd));
}
}
AppEvent::CloneDone { ok, failed } => {
let mut status = format!(
"cloned {} repo{}",
ok.len(),
if ok.len() == 1 { "" } else { "s" }
);
if !failed.is_empty() {
status.push_str(&format!(
", {} failed ({} …)",
failed.len(),
failed[0].1.chars().take(40).collect::<String>()
));
}
self.status = Some(status);
}
// v1.5 revision lenses (plans/0016 M1).
AppEvent::RefsLoaded { repo: _, refs } => {
if let Some(popup) = &mut self.refs_popup {
popup.set_refs(refs);
}
}
AppEvent::RefsFailed { repo: _, error } => {
self.status = Some(provider_status(&error));
}
AppEvent::LogLoaded {
path,
entries,
truncated,
} => {
if self.browser.history_path() == Some(path.as_str()) {
self.browser.history_loaded(entries, truncated);
}
}
AppEvent::LogFailed { path: _, error } => {
self.status = Some(provider_status(&error));
}
AppEvent::BlameLoaded { path, ranges } => {
if let Some(view) = &mut self.search_view
&& view.blame_loading_for(&path)
{
view.blame_store(path, ranges);
} else {
self.browser.blame_store(path, ranges);
}
}
AppEvent::LastCommitLoaded { repo, path, entry } => {
if let Some(entry) = entry {
// Compact at the boundary: 7-char sha, date-only
// — the band is a header, not a ledger.
let ctx = crate::components::preview::BandContext {
sha: entry.sha.chars().take(7).collect(),
subject: entry.subject.clone(),
author: entry.author.clone(),
date: entry
.date
.split('T')
.next()
.unwrap_or(&entry.date)
.to_string(),
};
let ref_ = self
.browser
.current_ref()
.map(str::to_string)
.unwrap_or_default();
self.last_commits
.insert((repo.clone(), path.clone(), ref_), entry);
// Dress whichever surface is showing this file now:
// the miller preview (not at-commit) and/or the
// search pane's expanded hit.
if !self.browser.at_commit_view()
&& self.browser.selected_file().is_some_and(|(p, _)| p == path)
{
self.browser
.preview
.set_band(Some(path.clone()), Some(ctx.clone()));
}
if let Some(view) = &mut self.search_view {
view.expanded_set_band(&path, Some(ctx));
}
}
}
AppEvent::BlameFailed { path, error } => {
if let Some(view) = &mut self.search_view
&& view.blame_loading_for(&path)
{
view.blame_clear();
}
self.status = Some(provider_status(&error));
}
AppEvent::BlobAtLoaded {
path,
ref_,
sha,
bytes,
subject,
author,
date,
} => {
// Open-at-commit: style like every blob, but show it
// directly — the tree cursor still names the
// present-day blob, so refresh_preview would revert it.
if crate::sanitize::is_binary(&bytes) {
self.status = Some("binary file at that commit".into());
return;
}
let text = crate::sanitize::sanitize(&bytes);
let short: String = ref_.chars().take(7).collect();
// The title carries the commit marker; highlighting and
// language detection read the real path — "main.rs @
// 42ec959" has no known extension (the demo caught the
// unhighlighted frame).
let name = format!("{path} @ {short}");
let lines = self.highlighter.highlight(&path, &text);
let lang = self.highlighter.language(&path);
let band = crate::components::preview::BandContext {
sha: short,
subject,
author,
date,
};
self.browser
.show_at_commit(&sha, &name, &lang, text, lines, Some(band));
// The lens' work is done — the commit's content is up.
self.browser.close_history();
self.history_return = Some(Mode::Preview);
self.mode = Mode::Preview;
self.status = None;
}
AppEvent::BlobAtFailed { path: _, error } => {
self.status = Some(provider_status(&error));
}
AppEvent::UpdateAvailable { tag, toast } => {
self.update_tag = Some(tag.clone());
// 0018 M2: the toast nags once a day and never steals
// the status line from real work — the chip is the
// persistent channel.
if toast && self.status.is_none() {
self.status = Some(format!("rootle {tag} is out — run `rootle update`"));
}
}
// 0019 M2: the consent install landed — hot-swap the
// provider, drop the popup, say so.
AppEvent::DeclarationInstalled { name } => {
self.consent = None;
self.degraded = None;
match provider::spawn_installed(&self.config, &name) {
Ok(p) => {
self.provider = p;
self.status = Some(format!("{name} ready"));
}
Err(e) => {
let note = format!("{name} unavailable: {e} — browsing github");
self.degraded = Some(note.clone());
self.status = Some(note);
}
}
}
AppEvent::DeclarationFailed { name, error } => {
// Honest degraded mode — the popup shows the error
// until dismissed, then the notice goes sticky.
let note = format!("{name} unavailable: {error} — browsing github");
self.degraded = Some(note.clone());
if let Some(popup) = &mut self.consent {
popup.set_state(crate::action::DeclarationState::Failed(error));
} else {
self.status = Some(note);
}
}
}
}
fn dispatch(&mut self, key: KeyEvent) -> Action {
// Overlays capture keys, topmost first — the consent popup is
// the very top: a pending trust decision outranks everything.
if let Some(consent) = &mut self.consent {
return consent.handle_key(key);
}
if let Some(wizard) = &mut self.wizard {
return wizard.handle_key(key);
}
if let Some(settings) = &mut self.settings {
return settings.handle_key(key);
}
if let Some(help) = &mut self.help {
return help.handle_key(key);
}
if let Some(refs) = &mut self.refs_popup {
return refs.handle_key(key);
}
if let Some(command_line) = &mut self.command_line {
return command_line.handle_key(key);
}
if let Some(view) = &mut self.search_view {
// While the leader layer is up, it owns the keys — the
// view regains them on the action that follows.
if self.mode == Mode::Leader {
return keymap::leader(key.code);
}
return view.handle_key(key);
}
if let Some(popup) = &mut self.popup {
return popup.handle_key(key);
}
match self.mode {
Mode::Browse => keymap::browsing(key.code),
Mode::Visual => keymap::visual(key.code),
Mode::Search => match self.browser.filter_input.handle_key(key) {
Outcome::Changed => Action::Noop, // filter applied below
Outcome::Submitted => Action::CommitFilter,
Outcome::Cancelled => Action::ClearFilter,
Outcome::Noop => Action::Noop,
},
Mode::Find => match self.browser.find_input.handle_key(key) {
Outcome::Changed => Action::UpdateFind,
Outcome::Submitted => Action::CommitFind,
Outcome::Cancelled => Action::CancelFind,
Outcome::Noop => Action::Noop,
},
Mode::Leader => keymap::leader(key.code),
Mode::History => {
// An active `/` session owns the keys until commit.
if self.browser.history_filtering() {
self.browser.history_filter_key(key);
Action::Noop
} else {
keymap::history(key.code)
}
}
Mode::Preview => self.browser.preview_key(key),
_ => Action::Noop,
}
}
pub fn handle_action(&mut self, action: Action) {
match action {
Action::Quit | Action::LeaderQuit => {
self.state.last_path = Some(self.browser.dir_path());
self.state.save();
self.should_quit = true;
}
Action::ClosePopup => {
trace("ClosePopup");
// Topmost overlay first; the search popup last.
if self.wizard.take().is_some()
|| self.settings.take().is_some()
|| self.help.take().is_some()
|| self.command_line.take().is_some()
{
return;
}
if self.refs_popup.take().is_some() {
// Revisions switcher cancelled: the live preview
// reverts to the committed revision.
let baseline = self.refs_baseline.clone();
self.browser.set_current_ref(baseline);
return;
}
self.popup = None;
self.mode = Mode::Browse;
}
Action::SearchSubmitted(_) => {
self.search_gen += 1;
self.provider.advise_cancel(); // superseded in-flight work
self.status = Some(format!("searching {}…", self.modeline.forge));
if let Some(popup) = &mut self.popup {
popup.update(&action);
}
if !self.offline {
self.spawn_search(self.search_gen);
}
}
Action::SearchResults { .. } | Action::SearchFailed { .. } => {
// Injected (tests) or misrouted worker outcomes.
if let Some(popup) = &mut self.popup {
popup.update(&action);
}
self.status = None;
}
Action::RepoSelected { owner, name } => {
trace(&format!("RepoSelected {owner}/{name}"));
self.state.record_repo(&owner, &name);
self.state.save();
self.browser.set_repo(&owner, &name);
self.popup = None;
self.mode = Mode::Browse;
self.handle_action(Action::LoadRepoTree { owner, name });
}
Action::OrgSelected(org) => {
trace(&format!("OrgSelected {org}"));
self.state.record_org(&org);
self.state.save();
self.browser.select_org(&org);
self.popup = None;
self.mode = Mode::Browse;
self.handle_action(Action::LoadOrgRepos(org));
}
Action::LoadOrgRepos(org) => {
self.status = Some(format!("loading {org}…"));
if !self.offline {
self.spawn_org_repos(org);
}
}
Action::OrgReposLoaded { org, repos } => {
self.status = None;
self.browser.org_repos_loaded(&org, repos);
}
Action::OrgReposFailed { org, error } => {
self.status = Some(format!("{org}: {}", provider_status(&error)));
}
Action::LoadRepoTree { owner, name } => {
self.status = Some(format!("loading {owner}/{name} tree…"));
if !self.offline {
self.spawn_tree(owner, name);
}
}
Action::TreeLoaded {
owner,
name,
entries,
truncated,
branch,
} => {
self.status = None;
self.browser
.tree_loaded(&owner, &name, entries, truncated, branch);
}
Action::TreeFailed { owner, name, error } => {
self.status = Some(format!("{owner}/{name}: {}", provider_status(&error)));
}
Action::LoadBlob { sha, name } => {
if !self.offline {
self.spawn_blob(sha, name);
}
}
Action::BlobLoaded { sha, name, bytes } => {
// Sanitize at the boundary, highlight once, cache in
// the browser (PLAN.md §9).
if crate::sanitize::is_binary(&bytes) {
self.browser.blob_failed(&sha, "binary file");
return;
}
let text = crate::sanitize::sanitize(&bytes);
let lines = self.highlighter.highlight(&name, &text);
let lang = self.highlighter.language(&name);
self.browser.blob_loaded(&sha, &name, &lang, text, lines);
self.band_apply_or_fetch();
}
Action::BlobFailed { sha, error } => {
self.status = Some(provider_status(&error));
self.browser.blob_failed(&sha, &error.message);
}
Action::HitContextFailed { sha: _, error } => {
// Auth/throttle surface; anything else stays quiet —
// the bare path remains and revisit retries (§2).
use crate::provider::ErrorKind;
if matches!(error.kind, ErrorKind::Auth | ErrorKind::RateLimited) {
self.status = Some(provider_status(&error));
}
}
Action::Leader => self.mode = Mode::Leader,
Action::KeybindsPopup => self.help = Some(KeybindsPopup::new()),
Action::CommandLine => self.command_line = Some(CommandLine::new()),
Action::RunCommand(name) => {
self.command_line = None;
match name.as_str() {
"settings" => {
let themes = Theme::available_names();
self.settings = Some(SettingsPopup::new(&self.config, themes));
}
"clone" => {
let (repos, orgs) = self.clone_candidates();
if orgs.is_empty() {
let cwd = std::env::current_dir().unwrap_or_default();
// Direct selections carry no listing
// metadata (v1.4): bare names.
let repos = repos
.into_iter()
.map(crate::provider::RepoInfo::bare)
.collect();
self.wizard = Some(CloneWizard::new(repos, cwd));
} else {
self.status = Some(format!("expanding {} org(s)…", orgs.len()));
if !self.offline {
self.spawn_expand_clone(repos, orgs);
}
}
}
other => {
// `:42` jumps to line 42 in a file view — the
// zoomed preview submode or a search hit's
// expanded file pane (plans/0016 M1).
match other.parse::<u32>() {
Ok(line) if line > 0 => {
let jumped = if let Some(view) = &mut self.search_view {
view.expanded_goto_line(line)
} else if self.browser.preview.text_line_count() > 0 {
self.browser.preview.set_cursor_line(line);
true
} else {
false
};
if !jumped {
self.status = Some(format!(":{other}: not in a file view"));
}
}
_ => self.status = Some(format!("unknown command: {other}")),
}
}
}
}
Action::Visual => {
self.mode = Mode::Visual;
self.browser.enter_visual();
}
Action::ExitVisual => {
self.mode = Mode::Browse;
self.browser.exit_visual();
}
Action::ToggleSelect => self.browser.toggle_selected(),
Action::LeaderReload => {
self.mode = Mode::Browse;
if let Some((owner, name)) = self.browser.repo_coords() {
// Conditional refetch: cheap when the ref ETag is
// still fresh (304), fresh tree when it moved.
self.handle_action(Action::LoadRepoTree { owner, name });
self.status = Some("reloading tree…".into());
} else if let Some(org) = self.browser.selected_org() {
self.handle_action(Action::LoadOrgRepos(org));
self.status = Some("reloading org repos…".into());
} else {
self.status = Some("nothing to reload".into());
}
}
Action::DeleteMarked => {
self.mode = Mode::Browse;
let deleted = self.browser.delete_marked_orgs();
if deleted.is_empty() {
self.status = Some("no marked orgs (mark orgs in VISUAL, ␣d)".into());
} else {
// Keep persisted recents in sync.
self.state.recent_orgs.retain(|o| !deleted.contains(o));
if self
.state
.last_org
.as_deref()
.is_some_and(|o| deleted.iter().any(|d| d == o))
{
self.state.last_org = None;
}
self.state.save();
self.status = Some(format!("deleted {} org(s)", deleted.len()));
}
}
Action::ClearMarks => {
self.mode = Mode::Browse;
self.browser.clear_marks();
self.status = Some("marks cleared".into());
}
Action::LeaderRefs => {
self.mode = Mode::Browse;
if !self.provider.capabilities().refs {
self.status = Some("provider has no revision listing".into());
} else if let Some((owner, name)) = self.browser.repo_coords() {
let current = self
.browser
.current_ref()
.or_else(|| self.browser.branch())
.unwrap_or("main")
.to_string();
self.refs_baseline = self.browser.current_ref().map(str::to_string);
self.refs_popup = Some(RefsPopup::new(¤t));
self.spawn_refs(format!("{owner}/{name}"));
} else {
self.status = Some("open a repo to switch revisions".into());
}
}
Action::RefsPreview(name) => {
// Live preview: the crumb follows the cursor (no fetch
// until commit).
self.browser.set_current_ref(Some(name));
}
Action::RefsCommit(name) => {
self.refs_popup = None;
self.refs_baseline = Some(name.clone());
self.browser.set_current_ref(Some(name.clone()));
self.status = Some(format!("switched to {name}"));
// The ref is read at spawn — refetch the tree now.
if let Some((owner, name)) = self.browser.repo_coords() {
self.handle_action(Action::LoadRepoTree { owner, name });
}
}
Action::LeaderPreview => {
self.mode = Mode::Browse;
if self.browser.repo_coords().is_none() {
self.status = Some("open a repo first".into());
} else {
self.mode = Mode::Preview;
}
}
Action::PreviewCopy => {
// GitHub's copy button: the visual selection, else the
// cursor line — from whichever file pane is up.
let target = if let Some(view) = &mut self.search_view {
view.expanded_copy_target()
} else {
self.browser.preview.copy_target()
};
match target {
Some((text, n)) => {
self.pending_clipboard = Some(text);
self.status =
Some(format!("copied {n} line{}", if n == 1 { "" } else { "s" }));
}
None => self.status = Some("nothing to copy".into()),
}
}
Action::ExitPreview => {
// The commit-view ladder: Esc restores the present-day
// blob first, exits the submode second.
if self.browser.at_commit_view() {
self.browser.commit_view_close();
} else {
self.mode = Mode::Browse;
}
}
Action::BlameToggle => {
// 0019 parity: the search view's expanded pane runs the
// same lens at the hit's default branch.
if let Some(view) = &mut self.search_view {
if view.blame_active() {
view.blame_clear();
} else if !self.provider.capabilities().blame {
self.status = Some("provider has no blame".into());
} else if !view.blame_toggle_on() {
self.status = Some("blame: preview is not a text file".into());
} else if let Some((repo, path, branch)) = view.blame_needed() {
view.blame_mark_loading(path.clone());
let ref_ = if branch.is_empty() {
None
} else {
Some(branch)
};
self.spawn_blame(repo, path, ref_);
self.status = Some("blame…".into());
}
} else if self.browser.preview.blaming() {
self.browser.clear_blame();
} else if !self.provider.capabilities().blame {
// Honest absence (Bitbucket has no blame API).
self.status = Some("provider has no blame".into());
} else if !self.browser.blame_toggle_on() {
self.status = Some("blame: preview is not a text file".into());
} else if let Some(path) = self.browser.blame_needed_for()
&& let Some((owner, name)) = self.browser.repo_coords()
{
self.browser.blame_mark_loading(path.clone());
let ref_ = self.browser.current_ref().map(str::to_string);
self.spawn_blame(format!("{owner}/{name}"), path, ref_);
self.status = Some("blame…".into());
}
}
Action::PreviewEnter => {
// Blaming: Enter opens the line's commit in the history
// lens; otherwise Enter is the editor handoff.
match self.browser.blame_line_sha() {
Some(sha) if self.provider.capabilities().log => {
if self.browser.open_history(Some(sha)) {
self.open_history_fetch();
self.history_return = Some(Mode::Preview);
self.mode = Mode::History;
}
}
_ => self.handle_action(Action::OpenSelected),
}
}
Action::LeaderHistory => {
let back = self.mode;
self.mode = Mode::Browse;
if !self.provider.capabilities().log {
self.status = Some("provider has no commit log".into());
} else if self.browser.open_history(None) {
self.history_return = Some(if back == Mode::Preview {
Mode::Preview
} else {
Mode::Browse
});
self.open_history_fetch();
self.mode = Mode::History;
} else {
self.status = Some("preview a file for its history".into());
}
}
Action::HistoryFilterBegin => self.browser.history_begin_filter(),
Action::HistoryYank => {
// The permalink that never rots: the URL carries the
// commit sha as its ref.
let target = self.browser.repo_coords().zip(self.browser.history_pick());
if let Some(((owner, name), (path, sha))) = target {
match self.provider.web_url(
&format!("{owner}/{name}"),
&path,
&sha,
None,
None,
true,
) {
Ok(u) => {
self.pending_clipboard = Some(u.clone());
self.status = Some(format!("yanked {u}"));
}
Err(e) => self.status = Some(provider_status(&e)),
}
}
}
Action::HistoryUp => self.browser.history_move(-1),
Action::HistoryDown => self.browser.history_move(1),
Action::HistoryOpen => {
// Open the file at the picked commit — bytes land via
// BlobAtLoaded; the restore point is noted there.
let target = self.browser.repo_coords().zip(self.browser.history_pick());
let entry = self.browser.history_pick_entry();
if let (Some(((owner, name), (path, sha))), Some(entry)) = (target, entry) {
self.spawn_blob_at(
format!("{owner}/{name}"),
path,
sha,
entry.subject,
entry.author,
entry.date,
);
self.status = Some("opening at commit".into());
}
}
Action::HistoryClose => {
// The wizard ladder: a committed filter clears first,
// the next Esc closes.
if self.browser.history_esc() {
self.mode = self.history_return.take().unwrap_or(Mode::Browse);
}
}
Action::LeaderYank => {
// Mock stage (plans/0003 §1): toast the URL that would
// be yanked; clipboard (OSC 52) wires up later.
// From the leader layer it drops back to Browse; from
// the preview submode (␣ p y) the pane stays focused.
if self.mode == Mode::Leader {
self.mode = Mode::Browse;
}
// URLs come from the provider — no GitHub grammar
// outside the GitHub impl (plans/0005).
let url = if let Some(view) = &self.search_view {
view.yank_target().and_then(|t| {
self.provider
.web_url(&t.repo, &t.path, &t.branch, t.line, t.end, true)
.ok()
})
} else if let Some((owner, repo)) = self.browser.repo_coords() {
// File under the cursor yanks the FILE (blob URL);
// otherwise the current directory (tree URL).
let (path, is_file) = match self.browser.selected_file() {
Some((file, _sha)) => (file, true),
None => (self.browser.dir_path(), false),
};
let branch = self.browser.branch().unwrap_or("");
// File yank anchors to the preview line cursor —
// or the visual range as `#L3-L7` (v1.5); dirs/orgs
// stay line-less.
let (line, end) = if is_file {
self.browser.yank_anchor()
} else {
(None, None)
};
self.provider
.web_url(
&format!("{owner}/{repo}"),
&path,
branch,
line,
end,
is_file,
)
.ok()
} else {
self.browser
.selected_org()
.and_then(|org| self.provider.org_url(&org).ok())
};
match url {
Some(u) => {
self.pending_clipboard = Some(u.clone());
self.status = Some(format!("yanked {u}"));
}
None => self.status = Some("nothing to yank".into()),
}
}
Action::LeaderSearch => {
// Resume: prefill with the last repo — one Enter
// re-runs the query back to where the user was.
let mut popup = SearchPopup::with_prefill(self.state.last_repo.as_deref());
popup.forge = self.modeline.forge.clone();
self.popup = Some(popup);
self.mode = Mode::Browse;
}
Action::LeaderFileFind | Action::LeaderGrep => {
let kind = if action == Action::LeaderFileFind {
SearchKind::FileFind
} else {
SearchKind::Grep
};
let repo = self
.browser
.repo_coords()
.map(|(owner, name)| format!("{owner}/{name}"));
let org = self.browser.selected_org();
let persisted_scope = self
.state
.search_scope
.as_deref()
.and_then(crate::components::global_search::Scope::from_stored);
let mut view = GlobalSearch::new(
kind,
repo,
org,
persisted_scope,
self.state.search_extension.clone(),
);
// plans/0016 M1a: off the default branch, index-backed
// search (GitHub) can't follow — the title says so.
if let (Some(r), Some(b)) = (self.browser.current_ref(), self.browser.branch())
&& r != b
{
view.search_ref_note = Some(format!("search: {b} only"));
}
self.search_view = Some(view);
self.mode = Mode::Browse;
}
Action::CloseSearchView => {
self.search_view = None;
self.mode = Mode::Browse;
}
Action::GlobalSearchSubmitted {
ref kind,
ref query,
ref scope,
ref extension,
} => {
// Persist last-used scope/extension (plans/0002 §6.4).
if let Some(view) = &self.search_view {
self.state.search_scope = Some(view.scope().stored().to_string());
self.state.search_extension = Some(view.extension_value());
self.state.save();
}
self.view_gen += 1;
self.provider.advise_cancel(); // superseded in-flight work
self.pending_context_sha = None;
if let Some(view) = &mut self.search_view {
view.update(&action);
}
if self.offline {
// Tests: inject the mock producer, same Action flow.
let hits =
crate::components::global_search::mock::hits(*kind, query, extension);
let hits = self.finish_hits(hits, *kind, query);
if let Some(view) = &mut self.search_view {
view.update(&Action::GlobalSearchResults {
hits,
clipped: false,
index: None,
client_filtered: 0,
unfiltered: vec![],
});
}
self.status = None;
// Bare selected hit (beyond the eager preview cap):
// ask for its context lazily (plans/0006 §1).
let request = self
.search_view
.as_ref()
.and_then(|view| view.context_request());
if let Some(action) = request {
self.handle_action(action);
}
} else {
self.status = Some("searching code…".into());
self.spawn_view_search(
self.view_gen,
*kind,
query.clone(),
scope.clone(),
extension.clone(),
);
}
}
Action::GlobalSearchResults { .. }
| Action::GlobalSearchDelta { .. }
| Action::GlobalSearchFailed { .. } => {
if let Some(view) = &mut self.search_view {
view.update(&action);
}
self.status = None;
}
Action::LoadHitContext { hit, query } => {
// Dedupe repeat selections of an in-flight fetch.
if self.pending_context_sha.as_deref() == Some(hit.sha.as_str()) {
return;
}
if self.offline {
return; // tests inject context via Action directly
}
// Cursor-rest debounce (plans/0008 §3): 200ms rearmed
// per selection change. Holding j through N hits costs
// one provider call — the resting one — instead of N
// requests plus N-1 advisory cancels.
let timer_gen = self
.context_debounce_gen
.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
+ 1;
let shared = self.context_debounce_gen.clone();
let tx = self.tx.clone();
let hit = *hit;
std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_millis(200));
if shared.load(std::sync::atomic::Ordering::SeqCst) == timer_gen {
let _ = tx.send(AppEvent::HitContextDebounceFired {
timer_gen,
hit,
query,
});
}
});
}
Action::HitContextDebounceFired {
timer_gen,
hit,
query,
} => {
// The timer thread already generation-checked; re-check
// here — another request may have landed while the
// event queued.
if timer_gen
!= self
.context_debounce_gen
.load(std::sync::atomic::Ordering::SeqCst)
{
return;
}
if self.pending_context_sha.as_deref() == Some(hit.sha.as_str()) {
return;
}
// A different pending fetch is superseded — tell the
// provider it can stop (v1.1).
if self.pending_context_sha.is_some() {
self.provider.advise_cancel();
}
self.pending_context_sha = Some(hit.sha.clone());
let gen_id = self.view_gen;
self.spawn_hit_context(gen_id, hit, query);
}
Action::HitContextLoaded { .. } | Action::HitContextMissing { .. } => {
if let Some(view) = &mut self.search_view {
view.update(&action);
}
}
// Expanded file pane (plans/0012 M2): fetch the hit's
// whole blob on a worker; the view shows a loading
// placeholder until the styled lines land.
Action::LoadHitFile { hit } => {
if !self.offline {
let gen_id = self.view_gen;
self.spawn_hit_file(gen_id, *hit);
}
}
Action::HitFileLoaded { .. } | Action::HitFileFailed { .. } => {
if let Some(view) = &mut self.search_view {
view.update(&action);
}
}
Action::OpenSearchHit(hit) => {
if !hit.sha.is_empty() {
// Real hit: materialize the blob like the browser
// does (cache-first; the UI is about to suspend).
if hit.repo.contains('/') {
match crate::editor::prepare(
&self.config,
self.provider.as_ref(),
&hit.repo,
&hit.path,
&hit.sha,
) {
Ok(job) => self.pending_editor = Some(job),
Err(message) => {
self.status = Some(format!("editor: {message}"));
}
}
}
} else {
// Mock hits: materialize the stand-in body.
let slug = self
.search_view
.as_ref()
.map(|v| v.kind().slug())
.unwrap_or("hit");
match crate::editor::resolve_program(&self.config) {
Some(program) => {
// Content-address the mock body like a real blob.
use sha2::{Digest, Sha256};
// digest 0.11 dropped `LowerHex` on its output —
// render the hex by hand.
use std::fmt::Write as _;
let digest = Sha256::digest(hit.body.as_bytes());
let mut sha = String::with_capacity(digest.len() * 2);
for byte in digest {
let _ = write!(sha, "{byte:02x}");
}
match crate::editor::materialize(
"mock",
slug,
&sha,
&hit.path,
hit.body.as_bytes(),
) {
Ok(file) => {
let mut args =
crate::editor::build_args(&program, &self.config);
args.push(file.to_string_lossy().into_owned());
self.pending_editor =
Some(crate::editor::EditorJob { program, args });
}
Err(e) => self.status = Some(format!("editor: {e}")),
}
}
None => {
self.status =
Some("no editor found — set [editor].program or $EDITOR".into());
}
}
}
}
Action::RunClone { repos, dest } => {
if repos.is_empty() {
self.status = Some("nothing selected to clone".into());
self.wizard = None;
} else {
let count = repos.len();
self.status = Some(format!("cloning {count} repos…"));
self.wizard = None;
if !self.offline {
self.spawn_clones(repos, dest);
}
}
}
Action::ApplySettings(config) => {
self.settings = None; // close the popup
let theme_changed = config.theme != self.config.theme;
let provider_changed = config.provider != self.config.provider;
let ui_changed = config.ui != self.config.ui;
self.config = config;
// Hot reload: rebuild the palette (and chrome prefs);
// every component reads Theme per render, so the
// repaint is automatic.
if theme_changed || ui_changed {
let name = self.config.theme.name.clone();
let border = BorderShape::parse(&self.config.ui.border).unwrap_or_default();
self.theme = Theme::load(&name)
.with_border(border)
.with_nerd_font(self.config.ui.nerd_font)
.with_separator(&self.config.ui.separator);
}
match self.config.save() {
Ok(()) => {
self.status = Some(if provider_changed {
"settings saved — provider applies after restart".into()
} else {
"settings saved".into()
})
}
Err(e) => self.status = Some(format!("settings: {e} (applied live)")),
}
}
Action::EnterSearch => {
self.browser.filter_input.submode = crate::components::vim_input::SubMode::Insert;
self.mode = Mode::Search;
}
Action::CommitFilter => self.mode = Mode::Browse,
Action::ClearFilter => {
// BROWSE Esc precedence (plans/0007 §3): a committed
// find clears first (:nohlsearch), then the list filter.
// In SEARCH mode Esc keeps its cancel-the-session role.
if self.mode == Mode::Browse && self.browser.preview.find_active() {
self.browser.preview.clear_find();
} else {
self.browser.clear_filter();
}
self.mode = Mode::Browse;
}
Action::LeaderFindInFile => {
// Reachable from the leader layer (Browse underneath)
// and from the preview submode — FIND returns to
// whichever raised it.
let back = self.mode;
self.find_return = Some(if back == Mode::Preview {
Mode::Preview
} else {
Mode::Browse
});
self.mode = Mode::Browse; // leader layer down either way
if self.browser.preview.findable() {
self.browser.find_input.clear();
self.browser.find_input.submode = crate::components::vim_input::SubMode::Insert;
self.browser.preview.begin_find();
self.mode = Mode::Find;
} else {
self.mode = self.find_return.take().unwrap_or(Mode::Browse);
self.status = Some("find: preview is not a text file".into());
}
}
Action::UpdateFind => {
let query = self.browser.find_input.value();
self.browser.preview.update_find(query);
}
Action::CommitFind => {
self.mode = self.find_return.take().unwrap_or(Mode::Browse);
}
Action::CancelFind => {
self.browser.preview.cancel_find();
self.browser.find_input.clear();
self.mode = self.find_return.take().unwrap_or(Mode::Browse);
}
Action::FindNext => {
self.browser.preview.find_step(1);
}
Action::FindPrev => {
self.browser.preview.find_step(-1);
}
Action::MoveUp
| Action::MoveDown
| Action::DrillIn
| Action::DrillOut
| Action::PreviewLineUp
| Action::PreviewLineDown => {
let follow = self.browser.update(&action);
self.handle_action(follow);
}
Action::OpenSelected => {
match self.browser.selected_kind() {
Some(EntryKind::File) => {
// Enter on a file → open in the editor (read-only,
// PLAN.md §12). The blocking blob fetch is fine:
// the UI is about to suspend anyway.
if let (Some((path, sha)), Some((owner, repo))) =
(self.browser.selected_file(), self.browser.repo_coords())
{
match crate::editor::prepare(
&self.config,
self.provider.as_ref(),
&format!("{owner}/{repo}"),
&path,
&sha,
) {
Ok(job) => self.pending_editor = Some(job),
Err(message) => self.status = Some(format!("editor: {message}")),
}
}
}
Some(EntryKind::Dir | EntryKind::Repo | EntryKind::Org) => {
let follow = self.browser.update(&Action::DrillIn);
self.handle_action(follow);
}
None => {}
}
}
// 0019 M2: the consent popup's answers.
Action::DeclarationAccept => {
if let Some(consent) = &mut self.consent {
let decl = consent.declaration().clone();
consent.set_state(crate::action::DeclarationState::Installing);
self.status = Some(format!("installing {}…", decl.name));
self.spawn_declared_install(decl);
}
}
Action::DeclarationDecline => {
if let Some(consent) = self.consent.take() {
let name = consent.declaration().name.clone();
// Honest degraded mode: the fallback is named, the
// declaration stays in the config, the retry is a
// command away — and the notice is sticky.
let note = format!(
"{name} not installed — browsing github (retry: rootle provider install {name})"
);
self.degraded = Some(note.clone());
self.status = Some(note);
}
}
Action::DeclarationState(state) => {
if let Some(consent) = &mut self.consent {
consent.set_state(state);
}
}
Action::Noop => {}
}
// Incremental filter: re-apply on every SEARCH keystroke.
if self.mode == Mode::Search {
self.browser.apply_filter();
}
// Theme switches (settings live preview, then commit) restyle
// the code the same frame the chrome recolors.
self.sync_highlight_theme();
// Any state change can leave a file under the cursor without its
// blob (navigation, filter commit/clear, tree loads) — drain it
// uniformly at the end of every route.
self.maybe_load_blob();
// Provider notices (a stdio child's successful restart) ride
// the status line once (plans/0008 §5).
if let Some(note) = self.provider.take_notice() {
self.status = Some(note);
}
}
/// The theme everything renders with: the settings popup's live
/// preview while it's browsing palettes, the committed theme
/// otherwise.
fn effective_theme(&self) -> Theme {
self.settings
.as_ref()
.and_then(SettingsPopup::preview_theme)
.unwrap_or(self.theme)
}
/// Re-highlight cached blobs when the effective theme's syntax
/// roles change. Cheap no-op per keystroke otherwise (SyntaxSet is
/// loaded once; only the color table rebuilds).
fn sync_highlight_theme(&mut self) {
let theme = self.effective_theme();
if theme.syntax == self.highlight_syntax {
return;
}
self.highlighter.set_theme(&theme);
self.browser.restyle_blobs(&self.highlighter);
self.highlight_syntax = theme.syntax;
}
/// If the selected file's blob isn't loaded, fetch it.
fn maybe_load_blob(&mut self) {
if let Some((sha, name)) = self.browser.take_blob_request() {
self.handle_action(Action::LoadBlob { sha, name });
}
}
/// Hand the prepared editor job to the main loop (which owns the
/// terminal and performs the suspend/resume dance).
pub fn take_editor_job(&mut self) -> Option<crate::editor::EditorJob> {
self.pending_editor.take()
}
/// Queued yank text, drained by the main loop once per iteration.
pub fn take_clipboard(&mut self) -> Option<String> {
self.pending_clipboard.take()
}
/// 0019 polish: the band's last-commit context for the file under
/// preview — memo hit dresses immediately, a miss spawns the
/// one-shot fetch (ambient; errors stay silent).
fn band_apply_or_fetch(&mut self) {
if !self.provider.capabilities().log || self.browser.at_commit_view() {
return;
}
let Some((owner, name)) = self.browser.repo_coords() else {
return;
};
let Some((path, _)) = self.browser.selected_file() else {
return;
};
let ref_ = self
.browser
.current_ref()
.map(str::to_string)
.unwrap_or_default();
let key = (format!("{owner}/{name}"), path.clone(), ref_.clone());
match self.last_commits.get(&key) {
Some(entry) => {
self.browser.preview.set_band(
Some(path),
Some(crate::components::preview::BandContext {
sha: entry.sha.clone(),
subject: entry.subject.clone(),
author: entry.author.clone(),
date: entry.date.clone(),
}),
);
}
None => {
self.spawn_last_commit(format!("{owner}/{name}"), path, Some(ref_));
}
}
}
/// 0018 M3: the quit-time restart trace — only when this session
/// knew about an update (the `↑` chip), compare the on-disk
/// binary once. The caller prints it after terminal restore.
pub fn update_exit_note(&self) -> Option<String> {
self.update_tag.as_ref()?;
crate::update::disk_newer_note()
}
/// Desired terminal cursor shape, if any text input is focused.
pub fn cursor_style(&self) -> Option<ratatui::crossterm::cursor::SetCursorStyle> {
if let Some(cl) = &self.command_line {
return cl.cursor_style();
}
if let Some(settings) = &self.settings {
return settings.cursor_style();
}
if let Some(view) = &self.search_view {
return view.cursor_style();
}
self.popup.as_ref().and_then(|p| p.cursor_style())
}
pub fn render(&mut self, frame: &mut Frame, area: Rect) {
let theme = self.effective_theme();
let mode = self.effective_mode();
// State vs keys, one hint surface per context: a view or
// overlay that draws its own border hint row (search view,
// popups, wizard) wins; the glued strip serves what has no
// border — the leader layer (always) and the browser's
// transient modes; the modeline is state-only either way.
let overlay_up = self.popup.is_some()
|| self.wizard.is_some()
|| self.settings.is_some()
|| self.help.is_some()
|| self.command_line.is_some()
|| self.refs_popup.is_some()
|| self.search_view.is_some();
let strip = mode == Mode::Leader || (!overlay_up && mode != Mode::Browse);
let rows = Layout::default()
.direction(Direction::Vertical)
.constraints(if strip {
vec![
Constraint::Min(1),
Constraint::Length(1),
Constraint::Length(1),
]
} else {
vec![Constraint::Min(1), Constraint::Length(1)]
})
.split(area);
if let Some(view) = &mut self.search_view {
view.render(frame, rows[0], &theme);
self.modeline.context = view.context();
} else {
// The preview submode (␣ p) and its lenses zoom the pane to
// the full row; FIND raised from it keeps the zoom.
let zoomed = matches!(self.mode, Mode::Preview | Mode::History)
|| (self.mode == Mode::Find && self.find_return == Some(Mode::Preview));
self.browser.preview.focused = zoomed;
self.browser.render(frame, rows[0], &theme, zoomed);
self.modeline.context = self.browser.context();
}
if strip {
frame.render_widget(
Paragraph::new(crate::components::modeline::hint_strip_line(
mode,
rows[1].width as usize,
&theme,
)),
rows[1],
);
}
self.modeline.status = self.status.clone().or_else(|| self.degraded.clone());
let modeline_row = rows[rows.len() - 1];
self.modeline.update_tag = self.update_tag.clone();
self.modeline.render(frame, modeline_row, mode, &theme);
if let Some(popup) = &mut self.popup {
popup.render(frame, rows[0], &theme);
}
// v0.3/v0.4 overlays, above the base view.
if let Some(help) = &mut self.help {
help.render(frame, rows[0], &theme);
}
if let Some(settings) = &mut self.settings {
settings.render(frame, rows[0], &theme);
}
if let Some(wizard) = &mut self.wizard {
wizard.render(frame, rows[0], &theme);
}
if let Some(refs) = &mut self.refs_popup {
refs.render(frame, rows[0], &theme);
}
// 0019 M2: the consent popup is the topmost surface — a
// pending trust decision renders above everything.
if let Some(consent) = &mut self.consent {
consent.render(frame, rows[0], &theme);
}
// Command strip sits on the modeline's doorstep, last.
if let Some(command_line) = &mut self.command_line {
command_line.render(frame, rows[0], &theme);
}
}
}
/// Worker debug tracing: enabled via ROOTLE_TRACE=/path/log (kept minimal,
/// no logging dependency; remove when the backend stabilizes).
pub fn trace(msg: &str) {
if let Ok(path) = std::env::var("ROOTLE_TRACE") {
use std::io::Write;
if let Ok(mut f) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(path)
{
let _ = writeln!(f, "{:?} {msg}", std::time::SystemTime::now());
}
}
}
#[cfg(test)]
mod tests {
use crate::provider::{ErrorKind, ProviderError};
use std::time::Duration;
#[test]
fn provider_status_renders_per_kind() {
let auth = ProviderError::new(ErrorKind::Auth, "bad credentials");
let rendered = super::provider_status(&auth);
assert!(rendered.contains("bad credentials"));
assert!(rendered.contains("refresh provider credentials"));
let throttled = ProviderError::new(ErrorKind::RateLimited, "slow down")
.with_retry_after(Duration::from_secs(37));
assert_eq!(
super::provider_status(&throttled),
"provider throttled — retry in 37s"
);
let plain = ProviderError::other("something broke");
assert_eq!(super::provider_status(&plain), "something broke");
}
}