rig-tui 0.45.0

A rig-harness plugin: the terminal view, with panels and tool renderers other plugins add to.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
//! The transcript's wrapped rows, kept per message. A frame re-renders and
//! re-wraps only the messages that changed (a message's look also depends
//! on the next message's results and its notices),
//! re-wraps without re-rendering when the width changed (but for a reply
//! with a table, which is fit to the width), and copies out
//! only the rows on screen. Each message keeps where its items are (the
//! message, its calls), so the view can scroll to one, select it and say
//! which is at the top.

use std::collections::{BTreeMap, HashMap, HashSet};
use std::hash::{DefaultHasher, Hash, Hasher};
use std::ops::Range;
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;

use bevy_ecs::prelude::*;
use ratatui::style::{Color, Style, Stylize};
use ratatui::text::Line;
use rig_core::completion::{AssistantContent, Message};
use rig_core::conversation;
use rig_core::error::ErrorReport;
use rig_core::message::{CallId, ToolCall, ToolFunction, ToolName, ToolResult, UserContent};
use rig_core::streaming::{PartKind, StreamEvent, parse_partial_arguments};
use rig_core::tool::ToolResultContext;

use super::markdown;
use super::render::{Lights, light, lit};
use super::renderers::{
    AsideView, CallState, ChildCall, ContentBlock, ContentView, DecoratedMessage, EntryView,
    MessageView, Renderers, Role, ToolCallView, plugin_name, result_style, result_text, text_rows,
};
use super::theme::Theme;
use super::view::{
    DrawnRow, DrawnTranscript, Highlight, ItemRow, MarkIn, RowWrap, ShownNotice, TextMark,
    TranscriptItem,
};
use super::wrap::wrap;
use rig_core::effect::{self, EffectId, EffectKind, EffectRecord};
use rig_ecs::agent::{AgentId, NoticeLevel, Partial};
use rig_ecs::prelude::{Aside, AsideId, Author, AuthorKind, MessageId};
use rig_ecs::stage::{EffectRecorded, Outcome};
use rig_ecs::tools::ToolRequest;
use rig_ecs::turn::{ModelRequest, SentTo, StreamDelta};
use rig_tools::attach::attached_file;

/// An item's rows (or lines) within a part.
pub(crate) type Marks = Vec<(TranscriptItem, Range<usize>)>;

/// What the view knows of the effects that settled, in this run and, once
/// [`PastEffects`] brought them, before it: what each tool call published
/// and how long it ran, by call id; and which calls each effect started,
/// through any effect between, for [`ToolCallView::children`]. All of it
/// comes from the kernel's effect records.
#[derive(Resource, Default)]
pub(crate) struct CallFacts {
    /// This run's effects, noted as they settle.
    run: Settled,
    /// The effects before this run, as [`PastEffects`] brought them.
    past: Arc<Settled>,
    /// Each agent's name by its id, as last named: a record names its
    /// agent by id, and a helper may be gone by the time it is drawn.
    names: HashMap<String, String>,
    /// How many times what it knows changed, so a look tells a change by
    /// this alone.
    changes: u64,
    /// The calls under each tool call of an agent that started any, by the
    /// agent's id, as the settled effects say: worked out when first asked
    /// for after a change, not every frame.
    children: Mutex<HashMap<String, Arc<CallsUnder>>>,
}

/// The calls under each tool call that started any, by its call id.
pub(crate) type CallsUnder = BTreeMap<CallId, Vec<ChildCall>>;

impl CallFacts {
    /// What `call` published and how long it ran, as far as known.
    fn of(&self, call: &CallId) -> (Option<&ToolResultContext>, Option<Duration>) {
        let facts = self.run.facts.get(call);
        let facts = facts.or_else(|| self.past.facts.get(call));
        facts.map_or((None, None), |(facts, took)| (facts.as_ref(), *took))
    }

    /// Notes the effect `record` settled in this run.
    fn note(&mut self, record: &EffectRecord) {
        if self.run.note(record) {
            self.changed();
        }
    }

    /// Takes over the effects before this run; a later batch replaces it.
    fn take_past(&mut self, past: Arc<Settled>) {
        self.past = past;
        self.changed();
    }

    /// Notes that the agent with the id `agent` is called `name`; whether
    /// that is new.
    pub(crate) fn name(&mut self, agent: &str, name: &str) -> bool {
        if self.names.get(agent).is_some_and(|known| known == name) {
            return false;
        }
        self.names.insert(agent.to_owned(), name.to_owned());
        self.changed();
        true
    }

    /// Notes a change: what was worked out from before it is gone.
    fn changed(&mut self) {
        self.changes = self.changes.wrapping_add(1);
        self.children
            .get_mut()
            .unwrap_or_else(PoisonError::into_inner)
            .clear();
    }

    /// The calls under each tool call of the agent with the id `agent`
    /// that started any, as the settled effects and the `live` ones (not
    /// settled) say: each call after the one that started it, in the order
    /// they were made, through any effect between that is no call. What
    /// the settled effects say is worked out once per change; over it, the
    /// tool calls a live effect is under, which change as it runs.
    pub(crate) fn children(&self, live: &CallTree, agent: &str) -> ChildCalls {
        let settled = self.settled_children(agent);
        let trees = [&self.past.calls, &self.run.calls, live];
        // Every live effect, and every effect it is under.
        let mut above = HashSet::new();
        for &effect in live.parents.keys() {
            let mut at = Some(effect);
            while let Some(effect) = at.filter(|&effect| above.insert(effect)) {
                at = trees
                    .iter()
                    .find_map(|tree| tree.parents.get(&effect).copied());
            }
        }
        let mut live = CallsUnder::new();
        for parent in above {
            let starts_any = trees.iter().any(|tree| tree.children.contains_key(&parent));
            match tool_call(&trees, parent) {
                Some((of, call)) if **of == *agent && starts_any && !live.contains_key(call) => {
                    live.insert(call.clone(), self.below(&trees, parent));
                }
                _ => {}
            }
        }
        ChildCalls { settled, live }
    }

    /// What [`Self::children`] works out from the settled effects alone.
    fn settled_children(&self, agent: &str) -> Arc<CallsUnder> {
        let mut known = self.children.lock().unwrap_or_else(PoisonError::into_inner);
        if let Some(found) = known.get(agent) {
            return Arc::clone(found);
        }
        let trees = [&self.past.calls, &self.run.calls];
        let mut found = CallsUnder::new();
        for parent in trees.iter().flat_map(|tree| tree.children.keys()) {
            match tool_call(&trees, *parent) {
                Some((of, call)) if **of == *agent && !found.contains_key(call) => {
                    found.insert(call.clone(), self.below(&trees, *parent));
                }
                _ => {}
            }
        }
        let found = Arc::new(found);
        known.insert(agent.to_owned(), Arc::clone(&found));
        found
    }

