cctop 0.22.1

An htop-like terminal monitor for AI coding agent sessions on Linux (Claude Code, Codex, Cursor, Devin, Gemini CLI, OpenCode, Pi, Windsurf)
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
//! What running agents report about themselves, and how the user is told.
//!
//! A transcript says what an agent did; only a hook says what it is doing right
//! now โ€” waiting for permission, idle, or working โ€” and that word has to be
//! believed for a while, reconciled against a pane's own pid, and dropped when
//! nothing confirms it. Attention is the other half of the same story: a
//! reported state is what makes a tab blink, ring a bell, or answer `b`. Both
//! belong to the reports rather than to the table they decorate.

use super::*;

/// Half-period of the tab-bar blink. Slow enough to read the title through,
/// fast enough to catch the eye.
const BLINK_MS: u128 = 600;

/// The eight characters a Gemini chat file is named after, out of the row id
/// that file produced: `session-2026-05-14T17-34-79709c93` yields `79709c93`.
///
/// `None` for every other harness's ids, which is what keeps this from matching
/// on the tail of a uuid that happens to line up: only a stem shaped like
/// Gemini's is looked up loosely, and only ever against a full id's prefix.
fn gemini_id_tail(session_id: &str) -> Option<&str> {
    let tail = session_id.strip_prefix("session-")?.rsplit_once('-')?.1;
    (tail.len() == 8 && tail.chars().all(|c| c.is_ascii_alphanumeric())).then_some(tail)
}

/// The report a session's hooks last made, however old, if they made one.
fn hook_report<'a>(
    hooked: &'a HashMap<String, crate::hook::Reported>,
    session_id: &str,
) -> Option<&'a crate::hook::Reported> {
    if let Some(reported) = hooked.get(session_id) {
        return Some(reported);
    }
    // Gemini CLI reports a full session id, but names the chat file it
    // writes โ€” which is the only identity cctop's rows have, because
    // resuming reuses the id across disjoint files โ€” after the *first eight
    // characters* of it. Without this last step every Gemini event lands on
    // no row at all.
    let tail = gemini_id_tail(session_id)?;
    hooked
        .iter()
        .find(|(id, _)| id.starts_with(tail))
        .map(|(_, reported)| reported)
}

/// What the stall alert needs from a session's hooks.
///
/// Read off the last report whether or not it is still believed. A working
/// claim lapses after a quarter of an hour of silence so that the row stops
/// saying "busy" about a session nobody is running โ€” but for the stall alert
/// that silence is the finding, not a reason to stop looking. The row's own
/// state, which does honour the lapse, is checked beside it.
fn stall_view(
    hooked: &HashMap<String, crate::hook::Reported>,
    session_id: &str,
) -> crate::alert::Hooked {
    use crate::alert::Hooked;
    use crate::hook::Signal;
    match hook_report(hooked, session_id).map(|r| r.signal) {
        None => Hooked::Unknown,
        Some(Signal::Busy | Signal::Started) => Hooked::Working,
        Some(Signal::Acting | Signal::Compacting) => Hooked::InFlight,
        Some(Signal::NeedsInput | Signal::Idle | Signal::Ended) => Hooked::Quiet,
    }
}

impl App {
    /// Promote every held permission prompt whose grace has expired, and say
    /// whether any had.
    ///
    /// Auto mode's answer arrives as its own event and replaces the report, so
    /// a prompt still sitting here when the grace runs out is one a person has
    /// to answer. Cleared rather than re-tested every tick: once a prompt is
    /// real it stays real, and leaving the flag up would have the whole table
    /// recomputed on every pass of the loop for the rest of the session.
    pub(super) fn promote_matured_prompts(&mut self) -> bool {
        let mut matured = false;
        for reported in self.hooked.values_mut() {
            if reported.provisional && reported.at.elapsed() >= crate::hook::PERMISSION_GRACE {
                reported.provisional = false;
                matured = true;
            }
        }
        self.needs_redraw |= matured;
        matured
    }

    /// Let the notifier see this refresh, and queue a bell for anything that
    /// crossed or fired.
    ///
    /// Called from the event loop only when the rows actually moved, which
    /// then rings once for the whole pass with
    /// [`Notifier::ring_pending`](crate::notify::Notifier::ring_pending). That
    /// has to run on this thread: the bell and the OSC 9 sequence go straight
    /// to stdout, which ratatui owns, and only here is it certain that no
    /// frame is halfway through being flushed.
    pub(super) fn check_bells(&mut self) {
        // The serve's link is what a webhook POST points at, so it is refreshed
        // with the crossings: starting `B` mid-run must not leave every future
        // notification saying there is nowhere to look.
        self.notify.link_base = self.serving.as_ref().map(|s| s.best().to_string());
        self.notify.observe(&self.sessions);

        let hooked = &self.hooked;
        let fired = self.alerts.observe(
            &self.settings.alert_rules(),
            &self.sessions,
            self.stats.spend_today,
            |s| stall_view(hooked, &s.session_id),
            Instant::now(),
            chrono::Utc::now(),
        );
        self.announce_alerts(fired);
    }

    /// Tell the user about the alerts that just fired: a toast each, whether
    /// or not `w` is on โ€” the thresholds are the opt-in, and a toast is quiet โ€”
    /// and one clause in the refresh's bell for the lot when it is.
    ///
    /// One clause, as with the sessions that finish together: three rings in
    /// a row is noise, and the toasts already name every one.
    fn announce_alerts(&mut self, fired: Vec<crate::alert::Fired>) {
        let Some(first) = fired.first() else {
            return;
        };
        self.notify.chime(&first.text, fired.len() - 1);
        for alert in fired {
            crate::elog::event(
                "alert",
                alert.kind_name(),
                serde_json::json!({ "text": alert.text, "session": alert.key }),
            );
            self.notify.post_event("alert", &alert.text);
            self.set_status(alert.text);
        }
    }

    /// A quota window that just opened back up.
    ///
    /// The same machinery as a session crossing โ€” the bell, the webhook, the
    /// log โ€” pointed at the other thing worth being interrupted for: "you can
    /// spend again" is the one event a monitor of agent spend owes a person
    /// who has stepped away.
    pub(super) fn announce_quota_freed(&mut self, text: &str) {
        crate::elog::event("quota", "freed", serde_json::json!({ "text": text }));
        self.notify.post_event("quota-freed", text);
        self.notify.chime(text, 0);
        self.set_status(text.to_string());
    }

    /// Turn the bell on or off, and remember which.
    pub(super) fn toggle_notifications(&mut self) {
        self.notify.enabled = !self.notify.enabled;
        self.save_prefs();
        self.set_status(if self.notify.enabled {
            "Notifications on โ€” bell and desktop alert when a session needs you"
        } else {
            "Notifications off"
        });
    }

