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
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
//! `handle_*` helpers: turning one input event, view event, or external
//! action into `App` state changes.
//!
//! Moved verbatim out of `ui.rs`.
use super::*;
/// Persist a `# foo` quick-add through the native memory store and surface
/// a status note to the user. Errors land in the same status channel so a
/// missing memory directory becomes visible without crashing the composer.
pub(crate) fn handle_memory_quick_add(app: &mut App, input: &str, config: &Config) {
let path = config.memory_path();
let note = input.trim_start_matches('#').trim();
let result = crate::native_memory::NativeMemoryStore::from_global_path(&path)
.ok_or_else(|| format!("{} is not a native memory path", path.display()))
.and_then(|store| {
store
.remember(crate::native_memory::MemoryScope::Global, None, note)
.map(|hit| hit.source)
.map_err(|err| err.to_string())
});
match result {
Ok(source) => {
app.status_message = Some(format!("memory: appended to {}", source.display()));
}
Err(err) => {
app.status_message = Some(format!(
"memory: failed to write {}: {}",
path.display(),
err
));
}
}
}
/// Route one terminal bracketed-paste event without exposing its contents.
///
/// Keeping the routing in one function makes the credential and ordinary
/// composer paths exercise the same observability boundary.
pub(crate) fn handle_bracketed_paste(app: &mut App, text: &str) {
tracing::debug!(
paste_bytes = text.len(),
paste_chars = text.chars().count(),
"Received bracketed paste event"
);
// Once a real bracketed-paste event has been observed in this session,
// the rapid-keystroke heuristic in paste_burst is redundant — disable it
// so fast typing / IME commits / autocomplete bursts don't get
// mis-classified as a paste.
app.bracketed_paste_seen = true;
if app.is_history_search_active() {
app.history_search_insert_str(text);
} else if paste_text_into_provider_picker(app, text) || app.view_stack.handle_paste(text) {
// Modal consumed the paste (e.g. provider picker key entry).
} else if !app.view_stack.is_empty() {
// A non-consumed modal is open — don't leak paste into composer.
} else {
// Paste into main input.
app.insert_paste_text(text);
}
}
/// Voice input toggle via Option+V (⌥V) — matches Muse Spark UX:
/// "Recording (⌥V to finish)" with a transient voice indicator, no slash
/// command needed. Handles both Alt+V and the macOS ⌥V glyph.
pub(crate) fn handle_voice_key(app: &mut App, key: &event::KeyEvent) -> bool {
let is_alt_v = matches!(key.code, KeyCode::Char('v') | KeyCode::Char('V'))
&& key.modifiers.contains(KeyModifiers::ALT)
&& !key.modifiers.contains(KeyModifiers::CONTROL)
&& !key.modifiers.contains(KeyModifiers::SUPER);
// Some terminals emit the literal "√" (Option+V on macOS) instead of Alt+V.
let is_glyph = matches!(key.code, KeyCode::Char('√') | KeyCode::Char('∫'));
if !is_alt_v && !is_glyph {
return false;
}
// Toggle voice capture — same path as /voice but via hotkey.
let result = crate::commands::voice::voice(app);
// Surface a Spark-style transient hint; the capture itself is async.
if app.voice_enabled {
app.status_message = Some("● Recording (⌥V to finish)".to_string());
}
// Suppress the default char insertion for this combo.
let _ = result;
true
}
/// The event-loop seam for Ctrl+T. Keeping the `KeyEvent` predicate and App
/// mutation together makes the real terminal route directly testable rather
/// than testing `cycle_effort` in isolation.
pub(crate) fn handle_reasoning_effort_key(app: &mut App, key: &event::KeyEvent) -> bool {
if !matches!(key.code, KeyCode::Char('t') | KeyCode::Char('T'))
|| key.modifiers != KeyModifiers::CONTROL
{
return false;
}
let _ = app.cycle_effort();
true
}
/// Let the transcript remain reviewable while an approval card owns focus.
pub(crate) fn handle_approval_transcript_key(app: &mut App, key: &event::KeyEvent) -> bool {
if app.view_stack.top_kind() != Some(ModalKind::Approval) {
return false;
}
let page = app.viewport.last_transcript_visible.max(1);
match key.code {
KeyCode::PageUp => app.scroll_up(page),
KeyCode::PageDown => app.scroll_down(page),
KeyCode::Up
if key
.modifiers
.intersects(KeyModifiers::ALT | KeyModifiers::SHIFT | KeyModifiers::CONTROL) =>
{
app.scroll_up(3);
}
KeyCode::Down
if key
.modifiers
.intersects(KeyModifiers::ALT | KeyModifiers::SHIFT | KeyModifiers::CONTROL) =>
{
app.scroll_down(3);
}
KeyCode::Home => app.scroll_up(usize::MAX),
KeyCode::End => app.scroll_to_bottom(),
_ => return false,
}
true
}
/// Route only non-text controls to a focused workflow panel.
///
/// Returning `false` for every character is deliberate: the caller then lets
/// the normal composer path insert it. A prior bare-letter contract used
/// t/c/j/k here, which made the first matching letter of a new chat disappear
/// after the user clicked the workflow card.
pub(crate) fn handle_workflow_panel_key(app: &mut App, key: &event::KeyEvent) -> bool {
if !app
.workflow_panel
.as_ref()
.is_some_and(|panel| panel.keyboard_focus)
{
return false;
}
if matches!(key.code, KeyCode::Char(_)) {
if let Some(panel) = app.workflow_panel.as_mut() {
panel.keyboard_focus = false;
}
app.needs_redraw = true;
return false;
}
if !key.modifiers.is_empty() && key.code != KeyCode::Esc {
return false;
}
match key.code {
KeyCode::Esc => {
if let Some(panel) = app.workflow_panel.as_mut() {
panel.keyboard_focus = false;
}
app.needs_redraw = true;
true
}
KeyCode::Enter => {
if let Some(panel) = app.workflow_panel.as_mut() {
let _ = panel.toggle_expanded();
}
app.needs_redraw = true;
true
}
KeyCode::Down => {
if let Some(panel) = app.workflow_panel.as_mut() {
panel.select_next_phase();
}
app.needs_redraw = true;
true
}
KeyCode::Up => {
if let Some(panel) = app.workflow_panel.as_mut() {
panel.select_prev_phase();
}
app.needs_redraw = true;
true
}
KeyCode::Delete => {
let Some(run_id) = app
.workflow_panel
.as_ref()
.and_then(|panel| panel.lifecycle.is_running().then(|| panel.run_id.clone()))
else {
return false;
};
app.input = format!("/workflow cancel {run_id}");
app.cursor_position = app.input.chars().count();
app.status_message = Some(app.tr(MessageId::SidebarDestructiveArmed).into_owned());
if let Some(panel) = app.workflow_panel.as_mut() {
panel.keyboard_focus = false;
}
app.needs_redraw = true;
true
}
_ => false,
}
}
/// One-shot "draft my constitution" call against the user's first configured
/// model, requested by `A` on the setup Constitution card. Runs inline in the
/// event loop like [`fetch_available_models`] (the wizard modal stays open
/// underneath) with a hard timeout so a slow provider cannot wedge setup.
///
/// On success the sanitized, bounded draft is installed into the open wizard
/// and its ratification preview opens on top — nothing persists until the
/// user ratifies with `G`. Every failure (no client, timeout, request error,
/// invalid or empty JSON) is a status line, never an error state: the
/// deterministic guided draft remains the standing fallback.
pub(crate) async fn handle_setup_constitution_model_draft(
app: &mut App,
config: &Config,
draft: crate::tui::setup::GuidedConstitutionDraft,
freeform_note: Option<String>,
locale: crate::localization::Locale,
) {
// Spawn the draft off the event loop (same pattern as the fleet drafter,
// #3757 review): awaiting it inline parked the whole TUI for up to the
// timeout. The loop polls constitution_draft_cell and delivers the result.
const DRAFT_TIMEOUT: Duration = Duration::from_secs(20);
let model_label = app.model_display_label();
let client = match DeepSeekClient::new(config) {
Ok(client) => client,
Err(err) => {
deliver_constitution_draft_result(
app,
model_label.clone(),
locale,
Err(format!("provider not ready: {err:#}")),
);
return;
}
};
let request_model = app.model.clone();
let cell = app.constitution_draft_cell.clone();
let spawn_label = model_label.clone();
let request_gen = app.next_draft_gen();
app.status_message = Some(match locale {
crate::localization::Locale::ZhHans => {
format!(
"{model_label} 正在生成协作准则草案……(最多 {}s)",
DRAFT_TIMEOUT.as_secs()
)
}
_ => format!(
"{model_label} is drafting your constitution… (up to {}s)",
DRAFT_TIMEOUT.as_secs()
),
});
app.needs_redraw = true;
tokio::spawn(async move {
let outcome = match tokio::time::timeout(
DRAFT_TIMEOUT,
crate::tui::setup::draft_constitution_with_model(
&client,
&request_model,
draft,
freeform_note,
locale,
),
)
.await
{
Err(_) => Err(format!("timed out after {}s", DRAFT_TIMEOUT.as_secs())),
Ok(result) => result,
};
if let Ok(mut guard) = cell.lock() {
*guard = Some((request_gen, spawn_label, locale, outcome));
}
});
}
/// One-shot fleet-profile draft: same contract as the constitution drafter —
/// minimal payload out, untrusted gate in, preview before ratify, degrade to
/// the manual authoring flow on any failure.
pub(crate) async fn handle_fleet_profile_model_draft(
app: &mut App,
config: &Config,
role: String,
model: String,
provider: Option<String>,
reasoning_effort: Option<String>,
locale: crate::localization::Locale,
) {
// The route the operator actually picked at `m`-press time (#4093). A
// model draft always comes back `provider: None` (the untrusted gate
// strips any provider), so this captured `(provider, model)` is what the
// ratified profile is pinned to — immune to the model omitting/altering
// the route AND to the selection changing while the draft is in flight.
// `None` for an `inherit` pick (no concrete route to keep).
let picked_route = provider.map(|provider| (provider, model.clone()));
// Do NOT await the network call on the event loop — that parks the whole
// TUI for up to the timeout (#3757 review). Spawn it into the shared
// fleet_draft_cell and let the loop poll + deliver the result, keeping
// the wizard interactive with a drafting status.
const DRAFT_TIMEOUT: Duration = Duration::from_secs(20);
let model_label = app.model_display_label();
let client = match DeepSeekClient::new(config) {
Ok(client) => client,
Err(err) => {
deliver_fleet_draft_result(
app,
model_label.clone(),
picked_route.clone(),
reasoning_effort.clone(),
Err(format!("provider not ready: {err:#}")),
locale,
);
return;
}
};
let request_model = app.model.clone();
let cell = app.fleet_draft_cell.clone();
let spawn_label = model_label.clone();
let request_gen = app.next_draft_gen();
let workspace = app.workspace.clone();
app.status_message = Some(match locale {
crate::localization::Locale::ZhHans => {
format!(
"{model_label} 正在起草配置……(最多 {}s)",
DRAFT_TIMEOUT.as_secs()
)
}
_ => format!(
"{model_label} is drafting the profile… (up to {}s)",
DRAFT_TIMEOUT.as_secs()
),
});
app.needs_redraw = true;
tokio::spawn(async move {
// Redacted, bounded workspace fingerprint (manifest names, test
// commands, branch + dirty count — no contents, secrets, or absolute
// paths). Computed off the event loop; the untrusted-output gate on
// the reply is unchanged.
let fingerprint = tokio::task::spawn_blocking(move || {
crate::tui::setup::workspace_fingerprint(&workspace)
})
.await
.unwrap_or_default();
let outcome = match tokio::time::timeout(
DRAFT_TIMEOUT,
crate::tui::setup::draft_fleet_profile_with_model(
&client,
&request_model,
&role,
&model,
locale,
&fingerprint,
),
)
.await
{
Err(_) => Err(format!("timed out after {}s", DRAFT_TIMEOUT.as_secs())),
Ok(result) => result,
};
if let Ok(mut guard) = cell.lock() {
*guard = Some((
request_gen,
spawn_label,
picked_route,
reasoning_effort,
outcome,
));
}
});
}
pub(crate) async fn handle_bang_shell_input(
app: &mut App,
engine_handle: &EngineHandle,
input: &str,
) -> Result<bool> {
let command = match shell_command_from_bang_input(input) {
Ok(Some(command)) => command,
Ok(None) => return Ok(false),
Err(message) => {
app.status_message = Some(format!("Error: {message}"));
return Ok(true);
}
};
engine_handle
.send(Op::RunShellCommand {
command: command.to_string(),
mode: app.mode,
allow_shell: app.allow_shell,
trust_mode: app.trust_mode,
auto_approve: app_auto_approve_enabled(app),
approval_mode: app.approval_mode,
})
.await?;
app.status_message = Some(format!("Shell command submitted: {command}"));
Ok(true)
}
pub(crate) async fn handle_mcp_ui_action(
app: &mut App,
engine_handle: &EngineHandle,
config: &Config,
action: crate::tui::app::McpUiAction,
) {
use crate::mcp::{self, McpWriteStatus};
let path = app.mcp_config_path.clone();
let mut changed = false;
let mut message = None;
let is_reload = matches!(&action, crate::tui::app::McpUiAction::Reload);
let discover = mcp_ui_action_refreshes_discovery(&action);
let action_result = match action {
crate::tui::app::McpUiAction::Show => Ok(()),
crate::tui::app::McpUiAction::Init { force } => {
changed = true;
match mcp::init_config(&path, force) {
Ok(McpWriteStatus::Created) => {
message = Some(format!("Created MCP config at {}", path.display()));
Ok(())
}
Ok(McpWriteStatus::Overwritten) => {
message = Some(format!("Overwrote MCP config at {}", path.display()));
Ok(())
}
Ok(McpWriteStatus::SkippedExists) => {
changed = false;
message = Some(format!(
"MCP config already exists at {} (use /mcp init --force to overwrite)",
path.display()
));
Ok(())
}
Err(err) => Err(err),
}
}
crate::tui::app::McpUiAction::AddStdio {
name,
command,
args,
} => {
changed = true;
mcp::add_server_config(&path, name.clone(), Some(command), None, args, None)
.map(|()| message = Some(format!("Added MCP stdio server '{name}'")))
}
crate::tui::app::McpUiAction::AddHttp {
name,
url,
transport,
} => {
changed = true;
mcp::add_server_config(&path, name.clone(), None, Some(url), Vec::new(), transport)
.map(|()| message = Some(format!("Added MCP HTTP/SSE server '{name}'")))
}
crate::tui::app::McpUiAction::Enable { name } => {
changed = true;
mcp::set_server_enabled(&path, &name, true)
.map(|()| message = Some(format!("Enabled MCP server '{name}'")))
}
crate::tui::app::McpUiAction::Disable { name } => {
changed = true;
mcp::set_server_enabled(&path, &name, false)
.map(|()| message = Some(format!("Disabled MCP server '{name}'")))
}
crate::tui::app::McpUiAction::Remove { name } => {
changed = true;
mcp::remove_server_config(&path, &name)
.map(|()| message = Some(format!("Removed MCP server '{name}'")))
}
crate::tui::app::McpUiAction::Login { name, scopes } => {
let result = async {
let cfg = mcp::load_config_with_workspace_and_plugins(
&path,
&app.workspace,
app.plugin_registry.as_ref(),
)?;
let server = cfg
.servers
.get(&name)
.ok_or_else(|| anyhow::anyhow!("MCP server '{name}' not found"))?;
let explicit_scopes = (!scopes.is_empty()).then_some(scopes);
mcp::oauth::perform_oauth_login_for_server(
&name,
server,
explicit_scopes,
config.mcp_oauth_callback_port,
config.mcp_oauth_callback_url.as_deref(),
)
.await
}
.await;
result.map(|()| {
changed = true;
message = Some(format!(
"Stored OAuth credentials for MCP server '{name}'. Run /mcp reload to reconnect it."
));
})
}
crate::tui::app::McpUiAction::Logout { name } => {
let result = (|| {
let cfg = mcp::load_config_with_workspace_and_plugins(
&path,
&app.workspace,
app.plugin_registry.as_ref(),
)?;
let server = cfg
.servers
.get(&name)
.ok_or_else(|| anyhow::anyhow!("MCP server '{name}' not found"))?;
mcp::oauth::delete_oauth_tokens_for_server(&name, server)
})();
result.map(|deleted| {
changed = deleted;
message = Some(if deleted {
format!(
"Deleted stored OAuth credentials for MCP server '{name}'. Run /mcp reload to reconnect it."
)
} else {
format!("No stored OAuth credentials found for MCP server '{name}'.")
});
})
}
crate::tui::app::McpUiAction::ImportList => {
let text = mcp_external_import_status_text(&app.workspace);
message = Some(text);
Ok(())
}
crate::tui::app::McpUiAction::ImportApprove { name } => {
match mcp_import_apply(&app.workspace, &path, &name, true) {
Ok(msg) => {
changed = msg.contains("Imported");
message = Some(msg);
Ok(())
}
Err(err) => Err(err),
}
}
crate::tui::app::McpUiAction::ImportDecline { name } => {
match mcp_import_apply(&app.workspace, &path, &name, false) {
Ok(msg) => {
message = Some(msg);
Ok(())
}
Err(err) => Err(err),
}
}
crate::tui::app::McpUiAction::Validate | crate::tui::app::McpUiAction::Reload => Ok(()),
};
if let Err(err) = action_result {
add_mcp_message(app, format!("MCP action failed: {err}"));
return;
}
if changed {
app.mcp_reload_required = true;
}
if let Some(message) = message {
add_mcp_message(app, message);
}
let snapshot_result = if is_reload {
match engine_handle.reload_mcp(path.clone()).await {
Ok(snapshot) => {
app.mcp_reload_required = false;
add_mcp_message(app, mcp_reload_summary(&snapshot));
Ok(snapshot)
}
Err(error) => {
app.mcp_reload_required = true;
Err(error)
}
}
} else if discover {
let network_policy = config.network.clone().map(|toml_cfg| {
crate::network_policy::NetworkPolicyDecider::with_default_audit(toml_cfg.into_runtime())
});
mcp::discover_manager_snapshot_with_workspace_and_plugins(
&path,
&app.workspace,
network_policy,
app.mcp_reload_required,
std::sync::Arc::clone(&app.plugin_registry),
)
.await
} else {
mcp::manager_snapshot_from_config_with_workspace_and_plugins(
&path,
&app.workspace,
app.mcp_reload_required,
app.plugin_registry.as_ref(),
)
};
match snapshot_result {
Ok(snapshot) => {
if discover {
add_mcp_message(
app,
"MCP discovery refreshed for the UI. Run /mcp reload after config or credential edits to rebuild the live model-visible tool pool.".to_string(),
);
}
// Keep the boot-time MCP-count chip in sync with the live
// snapshot so footers and panels reflect post-/mcp edits
// (#502).
app.mcp_configured_count = snapshot.servers.len();
app.mcp_snapshot = Some(snapshot.clone());
// #2068: keep the hotbar's MCP-tool actions in sync with the tools
// that are actually loaded; the hotbar never connects on its own.
app.hotbar_actions.replace_mcp_tools(Some(&snapshot));
open_mcp_manager_pager(app, &snapshot);
}
Err(err) if is_reload => add_mcp_message(
app,
format!("MCP reload failed; the live tool pool is unchanged: {err}"),
),
Err(err) => add_mcp_message(app, format!("MCP snapshot failed: {err}")),
}
}
pub(crate) fn handle_shell_job_action(app: &mut App, action: crate::tui::app::ShellJobAction) {
let Some(shell_manager) = app.runtime_services.shell_manager.clone() else {
add_shell_job_message(app, "No shell session is active.".to_string());
return;
};
let mut manager = match shell_manager.lock() {
Ok(manager) => manager,
Err(_) => {
add_shell_job_message(
app,
"Shell tracking hit an internal error — restart Codewhale to recover.".to_string(),
);
return;
}
};
match action {
crate::tui::app::ShellJobAction::List => {
let jobs = manager.list_jobs();
add_shell_job_message(app, format_shell_job_list(&jobs));
}
crate::tui::app::ShellJobAction::Show { id } => match manager.inspect_job(&id) {
Ok(detail) => open_shell_job_pager(app, &detail),
Err(err) => add_shell_job_message(app, format!("Command lookup failed: {err}")),
},
crate::tui::app::ShellJobAction::Poll { id, wait } => {
match manager.poll_delta(&id, wait, if wait { 5_000 } else { 1_000 }) {
Ok(delta) => add_shell_job_message(app, format_shell_poll(&delta.result)),
Err(err) => add_shell_job_message(app, format!("Command poll failed: {err}")),
}
}
crate::tui::app::ShellJobAction::SendStdin { id, input, close } => {
match manager.write_stdin(&id, &input, close) {
Ok(()) => match manager.poll_delta(&id, false, 1_000) {
Ok(delta) => add_shell_job_message(app, format_shell_poll(&delta.result)),
Err(err) => {
add_shell_job_message(
app,
format!("Command input sent; poll failed: {err}"),
);
}
},
Err(err) => add_shell_job_message(app, format!("Command input failed: {err}")),
}
}
crate::tui::app::ShellJobAction::Cancel { id } => match manager.kill(&id) {
Ok(result) => add_shell_job_message(app, format_shell_poll(&result)),
Err(err) => add_shell_job_message(app, format!("Command cancel failed: {err}")),
},
crate::tui::app::ShellJobAction::CancelAll => match manager.kill_running() {
Ok(results) => {
let count = results.len();
if count == 0 {
add_shell_job_message(app, "No running commands to cancel.".to_string());
} else {
let tasks: Vec<String> = results
.iter()
.filter_map(|result| result.task_id.clone())
.collect();
add_shell_job_message(
app,
format!("Canceled {count} command(s): {}", tasks.join(", ")),
);
}
}
Err(err) => add_shell_job_message(app, format!("Command cancel-all failed: {err}")),
},
}
}
pub(crate) async fn handle_skill_mutation_requested(
app: &mut App,
request: crate::skills::mutation::SkillMutationRequest,
) {
use crate::skills::install::{DEFAULT_MAX_SIZE_BYTES, DEFAULT_REGISTRY_URL};
use crate::skills::mutation::{MutationContext, SkillMutationOutcome, SkillMutationRequest};
let focus = match &request {
SkillMutationRequest::ImportExternal { source_id, .. } => Some(source_id.clone()),
SkillMutationRequest::Update { skill_id, .. }
| SkillMutationRequest::Remove { skill_id, .. }
| SkillMutationRequest::Trust { skill_id, .. } => Some(skill_id.clone()),
SkillMutationRequest::InstallRemote { .. }
| SkillMutationRequest::UpdateByName { .. }
| SkillMutationRequest::RemoveByName { .. }
| SkillMutationRequest::TrustByName { .. } => None,
};
let workspace = app.workspace.clone();
let home = crate::config::effective_home_dir();
let cfg = crate::config::Config::load(None, None).unwrap_or_default();
let network = cfg
.network
.clone()
.map(|policy| policy.into_runtime())
.unwrap_or_default();
let skills_cfg = cfg.skills.as_ref();
let max_size = skills_cfg
.and_then(|s| s.max_install_size_bytes)
.unwrap_or(DEFAULT_MAX_SIZE_BYTES);
let registry_url = skills_cfg
.and_then(|s| s.registry_url.clone())
.unwrap_or_else(|| DEFAULT_REGISTRY_URL.to_string());
let skills_dir = app.skills_dir.clone();
let result = {
let ctx = MutationContext {
workspace: &workspace,
home: home.as_deref(),
configured_skills_dir: Some(skills_dir.as_path()),
network: &network,
max_size,
registry_url: ®istry_url,
};
crate::skills::mutation::execute(request, &ctx).await
};
let (status, refresh_skills) = match result {
Ok(receipt) => {
let msg = match &receipt.outcome {
SkillMutationOutcome::Installed => {
format!(
"Installed '{}' → {}",
receipt.name, receipt.safe_target_path
)
}
SkillMutationOutcome::Updated => format!("Updated '{}'", receipt.name),
SkillMutationOutcome::NoChange => {
format!("'{}': no upstream change", receipt.name)
}
SkillMutationOutcome::Removed => format!("Removed '{}'", receipt.name),
SkillMutationOutcome::Trusted => format!("Trusted '{}'", receipt.name),
SkillMutationOutcome::Imported => {
format!("Imported '{}' → {}", receipt.name, receipt.safe_target_path)
}
SkillMutationOutcome::AlreadyPresent => {
format!("'{}' already present (exact duplicate)", receipt.name)
}
SkillMutationOutcome::NeedsApproval(host) => {
format!("Needs network approval for {host}")
}
SkillMutationOutcome::NetworkDenied(host) => {
format!("Network denied for {host}")
}
};
let refresh = !matches!(
receipt.outcome,
SkillMutationOutcome::NeedsApproval(_) | SkillMutationOutcome::NetworkDenied(_)
);
(msg, refresh)
}
Err(err) => (format!("Skill mutation failed: {err:#}"), false),
};
app.status_message = Some(status.clone());
if refresh_skills {
app.refresh_skill_cache();
}
refresh_skills_manager_if_open(app, Some(status), focus.as_ref());
app.needs_redraw = true;
}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn handle_config_updated(
terminal: &mut AppTerminal,
app: &mut App,
config: &mut Config,
task_manager: &SharedTaskManager,
engine_handle: &mut EngineHandle,
web_config_session: &mut Option<WebConfigSession>,
key: String,
value: String,
persist: bool,
) -> Result<bool> {
let result = prepare_config_update_result(
commands::set_config_value(app, &key, &value, persist),
persist,
);
let normalized_value = value.trim().to_ascii_lowercase().replace([' ', '_'], "-");
let cleared_root_approval = !result.is_error
&& persist
&& key == "approval_policy"
&& matches!(
normalized_value.as_str(),
"default" | "tui-default" | "use-tui-default"
);
// Theme / background changes require a full terminal repaint because
// ratatui's incremental diff cannot see colors remapped by the backend.
if matches!(
key.as_str(),
"theme" | "ui_theme" | "background_color" | "background" | "bg"
) {
app.force_next_full_repaint = true;
}
if apply_command_result(
terminal,
app,
engine_handle,
task_manager,
config,
web_config_session,
result,
)
.await?
{
return Ok(true);
}
let focus_key = if cleared_root_approval {
"permission_posture"
} else {
&key
};
refresh_config_view_if_open(app, focus_key);
Ok(false)
}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn handle_view_events(
terminal: &mut AppTerminal,
app: &mut App,
config: &mut Config,
task_manager: &SharedTaskManager,
engine_handle: &mut EngineHandle,
web_config_session: &mut Option<WebConfigSession>,
events: Vec<ViewEvent>,
) -> Result<bool> {
for event in events {
match event {
ViewEvent::TelemetryNoticeDecided { enabled, pending } => {
let applied = crate::telemetry_notice::apply_decision(&pending, enabled);
// Feed the just-made choice directly into the predicate. A
// failed write can make Codewhale ask again next launch, but
// it can never reverse Disable for this process.
crate::apply_tui_telemetry_decision(&pending, &applied.setup_state);
let status_message = app.tr(applied.status_message_id).into_owned();
app.push_status_toast(status_message, StatusToastLevel::Info, Some(8_000));
if std::mem::take(&mut app.start_remote_control_on_launch) {
start_remote_control_session(app);
}
submit_initial_input_if_ready(app, config, engine_handle).await?;
}
ViewEvent::TelemetryNoticeCancelled => {
let _ = engine_handle.send(Op::Shutdown).await;
return Ok(true);
}
ViewEvent::CommandPaletteSelected { action } => match action {
crate::tui::views::CommandPaletteAction::ExecuteCommand { command } => {
if execute_command_input(
terminal,
app,
engine_handle,
task_manager,
config,
&mut *web_config_session,
&command,
)
.await?
{
return Ok(true);
}
}
crate::tui::views::CommandPaletteAction::InsertText { text } => {
app.input = text;
app.cursor_position = app.input.chars().count();
app.status_message = Some(
"Inserted into composer. Finish the input or press Enter.".to_string(),
);
}
crate::tui::views::CommandPaletteAction::OpenTextPager { title, content } => {
open_text_pager(app, title, content);
}
},
ViewEvent::OpenTextPager { title, content } => {
open_text_pager(app, title, content);
}
ViewEvent::CopyToClipboard { text, label } => {
if text.is_empty() {
app.status_message = Some(format!("{label} is empty"));
} else if app.clipboard.write_text(&text).is_ok() {
app.status_message = Some(format!("{label} copied"));
} else {
app.status_message = Some(format!("Copy failed ({label})"));
}
}
ViewEvent::ApprovalDecision {
tool_id,
tool_name,
decision,
timed_out,
approval_key,
approval_grouping_key,
persistent_rules,
} => {
apply_approval_decision(
app,
engine_handle,
config,
ApprovalDecisionEvent {
tool_id,
tool_name,
decision,
timed_out,
approval_key,
approval_grouping_key,
persistent_rules,
},
)
.await;
if timed_out {
app.add_message(HistoryCell::System {
content: "Approval request timed out - denied".to_string(),
});
}
}
ViewEvent::ElevationDecision {
tool_id,
tool_name,
option,
} => {
use crate::tui::approval::ElevationOption;
match option {
ElevationOption::Abort => {
let _ = engine_handle.deny_tool_call(tool_id).await;
app.add_message(HistoryCell::System {
content: format!("Sandbox elevation aborted for {tool_name}"),
});
}
ElevationOption::WithNetwork => {
app.add_message(HistoryCell::System {
content: format!("Retrying {tool_name} with network access enabled"),
});
let policy = option.to_policy(&app.workspace);
let _ = engine_handle.retry_tool_with_policy(tool_id, policy).await;
}
ElevationOption::WithWriteAccess(_) => {
app.add_message(HistoryCell::System {
content: format!("Retrying {tool_name} with write access enabled"),
});
let policy = option.to_policy(&app.workspace);
let _ = engine_handle.retry_tool_with_policy(tool_id, policy).await;
}
ElevationOption::FullAccess => {
app.add_message(HistoryCell::System {
content: format!("Retrying {tool_name} with full access (no sandbox)"),
});
let policy = option.to_policy(&app.workspace);
let _ = engine_handle.retry_tool_with_policy(tool_id, policy).await;
}
}
}
ViewEvent::UserInputSubmitted { tool_id, response } => {
match engine_handle
.submit_user_input(tool_id.clone(), response)
.await
{
Ok(()) => {
app.pending_user_input_prompt = None;
}
Err(err) => {
tracing::warn!(tool_id = %tool_id, error = %err, "user input submit failed");
if let Some((id, request)) = app.pending_user_input_prompt.clone() {
app.view_stack.push(UserInputView::new(id, request));
}
app.push_status_toast(
format!("Failed to submit response: {err}"),
StatusToastLevel::Error,
None,
);
app.status_message =
Some(format!("Failed to submit response: {err} — try again"));
}
}
}
ViewEvent::UserInputCancelled { tool_id } => {
let _ = engine_handle.cancel_user_input(tool_id).await;
app.add_message(HistoryCell::System {
content: "User input cancelled".to_string(),
});
}
ViewEvent::SessionSelected { session_id } => {
let manager = match SessionManager::default_location() {
Ok(manager) => manager,
Err(err) => {
app.status_message =
Some(format!("Failed to open sessions directory: {err}"));
continue;
}
};
match manager.load_session(&session_id) {
Ok(session) => {
let next_config = config.clone();
let respawn = match apply_loaded_session_config_snapshot(
app,
config,
&session,
next_config,
false,
) {
Ok(outcome) => outcome,
Err(err) => {
app.status_message =
Some(format!("Failed to restore session: {err}"));
continue;
}
};
sync_runtime_workspace_state(task_manager, app.workspace.clone()).await;
if respawn {
let _ = engine_handle.send(Op::Shutdown).await;
*engine_handle =
spawn_tui_engine(build_engine_config(app, config), config);
} else {
let _ = engine_handle
.send(Op::SetModel {
model: app.model.clone(),
mode: app.mode,
route_limits: app.active_route_limits,
})
.await;
}
let _ = engine_handle
.send(Op::SyncSession {
session_id: app.current_session_id.clone(),
messages: app.api_messages.clone(),
system_prompt: app.system_prompt.clone(),
system_prompt_override: false,
model: app.model.clone(),
workspace: app.workspace.clone(),
mode: app.mode,
})
.await;
let _ = engine_handle
.send(Op::SetCompaction {
config: app.compaction_config(),
})
.await;
// Durable receipt, matching `/load`: the status toast
// alone is replaced by the next footer update, leaving
// no findable record that the resume happened.
let loaded_message = format!(
"Session loaded (ID: {}, {} messages)",
crate::session_manager::truncate_id(&session_id),
session.metadata.message_count
);
app.add_message(HistoryCell::System {
content: loaded_message.clone(),
});
app.status_message = Some(loaded_message);
app.launch.visible = false;
app.launch.status = None;
}
Err(err) => {
app.status_message = Some(format!(
"Failed to load session {}: {err}",
crate::session_manager::truncate_id(&session_id)
));
}
}
}
ViewEvent::SessionRenamed { metadata } => {
let session_id = metadata.id.clone();
let title = metadata.title.clone();
let mut work_snapshot_warning = None;
if apply_picker_session_rename_to_active_app(app, *metadata)
&& let Ok(manager) = SessionManager::default_location()
{
match build_session_snapshot(app, &manager) {
Ok(session) => {
if let Err(err) = persist_with_pending_work_boundary(
app,
PersistRequest::SessionSnapshot(session),
) {
tracing::warn!(
session_id = %session_id,
error = %err,
"Could not queue active session rename Work snapshot"
);
work_snapshot_warning = Some(format!(
"Session renamed, but Work snapshot is pending ({err})"
));
}
}
Err(err) => {
tracing::warn!(
session_id = %session_id,
error = %err,
"Could not queue active session rename snapshot"
);
}
}
}
app.status_message = Some(work_snapshot_warning.unwrap_or_else(|| {
format!(
"Renamed session {} to \"{}\"",
crate::session_manager::truncate_id(&session_id),
title
)
}));
}
ViewEvent::SessionArchived { metadata } => {
// The manager already wrote the flag. Keep the active app's
// cached metadata in step so the next autosave carries the new
// state forward instead of reverting it, and drop the rail
// cache so the row disappears (or returns) immediately.
if let Some(cached) = app.current_session_metadata.as_mut()
&& cached.id == metadata.id
{
cached.archived = metadata.archived;
}
app.status_message = Some(format!(
"{} session {} ({})",
if metadata.archived {
"Archived"
} else {
"Restored"
},
crate::session_manager::truncate_id(&metadata.id),
metadata.title
));
}
ViewEvent::SessionDeleted { session_id, title } => {
app.status_message = Some(format!(
"Deleted session {} ({})",
crate::session_manager::truncate_id(&session_id),
title
));
}
ViewEvent::ConfigUpdated {
key,
value,
persist,
} => {
if handle_config_updated(
terminal,
app,
config,
task_manager,
engine_handle,
web_config_session,
key,
value,
persist,
)
.await?
{
return Ok(true);
}
}
ViewEvent::StatusItemsUpdated { items, final_save } => {
// Apply to the live App immediately so the footer reflects
// every keystroke (live preview).
app.status_items = items.clone();
app.needs_redraw = true;
if final_save {
match crate::config_persistence::persist_status_items(&items) {
Ok(path) => {
app.status_message =
Some(format!("Status line saved to {}", path.display()));
}
Err(err) => {
app.add_message(HistoryCell::System {
content: format!("Failed to save status line: {err}"),
});
}
}
}
}
ViewEvent::HotbarSetupSaved { bindings } => {
apply_hotbar_setup_saved(app, config, bindings);
}
ViewEvent::SetupStateCommitRequested { state, message } => match state.save() {
Ok(()) => {
app.status_message = Some(message);
}
Err(err) => {
app.status_message = Some(format!("Setup state could not be saved: {err}"));
}
},
ViewEvent::SetupConstitutionCommitRequested {
constitution,
state,
message,
} => match crate::tui::setup::persist_user_constitution_choice(&constitution, &state) {
Ok(()) => {
app.status_message = Some(message);
}
Err(err) => {
app.status_message =
Some(format!("User constitution could not be saved: {err}"));
}
},
ViewEvent::SetupConstitutionModelDraftRequested {
draft,
freeform_note,
locale,
} => {
handle_setup_constitution_model_draft(app, config, draft, freeform_note, locale)
.await;
}
ViewEvent::FleetProfileModelDraftRequested {
role,
model,
provider,
reasoning_effort,
locale,
} => {
handle_fleet_profile_model_draft(
app,
config,
role,
model,
provider,
reasoning_effort,
locale,
)
.await;
}
ViewEvent::FleetRosterOpenSetupRequested { role } => {
// The roster view hands off to the authoring wizard (same
// path as AppAction::OpenFleetSetup), carrying the member role
// already selected so the wizard can begin at Model.
if app.view_stack.top_kind() != Some(ModalKind::FleetSetup) {
let _ = app.next_draft_gen();
app.view_stack.push(
crate::tui::views::fleet_setup::FleetSetupView::new_for_role(
app, config, &role,
),
);
}
}
ViewEvent::FleetListOpenDetailRequested { name, scope } => {
if app.view_stack.top_kind() != Some(ModalKind::FleetDetail) {
if let Some(view) = crate::tui::views::fleet_detail::FleetDetailView::open(
app, config, &name, scope,
) {
app.view_stack.push(view);
} else {
app.set_sticky_status(
format!(
"Could not open Fleet `{name}` ({}) — the file may have moved or become unreadable.",
scope.label()
),
crate::tui::app::StatusToastLevel::Error,
None,
);
}
}
}
ViewEvent::FleetStoreChanged { message } => {
app.status_message = Some(message);
// Refresh the dispatch roster from the fleet-aware source so
// selection changes take effect for the next spawn.
let roster =
crate::fleet::roster::FleetRoster::load(&config.fleet_config(), &app.workspace);
let _ = engine_handle.try_send(Op::SetFleetRoster {
roster: std::sync::Arc::new(roster),
});
}
ViewEvent::FleetRosterOpenFleetsRequested => {
if app.view_stack.top_kind() != Some(ModalKind::FleetList) {
app.view_stack
.push(crate::tui::views::fleet_list::FleetListView::new(
app, config,
));
}
}
ViewEvent::FleetRosterOpenWorkersRequested => {
if app.view_stack.top_kind() != Some(ModalKind::SubAgents) {
let agents = subagent_view_agents(app, &app.subagent_cache);
app.view_stack
.push(crate::tui::views::SubAgentsView::for_app(app, agents));
}
app.status_message =
Some(tr(app.ui_locale, MessageId::SubagentsFetching).to_string());
let _ = engine_handle.try_send(Op::ListSubAgents);
}
ViewEvent::FleetSetupExternalConsentActivationRequested { provider_id, model } => {
// Validate the selected Fleet route by minting the read-only
// external credential capability only for this exact
// provider/source/path. The check is route-scoped: a cloned
// config has the target provider active so credential discovery
// succeeds, but the parent session provider/model are never
// mutated.
let Some(provider) = ApiProvider::parse(&provider_id) else {
app.set_sticky_status(
format!("Fleet route activation failed: unknown provider `{provider_id}`"),
crate::tui::app::StatusToastLevel::Error,
None,
);
app.needs_redraw = true;
continue;
};
let provider_label = provider.display_name();
let mut scoped = config.clone();
scoped.provider = Some(provider_id.clone());
let validation =
crate::route_runtime::resolve_runtime_route(&scoped, provider, Some(&model))
.and_then(|route| route.validate().map_err(|err| err.to_string()));
match validation {
Ok(validated) => {
app.provider_health
.record_success(&scoped, provider, &validated.model);
app.push_status_toast(
format!(
"{provider_label} route activated for Fleet: {}",
validated.model
),
crate::tui::app::StatusToastLevel::Success,
Some(5_000),
);
}
Err(error) => {
let envelope = ErrorEnvelope::new(
ErrorCategory::Authentication,
ErrorSeverity::Error,
false,
"route_validation_failed",
&error,
);
app.provider_health
.record_failure(&scoped, provider, &model, &envelope);
app.push_status_toast(
format!("{provider_label} route activation failed: {error}"),
crate::tui::app::StatusToastLevel::Error,
None,
);
}
}
// Refresh the Fleet setup view from a snapshot built against the
// updated health state so the activated row becomes Ready
// without closing the modal.
if app.view_stack.top_kind() == Some(crate::tui::views::ModalKind::FleetSetup)
&& let Some(view) = app.view_stack.pop()
{
let mut restored = view;
if let Some(fleet_setup) = restored
.as_any_mut()
.downcast_mut::<crate::tui::views::fleet_setup::FleetSetupView>(
) {
let fresh = crate::tui::views::fleet_setup::FleetSetupSnapshot::from_app(
app, config,
);
fleet_setup.refresh_from_snapshot(fresh);
}
app.view_stack.push_boxed(restored);
}
app.needs_redraw = true;
}
ViewEvent::FleetProfileDraftCommitRequested { draft, scope } => {
// A project-scope save is refused (never silently redirected)
// when project profiles are disabled for this launch: the file
// would be written where nothing loads it.
if scope == crate::fleet::profile::FleetProfileScope::Project
&& !crate::fleet::roster::project_agent_profiles_enabled()
{
app.set_sticky_status(
tr(app.ui_locale, MessageId::FleetDestProjectDisabledSave).into_owned(),
StatusToastLevel::Error,
None,
);
app.needs_redraw = true;
continue;
}
// The TOML is rendered deterministically from the validated
// draft and written atomically; the target path is derived
// from the sanitized id, never model-chosen.
let profile_dir =
match crate::fleet::profile::agent_profile_dir_for_scope(scope, &app.workspace)
{
Ok(dir) => dir,
Err(err) => {
app.set_sticky_status(
format!("Fleet {} scope is unavailable: {err:#}", scope.label()),
StatusToastLevel::Error,
None,
);
app.needs_redraw = true;
continue;
}
};
let target = profile_dir.join(draft.file_name());
// A ratified profile must not silently clobber a differently
// named existing profile that shares this id (which would also
// make the whole agents dir fail to load on the duplicate).
// Overwriting the SAME file is fine — that is an intentional
// re-draft of this profile.
// The collision gate only needs file identities. Accept
// otherwise legacy profile fields here so an old, unrelated
// profile cannot block saving a current one. Malformed TOML,
// unreadable files, and invalid ids still fail closed because
// then we cannot prove there is no collision.
let existing_profiles =
crate::fleet::profile::load_agent_profile_identities_from_dir(&profile_dir);
if let Err(err) = &existing_profiles {
let message = tr(app.ui_locale, MessageId::FleetProfileIdentityVerifyFailed)
.replace("{error}", &format!("{err:#}"));
app.set_sticky_status(message, StatusToastLevel::Error, None);
app.needs_redraw = true;
continue;
}
let id_conflict = existing_profiles
.into_iter()
.flatten()
.find(|p| p.id.eq_ignore_ascii_case(&draft.id) && p.source != target);
if let Some(existing) = id_conflict {
let message = tr(app.ui_locale, MessageId::FleetProfileIdConflict)
.replace("{id}", &draft.id)
.replace("{path}", &existing.source.display().to_string());
app.set_sticky_status(message, StatusToastLevel::Error, None);
app.needs_redraw = true;
continue;
}
// #4093 AC #5: a profile may only pin a provider the operator
// has actually configured/credentialed. The picker already
// offers models only from configured providers, but a
// model-drafted or hand-edited route (or credentials removed
// after the pick) could still name an unconfigured one — which
// would fail loudly at launch. Catch it at save time with a
// clear message, reusing the SAME predicate the picker uses.
if let Some(provider_id) = draft.provider.as_deref()
&& let Some(provider) = crate::config::ApiProvider::parse(provider_id)
&& !crate::config::provider_is_configured_for_active(
config,
provider,
app.api_provider,
)
{
let message = tr(app.ui_locale, MessageId::FleetProfileProviderUnconfigured)
.replace("{provider}", provider_id)
.replace("{env}", &provider.env_vars_label());
app.set_sticky_status(message, StatusToastLevel::Error, None);
app.needs_redraw = true;
continue;
}
let mut txn = codewhale_config::persistence::SetupTransaction::new();
txn.stage(target.clone(), draft.render_toml().into_bytes());
match txn.commit() {
Ok(()) => {
let roster = std::sync::Arc::new(crate::fleet::roster::FleetRoster::load(
&config.fleet_config(),
&app.workspace,
));
let roster_refresh_failed = engine_handle
.try_send(Op::SetFleetRoster { roster })
.is_err();
let zh = app.ui_locale == crate::localization::Locale::ZhHans;
app.add_message(HistoryCell::System {
content: if zh {
format!("已保存 Fleet 配置:{}", target.display())
} else {
format!(
"Fleet {} profile saved: {}",
scope.label(),
target.display()
)
},
});
app.status_message = Some(if zh {
format!("已保存 Fleet 配置:{}", draft.file_name())
} else if roster_refresh_failed {
format!(
"Fleet {} profile saved, but the live roster could not refresh; restart before dispatching {}",
scope.label(),
draft.id
)
} else {
format!(
"Fleet {} profile saved: {}",
scope.label(),
draft.file_name()
)
});
}
Err(err) => {
app.status_message =
Some(if app.ui_locale == crate::localization::Locale::ZhHans {
format!("无法保存 Fleet 配置:{err:#}")
} else {
format!("Fleet profile could not be saved: {err:#}")
});
}
}
app.needs_redraw = true;
}
ViewEvent::SetupRuntimePresetApplyRequested {
preset,
state,
message,
} => match apply_setup_runtime_preset(app, config, preset, state) {
Ok(summary) => {
sync_mode_update(app, engine_handle).await;
app.status_message = Some(format!("{message} {summary}"));
}
Err(err) => {
app.status_message =
Some(format!("Runtime preset could not be applied: {err:#}"));
}
},
ViewEvent::SetupOpenProviderRequested => {
if app.view_stack.top_kind() != Some(ModalKind::ProviderPicker) {
let runtime_status = query_provider_runtime_status(engine_handle).await;
app.view_stack.push(
crate::tui::provider_picker::ProviderPickerView::new_for_setup(
app.api_provider,
Some(app.api_provider),
config,
runtime_status,
)
.with_locale(app.ui_locale)
.with_provider_health(&app.provider_health),
);
app.status_message =
Some("Provider setup opened from /setup readiness.".to_string());
}
}
ViewEvent::SetupOpenModelRequested => {
if app.view_stack.top_kind() != Some(ModalKind::ModelPicker) {
open_model_picker_for_provider(app, config, app.api_provider);
app.status_message =
Some("Model route picker opened from /setup readiness.".to_string());
}
}
ViewEvent::SetupOpenFleetRequested => {
if app.view_stack.top_kind() != Some(ModalKind::FleetSetup) {
let _ = app.next_draft_gen();
app.view_stack
.push(crate::tui::views::fleet_setup::FleetSetupView::new(
app, config,
));
app.status_message =
Some("Fleet setup opened from /setup Operate/Fleet readiness.".to_string());
}
}
ViewEvent::SetupOpenHotbarRequested => {
if app.view_stack.top_kind() != Some(ModalKind::HotbarSetup) {
app.view_stack
.push(crate::tui::hotbar::setup::HotbarSetupView::new(app, config));
app.status_message =
Some("Hotbar setup opened from /setup Hotbar readiness.".to_string());
}
}
ViewEvent::SetupOpenModeRequested => {
if app.view_stack.top_kind() != Some(ModalKind::ModePicker) {
app.view_stack
.push(crate::tui::views::mode_picker::ModePickerView::new(
app.mode,
app.ui_locale,
));
app.status_message =
Some("Work mode picker opened from /setup runtime posture.".to_string());
}
}
ViewEvent::SetupOpenConfigRequested => {
if app.view_stack.top_kind() != Some(ModalKind::Config) {
app.view_stack.push(ConfigView::new_for_app(app));
app.status_message =
Some("Config view opened from /setup runtime posture.".to_string());
}
}
ViewEvent::HotbarDisableRequested => {
disable_hotbar(app, config);
}
ViewEvent::SubAgentsRefresh => {
app.status_message = Some("Refreshing sub-agents...".to_string());
// #3802: non-blocking send — refresh op, safe to drop.
let _ = engine_handle.try_send(Op::ListSubAgents);
}
ViewEvent::SidebarAgentCancel { agent_id } => {
app.status_message = Some(format!("Cancelling {agent_id}..."));
if engine_handle
.send(Op::CancelSubAgent {
agent_id: agent_id.clone(),
})
.await
.is_err()
{
app.status_message = Some(format!("Could not cancel {agent_id}"));
}
}
ViewEvent::OpenAgentTranscript { agent_id } => {
// One agent, one destination: focus the worker so its full
// transcript owns the main area and the composer addresses
// its fork. The register modal closes so the focus is visible.
if app.view_stack.top_kind() == Some(ModalKind::SubAgents) {
app.view_stack.pop();
}
crate::tui::agent_focus::focus_agent(app, &agent_id);
app.needs_redraw = true;
}
ViewEvent::AgentDetailsClosed { agent_id } => {
crate::tui::work_surface::agent_details_closed(app, &agent_id);
}
ViewEvent::FilePickerSelected { path } => {
// Insert `@<path>` at the composer's cursor with surrounding
// whitespace so the existing `@`-mention parser picks it up.
let cursor = app.cursor_position;
let needs_leading_space = cursor > 0
&& !app
.input
.chars()
.nth(cursor.saturating_sub(1))
.is_some_and(|c| c.is_whitespace());
let mut insertion = String::new();
if needs_leading_space {
insertion.push(' ');
}
insertion.push('@');
insertion.push_str(&path);
insertion.push(' ');
app.insert_str(&insertion);
app.status_message = Some(format!("Attached @{path}"));
}
ViewEvent::ModelPickerApplied {
model,
provider,
provider_id,
effort,
previous_model,
previous_effort,
save_as_startup_default,
} => {
apply_model_picker_choice(
app,
engine_handle,
config,
model,
provider,
provider_id,
effort,
previous_model,
previous_effort,
save_as_startup_default,
)
.await;
}
ViewEvent::ModelPickerDismissed {
catalog_view,
view,
selected_row_id,
} => {
sync_config_provider_from_app(config, app);
app.model_picker_memory = Some(crate::tui::app::ModelPickerMemory {
catalog_view,
view: Some(view),
selected_row_id,
});
}
ViewEvent::ModelPickerRefresh => {
// Re-resolve readiness from the live credential state and
// rebuild catalog rows. Non-destructive: never clears the list
// when a refresh fails; just re-project from current config.
sync_config_provider_from_app(config, app);
if app.view_stack.top_kind() == Some(ModalKind::ModelPicker)
&& let Some(mut boxed) = app.view_stack.pop()
{
if let Some(picker) = boxed
.as_any_mut()
.downcast_mut::<crate::tui::model_picker::ModelPickerView>(
) {
picker.re_resolve_from_app(app, config);
app.status_message =
Some("Model readiness refreshed · catalog rows rebuilt".into());
}
app.view_stack.push_boxed(boxed);
} else {
app.status_message =
Some("Open /model to refresh readiness and catalog".into());
}
app.needs_redraw = true;
}
ViewEvent::ModelPickerTogglePin {
provider,
provider_id,
model,
} => {
let provider_key = provider_id.unwrap_or_else(|| provider.as_str().to_string());
match crate::settings::Settings::transact(|settings| {
Ok(settings.toggle_pinned_model(&provider_key, &model))
}) {
Ok(true) => app.status_message = Some(format!("Pinned {provider_key}/{model}")),
Ok(false) => {
app.status_message = Some(format!("Unpinned {provider_key}/{model}"))
}
Err(error) => {
app.status_message = Some(format!("Could not update pin: {error}"))
}
}
if let Ok(settings) = crate::settings::Settings::load_persisted() {
app.pinned_models = settings.pinned_models;
}
if let Some(mut boxed) = app.view_stack.pop() {
if let Some(picker) = boxed
.as_any_mut()
.downcast_mut::<crate::tui::model_picker::ModelPickerView>(
) {
picker.re_resolve_from_app(app, config);
}
app.view_stack.push_boxed(boxed);
}
app.needs_redraw = true;
}
ViewEvent::ModelPickerMovePin {
provider,
provider_id,
model,
delta,
} => {
let provider_key = provider_id.unwrap_or_else(|| provider.as_str().to_string());
let reordered = crate::settings::Settings::transact_opt(|settings| {
if !settings.move_pinned_model(&provider_key, &model, delta) {
return Ok(None);
}
Ok(Some(settings.pinned_models.clone()))
});
match reordered {
Ok(None) => {}
Ok(Some(pinned_models)) => {
app.pinned_models = pinned_models;
app.status_message = Some("Pinned model order updated".into());
if let Some(mut boxed) = app.view_stack.pop() {
if let Some(picker) = boxed
.as_any_mut()
.downcast_mut::<crate::tui::model_picker::ModelPickerView>(
) {
picker.re_resolve_from_app(app, config);
}
app.view_stack.push_boxed(boxed);
}
}
Err(error) => {
app.status_message = Some(format!("Could not reorder pin: {error}"));
}
}
app.needs_redraw = true;
}
ViewEvent::ModelPickerNeedsAuth {
provider,
model,
reason,
} => {
app.status_message = Some(reason);
// Close the model picker if it is still open, then hand off to
// the provider auth flow for the locked model's provider.
while app.view_stack.top_kind() == Some(ModalKind::ModelPicker) {
let _ = app.view_stack.pop();
}
if let Some(picker) =
crate::tui::provider_picker::ProviderPickerView::new_for_missing_auth(
app.api_provider,
provider,
config,
None,
)
{
app.view_stack.push(picker);
} else {
app.status_message = Some(format!(
"🔒 {model} needs {provider:?} credentials — open /provider to authenticate."
));
}
app.needs_redraw = true;
}
ViewEvent::StatusMessage { message } => {
app.status_message = Some(message);
app.needs_redraw = true;
}
ViewEvent::ProviderPickerDismissed {
catalog_view,
selected_provider_id,
} => {
let onboarding_provider_picker = app.onboarding == OnboardingState::Provider;
// A picker preview must never become route authority. During
// onboarding Esc is deliberately non-mutating: it returns to
// Language without touching config or the onboarding marker.
if !onboarding_provider_picker {
sync_config_provider_from_app(config, app);
}
app.provider_picker_memory = Some(crate::tui::app::ProviderPickerMemory {
catalog_view,
selected_provider_id,
});
if onboarding_provider_picker {
back_from_provider_onboarding(app);
}
}
ViewEvent::ProviderPickerApplied {
provider,
provider_id,
} => {
if let Some(provider_id) = provider_id {
set_active_custom_provider_in_memory(config, &provider_id);
}
let model_override = provider_picker_model_override(app, config, provider);
let switched =
switch_provider(app, engine_handle, config, provider, model_override).await;
if switched && app.onboarding == OnboardingState::Provider {
complete_provider_picker_onboarding(app, provider);
}
refresh_config_view_if_open(app, "provider");
}
ViewEvent::ProviderPickerApiKeySubmitted {
provider,
provider_id,
api_key,
base_url,
} => {
let identity = picker_provider_identity(config, provider, provider_id.as_deref())
.map_err(anyhow::Error::msg)?;
apply_provider_picker_api_key(
app,
engine_handle,
config,
identity,
api_key,
base_url,
)
.await;
refresh_config_view_if_open(app, "provider");
}
ViewEvent::ProviderPickerSetupConfirmed {
provider,
provider_id,
api_key,
model,
context_window,
base_url,
} => {
let identity = picker_provider_identity(config, provider, provider_id.as_deref())
.map_err(anyhow::Error::msg)?;
let completed = apply_provider_picker_setup_confirmed(
app,
engine_handle,
config,
identity,
api_key,
model,
context_window,
base_url,
)
.await;
if completed && app.onboarding == OnboardingState::Provider {
complete_provider_picker_onboarding(app, provider);
}
refresh_config_view_if_open(app, "provider");
}
ViewEvent::ProviderPickerCustomProviderSubmitted {
provider_id,
base_url,
model,
api_key_env,
} => {
let switched = apply_provider_picker_custom_provider(
app,
engine_handle,
config,
provider_id,
base_url,
model,
api_key_env,
)
.await;
complete_provider_picker_onboarding_if_switched(app, ApiProvider::Custom, switched);
refresh_config_view_if_open(app, "provider");
}
ViewEvent::ProviderPickerXaiOAuthRequested => {
let switched =
run_xai_device_login_from_tui(terminal, app, engine_handle, config).await?;
complete_provider_picker_onboarding_if_switched(app, ApiProvider::Xai, switched);
}
ViewEvent::ProviderPickerExternalConsentConfirmed {
provider,
consent_provider,
source,
path,
} => match persist_external_credential_consent_for_at(
app.config_path.as_deref(),
config,
provider,
consent_provider,
source,
&path,
) {
Ok(_) => {
let toast = app
.tr(MessageId::ProviderExternalGrantedToast)
.replace("{owner}", source.owner_label())
.replace("{provider}", provider.as_str());
app.push_status_toast(toast, StatusToastLevel::Success, Some(8_000));
let model_override = provider_picker_model_override(app, config, provider);
let switched =
switch_provider(app, engine_handle, config, provider, model_override).await;
// #4763: reusing an external CLI grant completes provider
// onboarding exactly like a submitted key or an applied
// route. Without this the picker closes on success and
// the user is returned to the provider step they just
// satisfied — the second half of the reported loop.
if switched && app.onboarding == OnboardingState::Provider {
complete_provider_picker_onboarding(app, provider);
}
refresh_config_view_if_open(app, "provider");
}
Err(error) => app.push_status_toast(
app.tr(MessageId::ProviderExternalSaveFailedToast)
.replace("{error}", &error.to_string()),
StatusToastLevel::Error,
None,
),
},
ViewEvent::ProviderPickerExternalConsentRevoked { provider } => {
match revoke_external_credential_consent_for_at(
app.config_path.as_deref(),
config,
provider,
) {
Ok(_) => app.push_status_toast(
app.tr(MessageId::ProviderExternalRevokedToast)
.replace("{provider}", provider.as_str()),
StatusToastLevel::Success,
Some(5_000),
),
Err(error) => app.push_status_toast(
app.tr(MessageId::ProviderExternalRevokeFailedToast)
.replace("{error}", &error.to_string()),
StatusToastLevel::Error,
None,
),
}
refresh_config_view_if_open(app, "provider");
}
ViewEvent::ProviderPickerOpenModels {
provider,
provider_id,
} => {
if let Some(provider_id) = provider_id {
set_active_custom_provider_in_memory(config, &provider_id);
}
open_model_picker_for_provider(app, config, provider);
}
ViewEvent::ModeSelected { mode } => {
let prior_mode = app.mode;
let msg = commands::switch_mode(app, mode);
if app.mode != prior_mode {
sync_mode_update(app, engine_handle).await;
}
app.add_message(HistoryCell::System { content: msg });
}
ViewEvent::BacktrackStep { direction } => {
app.backtrack.step(direction);
if let Some(idx) = app.backtrack.selected_idx() {
update_backtrack_overlay_selection(app, idx);
}
}
ViewEvent::BacktrackConfirm => {
if let Some(depth) = app.backtrack.confirm() {
apply_backtrack(app, depth);
let _ = engine_handle
.send(Op::SyncSession {
session_id: app.current_session_id.clone(),
messages: app.api_messages.clone(),
system_prompt: app.system_prompt.clone(),
system_prompt_override: false,
model: app.model.clone(),
workspace: app.workspace.clone(),
mode: app.mode,
})
.await;
}
}
ViewEvent::BacktrackCancel => {
app.backtrack.reset();
app.status_message = Some("Backtrack canceled".to_string());
app.needs_redraw = true;
}
ViewEvent::ContextMenuSelected {
action: ContextMenuAction::ExecuteCommand { command },
} => {
if execute_command_input(
terminal,
app,
engine_handle,
task_manager,
config,
&mut *web_config_session,
&command,
)
.await?
{
return Ok(true);
}
}
ViewEvent::ContextMenuSelected { action } => handle_context_menu_action(app, action),
ViewEvent::SkillMutationRequested { request } => {
handle_skill_mutation_requested(app, request).await;
}
ViewEvent::SkillsManagerToggleCompatible => {
if app.view_stack.top_kind() == Some(ModalKind::SkillsManager)
&& let Some(mut boxed) = app.view_stack.pop()
{
if let Some(view) = boxed
.as_any_mut()
.downcast_mut::<crate::tui::views::skills_manager::SkillsManagerView>(
) {
crate::tui::views::skills_manager::apply_toggle_compatible(view, app);
}
app.view_stack.push_boxed(boxed);
}
}
}
}
Ok(false)
}
/// Keep the very large modal-event dispatcher out of the already-large TUI
/// loop future. Config previews take a dedicated small path: polling the full
/// dispatcher on top of the event loop exceeds the macOS main-thread stack in
/// debug builds before a theme preview can reach its next frame.
#[allow(clippy::too_many_arguments)]
pub(crate) fn handle_view_events_boxed<'a>(
terminal: &'a mut AppTerminal,
app: &'a mut App,
config: &'a mut Config,
task_manager: &'a SharedTaskManager,
engine_handle: &'a mut EngineHandle,
web_config_session: &'a mut Option<WebConfigSession>,
events: Vec<ViewEvent>,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<bool>> + 'a>> {
Box::pin(async move {
for event in events {
match event {
ViewEvent::ConfigUpdated {
key,
value,
persist,
} => {
if handle_config_updated(
terminal,
app,
config,
task_manager,
engine_handle,
web_config_session,
key,
value,
persist,
)
.await?
{
return Ok(true);
}
}
other => {
if Box::pin(handle_view_events(
terminal,
app,
config,
task_manager,
engine_handle,
web_config_session,
vec![other],
))
.await?
{
return Ok(true);
}
}
}
}
Ok(false)
})
}