    /// The calls under `parent`, as `trees` say.
    fn below(&self, trees: &[&CallTree], parent: EffectId) -> Vec<ChildCall> {
        let mut out = Vec::new();
        self.add_below(trees, parent, 0, &mut HashSet::from([parent]), &mut out);
        out
    }

    /// Adds the calls under `parent`, `depth` below the tool call, to
    /// `out`, each followed by those under it; an effect that is no call
    /// adds those under it at its own depth. `seen` guards against an
    /// effect named as its own ancestor, and an effect two trees hold
    /// counts once.
    fn add_below(
        &self,
        trees: &[&CallTree],
        parent: EffectId,
        depth: usize,
        seen: &mut HashSet<EffectId>,
        out: &mut Vec<ChildCall>,
    ) {
        let children = trees.iter().filter_map(|tree| tree.children.get(&parent));
        let mut children: Vec<&Child> = children.flatten().collect();
        children.sort_by_key(|child| child.id);
        for child in children {
            if !seen.insert(child.id) {
                continue;
            }
            let Some(call) = &child.call else {
                self.add_below(trees, child.id, depth, seen, out);
                continue;
            };
            let name = child
                .agent
                .as_deref()
                .and_then(|agent| self.names.get(agent));
            out.push(ChildCall {
                depth,
                agent: name.cloned().or_else(|| call.agent.clone()),
                ..call.clone()
            });
            self.add_below(trees, child.id, depth + 1, seen, out);
        }
    }
}

/// The agent (by id) and call id of the tool call effect `id` is, as the
/// first of `trees` that knows says.
fn tool_call<'a>(trees: &[&'a CallTree], id: EffectId) -> Option<&'a (Arc<str>, CallId)> {
    trees.iter().find_map(|tree| tree.tool_calls.get(&id))
}

/// The calls under each tool call of an agent that started any, as
/// [`CallFacts::children`] works them out: the settled effects' and, over
/// them, those of the tool calls a live effect is under.
#[derive(Default)]
pub(crate) struct ChildCalls {
    settled: Arc<CallsUnder>,
    live: CallsUnder,
}

impl ChildCalls {
    /// The calls under the tool call `call`, if it started any.
    pub(crate) fn get(&self, call: &CallId) -> Option<&Vec<ChildCall>> {
        self.live.get(call).or_else(|| self.settled.get(call))
    }
}

/// Effects that settled, as the view keeps them: what each tool call
/// published and how long it ran, by call id, and which calls each
/// effect started.
#[derive(Clone, Default)]
pub(crate) struct Settled {
    facts: HashMap<CallId, (Option<ToolResultContext>, Option<Duration>)>,
    calls: CallTree,
    /// The tool calls of each model call's reply that no tool call's
    /// record claimed yet, by the model call: how a record, which names a
    /// call's tool and arguments but not its id, finds which call it is.
    replies: HashMap<EffectId, Vec<ToolCall>>,
}

impl Settled {
    /// Notes the effect `record` settled: under the effect that started
    /// it, as a call or as an effect calls go through; and, for a tool
    /// call, what it published and how long it ran. A record read twice
    /// counts once: whether it is new.
    fn note(&mut self, record: &EffectRecord) -> bool {
        if !self.calls.known.insert(record.id) {
            return false;
        }
        let outcome = record.reviewed.as_ref().unwrap_or(&record.outcome);
        let child = match &record.kind {
            EffectKind::Completion { .. } => {
                let reply = match outcome {
                    Ok(effect::Answered::Completion(reply)) => Some(reply),
                    _ => None,
                };
                let calls = reply.into_iter().flat_map(|reply| &reply.choice);
                let calls: Vec<ToolCall> = calls
                    .filter_map(|content| match content {
                        AssistantContent::ToolCall(call) => Some(call.clone()),
                        _ => None,
                    })
                    .collect();
                if !calls.is_empty() {
                    self.replies.insert(record.id, calls);
                }
                let model = record.key.as_str().strip_prefix("model:");
                let (failed, answer) = answer(Some(outcome), false);
                Some(ChildCall {
                    depth: 0,
                    call: None,
                    name: model.unwrap_or("model").to_owned(),
                    agent: None,
                    state: CallState::Done,
                    failed,
                    answer,
                })
            }
            EffectKind::ToolCall { name: tool, args } => {
                let call = self.claim(record, tool, args);
                if let (Some(call), Some(agent)) = (&call, &record.scope) {
                    self.calls.tool_call(record.id, agent, call.id.clone());
                    let took = record.finished_ms.zip(record.started_ms);
                    let took =
                        took.map(|(end, start)| Duration::from_millis(end.saturating_sub(start)));
                    self.facts
                        .insert(call.id.clone(), (record.published.clone(), took));
                }
                let (failed, answer) = answer(Some(outcome), true);
                Some(ChildCall {
                    depth: 0,
                    call,
                    name: tool.clone(),
                    agent: None,
                    state: CallState::Done,
                    failed,
                    answer,
                })
            }
            _ => None,
        };
        let agent = record.scope.clone();
        self.calls.add(record.parent, record.id, child, agent);
        true
    }

    /// The call of its parent model call's reply a tool call's `record`
    /// is: the first unclaimed one of that tool with these arguments, else
    /// of that tool (a plugin may have changed the arguments); one made
    /// from the record when its reply is not known, such as a call carried
    /// over a restart.
    fn claim(&mut self, record: &EffectRecord, tool: &str, args: &str) -> Option<ToolCall> {
        let parent = record.parent;
        let reply = parent.and_then(|parent| self.replies.get_mut(&parent));
        if let Some(calls) = reply {
            let named = |call: &ToolCall| call.function.name.as_str() == tool;
            let same = calls
                .iter()
                .position(|call| named(call) && call.function.raw_arguments() == args);
            let found = same.or_else(|| calls.iter().position(named));
            let call = found.map(|at| calls.remove(at));
            if calls.is_empty()
                && let Some(parent) = parent
            {
                self.replies.remove(&parent);
            }
            if call.is_some() {
                return call;
            }
        }
        let name = ToolName::new(tool).ok()?;
        let args = serde_json::from_str(args).unwrap_or_default();
        let id = CallId::from_wire(format!("effect-{}", record.id));
        Some(ToolCall::new(id, ToolFunction::new(name, args)))
    }
}

/// Effects by the effect that started them (its `parent`), each with its
/// own effect id and, for a tool or model call, the call; the effect each
/// one was started by; and each tool call's agent (by id) and call id, by
/// its effect.
#[derive(Clone, Default)]
pub(crate) struct CallTree {
    children: HashMap<EffectId, Vec<Child>>,
    parents: HashMap<EffectId, EffectId>,
    tool_calls: HashMap<EffectId, (Arc<str>, CallId)>,
    /// Every effect noted, so none is noted twice.
    known: HashSet<EffectId>,
}

/// An effect under the one that started it.
#[derive(Clone)]
struct Child {
    id: EffectId,
    /// The call it is; `None` when calls only go through it.
    call: Option<ChildCall>,
    /// The id of the agent it is for, whose name is looked up when it is
    /// drawn; `None` when the call names its agent itself.
    agent: Option<Arc<str>>,
}