    /// Jump the selection to whichever session the bell is still owed to.
    ///
    /// Several can have rung since the last press, so this asks the notifier
    /// which one it has not landed on yet โ€” a second `b` walks to the next
    /// rather than re-selecting the same row.
    pub(super) fn jump_to_bell(&mut self) {
        let on = self.selected_session().map(|s| s.key());
        let Some(rang) = self.notify.unanswered(on.as_deref()) else {
            self.set_status("Nothing has rung yet");
            return;
        };
        let key = rang.key.clone();
        self.reveal(&key);
        // The parent row, not a child of it: the bell rang for the session.
        match self
            .visible
            .iter()
            .position(|&r| matches!(r, Row::Session(i) if self.sessions[i].key() == key))
        {
            Some(row) => {
                self.selected = row;
                self.ensure_available_tab();
                self.needs_redraw = true;
            }
            // Answering it is the point, so say why it can't be reached rather
            // than moving the cursor somewhere arbitrary.
            None => self.set_status("The session that rang is hidden by the current filter"),
        }
    }

    /// What tab `index` wants, if anything. `0` is the dashboard, which never
    /// asks for itself.
    ///
    /// The tab you are already looking at is excluded โ€” its own focused pane is
    /// in front of you, so blinking its title tells you nothing you cannot see.
    pub fn tab_attention(&self, index: usize) -> Option<tabs::Attention> {
        let tab = self.tabs.get(index.checked_sub(1)?)?;
        let watched = index == self.tab;
        match tab.attention(watched, &|pid| self.pane_signal(pid))? {
            // Upgraded here rather than decided inside the tab: whether a turn
            // has been seen is the app's memory, not anything a pane holds โ€”
            // see [`seen`](super::seen). Only a tab that already reads as idle
            // is, so a disagreement between the row and the screen leaves the
            // screen's answer standing.
            tabs::Attention::Idle
                if tab
                    .unwatched_agents(watched)
                    .into_iter()
                    .any(|pid| self.pid_done(pid)) =>
            {
                Some(tabs::Attention::Done)
            }
            attention => Some(attention),
        }
    }

    /// Whether the agent running as `pid` finished a turn you have not looked
    /// at.
    pub(super) fn pid_done(&self, pid: u32) -> bool {
        self.sessions
            .iter()
            .filter(|session| session.root_pid() == Some(pid))
            .any(|session| self.seen.is_done(&session.key()))
    }

    /// The session being looked at, as [`seen`](super::seen) counts looking:
    /// the focused pane's agent in a tab, the selected row on the dashboard.
    fn viewed_session(&self) -> Option<String> {
        let pid = match self.tab {
            0 => return self.selected_session().map(Session::key),
            tab => {
                let tab = self.tabs.get(tab - 1)?;
                tab.panes.get(tab.focus)?.agent()
            }
        };
        self.sessions
            .iter()
            .find(|session| session.root_pid() == Some(pid))
            .map(Session::key)
    }

    /// Bring the unseen marks up to date with what the rows say and where you
    /// are looking. Returns whether any mark came or went.
    ///
    /// Every pass of the loop rather than on refresh alone: looking is a
    /// keypress, and a mark that outlived the look by a refresh interval would
    /// be a mark on the thing you are reading.
    pub(super) fn observe_seen(&mut self) -> bool {
        let viewed = self.viewed_session();
        let live: Vec<(String, seen::Phase)> = self
            .sessions
            .iter()
            .filter(|session| session.is_running())
            .map(|session| (session.key(), seen::Phase::of(session.activity_state)))
            .collect();
        self.seen.observe(
            live.iter().map(|(key, phase)| (key.as_str(), *phase)),
            viewed.as_deref(),
        )
    }

    /// Fold in whatever the agents have reported.
    ///
    /// These outrank anything read off disk or off a screen: an agent saying
    /// "my turn is over" is the fact those are both estimating.
    ///
    /// Returns whether anything arrived, and whether the set of sessions itself
    /// changed โ€” one that has just started or just ended is a row to go and
    /// find or forget now, rather than at the next poll.
    pub(super) fn apply_hooks(&mut self, events: Vec<crate::hook::Event>) -> (bool, bool) {
        let changed = !events.is_empty();
        let mut lifecycle = false;
        let mut moved = false;
        for event in events {
            crate::elog::event(
                "hook",
                "recv",
                serde_json::json!({
                    "session": event.session_id,
                    "signal": format!("{:?}", event.reported.signal),
                    // Which subagent spoke, if one did: a question the tab
                    // failed to show is only diagnosable from which agent
                    // asked and which sibling spoke over it.
                    "agent": event.agent.as_deref().unwrap_or_default(),
                    "provisional": event.reported.provisional,
                    "pids": event.pids.len(),
                    "cwd": &event.reported.cwd,
                }),
            );
            lifecycle |= event.reported.signal.is_lifecycle();
            if let Some(agent) = event.finished_agent {
                self.finished_agents.insert(agent);
            }
            match event.reported.signal {
                // Nothing more will be said about it, and leaving the last
                // signal behind would have the row claim a state forever.
                crate::hook::Signal::Ended => {
                    self.hooked.remove(&event.session_id);
                    self.asking_agents.remove(&event.session_id);
                    moved |= self.hook_pids.remove(&event.session_id).is_some();
                }
                _ => {
                    if !event.pids.is_empty()
                        && self.hook_pids.get(&event.session_id) != Some(&event.pids)
                    {
                        self.hook_pids.insert(event.session_id.clone(), event.pids);
                        moved = true;
                    }
                    let reported =
                        self.still_asking(&event.session_id, event.agent, event.reported);
                    self.hooked.insert(event.session_id, reported);
                }
            }
        }
        if moved {
            self.note_hook_pids();
        }
        // A working claim that nothing has confirmed for a quarter of an hour is
        // dropped rather than believed: see
        // [`Reported::is_current`](crate::hook::Reported::is_current). Swept
        // here because this is the only place the map grows, and a session that
        // was killed mid-turn will never send the event that would clear it.
        self.hooked.retain(|_, reported| reported.is_current());
        // A chain outlives its usefulness exactly when the report it came with
        // does, and a session that has been swept must stop claiming a pid โ€”
        // otherwise a reused pid would be handed to a session that is gone. A
        // waiting session is never swept, which is the case this exists for.
        let before = self.hook_pids.len();
        self.hook_pids.retain(|id, _| self.hooked.contains_key(id));
        if self.hook_pids.len() != before {
            self.note_hook_pids();
        }
        self.apply_finished_agents();
        self.apply_reports();
        (changed, lifecycle)
    }

