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
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0
//! App construction, builder configuration, and accessors over the active session
//! state (input, messages, scroll, panels, metrics, and display toggles).
use std::sync::Arc;
use std::time::Instant;
use tokio::sync::{Notify, mpsc, watch};
use zeph_common::task_supervisor::TaskSupervisor;
use crate::command::TuiCommand;
use crate::event::AgentEvent;
use crate::hyperlink::HyperlinkSpan;
use crate::metrics::MetricsSnapshot;
use crate::session::SessionRegistry;
use crate::types::PasteState;
use crate::widgets::tool_view::ToolDensity;
use super::{
AgentViewTarget, App, ChatMessage, InputMode, MAX_VISIBLE_INPUT_LINES, MessageRole, Panel,
RenderCache, SubAgentSidebarState, TranscriptCache, is_tool_use_only, parse_tool_output,
};
/// No-progress duration after which the wave transitions to `Stalled`.
/// TODO: wire to `config.tui.stall_threshold_secs` (deferred per #5096 v1 scope)
const STALL_THRESHOLD: std::time::Duration = std::time::Duration::from_secs(10);
impl App {
/// Create a new `App` with the given I/O channels.
///
/// The app starts in insert mode with the splash screen visible and no
/// messages in the buffer.
///
/// # Arguments
///
/// * `user_input_tx` — sender used to forward the user's typed text to the
/// agent loop via [`TuiChannel`](crate::TuiChannel).
/// * `agent_event_rx` — receiver for [`AgentEvent`] produced by the agent.
///
/// # Examples
///
/// ```rust
/// use tokio::sync::mpsc;
/// use zeph_tui::App;
///
/// let (user_tx, _user_rx) = mpsc::channel(64);
/// let (_agent_tx, agent_rx) = mpsc::channel(64);
/// let app = App::new(user_tx, agent_rx);
/// assert!(app.show_splash());
/// ```
#[must_use]
pub fn new(
user_input_tx: mpsc::Sender<String>,
agent_event_rx: mpsc::Receiver<AgentEvent>,
) -> Self {
Self {
sessions: SessionRegistry::bootstrap(),
show_side_panels: true,
show_help: false,
metrics: MetricsSnapshot::default(),
metrics_rx: None,
active_panel: Panel::Chat,
tool_expanded: false,
tool_density: ToolDensity::default(),
show_source_labels: false,
show_balance: true,
throbber_state: throbber_widgets_tui::ThrobberState::default(),
confirm_state: None,
elicitation_state: None,
command_palette: None,
command_tx: None,
file_picker_state: None,
file_index: None,
slash_autocomplete: None,
reverse_search: None,
should_quit: false,
user_input_tx,
agent_event_rx,
queued_count: 0,
pending_count: 0,
context_token_estimate: 0,
editing_queued: false,
hyperlinks: Vec::new(),
cancel_signal: None,
pending_file_index: None,
pending_theme: None,
pending_theme_name: None,
subagent_sidebar: SubAgentSidebarState::new(),
task_supervisor: None,
show_task_panel: false,
cached_task_snapshots: Vec::new(),
clipboard: crate::clipboard::ClipboardHandle::new(),
fleet_snapshot: crate::widgets::fleet::FleetSnapshot::default(),
fleet_list_state: ratatui::widgets::ListState::default(),
durable_snapshot: crate::widgets::durable::DurableSnapshot::default(),
durable_list_state: ratatui::widgets::ListState::default(),
theme: crate::theme::Theme::default(),
theme_generation: 0,
theme_name: "zephyr".to_owned(),
effective_color_mode: crate::theme::EffectiveColorMode::Truecolor,
unicode_capable: crate::theme::detect_unicode_capable(),
collapsed_panels: [false; 4],
motion: zeph_config::Motion::Full,
wave_tick: 0,
last_progress_at: Instant::now(),
show_equalizer: true,
delights: zeph_config::DelightsConfig::default(),
stream_rate: crate::delights::StreamRate::new(),
toasts: crate::delights::ToastQueue::new(),
splash_shimmer: crate::delights::SplashShimmer::new(),
mouse_enabled: false,
last_layout: None,
pending_mouse_capture: None,
remote_daemon_url: None,
}
}
/// Override the visual theme with a palette-derived [`crate::theme::Theme`].
///
/// Called once at startup after [`crate::theme::Theme::from_palette_with_mode`] has been
/// built from the user's config and detected terminal colour capability.
///
/// # Examples
///
/// ```rust
/// use tokio::sync::mpsc;
/// use zeph_tui::{App, theme::{Theme, SemanticPalette}};
///
/// let (user_tx, _) = mpsc::channel(64);
/// let (_, agent_rx) = mpsc::channel(64);
/// let app = App::new(user_tx, agent_rx)
/// .with_theme(Theme::from_palette(&SemanticPalette::zephyr()));
/// ```
#[must_use]
pub fn with_theme(mut self, theme: crate::theme::Theme) -> Self {
self.theme = theme;
self
}
/// Set the active theme name for cycle tracking and status echoes.
///
/// Must be called at every construction site that supplies a non-default theme so that
/// `cycle_theme` starts cycling from the correct position.
///
/// # Examples
///
/// ```rust
/// use tokio::sync::mpsc;
/// use zeph_tui::App;
///
/// let (user_tx, _) = mpsc::channel(64);
/// let (_, agent_rx) = mpsc::channel(64);
/// let app = App::new(user_tx, agent_rx).with_theme_name("gruvbox-dark");
/// ```
#[must_use]
pub fn with_theme_name(mut self, name: impl Into<String>) -> Self {
self.theme_name = name.into();
self
}
/// Set the resolved colour mode used to re-derive themes on runtime swap.
///
/// Store the `EffectiveColorMode` resolved once at startup so that `apply_theme`
/// produces consistent downgrade behaviour without re-running OS detection per swap.
///
/// # Examples
///
/// ```rust
/// use tokio::sync::mpsc;
/// use zeph_tui::{App, theme::EffectiveColorMode};
///
/// let (user_tx, _) = mpsc::channel(64);
/// let (_, agent_rx) = mpsc::channel(64);
/// let app = App::new(user_tx, agent_rx)
/// .with_effective_color_mode(EffectiveColorMode::Truecolor);
/// ```
#[must_use]
pub fn with_effective_color_mode(mut self, mode: crate::theme::EffectiveColorMode) -> Self {
self.effective_color_mode = mode;
self
}
/// Return the current theme generation counter.
///
/// Passed into `RenderCacheKey::theme_generation` so the render cache is
/// invalidated after every theme swap.
///
/// # Examples
///
/// ```rust
/// use tokio::sync::mpsc;
/// use zeph_tui::App;
///
/// let (user_tx, _) = mpsc::channel(64);
/// let (_, agent_rx) = mpsc::channel(64);
/// let app = App::new(user_tx, agent_rx);
/// assert_eq!(app.theme_generation(), 0);
/// ```
#[must_use]
pub fn theme_generation(&self) -> u64 {
self.theme_generation
}
/// Apply a named theme preset or user file.
///
/// Returns `Ok(true)` when the theme was applied immediately (built-in preset).
/// Returns `Ok(false)` when the user file load was dispatched asynchronously; the
/// result will be installed by `poll_pending_theme` on the next tick.
///
/// Cancels any in-flight user-file load when switching to a preset, so the earlier
/// async result cannot silently revert the newer choice.
///
/// # Errors
///
/// Returns [`crate::theme::ThemeLoadError`] for empty or path-unsafe names.
///
/// # Examples
///
/// ```rust
/// use tokio::sync::mpsc;
/// use zeph_tui::App;
///
/// let (user_tx, _) = mpsc::channel(64);
/// let (_, agent_rx) = mpsc::channel(64);
/// let mut app = App::new(user_tx, agent_rx);
/// let gen_before = app.theme_generation();
/// let _ = app.apply_theme("zephyr-light");
/// assert!(app.theme_generation() > gen_before);
/// ```
pub fn apply_theme(&mut self, name: &str) -> Result<bool, crate::theme::ThemeLoadError> {
use crate::theme::{Theme, ThemeLoadError, presets};
// Reject empty names — always routes to listing, never implicit preset resolution.
if name.is_empty() {
return Err(ThemeLoadError::UnsafeName(String::new()));
}
// Validate name before any I/O so callers get immediate feedback on bad input.
presets::validate_theme_name_pub(name)?;
// Built-in presets are compile-time constants — no I/O, apply synchronously.
if let Some(preset) = presets::Preset::from_name(name) {
// Cancel any in-flight user-file load so it cannot revert this newer choice.
self.pending_theme = None;
self.pending_theme_name = None;
let palette = preset.palette();
let new_theme = Theme::from_palette_with_mode(&palette, self.effective_color_mode);
self.theme = new_theme;
name.clone_into(&mut self.theme_name);
self.theme_generation += 1;
self.clear_all_render_caches();
return Ok(true);
}
// User file: offload blocking I/O to a spawn_blocking thread.
// The result is installed by `poll_pending_theme` on the next tick.
let name_owned = name.to_owned();
let (tx, rx) = tokio::sync::oneshot::channel();
tokio::task::spawn_blocking(move || {
let _ = tx.send(presets::load_user_theme(&name_owned));
});
self.pending_theme = Some(rx);
self.pending_theme_name = Some(name.to_owned());
Ok(false)
}
/// Install a pending user-theme load result if the background task has completed.
///
/// Must be called once per tick from `tui_loop` (alongside `poll_pending_file_index`).
pub fn poll_pending_theme(&mut self) {
use crate::theme::Theme;
let Some(rx) = self.pending_theme.as_mut() else {
return;
};
match rx.try_recv() {
Ok(result) => {
self.pending_theme = None;
let name = self.pending_theme_name.take().unwrap_or_default();
match result {
Ok(palette) => {
let new_theme =
Theme::from_palette_with_mode(&palette, self.effective_color_mode);
self.theme = new_theme;
name.clone_into(&mut self.theme_name);
self.theme_generation += 1;
self.clear_all_render_caches();
self.push_system_message_pub(format!("Theme switched to: {name}"));
}
Err(e) => {
self.push_system_message_pub(format!("Theme error: {e}"));
}
}
}
Err(tokio::sync::oneshot::error::TryRecvError::Empty) => {
// Not ready yet — keep waiting.
}
Err(tokio::sync::oneshot::error::TryRecvError::Closed) => {
// Sender dropped without sending (spawn_blocking panicked).
self.pending_theme = None;
self.pending_theme_name = None;
tracing::warn!("pending theme load task dropped without result");
}
}
}
/// Cycle to the next preset in the fixed cycle list `["zephyr", "zephyr-light", "high-contrast"]`.
///
/// Finds the current theme name in the cycle list and advances to the next entry,
/// wrapping around. If the current name is not in the list, starts from `"zephyr"`.
///
/// # Examples
///
/// ```rust
/// use tokio::sync::mpsc;
/// use zeph_tui::App;
///
/// let (user_tx, _) = mpsc::channel(64);
/// let (_, agent_rx) = mpsc::channel(64);
/// let mut app = App::new(user_tx, agent_rx).with_theme_name("zephyr");
/// app.cycle_theme();
/// assert_eq!(app.active_theme_name(), "zephyr-light");
/// ```
pub fn cycle_theme(&mut self) {
const CYCLE: &[&str] = &["zephyr", "zephyr-light", "high-contrast"];
let pos = CYCLE
.iter()
.position(|&n| n == self.theme_name.as_str())
.unwrap_or(0);
let next = CYCLE[(pos + 1) % CYCLE.len()];
if let Err(e) = self.apply_theme(next) {
tracing::warn!("cycle_theme: failed to apply '{}': {e}", next);
}
}
/// Return the name of the currently-active theme.
///
/// # Examples
///
/// ```rust
/// use tokio::sync::mpsc;
/// use zeph_tui::App;
///
/// let (user_tx, _) = mpsc::channel(64);
/// let (_, agent_rx) = mpsc::channel(64);
/// let app = App::new(user_tx, agent_rx).with_theme_name("gruvbox-dark");
/// assert_eq!(app.active_theme_name(), "gruvbox-dark");
/// ```
#[must_use]
pub fn active_theme_name(&self) -> &str {
&self.theme_name
}
/// Return the resolved terminal colour mode stored at startup.
///
/// Used by widgets to choose between Unicode and ASCII fallback rendering.
///
/// # Examples
///
/// ```rust
/// use tokio::sync::mpsc;
/// use zeph_tui::{App, theme::EffectiveColorMode};
///
/// let (user_tx, _) = mpsc::channel(64);
/// let (_, agent_rx) = mpsc::channel(64);
/// let app = App::new(user_tx, agent_rx);
/// assert_eq!(app.effective_color_mode(), EffectiveColorMode::Truecolor);
/// ```
#[must_use]
pub fn effective_color_mode(&self) -> crate::theme::EffectiveColorMode {
self.effective_color_mode
}
/// Return `true` when the terminal cannot render Unicode glyphs and ASCII-only output
/// should be used in place of box-drawing characters and spinners.
///
/// Unicode capability is detected independently from colour support. A terminal with
/// `NO_COLOR` set (which produces `EffectiveColorMode::Never`) may still render `▹▸`
/// perfectly. Only `TERM=dumb` or a non-UTF-8 locale forces ASCII mode.
///
/// # Examples
///
/// ```rust
/// use tokio::sync::mpsc;
/// use zeph_tui::App;
///
/// let (user_tx, _) = mpsc::channel(64);
/// let (_, agent_rx) = mpsc::channel(64);
/// // Default app created in a normal environment reports Unicode capable.
/// let app = App::new(user_tx, agent_rx);
/// // is_ascii_only() depends on TERM/LANG env vars, not color mode.
/// let _ = app.is_ascii_only();
/// ```
#[must_use]
pub fn is_ascii_only(&self) -> bool {
!self.unicode_capable
}
/// Invalidate render caches in every session slot.
///
/// Called on theme swap because cached `Line`s bake in theme `Style` values — stale
/// styles from the old theme would otherwise persist until a content change triggers a
/// miss. Must clear ALL sessions, not only the currently-active one.
fn clear_all_render_caches(&mut self) {
for slot in self.sessions.iter_mut() {
slot.render_cache.clear();
}
}
/// Return `true` while the splash screen should be displayed.
///
/// The splash screen is hidden as soon as the first chat message arrives.
#[must_use]
pub fn show_splash(&self) -> bool {
self.sessions.current().show_splash
}
/// Return `true` when the side panels column is visible.
///
/// Controlled by the `s` keybinding and automatically disabled on narrow
/// terminals (< 80 columns).
#[must_use]
pub fn show_side_panels(&self) -> bool {
self.show_side_panels
}
/// Returns `true` when the user has toggled back to subagents view (plan view overridden).
#[must_use]
pub fn plan_view_active(&self) -> bool {
self.sessions.current().plan_view_active
}
// ---- Accessors for fields relocated into SessionSlot (preserves pub API surface) ----
/// Returns the active session's render cache.
#[must_use]
pub fn render_cache(&self) -> &RenderCache {
&self.sessions.current().render_cache
}
/// Returns a mutable reference to the active session's render cache.
pub fn render_cache_mut(&mut self) -> &mut RenderCache {
&mut self.sessions.current_mut().render_cache
}
/// Returns the current chat area view target (main conversation or sub-agent transcript).
#[must_use]
pub fn view_target(&self) -> &AgentViewTarget {
&self.sessions.current().view_target
}
/// Returns the cached transcript for the currently-focused sub-agent, if any.
#[must_use]
pub fn transcript_cache(&self) -> Option<&TranscriptCache> {
self.sessions.current().transcript_cache.as_ref()
}
/// Populate the message buffer from a persisted session history.
///
/// Each element is a `(role, content)` pair where `role` is one of
/// `"user"`, `"assistant"`, or `"tool"`. Tool outputs are detected by a
/// sentinel suffix and rendered as [`MessageRole::Tool`] messages.
/// The splash screen is hidden after loading if any messages are present.
pub fn load_history(&mut self, messages: &[(&str, &str)]) {
const TOOL_SUFFIX: &str = "\n```";
for &(role_str, content) in messages {
if role_str == "user"
&& let Some((tool_name, body)) = parse_tool_output(content, TOOL_SUFFIX)
{
self.sessions
.current_mut()
.messages
.push(ChatMessage::new(MessageRole::Tool, body).with_tool(tool_name.into()));
continue;
}
let role = match role_str {
"user" => MessageRole::User,
"assistant" => {
if is_tool_use_only(content) {
continue;
}
MessageRole::Assistant
}
_ => continue,
};
if role == MessageRole::User {
self.sessions
.current_mut()
.input_history
.push(content.to_owned());
}
self.sessions
.current_mut()
.messages
.push(ChatMessage::new(role, content));
}
// Enforce the message buffer cap on initial history load as well.
self.trim_messages();
if !self.sessions.current().messages.is_empty() {
self.sessions.current_mut().show_splash = false;
}
}
/// Attach a cancel signal that Ctrl-C in the TUI will trigger.
///
/// # Examples
///
/// ```rust
/// use std::sync::Arc;
/// use tokio::sync::{Notify, mpsc};
/// use zeph_tui::App;
///
/// let (tx, _rx) = mpsc::channel(1);
/// let (_atx, arx) = mpsc::channel(1);
/// let notify = Arc::new(Notify::new());
/// let _app = App::new(tx, arx).with_cancel_signal(notify);
/// ```
#[must_use]
pub fn with_cancel_signal(mut self, signal: Arc<Notify>) -> Self {
self.cancel_signal = Some(signal);
self
}
/// Attach a metrics watch channel for live dashboard updates.
///
/// The current snapshot is read immediately; subsequent updates are polled
/// by [`poll_metrics`](Self::poll_metrics) each frame.
///
/// # Examples
///
/// ```rust
/// use tokio::sync::{mpsc, watch};
/// use zeph_tui::{App, MetricsSnapshot};
///
/// let (tx, _rx) = mpsc::channel(1);
/// let (_atx, arx) = mpsc::channel(1);
/// let (_metrics_tx, metrics_rx) = watch::channel(MetricsSnapshot::default());
/// let _app = App::new(tx, arx).with_metrics_rx(metrics_rx);
/// ```
#[must_use]
pub fn with_metrics_rx(mut self, rx: watch::Receiver<MetricsSnapshot>) -> Self {
self.metrics = rx.borrow().clone();
self.metrics_rx = Some(rx);
self
}
/// Attach the command dispatch sender used for slash-command routing.
///
/// # Examples
///
/// ```rust
/// use tokio::sync::mpsc;
/// use zeph_tui::{App, TuiCommand};
///
/// let (tx, _rx) = mpsc::channel(1);
/// let (_atx, arx) = mpsc::channel(1);
/// let (cmd_tx, _cmd_rx) = mpsc::channel(8);
/// let _app = App::new(tx, arx).with_command_tx(cmd_tx);
/// ```
#[must_use]
pub fn with_command_tx(mut self, tx: mpsc::Sender<TuiCommand>) -> Self {
self.command_tx = Some(tx);
self
}
/// Set the initial tool-output density from a loaded `TuiConfig`.
///
/// Applied once at startup; runtime changes via the `c` key override this
/// but are not persisted back to config.
///
/// # Examples
///
/// ```rust
/// use tokio::sync::mpsc;
/// use zeph_tui::App;
/// use zeph_config::ToolDensity;
///
/// let (tx, _rx) = mpsc::channel(1);
/// let (_atx, arx) = mpsc::channel(1);
/// let _app = App::new(tx, arx).with_tool_density(ToolDensity::Compact);
/// ```
#[must_use]
pub fn with_tool_density(mut self, density: ToolDensity) -> Self {
self.tool_density = density;
self
}
/// Record the remote daemon URL this session was attached to via `--connect <URL>`.
///
/// Set once at startup in `run_tui_remote`; there is no runtime mechanism to attach
/// to or detach from a daemon mid-session (#5509). Used by `daemon:status` to report
/// real connection state instead of a stub message.
///
/// # Examples
///
/// ```rust
/// use tokio::sync::mpsc;
/// use zeph_tui::App;
///
/// let (user_tx, _) = mpsc::channel(64);
/// let (_, agent_rx) = mpsc::channel(64);
/// let app = App::new(user_tx, agent_rx).with_remote_daemon_url("http://localhost:8765");
/// ```
#[must_use]
pub fn with_remote_daemon_url(mut self, url: impl Into<String>) -> Self {
self.remote_daemon_url = Some(url.into());
self
}
/// Return the remote daemon URL this session was attached to at startup, if any.
///
/// `None` means this is a local session (no `--connect <URL>` flag was used).
pub(crate) fn remote_daemon_url(&self) -> Option<&str> {
self.remote_daemon_url.as_deref()
}
/// Wire a [`TaskSupervisor`] into the `App` for the task registry panel.
///
/// The supervisor's task list is snapshotted once per render tick before
/// `terminal.draw()`, keeping the draw closure free of mutex contention.
/// Toggle the panel visibility with `/tasks`.
///
/// # Examples
///
/// ```rust,ignore
/// use tokio::sync::mpsc;
/// use tokio_util::sync::CancellationToken;
/// use zeph_common::task_supervisor::TaskSupervisor;
/// use zeph_tui::App;
///
/// let (user_tx, _) = mpsc::channel(64);
/// let (_, agent_rx) = mpsc::channel(64);
/// let cancel = CancellationToken::new();
/// let supervisor = TaskSupervisor::new(cancel);
/// let _app = App::new(user_tx, agent_rx).with_task_supervisor(supervisor);
/// ```
#[must_use]
pub fn with_task_supervisor(mut self, supervisor: TaskSupervisor) -> Self {
self.task_supervisor = Some(supervisor);
self
}
/// Refresh the cached task snapshot from the supervisor.
///
/// Must be called once per render tick **before** `terminal.draw()` to avoid
/// acquiring the supervisor's inner mutex inside the draw closure.
pub(crate) fn refresh_task_snapshots(&mut self) {
self.cached_task_snapshots = self
.task_supervisor
.as_ref()
.map(TaskSupervisor::snapshot)
.unwrap_or_default();
}
/// Return a truncated label for active `TaskSupervisor` tasks, or `None` when idle.
///
/// Used by the input widget to show a braille spinner with the name of the first
/// active (Running/Restarting) task when no other status is being displayed.
#[must_use]
pub fn supervisor_activity_label(&self) -> Option<String> {
self.task_supervisor.as_ref()?;
let mut active = self
.cached_task_snapshots
.iter()
.filter(|t| {
matches!(
t.status,
zeph_common::task_supervisor::TaskStatus::Running
| zeph_common::task_supervisor::TaskStatus::Restarting { .. }
)
})
.filter(|t| !t.name.starts_with("mem-"))
.peekable();
let first = active.next()?;
let label = if active.peek().is_none() {
first.name.to_string()
} else {
let extra = active.count() + 1; // +1 because we already consumed first
format!("{} +{} more", first.name, extra)
};
// Char-based truncation to avoid panicking on multi-byte UTF-8 boundaries.
let truncated: String = label.chars().take(38).collect();
Some(truncated)
}
/// Wire a cancel signal into a running App instance.
///
/// Used by the two-phase TUI startup path to connect the agent's cancel signal
/// after the agent has been constructed (Phase 2).
pub fn set_cancel_signal(&mut self, signal: Arc<Notify>) {
self.cancel_signal = Some(signal);
}
/// Wire a metrics receiver into a running App instance.
///
/// Used by the two-phase TUI startup path to connect the metrics channel
/// after the metrics watch channel has been created (Phase 2).
pub fn set_metrics_rx(&mut self, rx: watch::Receiver<MetricsSnapshot>) {
self.metrics = rx.borrow().clone();
self.metrics_rx = Some(rx);
}
/// Check the metrics watch channel for an updated snapshot and apply it.
///
/// Also clamps the sidebar selection and triggers a transcript reload if
/// the sub-agent's turn count has advanced. Called once per render frame.
pub fn poll_metrics(&mut self) {
if let Some(ref mut rx) = self.metrics_rx
&& rx.has_changed().unwrap_or(false)
{
let new_metrics = rx.borrow_and_update().clone();
// IC2: reset plan_view_active (subagents-override) when a new plan appears.
// Detect new plan by comparing graph_id; new plan should be shown immediately.
let new_graph_id = new_metrics
.orchestration_graph
.as_ref()
.map(|s| &s.graph_id);
let old_graph_id = self
.metrics
.orchestration_graph
.as_ref()
.map(|s| &s.graph_id);
if new_graph_id != old_graph_id && new_graph_id.is_some() {
self.sessions.current_mut().plan_view_active = false;
}
self.metrics = new_metrics;
}
// Clamp sidebar selection in case subagents count changed.
let count = self.metrics.sub_agents.len();
self.subagent_sidebar.clamp(count);
// Trigger transcript reload when turns count increased.
self.maybe_reload_transcript();
}
/// Evict oldest messages when the buffer exceeds `MAX_TUI_MESSAGES` (#2737).
///
/// Shifts the render cache to match the drained messages, preserving cached renders
/// for the remaining entries and avoiding a full re-render stall (#2775).
pub(super) fn trim_messages(&mut self) {
self.sessions.current_mut().trim_messages();
}
/// Return a slice of all chat messages currently in the buffer.
///
/// For the currently-displayed messages (which may be a sub-agent
/// transcript) use [`visible_messages`](Self::visible_messages) instead.
#[must_use]
pub fn messages(&self) -> &[ChatMessage] {
&self.sessions.current().messages
}
/// Return the current content of the text input field.
#[must_use]
pub fn input(&self) -> &str {
&self.sessions.current().input
}
/// Return the current input mode (normal vs. insert).
#[must_use]
pub fn input_mode(&self) -> InputMode {
self.sessions.current().input_mode
}
/// Return the cursor byte position within the input string.
#[must_use]
pub fn cursor_position(&self) -> usize {
self.sessions.current().cursor_position
}
/// Returns the composer height requested by the current draft, capped at three visible rows.
#[must_use]
pub(crate) fn desired_input_height(&self) -> u16 {
let content_lines = self.input_line_count().min(MAX_VISIBLE_INPUT_LINES);
content_lines.saturating_add(2)
}
/// Returns the number of logical lines in the current draft or indicator.
#[must_use]
pub(crate) fn input_line_count(&self) -> u16 {
if self.sessions.current().paste_state.is_some()
|| (self.sessions.current().input.is_empty()
&& matches!(self.sessions.current().input_mode, InputMode::Insert))
{
1
} else {
u16::try_from(self.sessions.current().input.matches('\n').count() + 1)
.unwrap_or(u16::MAX)
}
}
/// Return the number of lines the chat view is scrolled up from the bottom.
///
/// `0` means the view is at the bottom (latest messages visible).
#[must_use]
pub fn scroll_offset(&self) -> usize {
self.sessions.current().scroll_offset
}
/// Scroll to bottom only if already at (or near) the bottom.
pub(super) fn auto_scroll(&mut self) {
if self.sessions.current().scroll_offset <= 1 {
self.sessions.current_mut().scroll_offset = 0;
}
}
/// Return `true` when tool-output blocks are expanded to full height.
#[must_use]
pub fn tool_expanded(&self) -> bool {
self.tool_expanded
}
/// Return the active paste indicator state, if any.
///
/// `Some` when a multiline paste is in the input buffer and no edit
/// keypress has occurred since the paste. `None` otherwise.
#[must_use]
pub fn paste_state(&self) -> Option<&PasteState> {
self.sessions.current().paste_state.as_ref()
}
/// Return the current tool-output density level.
#[must_use]
pub fn tool_density(&self) -> ToolDensity {
self.tool_density
}
/// Return `true` when source-label badges are shown on assistant messages.
#[must_use]
pub fn show_source_labels(&self) -> bool {
self.show_source_labels
}
/// Toggle source-label visibility.
///
/// Clears the render cache so all messages are re-rendered with the new
/// setting on the next frame.
pub fn set_show_source_labels(&mut self, v: bool) {
if self.show_source_labels != v {
self.show_source_labels = v;
self.sessions.current_mut().render_cache.clear();
}
}
/// Return `true` when the Cocoon TON balance should be shown in the status bar.
///
/// Controlled by `[cocoon] show_balance` in config (default `true`). When `false`,
/// the balance is redacted to `*** TON` per spec §15.2.
#[must_use]
pub fn show_balance(&self) -> bool {
self.show_balance
}
/// Set whether the Cocoon TON balance is shown in the status bar.
pub fn set_show_balance(&mut self, v: bool) {
self.show_balance = v;
}
/// Replace the current hyperlink span list with `links`.
///
/// Called by the render loop after each frame to store spans detected in
/// the terminal buffer so they can be emitted as OSC 8 sequences.
pub fn set_hyperlinks(&mut self, links: Vec<HyperlinkSpan>) {
self.hyperlinks = links;
}
/// Take ownership of the accumulated hyperlink spans, clearing the list.
///
/// Called once per frame; the caller writes OSC 8 sequences to the terminal.
pub fn take_hyperlinks(&mut self) -> Vec<HyperlinkSpan> {
std::mem::take(&mut self.hyperlinks)
}
/// Return the current raw activity status label, if any.
///
/// This is the internal label as set by the agent loop (e.g.
/// `"Searching memory…"`, `"Executing tool: bash"`), not yet transformed
/// for display. The status bar passes it through
/// [`crate::widgets::status_verbs::humanize`] before rendering it next to
/// the spinner; other consumers (logs, debug output) use the raw form.
#[must_use]
pub fn status_label(&self) -> Option<&str> {
self.sessions.current().status_label.as_deref()
}
/// Return the number of messages queued or pending for the agent.
///
/// Displayed in the input bar to indicate backpressure.
#[must_use]
pub fn queued_count(&self) -> usize {
self.queued_count.max(self.pending_count)
}
/// Return the projected context token count from the last assembly, or 0 if not yet known.
///
/// The value is approximate (character-level heuristic) and is updated once per agent turn.
///
/// # Examples
///
/// ```rust
/// use tokio::sync::mpsc;
/// use zeph_tui::App;
///
/// let (tx, _) = mpsc::channel(1);
/// let (_, rx) = mpsc::channel(1);
/// let app = App::new(tx, rx);
/// assert_eq!(app.context_token_estimate(), 0);
/// ```
#[must_use]
pub fn context_token_estimate(&self) -> usize {
self.context_token_estimate
}
/// Return `true` when the user is currently editing a queued message.
#[must_use]
pub fn editing_queued(&self) -> bool {
self.editing_queued
}
/// Return `true` when the agent is actively processing (streaming or running a tool).
///
/// Used by the render loop to decide whether to show the activity spinner.
#[must_use]
pub fn is_agent_busy(&self) -> bool {
self.sessions.current().status_label.is_some()
|| self
.sessions
.current()
.messages
.last()
.is_some_and(|m| m.streaming)
}
/// Return `true` when the last message is a streaming tool output.
#[must_use]
pub fn has_running_tool(&self) -> bool {
self.sessions
.current()
.messages
.last()
.is_some_and(|m| m.role == MessageRole::Tool && m.streaming)
}
/// Return a reference to the throbber animation state.
///
/// Used by the status widget to render the spinner frame.
#[must_use]
pub fn throbber_state(&self) -> &throbber_widgets_tui::ThrobberState {
&self.throbber_state
}
/// Return a mutable reference to the throbber animation state.
///
/// Called by the tick handler to advance the spinner frame each tick.
pub fn throbber_state_mut(&mut self) -> &mut throbber_widgets_tui::ThrobberState {
&mut self.throbber_state
}
/// Toggle the collapsed state of a side-panel section by index.
///
/// Index mapping: `0` = Skills, `1` = Memory, `2` = Resources, `3` = `SubAgents`.
/// Out-of-range indices are silently ignored.
///
/// # Examples
///
/// ```rust
/// use tokio::sync::mpsc;
/// use zeph_tui::App;
///
/// let (tx, _) = mpsc::channel(1);
/// let (_, rx) = mpsc::channel(1);
/// let mut app = App::new(tx, rx);
/// app.toggle_panel_collapse(0);
/// assert!(app.collapsed_panels()[0]);
/// app.toggle_panel_collapse(0);
/// assert!(!app.collapsed_panels()[0]);
/// ```
pub fn toggle_panel_collapse(&mut self, idx: usize) {
if let Some(slot) = self.collapsed_panels.get_mut(idx) {
*slot = !*slot;
}
}
/// Return the current per-section collapse mask.
///
/// Index mapping: `0` = Skills, `1` = Memory, `2` = Resources, `3` = `SubAgents`.
///
/// # Examples
///
/// ```rust
/// use tokio::sync::mpsc;
/// use zeph_tui::App;
///
/// let (tx, _) = mpsc::channel(1);
/// let (_, rx) = mpsc::channel(1);
/// let app = App::new(tx, rx);
/// assert_eq!(app.collapsed_panels(), [false; 4]);
/// ```
#[must_use]
pub fn collapsed_panels(&self) -> [bool; 4] {
self.collapsed_panels
}
/// Compute the effective collapse mask used for layout and rendering.
///
/// Index 3 (`SubAgents` slot) is forced expanded when any overlay currently
/// owns that slot — Fleet, Durable, Tasks, plan view, or security events.
/// Indices 0–2 pass through the raw `collapsed_panels` value unchanged.
///
/// # Examples
///
/// ```rust
/// use tokio::sync::mpsc;
/// use zeph_tui::App;
///
/// let (tx, _) = mpsc::channel(1);
/// let (_, rx) = mpsc::channel(1);
/// let mut app = App::new(tx, rx);
/// // Collapsing slot 3 is honoured when no overlay is active.
/// app.toggle_panel_collapse(3);
/// assert!(app.effective_collapsed()[3]);
/// ```
#[must_use]
pub fn effective_collapsed(&self) -> [bool; 4] {
let mut eff = self.collapsed_panels;
// Force-expand slot 3 whenever an overlay is rendering into the subagents rect.
let slot3_has_overlay = matches!(
self.active_panel,
Panel::SubAgents | Panel::Fleet | Panel::Durable
) || self.show_task_panel
|| self
.metrics
.orchestration_graph
.as_ref()
.is_some_and(|s| !s.is_stale() && !self.sessions.current().plan_view_active)
|| self.has_recent_security_events();
if slot3_has_overlay {
eff[3] = false;
}
eff
}
/// Configure the animation budget from config.
///
/// # Examples
///
/// ```rust
/// use tokio::sync::mpsc;
/// use zeph_config::Motion;
/// use zeph_tui::App;
///
/// let (user_tx, _) = mpsc::channel(1);
/// let (_, agent_rx) = mpsc::channel(1);
/// let app = App::new(user_tx, agent_rx).with_motion(Motion::Minimal);
/// assert_eq!(app.motion(), Motion::Minimal);
/// ```
#[must_use]
pub fn with_motion(mut self, motion: zeph_config::Motion) -> Self {
self.motion = motion;
self
}
/// Return the current animation budget.
#[must_use]
pub fn motion(&self) -> zeph_config::Motion {
self.motion
}
/// Return the monotonic wave-tick counter.
///
/// Passed as `t` into [`crate::widgets::wave::sample`] / [`crate::widgets::wave::glyphs`].
#[must_use]
pub fn wave_tick(&self) -> u64 {
self.wave_tick
}
/// Advance the wave animation clock by one tick.
///
/// Called from the render loop's internal interval as an animation heartbeat
/// that is independent of the `EventReader`'s `AppEvent::Tick`s, so the
/// equalizer keeps moving even when the event channel is briefly starved by a
/// streaming burst. Only the wave counter is advanced here — the throbber and
/// micro-delights stay driven by `AppEvent::Tick`.
pub fn advance_wave_tick(&mut self) {
self.wave_tick = self.wave_tick.saturating_add(1);
}
/// Apply micro-delight configuration (#5104).
///
/// Called at construction time from `tui_bridge` to propagate `[tui.delights]` config.
///
/// # Examples
///
/// ```rust
/// use tokio::sync::mpsc;
/// use zeph_tui::App;
/// use zeph_config::DelightsConfig;
///
/// let (tx, _) = mpsc::channel(1);
/// let (_, rx) = mpsc::channel(1);
/// let app = App::new(tx, rx).with_delights(DelightsConfig::default());
/// ```
#[must_use]
pub fn with_delights(mut self, delights: zeph_config::DelightsConfig) -> Self {
self.delights = delights;
self
}
/// Return the current animation tick counter.
///
/// Aliased from `wave_tick` so animation code can read it by an intent-revealing name.
/// Free-running at ~10fps (100ms/tick via `EventReader`). Never pauses.
///
/// # Examples
///
/// ```rust
/// use tokio::sync::mpsc;
/// use zeph_tui::App;
///
/// let (tx, _) = mpsc::channel(1);
/// let (_, rx) = mpsc::channel(1);
/// let app = App::new(tx, rx);
/// assert_eq!(app.anim_tick(), 0);
/// ```
#[must_use]
pub fn anim_tick(&self) -> u64 {
self.wave_tick
}
/// Begin an animated scroll to `target_offset` for the current session.
///
/// When smooth-scroll is disabled (`motion = Off` or `delights.smooth_scroll = false`),
/// the offset is set directly. Single-line scrolls (j/k) bypass this and write
/// `scroll_offset` directly — animation is reserved for page-sized jumps.
pub(crate) fn begin_scroll(&mut self, target_offset: usize) {
let smooth = self.motion != zeph_config::Motion::Off && self.delights.smooth_scroll;
if smooth {
// Use the in-flight animation's destination as the starting point so that
// two rapid PageDown presses chain correctly instead of producing identical
// animations from the same stale scroll_offset.
let cur = self.sessions.current();
let from = cur.scroll_anim.as_ref().map_or(cur.scroll_offset, |a| a.to);
let now = self.anim_tick();
self.sessions.current_mut().scroll_anim = Some(crate::session::ScrollAnim {
from,
to: target_offset,
start_tick: now,
});
} else {
self.sessions.current_mut().scroll_offset = target_offset;
}
}
/// Enqueue an ephemeral toast notification.
///
/// **MUST** be called only from the render thread (inside `handle_event` /
/// `handle_agent_event`). Off-thread origins must be routed as `AgentEvent` or
/// `AppEvent` variants — never mutate the queue cross-thread.
pub(crate) fn push_toast(&mut self, text: impl Into<String>, kind: crate::delights::ToastKind) {
let tick = self.anim_tick();
self.toasts.push(text, kind, tick);
}
/// Whether any animation-driven feature is currently active.
///
/// Provided as an optional future hook for a deferred CPU-optimization issue
/// (suppress idle redraws when nothing animates). NOT wired to the redraw gate
/// in this PR — the `EventReader` already drives 10fps unconditionally.
#[must_use]
pub fn wants_animation_frame(&self) -> bool {
if self.motion == zeph_config::Motion::Off {
return false;
}
let t = self.anim_tick();
let flash_active = self
.sessions
.current()
.flash
.pending
.values()
.any(|&born| t.saturating_sub(born) < crate::session::FLASH_TICKS);
let scroll_active = self.sessions.current().scroll_anim.is_some();
self.toasts.has_active(t)
|| flash_active
|| scroll_active
|| self.splash_shimmer.is_active(t)
}
/// Derive the current wave animation state from live agent state.
///
/// Stalled is checked first so a hung turn never reads as Streaming or Swell.
///
/// # Stall behaviour
///
/// A slow time-to-first-token > `stall_threshold` shows `Stalled` before any token
/// arrives, because `last_progress_at` is set when the turn goes busy (Typing/Status)
/// and the threshold starts counting from that moment. Accepted for v1 simplicity.
#[must_use]
pub fn wave_state(&self) -> crate::widgets::wave::WaveState {
use crate::widgets::wave::WaveState;
let foreground = self.is_agent_busy();
let bg = self.background_inflight();
// Nothing running at all → flat baseline.
if !foreground && bg == 0 {
return WaveState::Idle;
}
// Stalled: a foreground turn with no progress past the threshold. Checked
// before background so a genuinely hung turn still surfaces the warning.
if foreground && self.last_progress_at.elapsed() > STALL_THRESHOLD {
return WaveState::Stalled;
}
// Foreground tool execution takes priority over background requests.
if foreground && self.has_running_tool() {
return WaveState::Tool;
}
// External/background requests (task-supervisor work: enrichment, telemetry,
// MCP, egress, background shell). Rendered in violet so concurrent background
// activity is visually distinct from the agent's own foreground turn.
if bg >= 1 {
#[allow(clippy::cast_possible_truncation)]
return WaveState::Network {
sines: (bg as u8).clamp(1, 3),
};
}
// Streaming: last message is a streaming assistant message.
if self
.sessions
.current()
.messages
.last()
.is_some_and(|m| m.streaming && m.role == crate::types::MessageRole::Assistant)
{
return WaveState::Streaming;
}
// Swell: busy but awaiting first token.
WaveState::Swell
}
/// Count in-flight background/external requests for the wave equalizer.
///
/// Combines the task-supervisor inflight gauge (`bg_inflight` — all classes,
/// already includes enrichment + telemetry) with in-flight background shell
/// runs. Used by [`Self::wave_state`] to drive the violet `Network` wave and
/// by the draw loop to keep the equalizer visible while background work runs
/// even when the agent itself is idle.
#[must_use]
pub fn background_inflight(&self) -> u64 {
self.metrics.bg_inflight + self.metrics.shell_background_runs.len() as u64
}
/// Advance all micro-delight animations by one tick.
///
/// Called from [`crate::app::events`] on every `AppEvent::Tick` so that
/// animation state advances unconditionally, regardless of whether a draw
/// frame is suppressed by `DirtyState::AnimationOnly`.
pub(crate) fn tick_delights(&mut self) {
let now = self.anim_tick();
// Prune expired toasts.
self.toasts.prune(now);
// Advance current session's scroll animation.
if let Some(ref anim) = self.sessions.current().scroll_anim {
let (offset, done) = anim.current_offset(now);
self.sessions.current_mut().scroll_offset = offset;
if done {
self.sessions.current_mut().scroll_anim = None;
}
}
// Prune expired flash entries for the current session.
self.sessions.current_mut().flash.prune(now);
// Detect show_splash rising edge (false → true) → reset shimmer for fresh sweep.
let cur_show_splash = self.sessions.current().show_splash;
if cur_show_splash && !self.sessions.current().prev_show_splash {
self.splash_shimmer.reset();
}
self.sessions.current_mut().prev_show_splash = cur_show_splash;
// Activate shimmer on first splash frame.
let shimmer_enabled =
self.motion != zeph_config::Motion::Off && self.delights.splash_shimmer;
if shimmer_enabled && cur_show_splash {
self.splash_shimmer.activate(now);
}
}
// ── Mouse mode (#5103) ────────────────────────────────────────────────────
/// Enable or disable opt-in mouse capture at startup.
///
/// Called from the builder chain in `tui_bridge` when `config.tui.mouse` is `true`.
/// Actual terminal-level capture is enabled **after** the first frame is drawn
/// (C3 — avoid delivering mouse events before `last_layout` is populated).
///
/// # Examples
///
/// ```rust
/// use tokio::sync::mpsc;
/// use zeph_tui::App;
///
/// let (tx, _) = mpsc::channel(1);
/// let (_, rx) = mpsc::channel(1);
/// let app = App::new(tx, rx).with_mouse(true);
/// assert!(app.mouse_enabled());
/// ```
#[must_use]
pub fn with_mouse(mut self, enabled: bool) -> Self {
self.mouse_enabled = enabled;
self
}
/// Return `true` when opt-in mouse capture is currently active.
///
/// # Examples
///
/// ```rust
/// use tokio::sync::mpsc;
/// use zeph_tui::App;
///
/// let (tx, _) = mpsc::channel(1);
/// let (_, rx) = mpsc::channel(1);
/// let app = App::new(tx, rx);
/// assert!(!app.mouse_enabled());
/// ```
#[must_use]
pub fn mouse_enabled(&self) -> bool {
self.mouse_enabled
}
/// Drain any pending mouse-capture toggle and return it.
///
/// Returns `Some(true)` to enable capture, `Some(false)` to disable, or `None`
/// if no toggle is pending.
///
/// Called by `tui_loop` in the shared post-select block after every event arm
/// (C2 — not inside an individual arm to avoid ordering hazards).
pub(crate) fn take_mouse_capture_request(&mut self) -> Option<bool> {
self.pending_mouse_capture.take()
}
// ── Pub(crate) helpers for the reducer ──────────────────────────────────
/// Push a system message visible in the chat area (public(crate) forwarding wrapper).
pub(crate) fn push_system_message_pub(&mut self, content: String) {
self.sessions.current_mut().show_splash = false;
self.sessions
.current_mut()
.messages
.push(crate::ChatMessage::new(crate::MessageRole::System, content));
self.sessions.current_mut().scroll_offset = 0;
}
/// Return the content of the last assistant message (pub(crate) for reducer).
pub(crate) fn last_assistant_content_pub(&self) -> Option<String> {
self.sessions
.current()
.messages
.iter()
.rev()
.find(|m| m.role == crate::MessageRole::Assistant)
.map(|m| m.content.clone())
}
/// Extract all fenced code blocks from the last assistant message (pub(crate) for reducer).
pub(crate) fn last_assistant_code_blocks_pub(&self) -> Vec<String> {
use pulldown_cmark::{CodeBlockKind, Event, Options, Parser, Tag, TagEnd};
let Some(content) = self.last_assistant_content_pub() else {
return Vec::new();
};
let options = Options::ENABLE_STRIKETHROUGH | Options::ENABLE_TABLES;
let parser = Parser::new_ext(&content, options);
let mut blocks: Vec<String> = Vec::new();
let mut current: Option<String> = None;
for event in parser {
match event {
Event::Start(Tag::CodeBlock(
CodeBlockKind::Fenced(_) | CodeBlockKind::Indented,
)) => {
current = Some(String::new());
}
Event::Text(text) => {
if let Some(ref mut buf) = current {
buf.push_str(&text);
}
}
Event::End(TagEnd::CodeBlock) => {
if let Some(buf) = current.take() {
blocks.push(buf);
}
}
_ => {}
}
}
if let Some(buf) = current
&& !buf.is_empty()
{
blocks.push(buf);
}
blocks
}
}
#[cfg(test)]
mod tests {
use tokio::sync::mpsc;
use super::App;
fn make_app() -> App {
let (user_tx, _) = mpsc::channel(1);
let (_, agent_rx) = mpsc::channel(1);
App::new(user_tx, agent_rx)
}
#[test]
fn apply_theme_path_traversal_rejected() {
let mut app = make_app();
assert!(
app.apply_theme("../../etc/passwd").is_err(),
"path traversal must be rejected"
);
assert!(
app.apply_theme("bad..name").is_err(),
"dotdot in name must be rejected"
);
assert!(app.apply_theme("").is_err(), "empty name must be rejected");
// Theme must remain unchanged after all failed attempts.
assert_eq!(app.active_theme_name(), "zephyr");
}
#[test]
fn apply_theme_valid_bumps_generation() {
let mut app = make_app();
let gen_before = app.theme_generation();
app.apply_theme("zephyr-light").expect("valid theme");
assert!(
app.theme_generation() > gen_before,
"generation must increment"
);
assert_eq!(app.active_theme_name(), "zephyr-light");
}
#[test]
fn apply_theme_invalidates_all_session_caches() {
use crate::app::RenderCacheKey;
use crate::widgets::tool_view::ToolDensity;
let mut app = make_app();
// Add a second session (pub(crate) — accessible within the same crate).
let _slot2_key = app.sessions.create("session 2");
// Populate the render cache of the current (first) session.
let dummy_key = RenderCacheKey {
content_hash: 1,
terminal_width: 80,
tool_expanded: false,
tool_density: ToolDensity::Inline,
show_labels: false,
theme_generation: 0,
};
app.sessions
.current_mut()
.render_cache
.put(0, dummy_key, vec![], vec![]);
// Verify the entry is present before the theme swap.
let hit_before = app.sessions.current().render_cache.get(0, &dummy_key);
assert!(hit_before.is_some(), "cache must contain the seeded entry");
// Swap theme → must clear caches in ALL sessions.
app.apply_theme("zephyr-light").expect("valid theme");
// After the swap the key has a stale theme_generation, so get() returns None.
let hit_after = app.sessions.current().render_cache.get(0, &dummy_key);
assert!(
hit_after.is_none(),
"cache must be cleared (or invalidated) on theme swap"
);
}
#[test]
fn with_theme_name_builder_sets_name() {
let (user_tx, _) = mpsc::channel(1);
let (_, agent_rx) = mpsc::channel(1);
let app = App::new(user_tx, agent_rx).with_theme_name("gruvbox-dark");
assert_eq!(app.active_theme_name(), "gruvbox-dark");
}
#[test]
fn with_remote_daemon_url_builder_sets_url() {
let (user_tx, _) = mpsc::channel(1);
let (_, agent_rx) = mpsc::channel(1);
let app = App::new(user_tx, agent_rx).with_remote_daemon_url("http://localhost:8765");
assert_eq!(app.remote_daemon_url(), Some("http://localhost:8765"));
}
#[test]
fn remote_daemon_url_defaults_to_none() {
let app = make_app();
assert_eq!(app.remote_daemon_url(), None);
}
}