impl CallTree {
    /// Notes the effect `id` as one `parent` started: `call` when it is a
    /// call, `None` when calls only go through it; for the agent with the
    /// id `agent`, when the call does not name it.
    pub(crate) fn add(
        &mut self,
        parent: Option<EffectId>,
        id: EffectId,
        call: Option<ChildCall>,
        agent: Option<Arc<str>>,
    ) {
        if let Some(parent) = parent {
            self.parents.insert(id, parent);
            let child = Child { id, call, agent };
            self.children.entry(parent).or_default().push(child);
        }
    }

    /// Notes that effect `id` is the tool call `call` of the agent with
    /// the id `agent`.
    pub(crate) fn tool_call(&mut self, id: EffectId, agent: &str, call: CallId) {
        self.tool_calls.insert(id, (Arc::from(agent), call));
    }
}

/// Whether an answer is a failure, and its text: a tool's result
/// (`tool`), else a model's reply, or why it failed; neither before it
/// has one.
pub(crate) fn answer(
    outcome: Option<&Result<effect::Answered, ErrorReport>>,
    tool: bool,
) -> (bool, Option<String>) {
    match (outcome, tool) {
        (None, _) => (false, None),
        (Some(outcome), true) => {
            let result = Outcome(outcome.clone()).tool_result();
            let failed = result.is_error() || result.is_refused();
            (failed, Some(result.output().render()))
        }
        (Some(Err(report)), false) => (true, Some(report.message.clone())),
        (Some(Ok(effect::Answered::Completion(reply))), false) => (false, Some(reply.text())),
        (Some(Ok(_)), false) => (false, None),
    }
}

/// A tool or model call not settled yet as one of
/// [`ToolCallView::children`], standing as `state`, `depth` 0; `None` for
/// any other effect.
pub(crate) fn live_call(
    (request, model, sent): (Option<&ToolRequest>, Option<&ModelRequest>, Option<&SentTo>),
    (agent, outcome): (Option<&Name>, Option<&Outcome>),
    state: CallState,
) -> Option<ChildCall> {
    let connection = sent.map(|SentTo(connection)| connection);
    let connection = connection.or(model.and_then(|model| model.connection.as_ref()));
    let name = match (request, model) {
        (Some(request), _) => request.call.function.name.to_string(),
        (None, Some(_)) => connection.map_or("model".to_owned(), |c| c.spec.reference()),
        (None, None) => return None,
    };
    let (failed, answer) = answer(outcome.map(|Outcome(outcome)| outcome), request.is_some());
    Some(ChildCall {
        depth: 0,
        call: request.map(|request| request.call.clone()),
        name,
        agent: agent.map(|name| name.as_str().to_owned()),
        state,
        failed,
        answer,
    })
}

/// Effects that settled before this run, such as a resumed session's, for
/// [`ToolCallView::children`] and each call's facts: read as the kernel's
/// [`EffectRecorded`] records are. `rig_basics::telemetry` sends the session's
/// effect log once it was restored. [`PastEffects::new`] does all the work
/// per record, so make it where the records are read, off the main thread
/// for a long log: the view only takes it over. A later one replaces it.
#[derive(Message, Clone)]
pub struct PastEffects(Arc<Settled>);

impl PastEffects {
    /// The effects `records` settled, in the order they settled.
    #[must_use]
    pub fn new(records: impl IntoIterator<Item = EffectRecord>) -> Self {
        let mut settled = Settled::default();
        for record in records {
            settled.note(&record);
        }
        Self(Arc::new(settled))
    }

    /// How many effects it holds.
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.calls.known.len()
    }

    /// Whether it holds no effect.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.calls.known.is_empty()
    }
}

/// Notes every effect that settled since the last frame, and takes over
/// those [`PastEffects`] brought.
pub(crate) fn note_effects(
    mut recorded: MessageReader<EffectRecorded>,
    mut past: MessageReader<PastEffects>,
    mut facts: ResMut<CallFacts>,
) {
    if recorded.is_empty() && past.is_empty() {
        return;
    }
    for PastEffects(settled) in past.read() {
        facts.take_past(Arc::clone(settled));
    }
    for EffectRecorded(record) in recorded.read() {
        facts.note(record);
    }
}

/// Notes each agent's name by its id, for the records that name it so.
pub(crate) fn note_agent_name(
    named: On<Insert<Name>>,
    agents: Query<(&AgentId, &Name)>,
    mut facts: ResMut<CallFacts>,
) {
    if let Ok((id, name)) = agents.get(named.entity)
        && facts
            .bypass_change_detection()
            .name(id.0.as_str(), name.as_str())
    {
        facts.set_changed();
    }
}

/// The tool calls a model call streams while its reply does ([`Partial`]
/// requires it), in the order they opened: each with the JSON of its
/// arguments so far, or finished (with none).
#[derive(Component, Default)]
pub(crate) struct StreamingCalls(Vec<(rig_core::streaming::Part, ToolCall, String)>);

impl StreamingCalls {
    /// The calls, in the order they opened, each with its arguments as far
    /// as they came: read once per drawing, not per fragment.
    pub(crate) fn calls(&self) -> impl Iterator<Item = ToolCall> {
        self.0.iter().map(|(_, call, json)| {
            let mut call = call.clone();
            if !json.is_empty() {
                call.function.arguments = parse_partial_arguments(json);
            }
            call
        })
    }
}

/// Follows the tool calls models stream: a call opens with its tool's
/// name, its arguments grow, and it ends with the finished call.
pub(crate) fn follow_streams(
    mut deltas: MessageReader<StreamDelta>,
    mut streams: Query<&mut StreamingCalls, With<Partial>>,
) {
    for delta in deltas.read() {
        let Ok(mut calls) = streams.get_mut(delta.effect) else {
            continue;
        };
        match &delta.event {
            StreamEvent::Start {
                part,
                kind: PartKind::ToolCall,
                name: Some(name),
            } => {
                let id = CallId::from_wire(format!("streaming-{}", part.index()));
                let call = ToolCall::new(id, ToolFunction::new(name.clone(), Default::default()));
                calls.0.push((*part, call, String::new()));
            }
            StreamEvent::Arguments { part, json } => {
                if let Some((.., text)) = calls.0.iter_mut().find(|(at, ..)| at == part) {
                    text.push_str(json);
                }
            }
            StreamEvent::End {
                part,
                content: AssistantContent::ToolCall(done),
            } => {
                if let Some((_, call, text)) = calls.0.iter_mut().find(|(at, ..)| at == part) {
                    *call = done.clone();
                    text.clear();
                }
            }
            _ => {}
        }
    }
}

/// Forgets a model call's streaming calls once its reply is in the
/// conversation, its [`Partial`] gone.
pub(crate) fn forget_streams(gone: On<Remove<Partial>>, mut streams: Query<&mut StreamingCalls>) {
    if let Ok(mut calls) = streams.get_mut(gone.entity) {
        calls.0.clear();
    }
}