    /// What a session should be taken to be doing after `reported`, given the
    /// questions its subagents are still waiting on.
    ///
    /// A subagent's question stands until *that* subagent says something else โ€”
    /// its tool running, or being denied, or it stopping โ€” however busy the
    /// agents beside it are. While any stands, the session is asking: the most
    /// recent open question is what it reports, so the tab stays lit and the
    /// bell's grace period is the question's own.
    fn still_asking(
        &mut self,
        session: &str,
        agent: Option<String>,
        reported: crate::hook::Reported,
    ) -> crate::hook::Reported {
        let open = self.asking_agents.entry(session.to_string()).or_default();
        match agent {
            Some(agent) => match reported.signal {
                crate::hook::Signal::NeedsInput => {
                    open.insert(agent, reported.clone());
                }
                _ => {
                    open.remove(&agent);
                }
            },
            // The session's own turn ending. A subagent it was waiting on cannot
            // still be asking once it has โ€” a prompt dismissed with Esc ends the
            // turn and sends nothing from the subagent โ€” and a question kept
            // past that would light the tab for good, since a question is never
            // aged out.
            //
            // ponytail: a *background* subagent asking across its parent's
            // `Stop` is taken to have been answered.
            None if reported.signal == crate::hook::Signal::Idle => open.clear(),
            None => {}
        }
        if reported.signal == crate::hook::Signal::NeedsInput {
            return reported;
        }
        match open.values().max_by_key(|asked| asked.at) {
            Some(asked) => asked.clone(),
            None => {
                self.asking_agents.remove(session);
                reported
            }
        }
    }

    /// Tell the worker which processes the agents say they are running under.
    ///
    /// This is the only thing that binds a session to a *process* by something
    /// an agent stated rather than something cctop inferred. Without it a plain
    /// `claude` โ€” which carries no session id on its command line โ€” is paired
    /// with a transcript by working directory and recency, so two agents in one
    /// checkout swap rows whenever their activity order changes, and the alerts
    /// follow the swap onto the wrong tab.
    ///
    /// Sent whole rather than incrementally: it is a handful of entries, and a
    /// replacement cannot drift from what this cctop believes the way a stream
    /// of deltas could.
    fn note_hook_pids(&self) {
        crate::hook::save_claims(&self.hook_pids);
        let _ = self
            .tx
            .send(super::worker::Request::HookClaims(self.hook_pids.clone()));
    }

    /// Stamp each session with what its own hooks reported: the permission mode
    /// it runs under, and whether it is blocked on a question.
    ///
    /// Also run after a walk, because the rows are rebuilt wholesale and a
    /// freshly discovered one has to pick up what was reported before it
    /// existed. `hooked` outlives the rows for exactly this reason.
    ///
    /// This is what puts a held permission prompt on a row at all. Everything
    /// downstream of the row reads it for free โ€” the STATE dot, the bell, the
    /// web report, `--json`, and a fleet peer โ€” rather than each of them being
    /// handed the UI's map of live reports and asked to agree with the others.
    pub(crate) fn apply_reports(&mut self) {
        if self.hooked.is_empty() && self.screen_read.is_empty() {
            return;
        }
        for session in &mut self.sessions {
            // The screen, when it is being read and says something, outranks
            // every report: it is what the agent is showing *now*, where a hook
            // event is what it said last โ€” late for a permission prompt, stale
            // for a question already answered, absent when hooks are not
            // installed at all. See [`App::read_screens`].
            let screen = session
                .root_pid()
                .and_then(|pid| self.screen_read.get(&pid).copied());
            if let Some(signal) = screen {
                use crate::session::ActivityState::{Asking, WaitingForInput, Working};
                match signal.activity() {
                    Some(state) => session.activity_state = state,
                    // Mid-turn on screen clears a waiting state a report left
                    // behind; an API error the transcript found stays put.
                    None if matches!(session.activity_state, Asking | WaitingForInput) => {
                        session.activity_state = Working;
                    }
                    None => {}
                }
            }
            if let Some(reported) = self.hooked.get(&session.session_id) {
                // Only ever set from a report. A session whose newest event did
                // not carry the field keeps the last mode that did, because the
                // setting has not changed just because one event was quiet
                // about it.
                if reported.permission.is_some() {
                    session.permission = reported.permission;
                }
                // The report is only allowed to say the two things the
                // transcript cannot โ€” see
                // [`Signal::activity`](crate::hook::Signal::activity) โ€” so a
                // stale-but-not-yet-expired working claim cannot talk a row out
                // of an API error it is genuinely sitting in.
                // A permission prompt auto mode may still answer is not yet
                // news: see
                // [`Reported::is_settled`](crate::hook::Reported::is_settled).
                // The row keeps whatever the transcript makes of it โ€” which is
                // "working", because that is what the agent is doing.
                if screen.is_none()
                    && reported.is_settled()
                    && let Some(state) = reported.signal.activity()
                {
                    session.activity_state = state;
                }
            }
        }
    }

    /// Read every tab's agent off its screen, when the setting asks for it. True when any verdict changed, so the rows are restamped.
    ///
    /// The hooks are how an agent says what it is doing, and they can fail in
    /// ways that look exactly like an agent with nothing to say: not installed,
    /// installed at a binary that has since moved, a session started before
    /// they were, a permission prompt announced six seconds late. The screen
    /// has none of those failure modes, only its own โ€” it has to be one cctop
    /// holds, and in words cctop knows โ€” which is why it is opt-in rather than
    /// the default.
    ///
    /// ponytail: tabs cctop has a live screen for only. A detached rmux tab has
    /// no parser here, and reading it would be a `capture-pane` per tab per
    /// tick; `rmux::capture` is the way in if that is ever wanted.
    pub(super) fn read_screens(&mut self) -> bool {
        let read: HashMap<u32, crate::hook::Signal> = match self.settings.read_screen == Some(true)
        {
            true => self
                .tabs
                .iter()
                .flat_map(|tab| &tab.panes)
                .filter_map(|pane| Some((pane.agent(), pane.read_screen()?)))
                .collect(),
            false => HashMap::new(),
        };
        let changed = read != self.screen_read;
        self.screen_read = read;
        changed
    }

    /// Mark the subagents whose own hook has reported them finished.
    ///
    /// Stamped onto the rows rather than consulted at each draw, so every reader
    /// of a `Subagent` โ€” the child rows, the Subagents tab, `--json` โ€” agrees
    /// without being handed the UI's state. The hook outranks the transcript
    /// heuristic: it is the agent saying so, where the heuristic is only the
    /// absence of writing.
    pub(super) fn apply_finished_agents(&mut self) {
        if self.finished_agents.is_empty() {
            return;
        }
        for session in &mut self.sessions {
            for sub in &mut session.subagents {
                // The hook names the bare id; the transcript is `agent-<id>`.
                let id = sub.agent_id.strip_prefix("agent-").unwrap_or(&sub.agent_id);
                if self.finished_agents.contains(id) {
                    sub.status = crate::session::SubagentStatus::Done;
                }
            }
        }
    }

    /// What a session's own hooks last said about it, if it has any.
    pub(super) fn hooked_signal(&self, session_id: &str) -> Option<crate::hook::Signal> {
        // Checked here as well as in the sweep: the sweep runs when an event
        // arrives, and a session that has gone silent is precisely the one that
        // sends none โ€” so between events the map still holds the stale claim.
        hook_report(&self.hooked, session_id)
            .filter(|reported| reported.is_current() && reported.is_settled())
            .map(|reported| reported.signal)
    }