/// What the messages' look depends on besides the messages.
pub(crate) struct Look<'a> {
    /// The looks plugins added.
    pub(crate) renderers: &'a Renderers<'a>,
    /// The state of each call of the running turn.
    pub(crate) calls: &'a BTreeMap<CallId, CallState>,
    /// The output so far of each of its running calls that reports it.
    pub(crate) outputs: &'a BTreeMap<CallId, String>,
    /// The notices and notes drawn inside a message, by its index, each
    /// with the content item it goes before.
    pub(crate) inside: HashMap<usize, Vec<(usize, Inside<'a>)>>,
    /// What settled calls published and how long they ran.
    pub(crate) facts: &'a CallFacts,
    /// The transcript's colors.
    pub(crate) theme: &'a Theme,
    /// The calls under each tool call that started any.
    pub(crate) children: &'a ChildCalls,
    /// The labels drawn inside replies' text.
    pub(crate) marks: &'a [TextMark],
}

/// What is drawn inside a message, before one of its items.
#[derive(Clone, Copy)]
pub(crate) enum Inside<'a> {
    /// A notice written there, and its index in the notices shown.
    Notice(usize, &'a ShownNotice),
    /// An aside whose entry was taken out, after the start of what stands
    /// for it.
    Aside(&'a ShownAside<'a>),
}

/// An aside a look draws in the conversation of the shown agent: a
/// plugin's note, or one of a kind with an aside renderer.
pub(crate) struct ShownAside<'a> {
    /// Its id.
    pub(crate) id: AsideId,
    /// The aside.
    pub(crate) aside: &'a Aside,
}

impl ShownAside<'_> {
    /// The aside's item.
    pub(crate) fn item(&self) -> TranscriptItem {
        TranscriptItem::Aside(self.id)
    }

    /// The aside as its renderer sees it, in `theme`'s colors.
    pub(crate) fn view(&self, theme: Theme) -> AsideView<'_> {
        AsideView {
            id: self.id,
            aside: self.aside,
            theme,
        }
    }

    /// Its lines in `theme`'s colors; none for a kind nothing draws.
    pub(crate) fn lines(&self, renderers: &Renderers<'_>, theme: &Theme) -> Vec<Line<'static>> {
        renderers.aside(&self.view(*theme)).unwrap_or_default()
    }
}