    /// What has been reported about the agent running as `pid`, if anything.
    ///
    /// Hooks first, because the agent said it outright; the transcript second,
    /// which can only report the question and not the finished turn; nothing at
    /// all if the session has not been discovered yet, which leaves the caller
    /// to fall back to the pane's screen.
    ///
    /// Scans the table rather than keeping an index: there are a handful of
    /// panes and this runs once per frame, so a map would be state to keep
    /// correct in exchange for nothing measurable.
    pub(super) fn pane_signal(&self, pid: u32) -> Option<crate::hook::Signal> {
        let screen = self.screen_read.get(&pid).copied();
        screen.or_else(|| self.reported_by(pid)).or_else(|| {
            self.sessions
                .iter()
                .filter(|session| session.root_pid() == Some(pid))
                .find_map(|session| {
                    match session.activity_state {
                        // Both of the row's waiting states are a tab worth
                        // colouring; which colour is the caller's business.
                        crate::session::ActivityState::Asking => {
                            Some(crate::hook::Signal::NeedsInput)
                        }
                        crate::session::ActivityState::WaitingForInput => {
                            Some(crate::hook::Signal::Idle)
                        }
                        _ => None,
                    }
                })
        })
    }

    /// What the agent running as `pid` last reported over its own hooks.
    ///
    /// The half of [`Self::pane_signal`] with no inference in it, split out
    /// because it is the only half worth writing onto an rmux session: a
    /// transcript reading is one every cctop on the machine can take for
    /// itself, off the same files, so recording one would be publishing a guess
    /// that the reader could already have made.
    pub(super) fn reported_by(&self, pid: u32) -> Option<crate::hook::Signal> {
        self.sessions
            .iter()
            .filter(|session| session.root_pid() == Some(pid))
            .find_map(|session| self.hooked_signal(&session.session_id))
    }

    /// Write what this cctop has heard onto the rmux sessions that carry it.
    ///
    /// The other direction of [`Shared::recorded`](tabs::Shared): every cctop
    /// reads these, so somebody has to write them, and the one that heard the
    /// event is the only one that can. It is not the hook that writes โ€” see
    /// [`rmux::set_state`](crate::rmux::set_state) for why the agent's deadline
    /// must not pay for this.
    ///
    /// Driven off `running` rather than off the tabs, so a session no tab of
    /// this cctop's stands for is still kept up to date: the row exists and its
    /// hooks report here whether or not anybody has opened a tab on it.
    ///
    /// The write condition is the whole of the rate limiting, and it is just
    /// "the session does not already say this". An unchanged state costs
    /// nothing, which matters because the sweep runs every
    /// [`SHARE_EVERY`] and a turn is mostly the same signal repeated. An
    /// expired one reads as saying nothing, so a working claim this cctop still
    /// believes is rewritten rather than allowed to lapse.
    pub(super) fn publish_states(&self, running: &[crate::rmux::Running]) {
        for (name, signal) in self.states_to_publish(running, crate::rmux::now_secs()) {
            crate::rmux::set_state(&name, signal);
        }
    }

    /// Which sessions are out of date and what to say about them โ€” the half of
    /// [`Self::publish_states`] with the judgement in it, split out so it can be
    /// tested without a daemon to write to.
    pub(super) fn states_to_publish(
        &self,
        running: &[crate::rmux::Running],
        now: u64,
    ) -> Vec<(String, crate::hook::Signal)> {
        if self.hooked.is_empty() {
            return Vec::new();
        }
        running
            .iter()
            .filter_map(|agent| {
                let signal = agent.pid.and_then(|pid| self.reported_by(pid))?;
                let recorded = agent
                    .state
                    .filter(|state| state.is_current(now))
                    .map(|state| state.signal);
                (recorded != Some(signal)).then(|| (agent.name.clone(), signal))
            })
            .collect()
    }

    /// Note that you have just typed into the terminal of the agent running as
    /// `pid`, so it is no longer waiting on you.
    ///
    /// The hooks cannot report this themselves. A permission prompt's answer
    /// produces no event of its own โ€” the next thing Claude Code says is
    /// `PostToolUse`, once the tool it just unblocked has *finished*, which for
    /// a long command is a minute of a tab blinking at you about a question you
    /// already answered.
    ///
    /// Only an existing report is overwritten. Inserting one for an agent
    /// without hooks would shadow the transcript, which is that agent's only
    /// source of state and the thing that would otherwise correct this.
    ///
    /// A tool call in flight is overwritten too, even though it is a working
    /// state: [`Signal::Acting`](crate::hook::Signal::Acting) plus a still
    /// screen is how a held permission prompt is recognised, and the keystroke
    /// that answered it is the only sign the prompt is gone.
    pub(super) fn mark_answered(&mut self, pid: u32) {
        let answered: Vec<String> = self
            .sessions
            .iter()
            .filter(|session| session.root_pid() == Some(pid))
            .map(|session| session.session_id.clone())
            .collect();
        for id in answered {
            if let Some(reported) = self.hooked.get_mut(&id)
                && reported.signal.awaits_you()
            {
                reported.signal = crate::hook::Signal::Busy;
            }
        }
    }

    /// Whether any hidden tab is explicitly waiting for input and should blink.
    pub fn any_attention(&self) -> bool {
        (1..=self.tabs.len()).any(|i| self.tab_attention(i) == Some(tabs::Attention::NeedsInput))
    }

    /// Which half of the blink cycle we are in. The pulse's fallback, for the
    /// tabs whose colours cannot be eased between โ€” see [`effects`].
    pub fn blink_on(&self) -> bool {
        (self.started.elapsed().as_millis() / BLINK_MS).is_multiple_of(2)
    }

    /// Where the needs-you pulse is, `0.0` at rest to `1.0` at its alert tone.
    /// On the same clock as the blink, so every tab asking pulses in step.
    pub fn pulse_level(&self) -> f32 {
        effects::pulse_level(self.started.elapsed())
    }

    /// How long ago tab `index` (in [`App::tab`]'s numbering) was restarted,
    /// while its sweep is still running.
    pub fn restart_flash(&self, index: usize) -> Option<Duration> {
        let tab = self.tabs.get(index.checked_sub(1)?)?;
        let since = tab.restarted?.elapsed();
        (since < effects::FLASH && !theme::no_color()).then_some(since)
    }

    /// Whether anything in the tab bar is moving, and the loop should be
    /// producing frames rather than waiting on input.
    ///
    /// Without colour there is nothing to ease: the pulse is the blink again,
    /// which asks for its own frames on the half-cycle it flips, and a restart
    /// is said by the status line alone.
    pub fn animating(&self) -> bool {
        (1..=self.tabs.len()).any(|i| self.restart_flash(i).is_some())
            || (!theme::no_color() && self.any_attention())
    }