impl Look<'_> {
    /// The marks in `text`, each with the span it draws.
    pub(crate) fn marks_in(&self, text: MarkIn) -> Vec<(usize, ratatui::text::Span<'static>)> {
        let marks = self.marks.iter().filter(|mark| mark.r#in == text);
        let span = |mark: &TextMark| ratatui::text::Span::styled(mark.label.clone(), mark.style);
        marks.map(|mark| (mark.at, span(mark))).collect()
    }

    /// The notices and notes inside message `index`.
    fn inside(&self, index: usize) -> &[(usize, Inside<'_>)] {
        self.inside.get(&index).map_or(&[], Vec::as_slice)
    }

    /// Hashes the notices and notes inside message `index`.
    fn hash_inside(&self, index: usize, hasher: &mut DefaultHasher) {
        for (item, inside) in self.inside(index) {
            item.hash(hasher);
            match inside {
                Inside::Notice(at, notice) => {
                    at.hash(hasher);
                    level_code(notice.level).hash(hasher);
                    notice.text.hash(hasher);
                }
                Inside::Aside(shown) => {
                    shown.id.hash(hasher);
                    (&shown.aside.kind, plugin_name(&shown.aside.author)).hash(hasher);
                    serde_json::to_vec(&shown.aside.value)
                        .unwrap_or_default()
                        .hash(hasher);
                }
            }
        }
    }

    /// Where the call `call` stands: as its effect says while it has one,
    /// else done once it has `result`.
    fn state(&self, call: &CallId, result: Option<&ToolResult>) -> CallState {
        match self.calls.get(call) {
            Some(state) => state.clone(),
            None if result.is_some() => CallState::Done,
            None => CallState::Running(None),
        }
    }

    /// A hash of what message `index` (with `id`) looks like besides its
    /// messages: its notices and its calls' states, output so far and
    /// running times.
    fn hash_message(&self, (index, id): (usize, Option<MessageId>), message: &Message) -> u64 {
        let hasher = &mut DefaultHasher::new();
        self.hash_inside(index, hasher);
        let marks = self.marks.iter();
        marks
            .filter(|mark| matches!(mark.r#in, MarkIn::Message { id: of, .. } if Some(of) == id))
            .for_each(|mark| mark.hash(hasher));
        if let Message::Assistant(assistant) = message {
            for item in assistant.content.iter() {
                if let AssistantContent::ToolCall(call) = item {
                    self.calls.get(&call.id).hash(hasher);
                    self.outputs.get(&call.id).hash(hasher);
                    self.facts.of(&call.id).1.hash(hasher);
                    hash_children(self.children.get(&call.id), hasher);
                }
            }
        }
        hasher.finish()
    }

    /// A hash of all of it but the renderers, whose changes
    /// [`Transcript::clear`] handles.
    fn digest(&self) -> u64 {
        let mut hasher = DefaultHasher::new();
        let mut indices: Vec<&usize> = self.inside.keys().collect();
        indices.sort();
        for index in indices {
            index.hash(&mut hasher);
            self.hash_inside(*index, &mut hasher);
        }
        self.calls.hash(&mut hasher);
        self.outputs.hash(&mut hasher);
        self.marks.hash(&mut hasher);
        self.theme.hash(&mut hasher);
        // The settled calls' facts and children change only with it.
        self.facts.changes.hash(&mut hasher);
        for (call, children) in &self.children.live {
            call.hash(&mut hasher);
            hash_children(Some(children), &mut hasher);
        }
        hasher.finish()
    }
}

/// Hashes what a call's renderer draws of `children`.
fn hash_children(children: Option<&Vec<ChildCall>>, hasher: &mut DefaultHasher) {
    for child in children.into_iter().flatten() {
        (child.depth, &child.name, &child.agent, &child.state).hash(hasher);
        (child.failed, &child.answer).hash(hasher);
        child.call.as_ref().map(|call| &call.id).hash(hasher);
    }
}

/// A number for each notice level.
fn level_code(level: NoticeLevel) -> u8 {
    match level {
        NoticeLevel::Info => 0,
        NoticeLevel::Warn => 1,
        NoticeLevel::Error => 2,
    }
}

/// One message's look: its lines and where its items are in them, and
/// those lines wrapped to the width.
struct Cached {
    /// The message as it was laid out.
    message: Arc<Message>,
    /// [`Look::hash_message`] of it then.
    look: u64,
    lines: Vec<Line<'static>>,
    line_marks: Marks,
    wrapped: Wrapped,
    /// Whether its lines depend on the width, as a reply's table does, so
    /// a new width renders it again rather than only wrapping it.
    fitted: bool,
}

/// Lines wrapped to a width: the rows, whether each continues the row
/// before it (a line wrapped), and where the items are in the rows.
#[derive(Default)]
pub(crate) struct Wrapped {
    rows: Vec<Line<'static>>,
    continues: Vec<Option<RowWrap>>,
    marks: Marks,
}

/// The wrapped rows of the shown agent's messages.
#[derive(Default)]
pub(crate) struct Transcript {
    agent: Option<Entity>,
    width: u16,
    /// The [`Look::digest`] the rows were made with.
    look: u64,
    messages: Vec<Cached>,
}

/// A part of the transcript, in order: a message's cached rows, or rows
/// made for this frame (notices, a note, the reply streaming in), with
/// where the items among them are.
pub(crate) enum Part {
    Message(usize),
    Rows(Wrapped),
}

impl Part {
    /// `lines`, with the items `marks` says are in them, wrapped to
    /// `width`.
    pub(crate) fn rows(
        lines: &[Line<'static>],
        marks: &[(TranscriptItem, Range<usize>)],
        width: usize,
    ) -> Self {
        Self::Rows(wrap_marked(lines, marks, width))
    }
}

/// The rows of the transcript on screen, and where it is.
pub(crate) struct Visible {
    /// The rows shown.
    pub(crate) rows: Vec<Line<'static>>,
    /// What is below them.
    pub(crate) below: Below,
    /// The first one's row in the whole transcript.
    pub(crate) first: usize,
    /// The item at the top and the row of it there, while the view is
    /// scrolled up.
    pub(crate) top: Option<(TranscriptItem, usize)>,
}

impl Transcript {
    /// Brings the rows up to date with the conversation of `agent` and
    /// `look` at `width`.
    /// `changed` says whether the messages may have changed since the last
    /// call; when neither they nor the look did, only a new agent or width
    /// costs anything.
    pub(crate) fn update(
        &mut self,
        agent: Entity,
        conversation: &conversation::Conversation,
        changed: bool,
        look: &Look<'_>,
        width: u16,
    ) {
        if self.agent != Some(agent) {
            self.agent = Some(agent);
            self.messages.clear();
        }
        let usable = usize::from(width.max(1));
        let resized = self.width != width;
        if resized {
            self.width = width;
            for cached in &mut self.messages {
                cached.wrapped = wrap_marked(&cached.lines, &cached.line_marks, usable);
            }
        }
        let refit = resized && self.messages.iter().any(|cached| cached.fitted);
        let messages = conversation.messages();
        let digest = look.digest();
        let looks_alike = std::mem::replace(&mut self.look, digest) == digest;
        if !changed && !refit && looks_alike && self.messages.len() == messages.len() {
            return;
        }
        // A message's look depends on it and its neighbours, so each is
        // compared once with the one laid out last time, before any is
        // replaced; a message past either end matches only another.
        let same: Vec<bool> = (0..=messages.len())
            .map(|at| match (self.messages.get(at), messages.get(at)) {
                (Some(cached), Some(message)) => Arc::ptr_eq(&cached.message, message),
                (cached, message) => cached.is_none() && message.is_none(),
            })
            .collect();
        self.messages.truncate(messages.len());
        for (index, message) in messages.iter().enumerate() {
            let previous = index.checked_sub(1).and_then(|before| messages.get(before));
            let (previous, next) = (
                previous.map(|m| &**m),
                messages.get(index + 1).map(|m| &**m),
            );
            let look_hash = look.hash_message((index, conversation.id(index)), message);
            if self
                .messages
                .get(index)
                .is_some_and(|cached| cached.look == look_hash && !(resized && cached.fitted))
                && (index.saturating_sub(1)..=index + 1).all(|at| same.get(at) == Some(&true))
            {
                continue;
            }
            let (lines, line_marks) = message_lines(
                message,
                (conversation, index),
                (previous, next),
                (look, usable),
            );
            let wrapped = wrap_marked(&lines, &line_marks, usable);
            let cached = Cached {
                message: message.clone(),
                look: look_hash,
                lines,
                line_marks,
                wrapped,
                fitted: fitted(message),
            };
            match self.messages.get_mut(index) {
                Some(slot) => *slot = cached,
                None => self.messages.push(cached),
            }
        }
    }

    /// Drops every cached row, after the renderers changed.
    pub(crate) fn clear(&mut self) {
        self.messages.clear();
    }

    /// A part's wrapped rows; `None` for a message not cached.
    fn wrapped<'a>(&'a self, part: &'a Part) -> Option<&'a Wrapped> {
        match part {
            Part::Message(index) => self.messages.get(*index).map(|cached| &cached.wrapped),
            Part::Rows(wrapped) => Some(wrapped),
        }
    }

    /// A part's rows.
    fn rows<'a>(&'a self, part: &'a Part) -> &'a [Line<'static>] {
        let wrapped = self.wrapped(part);
        wrapped
            .map(|wrapped| wrapped.rows.as_slice())
            .unwrap_or_default()
    }

    /// Where a part's items are in its rows.
    fn marks<'a>(&'a self, part: &'a Part) -> &'a [(TranscriptItem, Range<usize>)] {
        let wrapped = self.wrapped(part);
        wrapped
            .map(|wrapped| wrapped.marks.as_slice())
            .unwrap_or_default()
    }

    /// Every item's rows in the whole transcript `parts` make, top to
    /// bottom; a call's are within its message's.
    pub(crate) fn marks_in<'a>(
        &'a self,
        parts: &'a [Part],
    ) -> impl Iterator<Item = (&'a TranscriptItem, Range<usize>)> + 'a {
        let mut start = 0;
        parts.iter().flat_map(move |part| {
            let at = start;
            start += self.rows(part).len();
            let marks = self.marks(part).iter();
            marks.map(move |(item, rows)| (item, rows.start + at..rows.end + at))
        })
    }

    /// The rows of `item` in the transcript `parts` make.
    pub(crate) fn rows_of(&self, parts: &[Part], item: &TranscriptItem) -> Option<Range<usize>> {
        let mut marks = self.marks_in(parts);
        marks
            .find(|(marked, _)| *marked == item)
            .map(|(_, rows)| rows)
    }

    /// The rows of `parts` that fit `height` rows at `width`, where
    /// `scroll` places them, what is below them, and where the items are.
    /// A jump to an item's match counts the matches of `highlights`.
    pub(crate) fn visible(
        &self,
        parts: &[Part],
        (width, height): (u16, usize),
        scroll: &mut Scroll,
        highlights: &[Highlight],
    ) -> Visible {
        let counts: Vec<usize> = parts.iter().map(|part| self.rows(part).len()).collect();
        let lights = self.lights(parts, highlights);
        scroll.find(|item| self.rows_of(parts, item));
        let (mut top, mut below) = scroll.place(&counts, height, width);
        if let Some((item, to)) = scroll.jump.take() {
            let row = self.rows_of(parts, &item).map(|rows| {
                let lit = match to {
                    ItemRow::Lit(n) => self.lit_row(parts, &rows, &lights, n),
                    ItemRow::Top(_) | ItemRow::Reveal => None,
                };
                lit.unwrap_or(rows.start)
            });
            if let Some(row) = row.filter(|row| !(top..top + height).contains(row)) {
                scroll.at = Some(row);
                (top, below) = scroll.place(&counts, height, width);
            }
        }
        let mut shown = Vec::with_capacity(height);
        let mut start = 0;
        for (part, count) in parts.iter().zip(&counts) {
            let end = start + count;
            if end > top && start < top + height {
                let from = top.saturating_sub(start);
                let to = (top + height - start).min(*count);
                shown.extend(self.lit_rows(part, start, from..to, &lights));
            }
            start = end;
            if start >= top + height {
                break;
            }
        }
        let at_top = scroll.held.is_some().then(|| {
            // The innermost item there: the one that starts last.
            let holding = self.marks_in(parts).filter(|(_, rows)| rows.contains(&top));
            let item = holding.max_by_key(|(_, rows)| rows.start);
            item.map(|(item, rows)| (item.clone(), top - rows.start))
        });
        Visible {
            rows: shown,
            below,
            first: top,
            top: at_top.flatten(),
        }
    }

    /// The transcript of `agent` as `parts` lay it out, with the matches of
    /// `highlights` in each row, counted only when one is set, and
    /// `on_screen` on screen.
    pub(crate) fn laid_out(
        &self,
        agent: Option<Entity>,
        parts: &[Part],
        highlights: &[Highlight],
        on_screen: Range<usize>,
    ) -> DrawnTranscript {
        let items = self.marks_in(parts);
        let items = items.map(|(item, rows)| (item.clone(), rows)).collect();
        let lights = self.lights(parts, highlights);
        let counts = if lights.any() {
            lit(self.joined(parts), 0, &lights)
        } else {
            Vec::new()
        };
        let mut counts = counts.into_iter().map(|row| row.matches);
        let rows = self.joined(parts).map(|(row, continues)| DrawnRow {
            text: row.to_string(),
            continues: continues.cloned(),
            lit: counts.next().unwrap_or_default(),
        });
        DrawnTranscript::new(agent, rows.collect(), items, on_screen)
    }

    /// `highlights`, with where in `parts` their spans are.
    fn lights<'a>(&self, parts: &[Part], highlights: &'a [Highlight]) -> Lights<'a> {
        let mut lights = Lights {
            highlights,
            placed: HashMap::new(),
        };
        if highlights
            .iter()
            .all(|highlight| highlight.spans.is_empty())
        {
            return lights;
        }
        let starts: Vec<usize> = self
            .joined(parts)
            .enumerate()
            .filter(|(_, (_, joint))| joint.is_none())
            .map(|(row, _)| row)
            .collect();
        let items: HashMap<&TranscriptItem, Range<usize>> = self.marks_in(parts).collect();
        for (index, highlight) in highlights.iter().enumerate() {
            for span in &highlight.spans {
                let rows = match &span.item {
                    Some(item) => items.get(item).cloned(),
                    None => Some(0..usize::MAX),
                };
                let Some(rows) = rows else { continue };
                let first = starts.partition_point(|&start| start < rows.start);
                let line = starts
                    .get(first.saturating_add(span.line))
                    .filter(|row| rows.contains(row));
                if let Some(&row) = line {
                    let placed = lights.placed.entry((index, row)).or_default();
                    placed.push(span.bytes.clone());
                }
            }
        }
        lights
    }

    /// The row among `rows` of `parts` with match `n` of `lights`.
    fn lit_row(
        &self,
        parts: &[Part],
        rows: &Range<usize>,
        lights: &Lights<'_>,
        n: usize,
    ) -> Option<usize> {
        // An item's rows are whole lines, so its matches are all in them.
        let drawn = self.joined(parts).skip(rows.start).take(rows.len());
        let mut before = 0;
        for (at, row) in rows.clone().zip(lit(drawn, rows.start, lights)) {
            before += row.matches.iter().sum::<usize>();
            if before > n {
                return Some(at);
            }
        }
        None
    }

    /// Every row of `parts`, with how it continues the row before it.
    fn joined<'a>(
        &'a self,
        parts: &'a [Part],
    ) -> impl Iterator<Item = (&'a Line<'static>, Option<&'a RowWrap>)> + 'a {
        let wrapped = parts.iter().filter_map(|part| self.wrapped(part));
        let rows = wrapped.flat_map(|wrapped| wrapped.rows.iter().zip(&wrapped.continues));
        rows.map(|(row, continues)| (row, continues.as_ref()))
    }

    /// Rows `range` of `part`, which starts at row `start` of the
    /// transcript, with the matches of `lights` lit; each is sought in the
    /// whole line it is in, even where the line goes on past `range`.
    fn lit_rows(
        &self,
        part: &Part,
        start: usize,
        range: Range<usize>,
        lights: &Lights<'_>,
    ) -> Vec<Line<'static>> {
        let Some(wrapped) = self.wrapped(part) else {
            return Vec::new();
        };
        if !lights.any() {
            return wrapped.rows.get(range).unwrap_or_default().to_vec();
        }
        let continues = |row: usize| wrapped.continues.get(row).is_some_and(Option::is_some);
        let mut first = range.start;
        while first > 0 && continues(first) {
            first -= 1;
        }
        let mut end = range.end;
        while continues(end) {
            end += 1;
        }
        let rows = wrapped.rows.get(first..end).unwrap_or_default();
        let joints = wrapped.continues.get(first..end).unwrap_or_default();
        let lit = light(rows, joints, start + first, lights);
        let shown = lit.into_iter().skip(range.start - first);
        shown.take(range.len()).collect()
    }
}

/// `lines` wrapped to `width`, and `marks` of lines moved to the rows
/// they wrap to.
fn wrap_marked(
    lines: &[Line<'static>],
    marks: &[(TranscriptItem, Range<usize>)],
    width: usize,
) -> Wrapped {
    let mut rows = Vec::with_capacity(lines.len());
    let mut continues = Vec::with_capacity(lines.len());
    // The first row of each line, and past the last.
    let mut starts = Vec::with_capacity(lines.len() + 1);
    for line in lines {
        starts.push(rows.len());
        for (row, joint) in wrap(line, width) {
            rows.push(row);
            continues.push(joint);
        }
    }
    starts.push(rows.len());
    let row = |line: usize| starts.get(line).copied().unwrap_or(rows.len());
    let marks = marks
        .iter()
        .map(|(item, lines)| (item.clone(), row(lines.start)..row(lines.end)))
        .collect();
    Wrapped {
        rows,
        continues,
        marks,
    }
}

/// Where the transcript is scrolled: following its bottom, or held at the
/// row the user scrolled to, which then stays put as rows arrive below.
#[derive(Default)]
pub(crate) struct Scroll {
    /// The row held at the top of the screen; `None` follows the bottom.
    held: Option<Held>,
    /// Rows the keys moved the view since the last frame, up positive.
    moved: isize,
    /// An item to go to at the next frame, and which row of it.
    jump: Option<(TranscriptItem, ItemRow)>,
    /// The row to put at the top at the next frame, where a jump found it.
    at: Option<usize>,
}

/// The top row of a view scrolled up.
struct Held {
    /// Its index in the whole transcript.
    top: usize,
    /// The part it is in, its row there and that part's rows, to find it
    /// again after a resize re-wraps everything above it.
    part: usize,
    row: usize,
    rows: usize,
    /// The transcript's width and rows at the last frame.
    width: u16,
    total: usize,
    /// Whether rows arrived below since the view was held.
    grew: bool,
}

/// What is below a view scrolled up.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum Below {
    /// Nothing: the view follows the bottom.
    #[default]
    Nothing,
    /// Rows that were there when the view was scrolled up.
    More,
    /// Rows that arrived since.
    New,
}

impl Scroll {
    /// Moves the view `rows` up.
    pub(crate) fn up(&mut self, rows: usize) {
        self.moved = self
            .moved
            .saturating_add(isize::try_from(rows).unwrap_or(isize::MAX));
    }

    /// Moves the view `rows` down; reaching the bottom follows it again.
    pub(crate) fn down(&mut self, rows: usize) {
        self.moved = self
            .moved
            .saturating_sub(isize::try_from(rows).unwrap_or(isize::MAX));
    }

    /// Follows the bottom again.
    pub(crate) fn follow(&mut self) {
        *self = Self::default();
    }

    /// Shows `row` of `item` at the next frame.
    pub(crate) fn to(&mut self, item: TranscriptItem, row: ItemRow) {
        self.jump = Some((item, row));
    }

    /// Finds the row a jump to put a row of an item at the top goes to,
    /// by the item's rows: the item's first row and the row asked for, within
    /// the item. An item not there leaves the view where it is.
    fn find(&mut self, rows_of: impl Fn(&TranscriptItem) -> Option<Range<usize>>) {
        if let Some((item, ItemRow::Top(line))) = &self.jump {
            self.at = rows_of(item).map(|rows| {
                let last = rows.end.saturating_sub(1).max(rows.start);
                (rows.start + line).min(last)
            });
            self.jump = None;
        }
    }

    /// The top row of a view `height` rows high over parts of `counts`
    /// rows at `width`, after the keys' moves or a jump; holds it while it
    /// is above the bottom.
    fn place(&mut self, counts: &[usize], height: usize, width: u16) -> (usize, Below) {
        let total: usize = counts.iter().sum();
        let bottom = total.saturating_sub(height);
        let moved = std::mem::take(&mut self.moved);
        let (top, grew) = match (self.at.take(), &self.held) {
            (Some(at), _) => (at, false),
            (None, None) => (bottom, false),
            (None, Some(held)) if held.width == width => {
                (held.top, held.grew || total > held.total)
            }
            (None, Some(held)) => {
                let start: usize = counts.iter().take(held.part).sum();
                let rows = counts.get(held.part).copied().unwrap_or(0);
                let row = (held.row * rows / held.rows.max(1)).min(rows.saturating_sub(1));
                (start + row, held.grew)
            }
        };
        let top = top.saturating_add_signed(moved.saturating_neg());
        if top >= bottom {
            self.held = None;
            return (bottom, Below::Nothing);
        }
        let (mut part, mut start) = (0, 0);
        for (index, count) in counts.iter().enumerate() {
            part = index;
            if start + count > top {
                break;
            }
            start += count;
        }
        self.held = Some(Held {
            top,
            part,
            row: top - start,
            rows: counts.get(part).copied().unwrap_or(0),
            width,
            total,
            grew,
        });
        (top, if grew { Below::New } else { Below::More })
    }
}

/// The tool results a message carries.
fn tool_results(message: Option<&Message>) -> impl Iterator<Item = &ToolResult> {
    let content = match message {
        Some(Message::User { content }) => Some(content.iter()),
        _ => None,
    };
    content.into_iter().flatten().filter_map(|item| match item {
        UserContent::ToolResult(result) => Some(result),
        _ => None,
    })
}

/// Whether `message` is a reply holding the call `result` answers.
fn answers(message: Option<&Message>, result: &ToolResult) -> bool {
    match message {
        Some(Message::Assistant(assistant)) => assistant
            .content
            .iter()
            .any(|item| matches!(item, AssistantContent::ToolCall(call) if call.id == result.call)),
        _ => false,
    }
}

/// Draws `message`, the `at`-th of `conversation`, with the notices and
/// notes inside it before their items, and says which lines are the
/// message and which each of its calls and notes. A tool call's result, which comes
/// in the `next` message, is drawn with the call, so the results of a
/// reply's calls are not drawn after all of its calls.
fn message_lines(
    message: &Message,
    (conversation, at): (&conversation::Conversation, usize),
    (previous, next): (Option<&Message>, Option<&Message>),
    (look, width): (&Look<'_>, usize),
) -> (Vec<Line<'static>>, Marks) {
    let mut lines = Vec::new();
    let mut marks = Marks::new();
    let id = conversation.id(at);
    let author = conversation.author(at);
    let stopped = conversation
        .entries()
        .nth(at)
        .is_some_and(|entry| entry.is_stop_marker());
    let inside = look.inside(at);
    let inside_before = |item: usize, lines: &mut Vec<Line<'static>>, marks: &mut Marks| {
        for (_, inside) in inside.iter().filter(|(before, _)| *before == item) {
            match inside {
                Inside::Notice(at, notice) => notice_lines((*at, notice), lines, marks),
                Inside::Aside(shown) => {
                    let start = lines.len();
                    lines.push(Line::default());
                    lines.extend(on_band(
                        shown.lines(look.renderers, look.theme),
                        look.theme.tool,
                    ));
                    marks.push((shown.item(), start..lines.len()));
                }
            }
        }
    };
    match message {
        Message::System { .. } => {}
        Message::User { content } => {
            for (item_at, item) in content.iter().enumerate() {
                inside_before(item_at, &mut lines, &mut marks);
                match item {
                    UserContent::Text(text) => {
                        if let Some((label, body)) = attached_file(&text.text) {
                            let count = body.lines().count();
                            let header = Line::from(format!("  [{label}, {count} lines]")).dim();
                            let body = text_rows(body, Style::new().dim());
                            lines.extend(on_band(
                                std::iter::once(header).chain(body),
                                look.theme.user,
                            ));
                            continue;
                        }
                        if stopped {
                            let stop = Line::from("  [stopped before it was answered]").dim();
                            lines.extend(on_band([stop], look.theme.user));
                            continue;
                        }
                        lines.push(Line::default());
                        // The user's own text has no author, or the user with no title.
                        let other = |author: &&Author| {
                            author.kind != AuthorKind::User || author.title.is_some()
                        };
                        // Text beside tool results is no one's typing, such
                        // as compaction's notes on outputs it cleared.
                        let results = content
                            .iter()
                            .any(|part| matches!(part, UserContent::ToolResult(_)));
                        match author.filter(other) {
                            Some(author) => lines.extend(on_band(
                                delivered_lines(author, &text.text, look),
                                look.theme.tool,
                            )),
                            None if results => lines.extend(on_band(
                                text_rows(&text.text, Style::new().dim()),
                                look.theme.tool,
                            )),
                            None => lines.extend(on_band(
                                MessageView {
                                    role: Role::User,
                                    message: id,
                                    block: item_at,
                                    text: &text.text,
                                    marks: &[],
                                    width,
                                    theme: *look.theme,
                                }
                                .default_lines(),
                                look.theme.user,
                            )),
                        }
                    }
                    // Drawn under its call already.
                    UserContent::ToolResult(result) if answers(previous, result) => {}
                    UserContent::ToolResult(result) => {
                        let style = result_style(result.is_error);
                        let rows = text_rows(&result_text(result), style);
                        lines.extend(on_band(rows, look.theme.tool));
                    }
                    other => {
                        if let Some(block) = ContentBlock::of_user(other) {
                            let view = (id, item_at, block, false);
                            content_lines(view, look, (&mut lines, &mut marks));
                        }
                    }
                }
            }
        }
        Message::Assistant(assistant) => {
            for (item_at, item) in assistant.content.iter().enumerate() {
                inside_before(item_at, &mut lines, &mut marks);
                match item {
                    AssistantContent::Text(text) => {
                        lines.push(Line::default());
                        let marks =
                            id.map(|id| look.marks_in(MarkIn::Message { id, block: item_at }));
                        lines.extend(
                            MessageView {
                                role: Role::Assistant,
                                message: id,
                                block: item_at,
                                text: &text.text,
                                marks: &marks.unwrap_or_default(),
                                width,
                                theme: *look.theme,
                            }
                            .default_lines(),
                        );
                    }
                    AssistantContent::Reasoning(reasoning) => {
                        lines.extend(
                            MessageView {
                                role: Role::Reasoning,
                                message: id,
                                block: item_at,
                                text: &reasoning.text,
                                marks: &[],
                                width,
                                theme: *look.theme,
                            }
                            .default_lines(),
                        );
                    }
                    AssistantContent::ToolCall(call) => {
                        let result = tool_results(next).find(|result| result.call == call.id);
                        let (facts, took) = look.facts.of(&call.id);
                        let item = TranscriptItem::Call(call.id.clone());
                        let view = ToolCallView {
                            call,
                            result,
                            state: look.state(&call.id, result),
                            theme: *look.theme,
                            facts,
                            took,
                            output: look.outputs.get(&call.id).map(String::as_str),
                            children: look.children.get(&call.id).map_or(&[], Vec::as_slice),
                        };
                        let (drawn, decorated) = look.renderers.call_decorated(&view);
                        let start = lines.len();
                        lines.extend(on_band(drawn, look.theme.tool));
                        marks.push((item, start..lines.len()));
                        for (name, rows) in decorated {
                            let decoration = TranscriptItem::Decoration(call.id.clone(), name);
                            marks.push((decoration, start + rows.start..start + rows.end));
                        }
                    }
                    // A provider item with no meaning here shows nothing.
                    other => {
                        if let Some(block) = ContentBlock::of_assistant(other) {
                            let view = (id, item_at, block, true);
                            content_lines(view, look, (&mut lines, &mut marks));
                        }
                    }
                }
            }
        }
    }
    if !matches!(message, Message::System { .. }) {
        let decorated = DecoratedMessage {
            message,
            id,
            author,
        };
        let (drawn, decorations) = look.renderers.message_decorations(&decorated);
        let start = lines.len();
        lines.extend(drawn);
        for (name, rows) in decorations {
            if let Some(id) = id {
                let decoration = TranscriptItem::MessageDecoration(id, name);
                marks.push((decoration, start + rows.start..start + rows.end));
            }
        }
    }
    if let Some(id) = id {
        marks.insert(0, (TranscriptItem::Message(id), 0..lines.len()));
    }
    (lines, marks)
}

/// Draws the content block `block`, the `index`-th of the message `id`
/// (by `assistant` or not), by its kind's look, and marks its rows when
/// the message has an id.
fn content_lines(
    (id, index, block, assistant): (Option<MessageId>, usize, ContentBlock<'_>, bool),
    look: &Look<'_>,
    (lines, marks): (&mut Vec<Line<'static>>, &mut Marks),
) {
    let view = ContentView {
        message: id,
        index,
        block,
        assistant,
    };
    let start = lines.len();
    lines.extend(look.renderers.content(&view));
    if let Some(id) = id {
        marks.push((TranscriptItem::Content(id, index), start..lines.len()));
    }
}

/// Text an agent or a plugin sent, without the header the model reads:
/// drawn by the renderer of the plugin that sent it, if it has one, else
/// as where it came from and its start.
fn delivered_lines(author: &Author, text: &str, look: &Look<'_>) -> Vec<Line<'static>> {
    let body = author
        .header()
        .and_then(|header| text.strip_prefix(&header))
        .map_or(text, |body| body.trim_start_matches('\n'));
    let label = author.label();
    let view = EntryView {
        plugin: plugin_name(author),
        title: &label,
        text: body,
    };
    look.renderers.entry(&view)
}

/// The lines of the notice `at` in the notices shown, coloured by its
/// level, marked as that item.
pub(crate) fn notice_lines(
    (at, notice): (usize, &ShownNotice),
    lines: &mut Vec<Line<'static>>,
    marks: &mut Marks,
) {
    let style = match notice.level {
        NoticeLevel::Info => Style::new().fg(Color::Magenta),
        NoticeLevel::Warn => Style::new().fg(Color::Yellow),
        NoticeLevel::Error => Style::new().fg(Color::Red),
    };
    let start = lines.len();
    lines.extend(plain_lines(&notice.text, style));
    marks.push((TranscriptItem::Notice(at), start..lines.len()));
}

/// `lines` on the band `band`, each where it has no background of its
/// own, such as a diff's line: the background of every row it wraps to.
pub(crate) fn on_band(
    lines: impl IntoIterator<Item = Line<'static>>,
    band: Color,
) -> impl Iterator<Item = Line<'static>> {
    lines.into_iter().map(move |mut line| {
        line.style.bg = line.style.bg.or(Some(band));
        line
    })
}

/// Whether `message`'s lines depend on the width: a reply with a table.
fn fitted(message: &Message) -> bool {
    let Message::Assistant(assistant) = message else {
        return false;
    };
    let texts = assistant.content.iter().filter_map(|item| match item {
        AssistantContent::Text(text) => Some(text.text.as_str()),
        _ => None,
    });
    texts.into_iter().any(markdown::has_table)
}

/// `text`'s lines in one style.
pub(crate) fn plain_lines(text: &str, style: Style) -> Vec<Line<'static>> {
    text.lines()
        .map(|line| Line::styled(line.replace('\t', "    "), style))
        .collect()
}

#[cfg(test)]
mod tests;