    /// What a still-running agent in the launcher is doing, if it has said.
    ///
    /// This is the whole reason the offer carries a pid. A list of rmux session
    /// names says which agents exist; this says which one is stuck on a question
    /// and which finished ten minutes ago, from the same hooks the dashboard
    /// reads โ€” so choosing which to go back to is a decision rather than a guess.
    pub fn waiting_state(&self, agent: &crate::rmux::Running) -> Option<crate::hook::Signal> {
        self.pane_signal(agent.pid?)
    }

    /// What to call a still-running agent, when cctop can do better than its
    /// rmux session name.
    ///
    /// That name is an identity and not something written to be read: a resumed
    /// session's carries the whole session id, so it comes out as a timestamp
    /// and a uuid that no two rows differ in until well past the width of the
    /// column. The agent's pid finds its row, and the row already knows what the
    /// dashboard calls it โ€” which is the name the user recognises.
    pub fn waiting_label(&self, agent: &crate::rmux::Running) -> Option<String> {
        let pid = agent.pid?;
        self.sessions
            .iter()
            .find(|session| session.root_pid() == Some(pid))
            .map(|session| session.display_label().to_string())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// One hook event for session `a`, from `agent` when it is a subagent's.
    fn heard(signal: crate::hook::Signal, agent: Option<&str>) -> crate::hook::Event {
        crate::hook::Event {
            session_id: "a".into(),
            pids: Vec::new(),
            reported: crate::hook::Reported {
                signal,
                cwd: "/w/proj".into(),
                permission: None,
                at: std::time::Instant::now(),
                provisional: false,
            },
            finished_agent: None,
            agent: agent.map(str::to_string),
        }
    }

    /// The bug: two subagents running side by side, one stopped on a
    /// permission prompt โ€” and the other's next tool call overwrote the
    /// question, so the parent's tab stopped asking while the prompt was still
    /// up. The question stands until the subagent that asked it moves on.
    #[test]
    fn a_subagents_question_outlives_what_its_sibling_does_next() {
        use crate::hook::Signal::{Acting, Busy, Idle, NeedsInput};
        let mut app = test_app();
        let now = |app: &App| app.hooked.get("a").map(|r| r.signal);

        app.apply_hooks(vec![heard(NeedsInput, Some("sub-1"))]);
        app.apply_hooks(vec![heard(Acting, Some("sub-2"))]);
        assert_eq!(
            now(&app),
            Some(NeedsInput),
            "a sibling's tool call hid the question"
        );
        app.apply_hooks(vec![heard(Busy, None)]);
        assert_eq!(
            now(&app),
            Some(NeedsInput),
            "the parent's own work hid the question"
        );

        // Answered: the subagent that asked runs its tool.
        app.apply_hooks(vec![heard(Busy, Some("sub-1"))]);
        assert_eq!(now(&app), Some(Busy));

        // Dismissed with Esc, which sends nothing from the subagent: the
        // parent's turn ending is what closes it.
        app.apply_hooks(vec![heard(NeedsInput, Some("sub-1"))]);
        app.apply_hooks(vec![heard(Idle, None)]);
        assert_eq!(now(&app), Some(Idle), "a dismissed question stayed up");
        assert!(!app.asking_agents.contains_key("a"));
    }
    use crate::ui::tests::{session, test_app};
    /// What gets written onto a session, and โ€” mostly โ€” what does not.
    ///
    /// The sweep runs every [`SHARE_EVERY`] and a turn is largely the same
    /// signal repeated, so "the session already says this" has to be the common
    /// answer. Each write is a process spawn and a round trip to the daemon;
    /// doing one per sweep per tab would make the tab bar pay for the feature.
    #[test]
    fn a_session_is_only_written_to_when_it_is_out_of_date() {
        let agent = |state| crate::rmux::Running {
            name: "cctop-a".into(),
            pid: Some(4321),
            cwd: None,
            attached: false,
            activity: None,
            label: None,
            profile: None,
            order: None,
            state,
            color: None,
        };
        let now = 1_700_000_000;
        let recorded = |signal, ago: u64| {
            Some(crate::rmux::State {
                signal,
                at: now - ago,
            })
        };

        let mut app = test_app();
        let mut row = session("a", true, "proj");
        row.process.as_mut().unwrap().process_list = vec![crate::proc::ProcEntry {
            pid: 4321,
            is_root: true,
            ghost: false,
            cpu: 0.0,
            memory: 0,
            args: String::new(),
        }];
        app.sessions = vec![row];

        // Nothing heard yet: nothing to say, whatever the session claims.
        assert!(app.states_to_publish(&[agent(None)], now).is_empty());

        app.apply_hooks(vec![crate::hook::Event {
            session_id: "a".into(),
            pids: Vec::new(),
            reported: crate::hook::Reported {
                signal: crate::hook::Signal::NeedsInput,
                cwd: "/w/proj".into(),
                permission: None,
                at: std::time::Instant::now(),
                provisional: false,
            },
            finished_agent: None,
            agent: None,
        }]);

        assert_eq!(
            app.states_to_publish(&[agent(None)], now),
            vec![("cctop-a".to_string(), crate::hook::Signal::NeedsInput)],
            "a session saying nothing is told"
        );
        assert!(
            app.states_to_publish(&[agent(recorded(crate::hook::Signal::NeedsInput, 30))], now)
                .is_empty(),
            "a session already saying it is left alone"
        );
        assert_eq!(
            app.states_to_publish(&[agent(recorded(crate::hook::Signal::Busy, 30))], now)
                .len(),
            1,
            "a session saying something else is corrected"
        );
        // A row whose pid nothing has reported for is not published from
        // somebody else's report.
        assert!(
            app.states_to_publish(
                &[crate::rmux::Running {
                    pid: Some(9999),
                    ..agent(None)
                }],
                now
            )
            .is_empty()
        );

        // An expired record reads as saying nothing, so a claim this cctop
        // still believes is rewritten rather than left to lapse under it. This
        // is the one case where the session and the report agree and a write
        // happens anyway โ€” without it, a long quiet turn would go dark at
        // fifteen minutes for every cctop but this one.
        app.apply_hooks(vec![crate::hook::Event {
            session_id: "a".into(),
            pids: Vec::new(),
            reported: crate::hook::Reported {
                signal: crate::hook::Signal::Busy,
                cwd: "/w/proj".into(),
                permission: None,
                at: std::time::Instant::now(),
                provisional: false,
            },
            finished_agent: None,
            agent: None,
        }]);
        assert!(
            app.states_to_publish(&[agent(recorded(crate::hook::Signal::Busy, 30))], now)
                .is_empty(),
            "a fresh agreement needs no write"
        );
        assert_eq!(
            app.states_to_publish(
                &[agent(recorded(crate::hook::Signal::Busy, 3 * 3_600))],
                now
            )
            .len(),
            1,
            "an agreement old enough to have lapsed is renewed"
        );
    }

    /// A permission prompt leaves no trace in a transcript โ€” the newest record
    /// is a tool call in flight, which reads as ordinary work โ€” so before the
    /// hooks reached the row, an agent stopped dead waiting for you was drawn
    /// exactly like an agent that was busy, and a finished turn was drawn like
    /// both. Only the report can tell the three apart.
    #[test]
    fn a_row_learns_from_its_hooks_what_a_transcript_cannot_say() {
        let event = |signal| crate::hook::Event {
            session_id: "a".into(),
            pids: Vec::new(),
            reported: crate::hook::Reported {
                provisional: false,
                signal,
                cwd: "/w/proj".into(),
                permission: None,
                at: std::time::Instant::now(),
            },
            finished_agent: None,
            agent: None,
        };
        let mut app = test_app();
        app.sessions = vec![session("a", true, "proj")];
        // What the walk left behind: a tool call in flight.
        app.sessions[0].activity_state = crate::session::ActivityState::Working;

        app.apply_hooks(vec![event(crate::hook::Signal::NeedsInput)]);
        assert_eq!(
            app.sessions[0].activity_state,
            crate::session::ActivityState::Asking
        );

        app.apply_hooks(vec![event(crate::hook::Signal::Idle)]);
        assert_eq!(
            app.sessions[0].activity_state,
            crate::session::ActivityState::WaitingForInput,
            "a finished turn is the quieter of the two waits"
        );

        // A working report leaves the row alone rather than overwriting it: the
        // transcript reads work correctly and is the only one of the two that
        // can see an API error.
        app.sessions[0].activity_state = crate::session::ActivityState::ApiError;
        app.apply_hooks(vec![event(crate::hook::Signal::Busy)]);
        assert_eq!(
            app.sessions[0].activity_state,
            crate::session::ActivityState::ApiError
        );
    }

    /// The whole way from bytes on a pane to a verdict: a Claude tab whose
    /// footer holds a prompt reads as asking, but only with the setting on; the
    /// same words are a turn in flight in Gemini; and a shell is not read.
    #[test]
    fn a_tab_is_read_off_its_screen_when_asked() {
        use super::tabs::{Pane, Tab};
        use crate::hook::Signal;
        let footer = " Do you want to proceed?\r\n \u{276f} 1. Yes\r\n\r\n Esc to cancel \u{b7} Tab to amend";
        let tab = |label: &str, text: &str| {
            let mut pane = Pane::for_test(label);
            pane.view.parser.process(text.as_bytes());
            Tab::new(pane)
        };
        let mut app = test_app();
        app.tabs = vec![tab("claude", footer)];
        assert!(!app.read_screens(), "off unless the file says so");
        assert!(app.screen_read.is_empty());

        app.settings.read_screen = Some(true);
        assert!(app.read_screens(), "a new verdict is a change");
        assert_eq!(app.screen_read.get(&4321), Some(&Signal::NeedsInput));
        assert_eq!(app.pane_signal(4321), Some(Signal::NeedsInput));
        assert!(!app.read_screens(), "the same verdict twice is not");

        app.tabs = vec![tab("gemini", " \u{280f} Reading files (esc to cancel, 3s)")];
        assert!(app.read_screens());
        assert_eq!(
            app.screen_read.get(&4321),
            Some(&Signal::Busy),
            "Gemini's working hint"
        );

        app.tabs = vec![tab("zsh", footer)];
        assert!(app.read_screens());
        assert!(app.screen_read.is_empty(), "a shell has no footer to read");
    }

    /// With the screen read, what it shows outranks what the hook last said โ€”
    /// in both directions โ€” and a screen with nothing recognisable on it
    /// leaves the hook's word standing.
    #[test]
    fn the_screen_outranks_a_stale_report() {
        use crate::hook::Signal;
        use crate::session::ActivityState;
        let mut app = test_app();
        let mut row = session("a", true, "proj");
        row.process.as_mut().unwrap().process_list = vec![crate::proc::ProcEntry {
            pid: 4321,
            is_root: true,
            ghost: false,
            cpu: 0.0,
            memory: 0,
            args: String::new(),
        }];
        app.sessions = vec![row];
        app.apply_hooks(vec![crate::hook::Event {
            session_id: "a".into(),
            pids: Vec::new(),
            reported: crate::hook::Reported {
                signal: Signal::Idle,
                cwd: "/w/proj".into(),
                permission: None,
                at: std::time::Instant::now(),
                provisional: false,
            },
            finished_agent: None,
            agent: None,
        }]);
        app.apply_reports();
        assert_eq!(
            app.sessions[0].activity_state,
            ActivityState::WaitingForInput
        );

        // A permission prompt the hook has not announced yet.
        app.screen_read.insert(4321, Signal::NeedsInput);
        app.apply_reports();
        assert_eq!(app.sessions[0].activity_state, ActivityState::Asking);
        assert_eq!(app.pane_signal(4321), Some(Signal::NeedsInput));

        // Answered, and back to work: the waiting state goes with it.
        app.screen_read.insert(4321, Signal::Busy);
        app.apply_reports();
        assert_eq!(app.sessions[0].activity_state, ActivityState::Working);

        // Nothing on screen to read: the hook's word again.
        app.screen_read.clear();
        app.apply_reports();
        assert_eq!(
            app.sessions[0].activity_state,
            ActivityState::WaitingForInput
        );
        assert_eq!(app.pane_signal(4321), Some(Signal::Idle));
    }

    /// The mode is reported by a live agent but drawn on a row rebuilt by every
    /// walk, so the two have to survive arriving in either order.
    #[test]
    fn the_permission_mode_survives_the_rows_being_rebuilt() {
        let reported = |mode: Option<crate::hook::Permission>| crate::hook::Event {
            session_id: "a".into(),
            pids: Vec::new(),
            reported: crate::hook::Reported {
                provisional: false,
                signal: crate::hook::Signal::Busy,
                cwd: "/w/proj".into(),
                permission: mode,
                at: std::time::Instant::now(),
            },
            finished_agent: None,
            agent: None,
        };
        let mut app = test_app();

        // Reported before the row exists, which is the ordinary order: a
        // `SessionStart` beats the walk that discovers its transcript.
        app.apply_hooks(vec![reported(Some(crate::hook::Permission::Bypass))]);
        app.sessions = vec![session("a", true, "proj")];
        assert_eq!(app.sessions[0].permission, None, "not stamped yet");

        app.apply_reports();
        assert_eq!(
            app.sessions[0].permission,
            Some(crate::hook::Permission::Bypass),
            "a row discovered after the report still picks it up"
        );

        // An event that says nothing about the mode must not erase it: the
        // setting has not changed just because one event was quiet.
        app.apply_hooks(vec![reported(None)]);
        assert_eq!(
            app.sessions[0].permission,
            Some(crate::hook::Permission::Bypass)
        );

        // A real change is followed.
        app.apply_hooks(vec![reported(Some(crate::hook::Permission::Plan))]);
        assert_eq!(
            app.sessions[0].permission,
            Some(crate::hook::Permission::Plan)
        );
    }

    /// A reported state is kept until the session says it is over, and the
    /// events that change *which sessions exist* ask for a rescan while the
    /// ones that only change a state do not.
    #[test]
    fn a_reported_state_is_kept_until_the_session_ends() {
        let event = |id: &str, signal: crate::hook::Signal| crate::hook::Event {
            session_id: id.into(),
            pids: Vec::new(),
            reported: crate::hook::Reported {
                provisional: false,
                signal,
                cwd: "/w/proj".into(),
                permission: None,
                at: std::time::Instant::now(),
            },
            // This test is about the session's own state; subagent events are
            // covered where subagents are.
            finished_agent: None,
            agent: None,
        };
        let mut app = test_app();

        // Nothing arriving is not "nothing is happening": an absent entry means
        // fall back to the transcript, so it must stay absent.
        assert_eq!(app.apply_hooks(Vec::new()), (false, false));
        assert!(app.hooked_signal("a").is_none());

        // A start is a row to go and find now.
        assert_eq!(
            app.apply_hooks(vec![event("a", crate::hook::Signal::Started)]),
            (true, true)
        );
        // Ordinary state changes are not worth a rescan of the disk.
        assert_eq!(
            app.apply_hooks(vec![
                event("a", crate::hook::Signal::Busy),
                event("a", crate::hook::Signal::Idle),
            ]),
            (true, false)
        );
        assert_eq!(app.hooked_signal("a"), Some(crate::hook::Signal::Idle));
        assert_eq!(app.reporting(), vec![("proj".to_string(), "idle")]);

        // And an ended session is forgotten rather than left claiming its last
        // state forever โ€” which is also a rescan, since the row is going.
        assert_eq!(
            app.apply_hooks(vec![event("a", crate::hook::Signal::Ended)]),
            (true, true)
        );
        assert!(app.hooked_signal("a").is_none());
        assert!(app.reporting().is_empty());
    }

    /// A session that was killed, interrupted, or had its terminal closed sends
    /// no event saying so โ€” the tool never comes back, the turn never ends โ€” and
    /// a claim to be working is the one thing that cannot quietly stay true.
    ///
    /// Regression. Before this, whatever a session last said it was doing was
    /// believed for as long as cctop ran: a tab whose agent had been dead for an
    /// hour was still drawn as busy, and a tool call cut off mid-flight still
    /// read as a permission prompt waiting for an answer.
    #[test]
    fn a_working_claim_nothing_confirms_is_dropped() {
        let stale = |id: &str, signal: crate::hook::Signal| crate::hook::Event {
            session_id: id.into(),
            pids: Vec::new(),
            reported: crate::hook::Reported {
                provisional: false,
                signal,
                cwd: "/w/proj".into(),
                permission: None,
                at: std::time::Instant::now() - std::time::Duration::from_secs(60 * 60),
            },
            finished_agent: None,
            agent: None,
        };
        let mut app = test_app();

        // An hour-old tool call in flight: the tool is not coming back, and
        // reading it as a held question is how a dead tab keeps blinking.
        app.apply_hooks(vec![stale("gone", crate::hook::Signal::Acting)]);
        assert!(app.hooked_signal("gone").is_none());
        assert!(
            app.reporting().is_empty(),
            "the panel listed a state nothing was in"
        );

        // A question that old is still a question: it is waiting on a person,
        // and people take longer than an hour.
        app.apply_hooks(vec![stale("asking", crate::hook::Signal::NeedsInput)]);
        assert_eq!(
            app.hooked_signal("asking"),
            Some(crate::hook::Signal::NeedsInput)
        );
    }

    /// Gemini CLI is the one harness whose rows are not named after the id it
    /// reports: a chat file is named after the first eight characters of the
    /// session id, and that filename is the row's identity because resuming
    /// reuses the id across disjoint files. Without the loose match every Gemini
    /// event would land on no row at all.
    #[test]
    fn a_gemini_event_finds_the_chat_file_it_belongs_to() {
        let mut app = test_app();
        app.apply_hooks(vec![crate::hook::Event {
            session_id: "79709c93-1111-4111-8111-111111111111".into(),
            pids: Vec::new(),
            reported: crate::hook::Reported {
                provisional: false,
                signal: crate::hook::Signal::Idle,
                cwd: "/w/proj".into(),
                permission: None,
                at: std::time::Instant::now(),
            },
            finished_agent: None,
            agent: None,
        }]);

        assert_eq!(
            app.hooked_signal("session-2026-05-14T17-34-79709c93"),
            Some(crate::hook::Signal::Idle)
        );
        // And only that one: a stem whose tail belongs to another session, or an
        // id that is not shaped like Gemini's at all, must not borrow it.
        assert!(
            app.hooked_signal("session-2026-05-14T17-34-deadbeef")
                .is_none()
        );
        assert!(app.hooked_signal("79709c93").is_none());
        assert_eq!(
            gemini_id_tail("session-2026-05-14T17-34-79709c93"),
            Some("79709c93")
        );
        assert_eq!(gemini_id_tail("019fda22-5315-7580-84de-033e4f6835b5"), None);
    }

    /// Answering a prompt in a pane stops the tab asking about it, without
    /// waiting for a hook that only fires once the unblocked tool has finished.
    #[test]
    fn typing_into_a_pane_settles_the_question_it_answers() {
        let mut app = test_app();
        let mut session = session("a", true, "proj");
        session.process.as_mut().unwrap().process_list = vec![crate::proc::ProcEntry {
            pid: 7,
            is_root: true,
            ghost: false,
            cpu: 0.0,
            memory: 0,
            args: String::new(),
        }];
        app.sessions = vec![session];

        // An agent with no hooks has only its transcript to speak for it, and
        // fabricating a report here would shadow it for the rest of the session.
        app.mark_answered(7);
        assert!(app.hooked_signal("a").is_none());

        app.apply_hooks(vec![crate::hook::Event {
            session_id: "a".into(),
            pids: Vec::new(),
            reported: crate::hook::Reported {
                provisional: false,
                signal: crate::hook::Signal::NeedsInput,
                cwd: "/w/proj".into(),
                permission: None,
                at: std::time::Instant::now(),
            },
            finished_agent: None,
            agent: None,
        }]);
        assert_eq!(
            app.hooked_signal("a"),
            Some(crate::hook::Signal::NeedsInput)
        );

        // The keystroke is the answer, so the agent is working again.
        app.mark_answered(7);
        assert_eq!(app.hooked_signal("a"), Some(crate::hook::Signal::Busy));

        // A different agent's keys settle nothing here.
        app.apply_hooks(vec![crate::hook::Event {
            session_id: "a".into(),
            pids: Vec::new(),
            reported: crate::hook::Reported {
                provisional: false,
                signal: crate::hook::Signal::NeedsInput,
                cwd: "/w/proj".into(),
                permission: None,
                at: std::time::Instant::now(),
            },
            finished_agent: None,
            agent: None,
        }]);
        app.mark_answered(8);
        assert_eq!(
            app.hooked_signal("a"),
            Some(crate::hook::Signal::NeedsInput)
        );
    }

    /// A permission prompt is not put in front of anyone until auto mode has
    /// had its few seconds to answer it.
    ///
    /// Claude Code's auto mode asks a model whether to allow a tool call, which
    /// takes a moment; the hook fires when the prompt is raised, not when it is
    /// decided. Ringing the bell there means ringing it for every auto-approved
    /// call โ€” the surest way to teach someone to ignore the bell.
    #[test]
    fn a_held_prompt_becomes_news_only_if_nothing_answers_it() {
        use crate::hook::{Event, Reported, Signal};
        use crate::session::ActivityState;

        let raised = |signal: Signal, provisional: bool| Event {
            session_id: "a".to_string(),
            pids: Vec::new(),
            finished_agent: None,
            agent: None,
            reported: Reported {
                signal,
                cwd: String::new(),
                permission: None,
                at: std::time::Instant::now(),
                provisional,
            },
        };

        let mut app = test_app();
        app.sessions = vec![session("a", true, "proj")];

        // The prompt goes up. Nothing on the row says so yet.
        app.apply_hooks(vec![raised(Signal::NeedsInput, true)]);
        assert_eq!(app.sessions[0].activity_state, ActivityState::Working);
        assert_eq!(app.hooked_signal("a"), None, "the prompt was shown at once");

        // Auto mode answers inside the grace: the row never reported it, and
        // the newer event has replaced it, so nothing is left to mature.
        app.apply_hooks(vec![raised(Signal::Busy, false)]);
        assert!(!app.promote_matured_prompts());
        assert_eq!(app.sessions[0].activity_state, ActivityState::Working);

        // A prompt nobody answered. Once its grace runs out it is a person's
        // problem, and no event is coming to say so.
        app.apply_hooks(vec![raised(Signal::NeedsInput, true)]);
        let held = app.hooked.get_mut("a").expect("the report");
        held.at = std::time::Instant::now()
            - (crate::hook::PERMISSION_GRACE + std::time::Duration::from_secs(1));
        assert!(app.promote_matured_prompts(), "the grace never ran out");
        app.apply_reports();
        assert_eq!(app.sessions[0].activity_state, ActivityState::Asking);
        assert_eq!(app.hooked_signal("a"), Some(Signal::NeedsInput));

        // And it is promoted once, not on every pass of the event loop.
        assert!(!app.promote_matured_prompts());
    }

    /// The other half of the bell: hearing it is useless if the row it came
    /// from is somewhere in a list of a dozen.
    #[test]
    fn b_jumps_the_selection_to_the_session_that_rang() {
        let mut app = test_app();
        app.sessions = vec![session("a", true, "/x/a"), session("b", true, "/x/b")];
        app.refilter();
        let target = app.sessions[1].key();
        app.notify.record_for_test(crate::notify::Rang {
            key: target.clone(),
            label: "b".into(),
            reason: crate::notify::Reason::NeedsInput,
            at: Instant::now(),
        });

        app.selected = 0;
        app.jump_to_bell();
        assert_eq!(app.selected_session().map(Session::key), Some(target));

        // Filtered out of the table, the bell has nowhere to land โ€” and says so
        // rather than moving the cursor to an unrelated row.
        app.search = "x/a".into();
        app.refilter();
        app.selected = 0;
        app.jump_to_bell();
        assert_eq!(app.selected, 0);
        assert!(app.status().is_some());
    }

    /// An alert reaches the user as a toast on the refresh that sees the
    /// crossing, and the row keeps its marker after the toast has gone โ€” but
    /// the next refresh, still over, says nothing new.
    #[test]
    fn an_alert_crossing_is_toasted_once_and_marked_while_it_holds() {
        let mut app = test_app();
        app.settings = crate::settings::Settings::parse("[settings]\nalert_cost = 5\n");
        app.sessions = vec![session("a", true, "proj")];
        app.sessions[0].total_cost = Some(1.0);
        app.check_bells();
        assert_eq!(app.toasts.latest(), None);

        app.sessions[0].total_cost = Some(6.0);
        app.check_bells();
        let said = app.toasts.latest().map(str::to_string);
        assert!(
            said.as_deref().is_some_and(|t| t.contains("$6.00")),
            "{said:?}"
        );
        let key = app.sessions[0].key();
        assert_eq!(app.alerts.marker(&key), Some(crate::alert::Kind::Cost));

        app.toasts = toast::Toasts::default();
        app.check_bells();
        assert_eq!(app.toasts.latest(), None, "still over is not news");
        assert_eq!(app.alerts.marker(&key), Some(crate::alert::Kind::Cost));
    }

    /// A session finishing its turn on the same refresh an alert fires is one
    /// moment, and it used to be two bells and two desktop notifications. It
    /// is one now, naming both.
    #[test]
    fn a_crossing_and_an_alert_on_one_refresh_ring_once() {
        let mut app = test_app();
        app.notify.enabled = true;
        app.settings = crate::settings::Settings::parse("[settings]\nalert_cost = 5\n");
        app.sessions = vec![session("a", true, "api"), session("b", true, "web")];
        app.sessions[1].total_cost = Some(1.0);
        app.check_bells();
        app.notify.ring_pending();
        assert!(
            crate::notify::take_rung().is_empty(),
            "nothing has happened"
        );

        app.sessions[0].activity_state = crate::session::ActivityState::WaitingForInput;
        app.sessions[1].total_cost = Some(6.0);
        app.check_bells();
        app.notify.ring_pending();
        let rung = crate::notify::take_rung();
        assert_eq!(rung.len(), 1, "one refresh, one bell: {rung:?}");
        assert!(
            rung[0].starts_with("cctop: ") && rung[0].contains("waiting for input ยท "),
            "{rung:?}"
        );
        assert!(rung[0].contains("$6.00"), "the alert went unsaid: {rung:?}");

        // And the next pass, with nothing new, is silent.
        app.check_bells();
        app.notify.ring_pending();
        assert!(crate::notify::take_rung().is_empty());
    }

    /// The stall alert reads the hooks' last word even once the row has
    /// stopped believing it, and a finished turn is never a stall.
    #[test]
    fn a_stall_reads_the_last_hook_report_however_old() {
        use crate::alert::Hooked;
        use crate::hook::Signal;
        let report = |signal, age| crate::hook::Reported {
            signal,
            cwd: String::new(),
            permission: None,
            at: Instant::now() - std::time::Duration::from_secs(age),
            provisional: false,
        };
        let mut hooked = HashMap::new();
        assert_eq!(stall_view(&hooked, "a"), Hooked::Unknown);
        hooked.insert("a".to_string(), report(Signal::Busy, 3_600));
        assert_eq!(stall_view(&hooked, "a"), Hooked::Working);
        hooked.insert("a".to_string(), report(Signal::Acting, 0));
        assert_eq!(stall_view(&hooked, "a"), Hooked::InFlight);
        hooked.insert("a".to_string(), report(Signal::Idle, 0));
        assert_eq!(stall_view(&hooked, "a"), Hooked::Quiet);
    }
}