ratasm 0.3.0

A terminal IDE and debugger for x86_64 assembly
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
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
//! The loop that draws, reads input and performs effects.

use std::path::Path;
use std::time::Duration;

use anyhow::{Context, Result};
use crossterm::event::{Event, EventStream, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use futures_util::StreamExt as _;

use crate::assembler::{self, BuildOptions};
use crate::command::Command;
use crate::debugger::mi::{command as mi, Record};
use crate::debugger::registers::parse_register_values;
use crate::debugger::session::GdbSession;
use crate::debugger::state::Transition;
use crate::disassembler;
use crate::editor::workspace;
use crate::process::pty::{PtyControl, PtyEvent, PtySize};
use crate::ui::clipboard;
use crate::ui::render;
use crate::ui::Tui;

use super::state::{Effect, StepKind};
use super::{App, Status};

/// How long to wait for the program to stop after a step.
const STOP_TIMEOUT: Duration = Duration::from_secs(15);

/// How often open files are compared with what is on disk.
const DISK_CHECK: Duration = Duration::from_secs(1);

/// How often to redraw when nothing has happened.
const TICK: Duration = Duration::from_millis(250);

/// The result of work that ran off the event loop.
enum Background {
    /// The scratchpad snippet finished, or could not be run.
    Scratchpad(Result<crate::scratchpad::Outcome, String>),
    /// A resumed inferior stopped again, or the wait failed.
    DebugStopped {
        session: Box<GdbSession>,
        result: Result<Record, String>,
    },
}

/// Work in flight, so a second request can be refused and the first cancelled.
#[derive(Default)]
struct Running {
    /// The task, kept so stopping can abort it.
    handle: Option<tokio::task::JoinHandle<()>>,
    /// Commands for an interactive child, when the task owns a PTY.
    control: Option<tokio::sync::mpsc::UnboundedSender<PtyControl>>,
    /// Interrupt request for a GDB wait task.
    interrupt: Option<tokio::sync::mpsc::UnboundedSender<()>>,
}

impl Running {
    /// Whether something is still running.
    fn is_busy(&self) -> bool {
        self.handle.as_ref().is_some_and(|task| !task.is_finished())
    }

    /// Aborts the task, if any.
    fn cancel(&mut self) -> bool {
        if let Some(control) = &self.control {
            if control.send(PtyControl::Stop).is_ok() {
                return true;
            }
        }
        match self.handle.take() {
            Some(task) if !task.is_finished() => {
                task.abort();
                self.interrupt = None;
                true
            }
            _ => false,
        }
    }

    /// Asks a terminal transport to flush and close itself.
    fn request_stop(&self) -> bool {
        self.control
            .as_ref()
            .is_some_and(|control| control.send(PtyControl::Stop).is_ok())
    }

    /// Sends bytes to the interactive child.
    fn input(&self, bytes: Vec<u8>) -> bool {
        self.control
            .as_ref()
            .is_some_and(|control| control.send(PtyControl::Input(bytes)).is_ok())
    }

    /// Resizes the interactive child's PTY.
    fn resize(&self, size: PtySize) {
        if let Some(control) = &self.control {
            let _ = control.send(PtyControl::Resize(size));
        }
    }

    /// Stops and forgets a transport that has no child process of its own.
    fn abort(&mut self) {
        if let Some(control) = self.control.take() {
            let _ = control.send(PtyControl::Stop);
        }
        if let Some(task) = self.handle.take() {
            task.abort();
        }
        self.interrupt = None;
    }
}

/// The ordinary background task and the debugger inferior's terminal transport.
#[derive(Default)]
struct Runtimes {
    background: Running,
    debugger: Running,
}

impl Runtimes {
    fn terminal(&self) -> &Running {
        if self.background.control.is_some() {
            &self.background
        } else {
            &self.debugger
        }
    }

    fn resize(&self, size: PtySize) {
        self.background.resize(size);
        self.debugger.resize(size);
    }

    fn inferior_orphaned(&self, has_session: bool) -> bool {
        !has_session && !self.background.is_busy() && self.debugger.is_busy()
    }
}

/// Runs the interface until the user quits.
pub async fn run(mut app: App, terminal: &mut Tui) -> Result<()> {
    let mut events = EventStream::new();
    let mut session: Option<GdbSession> = None;
    let (finished_tx, mut finished_rx) = tokio::sync::mpsc::unbounded_channel::<Background>();
    let (pty_tx, mut pty_rx) = tokio::sync::mpsc::unbounded_channel::<PtyEvent>();
    let mut runtimes = Runtimes::default();
    let mut last_disk_check = std::time::Instant::now();

    loop {
        let size = terminal.size().context("cannot read the terminal size")?;
        sync_terminal_size(&mut app, &runtimes, size.width, size.height);
        render::sync_scroll(&mut app, size.width, size.height);
        terminal
            .draw(|frame| render::draw(frame, &app))
            .context("cannot draw to the terminal")?;

        if app.should_quit {
            break;
        }

        let effect = tokio::select! {
            event = events.next() => match event {
                Some(Ok(Event::Key(key))) => handle_key_event(&mut app, &runtimes, key),
                Some(Ok(Event::Paste(text))) => {
                    handle_terminal_paste(&app, &runtimes, text);
                    Effect::None
                }
                Some(Ok(Event::Mouse(mouse))) => {
                    crate::event::handle_mouse(&mut app, mouse, size.width, size.height)
                }
                Some(Ok(Event::Resize(..))) => Effect::None,
                Some(Ok(_)) => Effect::None,
                Some(Err(_)) | None => break,
            },
            Some(done) = finished_rx.recv() => {
                runtimes.background.handle = None;
                runtimes.background.interrupt = None;
                finish_background(&mut app, &mut session, done).await;
                Effect::None
            },
            Some(event) = pty_rx.recv() => {
                finish_pty_event(&mut app, &mut runtimes, event);
                Effect::None
            },
            () = tokio::time::sleep(TICK) => Effect::None,
        };

        perform(
            &mut app,
            &mut session,
            &finished_tx,
            &pty_tx,
            &mut runtimes,
            (size.width, size.height),
            effect,
        )
        .await;
        drain_debugger_events(&mut app, &mut session).await;
        if last_disk_check.elapsed() >= DISK_CHECK {
            last_disk_check = std::time::Instant::now();
            report_disk_changes(&mut app);
            app.refresh_project_files();
        }
        if runtimes.inferior_orphaned(session.is_some()) {
            let _ = runtimes.debugger.request_stop();
        }
    }

    runtimes.background.abort();
    runtimes.debugger.abort();
    if let Some(path) = super::session::path_for(app.project.root()) {
        if let Err(error) = super::session::save(&app, &path) {
            tracing::warn!(%error, "cannot save the session");
        }
    }

    if let Some(session) = session {
        session.shutdown().await;
    }
    Ok(())
}

/// Applies one key event.
fn handle_key_event(app: &mut App, runtimes: &Runtimes, key: KeyEvent) -> Effect {
    if !app.mode.is_overlay() && key.kind != KeyEventKind::Release {
        if let Some(command) = terminal_escape(key) {
            return app.apply(&command);
        }
    }
    if app.terminal.is_some() && app.focus == super::Panel::Output && !app.mode.is_overlay() {
        if let Some(command) = app.keymap.command_for_event(key).cloned() {
            if terminal_reserved_command(&command) {
                return app.apply(&command);
            }
        }
        let application_cursor = app
            .terminal
            .as_ref()
            .is_some_and(|terminal| terminal.screen().application_cursor());
        if let Some(bytes) = terminal_key_bytes(key, application_cursor) {
            let _ = runtimes.terminal().input(bytes);
        }
        return Effect::None;
    }
    crate::event::handle_key(app, key)
}

fn terminal_escape(key: KeyEvent) -> Option<Command> {
    if key.modifiers != KeyModifiers::ALT {
        return None;
    }
    Some(match key.code {
        KeyCode::Right => Command::NextPanel,
        KeyCode::Left => Command::PreviousPanel,
        _ => return None,
    })
}

/// Commands that remain reachable while the Output panel sends ordinary keys to the child.
fn terminal_reserved_command(command: &Command) -> bool {
    matches!(
        command,
        Command::Stop
            | Command::Quit
            | Command::OpenPalette
            | Command::Run
            | Command::DebugContinue
            | Command::DebugInterrupt
            | Command::DebugStop
            | Command::GoToPage(_)
            | Command::NextPage
            | Command::PreviousPage
            | Command::NextPanel
            | Command::PreviousPanel
            | Command::FocusPanel(_)
    )
}

/// Encodes a crossterm key as the byte sequence expected by a VT terminal.
fn terminal_key_bytes(key: KeyEvent, application_cursor: bool) -> Option<Vec<u8>> {
    if key.kind == KeyEventKind::Release {
        return None;
    }

    let sequence = match key.code {
        KeyCode::Char(character) if key.modifiers.contains(KeyModifiers::CONTROL) => {
            let upper = character.to_ascii_uppercase();
            let byte = match upper {
                '@' | ' ' => 0,
                'A'..='_' => (upper as u8) & 0x1f,
                '?' => 0x7f,
                _ => return None,
            };
            vec![byte]
        }
        KeyCode::Char(character) => {
            let mut bytes = Vec::new();
            if key.modifiers.contains(KeyModifiers::ALT) {
                bytes.push(0x1b);
            }
            let mut encoded = [0; 4];
            bytes.extend_from_slice(character.encode_utf8(&mut encoded).as_bytes());
            bytes
        }
        KeyCode::Enter => b"\r".to_vec(),
        KeyCode::Backspace => vec![0x7f],
        KeyCode::Tab => b"\t".to_vec(),
        KeyCode::BackTab => b"\x1b[Z".to_vec(),
        KeyCode::Esc => vec![0x1b],
        KeyCode::Up if application_cursor => b"\x1bOA".to_vec(),
        KeyCode::Down if application_cursor => b"\x1bOB".to_vec(),
        KeyCode::Right if application_cursor => b"\x1bOC".to_vec(),
        KeyCode::Left if application_cursor => b"\x1bOD".to_vec(),
        KeyCode::Up => b"\x1b[A".to_vec(),
        KeyCode::Down => b"\x1b[B".to_vec(),
        KeyCode::Right => b"\x1b[C".to_vec(),
        KeyCode::Left => b"\x1b[D".to_vec(),
        KeyCode::Home => b"\x1b[H".to_vec(),
        KeyCode::End => b"\x1b[F".to_vec(),
        KeyCode::Insert => b"\x1b[2~".to_vec(),
        KeyCode::Delete => b"\x1b[3~".to_vec(),
        KeyCode::PageUp => b"\x1b[5~".to_vec(),
        KeyCode::PageDown => b"\x1b[6~".to_vec(),
        KeyCode::F(number) => function_key(number)?.to_vec(),
        KeyCode::Null => vec![0],
        _ => return None,
    };
    Some(sequence)
}

fn function_key(number: u8) -> Option<&'static [u8]> {
    Some(match number {
        1 => b"\x1bOP",
        2 => b"\x1bOQ",
        3 => b"\x1bOR",
        4 => b"\x1bOS",
        5 => b"\x1b[15~",
        6 => b"\x1b[17~",
        7 => b"\x1b[18~",
        8 => b"\x1b[19~",
        9 => b"\x1b[20~",
        10 => b"\x1b[21~",
        11 => b"\x1b[23~",
        12 => b"\x1b[24~",
        _ => return None,
    })
}

fn handle_terminal_paste(app: &App, runtimes: &Runtimes, text: String) {
    if app.terminal.is_none() || app.focus != super::Panel::Output || app.mode.is_overlay() {
        return;
    }
    let bracketed = app
        .terminal
        .as_ref()
        .is_some_and(|terminal| terminal.screen().bracketed_paste());
    let bytes = if bracketed {
        format!("\x1b[200~{text}\x1b[201~").into_bytes()
    } else {
        text.into_bytes()
    };
    let _ = runtimes.terminal().input(bytes);
}

/// Keeps both the parser and the kernel PTY aligned with the visible Output panel.
fn sync_terminal_size(app: &mut App, runtimes: &Runtimes, width: u16, height: u16) {
    let Some(size) = output_terminal_size(app, width, height) else {
        return;
    };
    let changed = app
        .terminal
        .as_ref()
        .is_some_and(|terminal| terminal.size() != size);
    if changed {
        if let Some(terminal) = &mut app.terminal {
            terminal.resize(size);
        }
        runtimes.resize(size);
    }
}

fn output_terminal_size(app: &App, width: u16, height: u16) -> Option<PtySize> {
    let layout = crate::ui::layout::compute(
        ratatui::layout::Rect::new(0, 0, width, height),
        app.page,
        app.focus,
    );
    let area = layout.area_of(super::Panel::Output)?;
    Some(PtySize::new(
        area.width.saturating_sub(2),
        area.height.saturating_sub(2),
    ))
}

/// Performs an effect, folding the result back into the application.
async fn perform(
    app: &mut App,
    session: &mut Option<GdbSession>,
    finished: &tokio::sync::mpsc::UnboundedSender<Background>,
    pty_events: &tokio::sync::mpsc::UnboundedSender<PtyEvent>,
    runtimes: &mut Runtimes,
    viewport: (u16, u16),
    effect: Effect,
) {
    match effect {
        Effect::None | Effect::Quit => {}

        Effect::Build { debug } => {
            build(app, debug).await;
        }

        Effect::Run => {
            if runtimes.background.is_busy() || runtimes.debugger.is_busy() {
                app.status = Status::warning("Something is already running");
            } else if build(app, false).await {
                start_program(
                    app,
                    pty_events,
                    &mut runtimes.background,
                    viewport.0,
                    viewport.1,
                );
            }
        }

        Effect::StopProgram => {
            if app.debugger.state() == crate::debugger::DebuggerState::Running
                && session.is_none()
                && runtimes.background.cancel()
            {
                stop_session(app, session).await;
                let _ = runtimes.debugger.request_stop();
                app.status = Status::warning("Debug session stopped");
            } else if runtimes.background.cancel() {
                app.status = Status::warning("Stopped");
            } else if app.debugger.state().can_stop() {
                stop_session(app, session).await;
                let _ = runtimes.debugger.request_stop();
                app.status = Status::warning("Debug session stopped");
            } else {
                app.status = Status::info("Nothing is running");
            }
        }

        Effect::SaveFile(path) => match app.workspace.save_active_as(&path) {
            Ok(path) => {
                app.status = Status::success(format!("Saved {}", path.display()));
                app.refresh_project_files();
            }
            Err(error) => app.status = Status::error(error.to_string()),
        },

        Effect::SaveAndClose(path) => match app.workspace.save_active_as(&path) {
            Ok(_) => {
                app.close_active_document();
                app.refresh_project_files();
            }
            Err(error) => app.status = Status::error(error.to_string()),
        },

        Effect::SaveProject => match app.project.save() {
            Ok(path) => {
                app.status = Status::success(format!(
                    "Added to {}; it is assembled with the project now",
                    crate::editor::workspace::display_path(&path)
                ));
                app.refresh_project_files();
            }
            Err(error) => app.status = Status::error(error.to_string()),
        },

        Effect::SaveAll => {
            app.status = match save_everything(app) {
                Ok(status) => status,
                Err(error) => Status::error(error.to_string()),
            };
        }

        Effect::OpenFile(path) => match app.workspace.open(&path) {
            Ok(_) => {
                app.workspace
                    .active_mut()
                    .set_indent_width(app.settings.indent_width());
                app.status = Status::success(format!("Opened {}", path.display()));
                app.focus = super::Panel::Editor;
                app.refresh_project_files();
            }
            Err(error) => app.status = Status::error(error.to_string()),
        },

        Effect::DebugStart => {
            let size =
                output_terminal_size(app, viewport.0, viewport.1).unwrap_or(PtySize::new(80, 24));
            start_session(app, session, runtimes, pty_events, size).await;
        }
        Effect::DebugStop => {
            if session.is_none() && app.debugger.state() == crate::debugger::DebuggerState::Running
            {
                runtimes.background.abort();
            }
            stop_session(app, session).await;
            let _ = runtimes.debugger.request_stop();
        }

        Effect::DebugContinue => {
            resume(
                app,
                session,
                finished,
                &mut runtimes.background,
                &mi::exec_continue(),
                true,
                "continuing",
            )
            .await;
        }
        Effect::Step(kind) => {
            let forward = !matches!(
                kind,
                StepKind::Back | StepKind::BackOver | StepKind::ReverseContinue
            );
            let command = match kind {
                StepKind::Instruction => mi::exec_step_instruction(),
                StepKind::Over => mi::exec_next_instruction(),
                StepKind::Line => mi::exec_step(),
                StepKind::Out => mi::exec_finish(),
                StepKind::Back => mi::exec_step_instruction_reverse(),
                StepKind::BackOver => mi::exec_next_instruction_reverse(),
                StepKind::ReverseContinue => mi::exec_continue_reverse(),
            };
            resume(
                app,
                session,
                finished,
                &mut runtimes.background,
                &command,
                forward,
                "stepping",
            )
            .await;
        }

        Effect::DebugInterrupt => {
            if let Some(interrupt) = &runtimes.background.interrupt {
                if interrupt.send(()).is_ok() {
                    app.status = Status::info("Interrupting…");
                }
            } else {
                app.status = Status::warning("The program is not running");
            }
        }

        Effect::SyncBreakpoints => sync_breakpoints(app, session).await,

        Effect::ReadMemory(address) => read_memory(app, session, address).await,

        Effect::CreateFile(path) => create_file(app, &path),

        Effect::Make(target) => {
            if let Err(error) = save_everything(app) {
                app.fail_build(error.to_string());
            } else {
                match assembler::make::build(&app.project, Some(&target)).await {
                    Ok(outcome) => {
                        let finished = outcome.success.then_some(outcome.duration.as_millis());
                        app.finish_build(outcome);
                        if let Some(millis) = finished {
                            app.status =
                                Status::success(format!("make {target} finished in {millis} ms"));
                        }
                    }
                    Err(error) => app.fail_build(error.to_string()),
                }
            }
        }

        Effect::RenameFile { from, to } => {
            rename_file(app, &from, &to);
            sync_breakpoints(app, session).await;
        }
        Effect::DeleteFile(path) => {
            delete_file(app, &path);
            sync_breakpoints(app, session).await;
        }
        Effect::SetRegister(expression) => match session.as_mut() {
            Some(active) => match active
                .execute(&mi::data_evaluate_expression(&expression))
                .await
            {
                Ok(_) => {
                    refresh_state(app, session).await;
                    app.status = Status::success(format!("Set {expression}"));
                }
                Err(error) => app.status = Status::error(error.to_string()),
            },
            None => app.status = Status::warning("No debug session"),
        },

        Effect::RunScratchpad => {
            if runtimes.background.is_busy() || runtimes.debugger.is_busy() {
                app.status = Status::warning("Something is already running");
            } else {
                start_snippet(app, finished, &mut runtimes.background);
            }
        }

        Effect::SetSystemClipboard(text) => match clipboard::set_sequence(&text) {
            Some(sequence) => {
                use std::io::Write as _;
                let mut out = std::io::stdout();
                if write!(out, "{sequence}")
                    .and_then(|()| out.flush())
                    .is_err()
                {
                    tracing::debug!("could not write the clipboard sequence");
                }
            }
            None => {
                app.status = Status::warning(format!(
                    "Copied within ratasm; too large for the terminal clipboard (over {} KiB)",
                    clipboard::MAX_BYTES / 1024
                ));
            }
        },
    }
}

fn create_file(app: &mut App, path: &Path) {
    if !path.exists() {
        let written = path
            .parent()
            .map_or(Ok(()), std::fs::create_dir_all)
            .and_then(|()| std::fs::write(path, ""));
        if let Err(error) = written {
            app.status = Status::error(format!("cannot create {}: {error}", path.display()));
            return;
        }
    }
    match app.workspace.open(path) {
        Ok(_) => {
            app.focus_panel(super::Panel::Editor);
            app.status = Status::success(format!("Created {}", workspace::display_path(path)));
        }
        Err(error) => app.status = Status::error(error.to_string()),
    }
    app.refresh_project_files();
}

fn rename_file(app: &mut App, from: &Path, to: &Path) {
    if to.exists() {
        app.status = Status::error(format!("{} already exists", workspace::display_path(to)));
        return;
    }
    if let Some(parent) = to.parent() {
        let _ = std::fs::create_dir_all(parent);
    }
    if let Err(error) = std::fs::rename(from, to) {
        app.status = Status::error(format!("cannot rename: {error}"));
        return;
    }
    if let Some(index) = app.index_of_document(from) {
        app.workspace.set_active(index);
        app.workspace.active_mut().set_path(to);
    }
    app.breakpoints.move_file(from, Some(to));
    let mut status = Status::success(format!("Renamed to {}", workspace::display_path(to)));
    match app.project.rename_source(from, to) {
        Ok(true) => {
            if let Err(error) = app.project.save() {
                status = Status::error(error.to_string());
            }
        }
        Ok(false) => {}
        Err(error) => status = Status::warning(error.to_string()),
    }
    app.status = status;
    app.refresh_project_files();
}

fn delete_file(app: &mut App, path: &Path) {
    if workspace::same_target(path, &app.project.entry_path()) {
        app.status =
            Status::warning("The entry file cannot be deleted; change project.entry first");
        return;
    }
    if let Err(error) = std::fs::remove_file(path) {
        app.status = Status::error(format!("cannot delete: {error}"));
        return;
    }
    if let Some(index) = app.index_of_document(path) {
        let _ = app.workspace.close(index);
    }
    app.breakpoints.move_file(path, None);
    let mut status = Status::warning(format!("Deleted {}", workspace::display_path(path)));
    if app.project.remove_source(path) {
        if let Err(error) = app.project.save() {
            status = Status::error(error.to_string());
        }
    }
    app.status = status;
    app.refresh_project_files();
}

fn report_disk_changes(app: &mut App) {
    let changes = app.workspace.check_disk();
    let Some(last) = changes.last() else {
        return;
    };
    use crate::editor::DiskChange;
    app.status = match last {
        DiskChange::Reloaded(path) => Status::info(format!(
            "{} changed on disk and was reloaded",
            workspace::display_path(path)
        )),
        DiskChange::Conflict(path) => Status::warning(format!(
            "{} changed on disk; your unsaved edits were kept, saving overwrites it",
            workspace::display_path(path)
        )),
        DiskChange::Deleted(path) => Status::warning(format!(
            "{} was deleted on disk; save to write it again",
            workspace::display_path(path)
        )),
    };
}

/// Builds the project, reporting the outcome.
fn save_everything(app: &mut App) -> Result<Status, crate::editor::workspace::FileError> {
    let (written, skipped) = app.workspace.save_all()?;
    Ok(match (written, skipped) {
        (0, 0) => Status::info("Nothing to save"),
        (_, 0) => Status::success(format!("Saved {written} file(s)")),
        (_, _) => Status::warning(format!(
            "Saved {written} file(s); {skipped} buffer(s) have no file name yet"
        )),
    })
}

async fn build(app: &mut App, debug: bool) -> bool {
    app.project.rescan();
    if let Err(error) = app.workspace.save_all() {
        app.fail_build(error.to_string());
        return false;
    }

    let options = if debug {
        BuildOptions::debug()
    } else {
        BuildOptions::release()
    };

    if app.debugger.state().can_build() {
        let _ = app.debugger.apply(Transition::BuildStarted);
    }

    match assembler::build(&app.project, options).await {
        Ok(outcome) => {
            let executable = outcome.executable.clone();
            app.finish_build(outcome);
            if let Some(path) = &executable {
                load_static_disassembly(app, path);
            }
            executable.is_some()
        }
        Err(error) => {
            app.fail_build(error.to_string());
            false
        }
    }
}

/// Starts the built program on its own task.
fn start_program(
    app: &mut App,
    events: &tokio::sync::mpsc::UnboundedSender<PtyEvent>,
    running: &mut Running,
    width: u16,
    height: u16,
) {
    let Some(executable) = app
        .build
        .as_ref()
        .and_then(|outcome| outcome.executable.clone())
    else {
        app.status = Status::warning(
            "The build produced no program to run; set build.executable in .ratasm.toml",
        );
        return;
    };

    app.focus_panel(super::Panel::Output);
    let size = output_terminal_size(app, width, height).unwrap_or(PtySize::new(80, 24));
    app.terminal = Some(super::terminal::TerminalScreen::new(size));
    app.output.clear();
    app.status = Status::info("Running… Type in Output; Ctrl+F5 stops");
    let spec = assembler::run_command(&app.project, &executable);
    let (control_tx, control_rx) = tokio::sync::mpsc::unbounded_channel();
    let events = events.clone();
    running.control = Some(control_tx);
    running.handle = Some(tokio::spawn(async move {
        crate::process::pty::run_interactive(spec, size, control_rx, events).await;
    }));
}

/// Starts the scratchpad snippet on its own task.
fn start_snippet(
    app: &mut App,
    finished: &tokio::sync::mpsc::UnboundedSender<Background>,
    running: &mut Running,
) {
    app.status = Status::info("Running the snippet…");
    let gdb = app.settings.debugger.gdb.clone();
    let scratchpad = app.scratchpad.clone();
    let finished = finished.clone();
    running.handle = Some(tokio::spawn(async move {
        let result = scratchpad
            .run(&gdb)
            .await
            .map_err(|error| error.to_string());
        let _ = finished.send(Background::Scratchpad(result));
    }));
}

/// Folds the result of a background task back into the application.
async fn finish_background(app: &mut App, session: &mut Option<GdbSession>, done: Background) {
    match done {
        Background::Scratchpad(Ok(outcome)) => {
            app.status = if outcome.is_empty() {
                Status::info("The snippet changed nothing")
            } else {
                Status::success(format!("{} register(s) changed", outcome.changes.len()))
            };
            app.scratchpad_result = Some(Ok(outcome));
        }
        Background::Scratchpad(Err(error)) => {
            app.status = Status::error(error.clone());
            app.scratchpad_result = Some(Err(error));
        }
        Background::DebugStopped {
            session: active,
            result,
        } => {
            // The task that owned this sender has completed.
            *session = Some(*active);
            match result {
                Ok(record) => handle_stop(app, session, &record).await,
                Err(error) => {
                    app.status = Status::error(error);
                    let _ = app.debugger.apply(Transition::SessionFailed);
                    if let Some(active) = session.take() {
                        active.shutdown().await;
                    }
                }
            }
        }
    }
}

fn finish_pty_event(app: &mut App, runtimes: &mut Runtimes, event: PtyEvent) {
    match event {
        PtyEvent::Output(bytes) => {
            if let Some(terminal) = &mut app.terminal {
                terminal.process(&bytes);
            }
        }
        PtyEvent::Finished(result) => {
            runtimes.background.handle = None;
            runtimes.background.control = None;
            match result {
                Ok(output) => app.finish_run(output),
                Err(error) => {
                    app.terminal = None;
                    app.status = Status::error(error.to_string());
                }
            }
        }
        PtyEvent::Closed => {
            runtimes.debugger.handle = None;
            runtimes.debugger.control = None;
            app.finish_terminal();
        }
    }
}

/// Disassembles the built executable so the panel has something to show before a session starts.
fn load_static_disassembly(app: &mut App, executable: &Path) {
    let Ok(image) = disassembler::ElfImage::load(executable) else {
        return;
    };
    let Some(text) = image.text_section() else {
        return;
    };

    let decoded = disassembler::decode(&text.data, text.address, app.disassembly_syntax);
    app.disassembly = disassembler::annotate_with_symbols(decoded, &image.symbols);
    if app.current_address.is_none() {
        app.current_address = Some(image.entry);
    }
}

/// Starts a debug session.
async fn start_session(
    app: &mut App,
    session: &mut Option<GdbSession>,
    runtimes: &mut Runtimes,
    terminal_events: &tokio::sync::mpsc::UnboundedSender<PtyEvent>,
    terminal_size: PtySize,
) {
    if !build(app, true).await {
        return;
    }
    let terminal_runtime = &mut runtimes.debugger;
    let Some(executable) = app
        .build
        .as_ref()
        .and_then(|outcome| outcome.executable.clone())
    else {
        app.status = Status::warning(
            "The build produced no program to debug; set build.executable in .ratasm.toml",
        );
        return;
    };

    if let Some(existing) = session.take() {
        existing.shutdown().await;
    }
    let _ = app.debugger.apply(Transition::LaunchRequested);
    app.status = Status::info("Starting the debugger…");

    let mut active = match GdbSession::start(&app.settings.debugger.gdb).await {
        Ok(active) => active,
        Err(error) => {
            let _ = app
                .debugger
                .fail(Transition::LaunchFailed, error.to_string());
            app.status = Status::error(error.to_string());
            return;
        }
    };
    active.set_timeout(app.settings.debugger_timeout());

    terminal_runtime.abort();
    let (tty_path, endpoint) = match crate::process::pty::PtyPair::open(terminal_size)
        .and_then(crate::process::pty::PtyPair::into_endpoint)
    {
        Ok(terminal) => terminal,
        Err(error) => {
            let _ = app
                .debugger
                .fail(Transition::LaunchFailed, error.to_string());
            app.status = Status::error(error.to_string());
            active.shutdown().await;
            return;
        }
    };
    let (control_tx, control_rx) = tokio::sync::mpsc::unbounded_channel();
    let events = terminal_events.clone();
    terminal_runtime.control = Some(control_tx);
    terminal_runtime.handle = Some(tokio::spawn(endpoint.run(control_rx, events)));
    app.terminal = Some(super::terminal::TerminalScreen::new(terminal_size));
    app.output.clear();

    let setup = async {
        active
            .execute(&mi::file_exec_and_symbols(&executable))
            .await?;
        active
            .execute(&mi::environment_cd(&app.project.run_directory()))
            .await?;
        active.execute(&mi::inferior_tty_set(&tty_path)).await?;
        active
            .execute(&mi::set_disassembly_flavor(
                app.disassembly_syntax == disassembler::Syntax::Intel,
            ))
            .await?;
        if !app.project.config().run.args.is_empty() {
            active
                .execute(&mi::exec_arguments(app.project.config().run.args.clone()))
                .await?;
        }
        Ok::<(), crate::debugger::SessionError>(())
    };

    if let Err(error) = setup.await {
        let _ = app
            .debugger
            .fail(Transition::LaunchFailed, error.to_string());
        app.status = Status::error(error.to_string());
        active.shutdown().await;
        return;
    }

    app.breakpoints.detach();
    let mut holder = Some(active);
    sync_breakpoints(app, &mut holder).await;
    let Some(mut active) = holder else {
        return;
    };

    match disassembler::ElfImage::load(&executable) {
        Ok(image) => {
            let start = image
                .symbols
                .iter()
                .find(|symbol| symbol.name == "main")
                .map_or(image.entry, |symbol| symbol.address);
            let _ = active
                .try_execute(&mi::break_insert_temporary_at_address(start))
                .await;
        }
        Err(_) => {
            let _ = active
                .try_execute(&mi::break_insert_temporary("_start"))
                .await;
        }
    }

    if let Err(error) = active.execute(&mi::exec_run()).await {
        let _ = app
            .debugger
            .fail(Transition::LaunchFailed, error.to_string());
        app.status = Status::error(error.to_string());
        active.shutdown().await;
        return;
    }
    let _ = app.debugger.apply(Transition::LaunchSucceeded);

    match active.wait_for_stop(STOP_TIMEOUT).await {
        Ok(record) => {
            if app.settings.debugger.record {
                let recorded = active.execute(&mi::record_full()).await.is_ok();
                if !recorded {
                    tracing::warn!("execution recording unavailable");
                }
                app.recording = recorded;
            } else {
                app.recording = false;
            }

            *session = Some(active);
            handle_stop(app, session, &record).await;
        }
        Err(error) => {
            let _ = app.debugger.apply(Transition::SessionFailed);
            app.status = Status::error(error.to_string());
            active.shutdown().await;
        }
    }
}

/// Ends the session and clears the state it produced.
async fn stop_session(app: &mut App, session: &mut Option<GdbSession>) {
    if let Some(active) = session.take() {
        active.shutdown().await;
    }
    let _ = app.debugger.exited(None);
    let _ = app.debugger.apply(Transition::Reset);

    app.recording = false;
    app.at_exit = false;
    app.registers.clear();
    app.breakpoints.detach();
    app.frames.clear();
    app.stack = Default::default();
    app.memory = Default::default();
    app.current_address = None;
    app.current_line = None;
    app.status = Status::info("Debug session ended");
}

/// Resumes the program and waits for it to stop again.
async fn resume(
    app: &mut App,
    session: &mut Option<GdbSession>,
    finished: &tokio::sync::mpsc::UnboundedSender<Background>,
    running: &mut Running,
    command: &crate::debugger::mi::Command,
    forward: bool,
    what: &str,
) {
    let Some(mut active) = session.take() else {
        app.status = Status::warning("No debug session");
        return;
    };
    if forward && app.at_exit && active.execute(&mi::record_stop()).await.is_ok() {
        app.recording = false;
        app.at_exit = false;
    }

    if let Err(error) = active.execute(command).await {
        app.status = Status::error(error.to_string());
        *session = Some(active);
        return;
    }
    let _ = app.debugger.apply(Transition::Resumed);
    app.status = Status::info(format!("{what}…"));

    let finished = finished.clone();
    let what = what.to_owned();
    let (interrupt_tx, mut interrupt_rx) = tokio::sync::mpsc::unbounded_channel();
    running.interrupt = Some(interrupt_tx);
    running.handle = Some(tokio::spawn(async move {
        let stopped = tokio::select! {
            result = active.wait_for_stop(STOP_TIMEOUT) => result,
            request = interrupt_rx.recv() => {
                if request.is_none() {
                    Err(crate::debugger::SessionError::Terminated)
                } else {
                    match active.execute(&mi::exec_interrupt()).await {
                        Ok(_) => active.wait_for_stop(STOP_TIMEOUT).await,
                        Err(error) => Err(error),
                    }
                }
            }
        };
        let result = stopped.map_err(|error| format!("{what}: {error}"));
        let _ = finished.send(Background::DebugStopped {
            session: Box::new(active),
            result,
        });
    }));
}

/// Records a stop and refreshes everything that depends on it.
async fn handle_stop(app: &mut App, session: &mut Option<GdbSession>, record: &Record) {
    if record.is_program_exit() {
        let code = record.exit_code();
        let _ = app.debugger.exited(code);
        app.registers.clear();
        app.frames.clear();
        app.current_address = None;
        app.current_line = None;

        app.status = match code {
            Some(0) => Status::success("Program exited normally"),
            Some(code) => Status::warning(format!("Program exited with status {code}")),
            None => Status::warning("Program exited"),
        };

        if let Some(active) = session.take() {
            active.shutdown().await;
        }
        return;
    }

    let _ = app.debugger.apply(Transition::Stopped);
    app.at_exit = app.recording && is_recorded_exit(record);

    if let Some(frame) = record.get("frame") {
        app.current_address = frame.get_address("addr");
        if let (Some(file), Some(line)) = (frame.get_str("file"), frame.get_int("line")) {
            if let Ok(line) = usize::try_from(line) {
                app.current_line = Some((std::path::PathBuf::from(file), line));
            }
        }
    }

    app.show_execution();

    if let Some(number) = record.get("bkptno").and_then(|value| value.as_str()) {
        if let Ok(number) = number.parse::<u32>() {
            app.breakpoints.record_hit(number);
        }
    }

    app.status = match record.stop_reason() {
        _ if app.at_exit => {
            Status::info("The program is about to exit; F5 lets it, Shift+F7 steps back")
        }
        Some("breakpoint-hit") if record.get_str("disp") == Some("del") => {
            Status::info("Stopped at the entry point")
        }
        Some("breakpoint-hit") => Status::success("Stopped at a breakpoint"),
        Some("signal-received") => {
            let signal = record.get_str("signal-name").unwrap_or("a signal");
            match app.current_address {
                Some(address) => Status::error(format!("{signal} at 0x{address:x}")),
                None => Status::error(format!("Received {signal}")),
            }
        }
        Some("end-stepping-range") | Some("function-finished") => Status::info("Stepped"),
        Some(reason) => Status::info(format!("Stopped: {reason}")),
        None => Status::info("Stopped"),
    };

    refresh_state(app, session).await;
}

fn is_recorded_exit(record: &Record) -> bool {
    record.stop_reason() == Some("signal-received") && record.get_str("signal-name") == Some("0")
}

/// Reads registers, the stack and the disassembly after a stop.
async fn refresh_state(app: &mut App, session: &mut Option<GdbSession>) {
    let Some(active) = session.as_mut() else {
        return;
    };

    let names = active.execute(&mi::data_list_register_names()).await;
    let values = active.execute(&mi::data_list_register_values()).await;

    if let (Ok(names), Ok(values)) = (names, values) {
        if let (Some(names), Some(values)) =
            (names.get("register-names"), values.get("register-values"))
        {
            app.registers.update(parse_register_values(names, values));
        }
    }

    match active.execute(&mi::stack_list_frames()).await {
        Ok(record) => {
            app.frames = record
                .get("stack")
                .map(crate::debugger::frames::parse_frames)
                .unwrap_or_default();
            app.frame_selected = 0;
        }
        Err(_) => app.frames.clear(),
    }

    if let Some(rsp) = app.registers.rsp() {
        let depth = app.settings.stack_depth() * 8;
        if let Ok(record) = active
            .execute(&mi::data_read_memory_bytes(rsp, depth))
            .await
        {
            if let Some(block) = record
                .get("memory")
                .and_then(crate::debugger::memory::parse_memory_reply)
            {
                app.stack = block;
            }
        }
    }

    let listed = |rip: u64| {
        app.disassembly
            .iter()
            .any(|line| line.instruction.address == rip)
    };
    if let Some(rip) = app.registers.rip().filter(|rip| !listed(*rip)) {
        let window = 128u64;
        if let Ok(record) = active
            .execute(&mi::data_read_memory_bytes(rip, window as usize))
            .await
        {
            if let Some(memory) = record.get("memory") {
                if let Some(block) = crate::debugger::memory::parse_memory_reply(memory) {
                    let decoded =
                        disassembler::decode(&block.bytes, block.address, app.disassembly_syntax);
                    app.disassembly = decoded
                        .into_iter()
                        .map(disassembler::DisassemblyLine::bare)
                        .collect();
                }
            }
        }
    }

    reveal_current_instruction(app);

    if let Some(address) = app.memory_address {
        read_memory(app, session, address).await;
    }
}

fn reveal_current_instruction(app: &mut App) {
    let Some(row) = app.current_address.and_then(|address| {
        app.disassembly
            .iter()
            .position(|line| line.instruction.address == address)
    }) else {
        return;
    };
    let last = app.disassembly.len().saturating_sub(1);
    app.scroll
        .reveal(super::Panel::Disassembly, (row + 4).min(last));
    app.scroll
        .reveal(super::Panel::Disassembly, row.saturating_sub(2));
}

/// Reads memory into the memory panel.
async fn read_memory(app: &mut App, session: &mut Option<GdbSession>, address: u64) {
    let Some(active) = session.as_mut() else {
        app.status = Status::warning("Start a debug session to read memory");
        return;
    };

    let count = app.settings.memory_window();
    match active
        .execute(&mi::data_read_memory_bytes(address, count))
        .await
    {
        Ok(record) => match record
            .get("memory")
            .and_then(crate::debugger::memory::parse_memory_reply)
        {
            Some(block) => {
                app.memory = block;
                app.memory_address = Some(address);
            }
            None => app.status = Status::error(format!("Cannot read memory at 0x{address:x}")),
        },
        Err(error) => app.status = Status::error(error.to_string()),
    }
}

/// Sends breakpoint changes to a running session.
async fn sync_breakpoints(app: &mut App, session: &mut Option<GdbSession>) {
    let Some(active) = session.as_mut() else {
        return;
    };

    for number in app.breakpoints.take_removed() {
        let _ = active.execute(&mi::break_delete(number)).await;
    }
    let mut placed = Vec::new();
    let mut rejected = None;
    for breakpoint in app.breakpoints.pending() {
        let location = breakpoint.location.clone();
        let command = match &location {
            crate::debugger::breakpoints::Location::Watch(expression) => {
                mi::break_watch(expression)
            }
            _ => mi::break_insert_with(
                &location.to_gdb_location(),
                breakpoint.enabled,
                breakpoint.condition.as_deref(),
            ),
        };
        let watch = matches!(location, crate::debugger::breakpoints::Location::Watch(_));
        match active.execute(&command).await {
            Ok(record) => {
                if let Some(bkpt) = record.get("bkpt").or_else(|| record.get("wpt")) {
                    placed.push((location, bkpt.clone(), watch));
                }
            }
            Err(error) => rejected = Some(format!("{}: {error}", location.display())),
        }
    }
    for (location, record, watch) in placed {
        app.breakpoints.adopt(&location, &record);
        if watch {
            if let Some(number) = record.get_int("number").and_then(|n| u32::try_from(n).ok()) {
                app.breakpoints.mark_synced(number, true, None);
            }
        }
    }
    for (number, enabled, condition) in app.breakpoints.out_of_sync() {
        let toggled = if enabled {
            mi::break_enable(number)
        } else {
            mi::break_disable(number)
        };
        let applied = active.execute(&toggled).await.is_ok()
            && active
                .execute(&mi::break_condition(number, condition.as_deref()))
                .await
                .is_ok();
        if applied {
            app.breakpoints.mark_synced(number, enabled, condition);
        }
    }
    if let Some(message) = rejected {
        app.status = Status::error(message);
    }
}

/// Notices asynchronous records that arrived while nothing was being asked.
async fn drain_debugger_events(app: &mut App, session: &mut Option<GdbSession>) {
    let Some(active) = session.as_mut() else {
        return;
    };

    if !active.is_alive() {
        app.debugger
            .force_failed("the debugger exited unexpectedly");
        app.status = Status::error("The debugger exited unexpectedly");
        *session = None;
        return;
    }

    let events = active.take_events();
    let stop = events.into_iter().find(Record::is_stopped);
    if let Some(record) = stop {
        handle_stop(app, session, &record).await;
    }
}

/// Loads the file the user asked for on the command line.
pub fn open_initial_file(app: &mut App, path: &Path) {
    if !path.is_file() {
        return;
    }
    match app.workspace.open(path) {
        Ok(_) => {
            app.workspace
                .active_mut()
                .set_indent_width(app.settings.indent_width());
        }
        Err(error) => app.status = Status::error(error.to_string()),
    }
}

/// Loads the project's entry file, so the editor is not empty on start-up.
pub fn open_project_entry(app: &mut App) {
    let entry = app.project.entry_path();
    if entry.is_file() {
        open_initial_file(app, &entry);
    } else if app.project.is_explicit() {
        app.status = Status::warning(format!(
            "{} does not exist yet",
            workspace::display_path(&entry)
        ));
    } else {
        app.status = Status::info("No assembly files here yet; Ctrl+N creates one");
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::Settings;
    use crate::project::Project;

    fn app_for(dir: &Path) -> App {
        let project = Project::create(dir, "runtest").expect("create");
        App::new(project, Settings::default()).expect("databases load")
    }

    #[test]
    fn the_project_entry_is_opened_at_start_up() {
        let dir = tempfile::tempdir().expect("temp dir");
        let mut app = app_for(dir.path());

        open_project_entry(&mut app);
        assert_eq!(app.workspace.active().display_name(), "main.asm");
        assert!(app
            .workspace
            .active()
            .buffer()
            .to_text()
            .contains("global _start"));
    }

    #[test]
    fn a_missing_entry_file_is_reported_rather_than_silently_empty() {
        let dir = tempfile::tempdir().expect("temp dir");
        let mut app = app_for(dir.path());
        std::fs::remove_file(app.project.entry_path()).expect("remove");

        open_project_entry(&mut app);
        assert_eq!(app.status.severity, crate::app::Severity::Warning);
    }

    #[test]
    fn terminal_keys_use_vt_sequences_and_control_bytes() {
        let key = |code, modifiers| KeyEvent::new(code, modifiers);
        assert_eq!(
            terminal_key_bytes(key(KeyCode::Char('c'), KeyModifiers::CONTROL), false),
            Some(vec![3])
        );
        assert_eq!(
            terminal_key_bytes(key(KeyCode::Up, KeyModifiers::NONE), false),
            Some(b"\x1b[A".to_vec())
        );
        assert_eq!(
            terminal_key_bytes(key(KeyCode::Up, KeyModifiers::NONE), true),
            Some(b"\x1bOA".to_vec())
        );
        assert_eq!(
            terminal_key_bytes(key(KeyCode::Char('ş'), KeyModifiers::ALT), false),
            Some("\x1bş".as_bytes().to_vec())
        );
    }

    #[test]
    fn release_events_are_not_sent_to_the_child() {
        let mut key = KeyEvent::new(KeyCode::Char('a'), KeyModifiers::NONE);
        key.kind = KeyEventKind::Release;
        assert_eq!(terminal_key_bytes(key, false), None);
    }

    /// Performs one effect the way the run loop does, then waits for the work it started.
    async fn settle(app: &mut App, session: &mut Option<GdbSession>, effect: Effect) {
        let (finished, mut incoming) = tokio::sync::mpsc::unbounded_channel();
        let (pty_events, mut pty_incoming) = tokio::sync::mpsc::unbounded_channel();
        let mut runtimes = Runtimes::default();
        perform(
            app,
            session,
            &finished,
            &pty_events,
            &mut runtimes,
            (160, 48),
            effect,
        )
        .await;
        while runtimes.background.handle.is_some() {
            tokio::select! {
                Some(done) = incoming.recv() => {
                    runtimes.background.handle = None;
                    runtimes.background.interrupt = None;
                    finish_background(app, session, done).await;
                }
                Some(event) = pty_incoming.recv() => {
                    finish_pty_event(app, &mut runtimes, event);
                }
            }
        }
    }

    async fn start_test_session(
        app: &mut App,
        session: &mut Option<GdbSession>,
    ) -> (Running, tokio::sync::mpsc::UnboundedReceiver<PtyEvent>) {
        let mut runtimes = Runtimes::default();
        let (events, incoming) = tokio::sync::mpsc::unbounded_channel();
        start_session(app, session, &mut runtimes, &events, PtySize::new(80, 24)).await;
        (std::mem::take(&mut runtimes.debugger), incoming)
    }

    #[tokio::test]
    async fn building_writes_every_edited_buffer_first() {
        if !crate::process::is_available(Path::new("nasm"))
            || !crate::process::is_available(Path::new("ld"))
        {
            eprintln!("skipping: nasm or ld not installed");
            return;
        }

        let dir = tempfile::tempdir().expect("temp dir");
        let mut app = app_for(dir.path());
        let entry = app.project.entry_path();

        open_initial_file(&mut app, &entry);
        app.workspace.active_mut().insert("; edited\n");
        assert!(app.workspace.has_unsaved_changes());

        assert!(build(&mut app, false).await, "the build should succeed");
        assert!(
            !app.workspace.has_unsaved_changes(),
            "an unsaved buffer would have been assembled from its old contents"
        );
        assert!(std::fs::read_to_string(&entry)
            .expect("read")
            .contains("; edited"));
    }

    #[tokio::test]
    async fn saving_everything_reports_what_it_wrote() {
        let dir = tempfile::tempdir().expect("temp dir");
        let mut app = app_for(dir.path());
        let mut session = None;

        settle(&mut app, &mut session, Effect::SaveAll).await;
        assert_eq!(app.status.severity, crate::app::Severity::Info);

        let entry = app.project.entry_path();
        open_initial_file(&mut app, &entry);
        app.workspace.active_mut().insert("x");
        settle(&mut app, &mut session, Effect::SaveAll).await;
        assert_eq!(app.status.severity, crate::app::Severity::Success);
        assert!(!app.workspace.has_unsaved_changes());
    }

    #[tokio::test]
    async fn building_a_working_project_produces_disassembly() {
        if !crate::process::is_available(Path::new("nasm"))
            || !crate::process::is_available(Path::new("ld"))
        {
            eprintln!("skipping: nasm or ld not installed");
            return;
        }

        let dir = tempfile::tempdir().expect("temp dir");
        let mut app = app_for(dir.path());

        assert!(build(&mut app, false).await, "the build should succeed");
        assert_eq!(app.status.severity, crate::app::Severity::Success);
        assert!(
            !app.disassembly.is_empty(),
            "the executable should have been disassembled"
        );
        assert!(app.current_address.is_some(), "the entry point is known");
    }

    #[tokio::test]
    async fn a_broken_project_reports_the_error_and_produces_nothing() {
        if !crate::process::is_available(Path::new("nasm")) {
            eprintln!("skipping: nasm not installed");
            return;
        }

        let dir = tempfile::tempdir().expect("temp dir");
        let mut app = app_for(dir.path());
        std::fs::write(app.project.entry_path(), "    this is not assembly\n").expect("write");

        assert!(!build(&mut app, false).await);
        assert_eq!(app.status.severity, crate::app::Severity::Error);
        assert!(app.disassembly.is_empty());
        assert!(!app.diagnostics.is_empty(), "the error should be recorded");
    }

    #[tokio::test]
    async fn a_program_that_runs_reports_its_output() {
        if !crate::process::is_available(Path::new("nasm"))
            || !crate::process::is_available(Path::new("ld"))
        {
            eprintln!("skipping: nasm or ld not installed");
            return;
        }

        let dir = tempfile::tempdir().expect("temp dir");
        let mut app = app_for(dir.path());

        settle(&mut app, &mut None, Effect::Run).await;

        assert!(
            app.output.iter().any(|line| line.contains("Hello, world!")),
            "program output missing: {:?}",
            app.output
        );
        assert_eq!(app.status.severity, crate::app::Severity::Success);
    }

    #[tokio::test]
    async fn reading_memory_without_a_session_says_so() {
        let dir = tempfile::tempdir().expect("temp dir");
        let mut app = app_for(dir.path());
        let mut session = None;

        read_memory(&mut app, &mut session, 0x4000).await;
        assert_eq!(app.status.severity, crate::app::Severity::Warning);
        assert!(app.memory.is_empty());
    }

    #[tokio::test]
    async fn effects_without_a_session_do_not_panic() {
        let dir = tempfile::tempdir().expect("temp dir");
        let mut app = app_for(dir.path());
        let mut session = None;

        for effect in [
            Effect::None,
            Effect::DebugContinue,
            Effect::Step(StepKind::Instruction),
            Effect::DebugInterrupt,
            Effect::DebugStop,
            Effect::SyncBreakpoints,
            Effect::ReadMemory(0x1000),
            Effect::StopProgram,
        ] {
            settle(&mut app, &mut session, effect).await;
        }
    }

    #[tokio::test]
    async fn a_running_program_can_be_stopped() {
        if !crate::process::is_available(Path::new("nasm"))
            || !crate::process::is_available(Path::new("ld"))
        {
            eprintln!("skipping: nasm or ld not installed");
            return;
        }

        let dir = tempfile::tempdir().expect("temp dir");
        let mut app = app_for(dir.path());
        std::fs::write(
            dir.path().join("src").join("main.asm"),
            "section .text\n    global _start\n_start:\n    jmp _start\n",
        )
        .expect("write the source");

        let (finished, _incoming) = tokio::sync::mpsc::unbounded_channel();
        let (pty_events, mut pty_incoming) = tokio::sync::mpsc::unbounded_channel();
        let mut runtimes = Runtimes::default();
        let mut session = None;

        perform(
            &mut app,
            &mut session,
            &finished,
            &pty_events,
            &mut runtimes,
            (160, 48),
            Effect::Run,
        )
        .await;
        assert!(
            runtimes.background.is_busy(),
            "the program should still be looping"
        );

        perform(
            &mut app,
            &mut session,
            &finished,
            &pty_events,
            &mut runtimes,
            (160, 48),
            Effect::StopProgram,
        )
        .await;
        assert_eq!(app.status.severity, crate::app::Severity::Warning);
        while runtimes.background.handle.is_some() {
            let event = tokio::time::timeout(Duration::from_secs(2), pty_incoming.recv())
                .await
                .expect("the stopped process should finish")
                .expect("PTY event channel");
            finish_pty_event(&mut app, &mut runtimes, event);
        }
        assert!(!runtimes.background.is_busy());
    }

    #[tokio::test]
    async fn stopping_with_nothing_running_says_so() {
        let dir = tempfile::tempdir().expect("temp dir");
        let mut app = app_for(dir.path());
        let mut session = None;

        settle(&mut app, &mut session, Effect::StopProgram).await;
        assert_eq!(app.status.severity, crate::app::Severity::Info);
    }

    #[tokio::test]
    async fn saving_through_an_effect_writes_the_file() {
        let dir = tempfile::tempdir().expect("temp dir");
        let mut app = app_for(dir.path());
        let mut session = None;

        app.workspace.active_mut().insert("ret\n");
        let path = dir.path().join("written.asm");
        settle(&mut app, &mut session, Effect::SaveFile(path.clone())).await;

        assert_eq!(std::fs::read_to_string(&path).expect("read"), "ret\n");
        assert_eq!(app.status.severity, crate::app::Severity::Success);
    }

    #[tokio::test]
    async fn opening_a_missing_file_reports_the_error() {
        let dir = tempfile::tempdir().expect("temp dir");
        let mut app = app_for(dir.path());
        let mut session = None;

        settle(
            &mut app,
            &mut session,
            Effect::OpenFile(dir.path().join("absent.asm")),
        )
        .await;
        assert_eq!(app.status.severity, crate::app::Severity::Error);
    }

    #[tokio::test]
    async fn the_explanation_gains_real_values_once_the_program_stops() {
        for tool in ["nasm", "ld", "gdb"] {
            if !crate::process::is_available(Path::new(tool)) {
                eprintln!("skipping: {tool} not installed");
                return;
            }
        }

        let dir = tempfile::tempdir().expect("temp dir");
        let mut app = app_for(dir.path());
        std::fs::write(
            app.project.entry_path(),
            "section .text\n    global _start\n_start:\n    mov rax, 1\n    mov rbx, 2\n    \
             add rax, rbx\n    mov rax, 60\n    xor edi, edi\n    syscall\n",
        )
        .expect("write");
        open_project_entry(&mut app);

        let mut session = None;
        let (_terminal_runtime, _terminal_events) =
            start_test_session(&mut app, &mut session).await;
        assert!(session.is_some(), "session: {}", app.status.text);

        settle(&mut app, &mut session, Effect::Step(StepKind::Instruction)).await;
        settle(&mut app, &mut session, Effect::Step(StepKind::Instruction)).await;

        assert_eq!(app.registers.value_of("rax"), Some(1));
        assert_eq!(app.registers.value_of("rbx"), Some(2));

        let explanation = app.current_explanation().expect("an explanation");
        assert_eq!(explanation.mnemonic, "add");
        assert_eq!(
            explanation.concrete.as_deref(),
            Some("RAX ← 0x1 + 0x2"),
            "the explainer should be reading live registers"
        );

        settle(&mut app, &mut session, Effect::DebugStop).await;
    }

    #[tokio::test]
    async fn stepping_backwards_restores_the_previous_register_values() {
        for tool in ["nasm", "ld", "gdb"] {
            if !crate::process::is_available(Path::new(tool)) {
                eprintln!("skipping: {tool} not installed");
                return;
            }
        }

        let dir = tempfile::tempdir().expect("temp dir");
        let mut app = app_for(dir.path());
        std::fs::write(
            app.project.entry_path(),
            "section .text\n    global _start\n_start:\n    mov rax, 1\n    mov rax, 2\n    \
             mov rax, 60\n    xor edi, edi\n    syscall\n",
        )
        .expect("write");

        let mut session = None;
        let (_terminal_runtime, _terminal_events) =
            start_test_session(&mut app, &mut session).await;
        assert!(session.is_some(), "session: {}", app.status.text);

        settle(&mut app, &mut session, Effect::Step(StepKind::Instruction)).await;
        assert_eq!(
            app.registers.value_of("rax"),
            Some(1),
            "after the first mov"
        );

        settle(&mut app, &mut session, Effect::Step(StepKind::Instruction)).await;
        assert_eq!(app.registers.value_of("rax"), Some(2), "after the second");

        settle(&mut app, &mut session, Effect::Step(StepKind::Back)).await;
        assert_eq!(
            app.registers.value_of("rax"),
            Some(1),
            "stepping back must undo the write, not just move RIP: {}",
            app.status.text
        );

        settle(&mut app, &mut session, Effect::DebugStop).await;
    }

    #[test]
    fn stepping_backwards_without_recording_says_why() {
        let dir = tempfile::tempdir().expect("temp dir");
        let mut app = app_for(dir.path());
        app.settings.debugger.record = false;

        assert_eq!(app.apply(&crate::command::Command::StepBack), Effect::None);
        assert_eq!(app.status.severity, crate::app::Severity::Warning);
        assert!(
            app.status.text.contains("record"),
            "the message should name the setting: {}",
            app.status.text
        );
    }

    #[tokio::test]
    async fn a_libc_program_is_debugged_from_main() {
        for tool in ["nasm", "gcc", "gdb"] {
            if !crate::process::is_available(Path::new(tool)) {
                eprintln!("skipping: {tool} not installed");
                return;
            }
        }
        let dir = tempfile::tempdir().expect("temp dir");
        let project = crate::project::Project::create_with_libc(dir.path(), "c").expect("create");
        let mut app = App::new(project, crate::config::Settings::default()).expect("app");
        app.settings.debugger.record = false;
        let mut session = None;
        let (mut terminal, _events) = start_test_session(&mut app, &mut session).await;
        assert!(session.is_some(), "{}", app.status.text);
        let (file, line) = app.current_line.clone().expect("stopped in the source");
        assert!(file.ends_with("main.asm"), "{}", file.display());
        assert_eq!(line, 18, "the first instruction of main");
        settle(&mut app, &mut session, Effect::DebugContinue).await;
        assert!(session.is_none(), "{}", app.status.text);
        terminal.abort();
    }

    #[test]
    fn the_disassembly_scrolls_to_the_instruction_being_executed() {
        let dir = tempfile::tempdir().expect("temp dir");
        let mut app = app_for(dir.path());
        let bytes = [0x90u8; 64];
        app.disassembly = disassembler::decode(&bytes, 0x1000, app.disassembly_syntax)
            .into_iter()
            .map(disassembler::DisassemblyLine::bare)
            .collect();
        app.scroll.fit(super::super::Panel::Disassembly, 64, 10);
        app.current_address = Some(0x1000 + 40);
        reveal_current_instruction(&mut app);
        let offset = app.scroll.offset(super::super::Panel::Disassembly);
        assert!((31..=38).contains(&offset), "{offset}");
    }

    #[test]
    fn renaming_and_deleting_keep_the_project_in_step() {
        let dir = tempfile::tempdir().expect("temp dir");
        let project = crate::project::Project::create(dir.path(), "demo").expect("create");
        let mut app = App::new(project, crate::config::Settings::default()).expect("app");
        let util = dir.path().join("src/util.asm");
        std::fs::write(&util, "ret\n").expect("write");
        app.project.add_source(&util).expect("add");
        app.workspace.open(&util).expect("open");
        app.toggle_breakpoint_in(&util, 1);

        let moved = dir.path().join("lib/helpers.asm");
        rename_file(&mut app, &util, &moved);
        assert!(moved.is_file() && !util.exists(), "{}", app.status.text);
        assert!(app.breakpoints.is_set_at(&moved, 1));
        let saved = std::fs::read_to_string(dir.path().join(".ratasm.toml")).expect("read");
        assert!(saved.contains("lib/helpers.asm"), "{saved}");

        delete_file(&mut app, &moved);
        assert!(!moved.exists());
        assert!(app.breakpoints.is_empty());
        assert!(!app.project.builds(&moved));

        let entry = app.project.entry_path();
        delete_file(&mut app, &entry);
        assert!(app.project.entry_path().exists(), "the entry is kept");
    }

    #[tokio::test]
    async fn breakpoint_edits_and_register_writes_reach_gdb() {
        for tool in ["nasm", "ld", "gdb"] {
            if !crate::process::is_available(Path::new(tool)) {
                eprintln!("skipping: {tool} not installed");
                return;
            }
        }
        let dir = tempfile::tempdir().expect("temp dir");
        let mut app = app_for(dir.path());
        app.settings.debugger.record = false;
        let entry = app.project.entry_path();
        std::fs::write(
            &entry,
            "global _start\n_start:\n    mov rcx, 5\nagain:\n    dec rcx\n    jnz again\n    \
             mov eax, 60\n    mov rdi, rbx\n    syscall\n",
        )
        .expect("write");
        app.workspace.open(&entry).expect("open");
        app.toggle_breakpoint_in(&entry, 5);
        app.breakpoints
            .set_condition(0, Some("$rcx == 2".to_owned()));

        let mut session = None;
        let (mut terminal, _events) = start_test_session(&mut app, &mut session).await;
        assert!(session.is_some(), "{}", app.status.text);
        settle(&mut app, &mut session, Effect::DebugContinue).await;
        assert_eq!(
            app.registers.value_of("rcx"),
            Some(2),
            "{}",
            app.status.text
        );

        settle(
            &mut app,
            &mut session,
            Effect::SetRegister("$rbx = 9".into()),
        )
        .await;
        assert_eq!(app.registers.value_of("rbx"), Some(9));

        app.breakpoints.toggle_line(&entry, 5);
        settle(&mut app, &mut session, Effect::SyncBreakpoints).await;
        settle(&mut app, &mut session, Effect::DebugContinue).await;
        assert!(session.is_none(), "{}", app.status.text);
        assert!(app.status.text.contains('9'), "{}", app.status.text);
        terminal.abort();
    }

    #[tokio::test]
    async fn the_flags_are_read_from_a_live_session() {
        for tool in ["nasm", "ld", "gdb"] {
            if !crate::process::is_available(Path::new(tool)) {
                eprintln!("skipping: {tool} not installed");
                return;
            }
        }

        let dir = tempfile::tempdir().expect("temp dir");
        let mut app = app_for(dir.path());
        std::fs::write(
            app.project.entry_path(),
            "section .text\n    global _start\n_start:\n    mov rax, 7\n    sub rax, rax\n    \
             mov rax, 60\n    xor edi, edi\n    syscall\n",
        )
        .expect("write");

        let mut session = None;
        let (_terminal_runtime, _terminal_events) =
            start_test_session(&mut app, &mut session).await;
        assert!(session.is_some(), "session: {}", app.status.text);

        settle(&mut app, &mut session, Effect::Step(StepKind::Instruction)).await;
        settle(&mut app, &mut session, Effect::Step(StepKind::Instruction)).await;

        let flags = app.registers.flags().expect("the flags must be readable");
        assert!(
            flags.has(crate::instruction::Flag::Zero),
            "ZF should be set after sub rax, rax; got {}",
            flags.summary()
        );

        settle(&mut app, &mut session, Effect::DebugStop).await;
    }

    #[tokio::test]
    async fn the_call_stack_shows_the_chain_of_calls() {
        for tool in ["nasm", "ld", "gdb"] {
            if !crate::process::is_available(Path::new(tool)) {
                eprintln!("skipping: {tool} not installed");
                return;
            }
        }

        let dir = tempfile::tempdir().expect("temp dir");
        let mut app = app_for(dir.path());
        std::fs::write(
            app.project.entry_path(),
            "section .text\n    global _start\nhelper:\n    nop\n    ret\n_start:\n    \
             call helper\n    mov rax, 60\n    xor edi, edi\n    syscall\n",
        )
        .expect("write");

        app.breakpoints.add_symbol("helper");

        let mut session = None;
        let (_terminal_runtime, _terminal_events) =
            start_test_session(&mut app, &mut session).await;
        assert!(session.is_some(), "session: {}", app.status.text);

        settle(&mut app, &mut session, Effect::DebugContinue).await;

        assert!(
            app.frames.len() >= 2,
            "expected a caller above the callee, got {:?}",
            app.frames.iter().map(|f| f.describe()).collect::<Vec<_>>()
        );
        assert_eq!(app.frames[0].function.as_deref(), Some("helper"));
        assert_eq!(app.frames[1].function.as_deref(), Some("_start"));
        assert!(app.frames[0].is_innermost());

        settle(&mut app, &mut session, Effect::DebugStop).await;
        assert!(
            app.frames.is_empty(),
            "frames must be cleared with the session"
        );
    }

    #[tokio::test]
    async fn a_full_debug_session_steps_and_updates_the_registers() {
        for tool in ["nasm", "ld", "gdb"] {
            if !crate::process::is_available(Path::new(tool)) {
                eprintln!("skipping: {tool} not installed");
                return;
            }
        }

        let dir = tempfile::tempdir().expect("temp dir");
        let mut app = app_for(dir.path());
        std::fs::write(
            app.project.entry_path(),
            "section .text\n    global _start\n_start:\n    mov rax, 1\n    mov rbx, 2\n    \
             add rax, rbx\n    mov rax, 60\n    xor edi, edi\n    syscall\n",
        )
        .expect("write");

        let mut session = None;
        let (_terminal_runtime, _terminal_events) =
            start_test_session(&mut app, &mut session).await;

        assert!(
            session.is_some(),
            "a session should be running: {}",
            app.status.text
        );
        assert_eq!(
            app.debugger.state(),
            crate::debugger::DebuggerState::Paused,
            "{}",
            app.status.text
        );
        assert!(!app.registers.is_empty(), "registers should have been read");
        assert!(app.current_address.is_some());

        let first = app.registers.rip();
        settle(&mut app, &mut session, Effect::Step(StepKind::Instruction)).await;
        let second = app.registers.rip();

        assert_ne!(first, second, "stepping must advance the program counter");
        assert!(!app.stack.is_empty(), "the stack should have been read");

        settle(&mut app, &mut session, Effect::DebugStop).await;
        assert!(session.is_none(), "the session should be gone");
        assert!(app.registers.is_empty(), "state should have been cleared");
    }

    #[tokio::test]
    async fn resuming_keeps_the_inferior_terminal_open() {
        let forever = || tokio::spawn(std::future::pending::<()>());
        let mut runtimes = Runtimes::default();
        runtimes.debugger.handle = Some(forever());
        assert!(runtimes.inferior_orphaned(false));
        assert!(!runtimes.inferior_orphaned(true));
        runtimes.background.handle = Some(forever());
        assert!(!runtimes.inferior_orphaned(false));
        runtimes.background.abort();
        runtimes.debugger.abort();
    }

    #[tokio::test]
    async fn a_recorded_program_runs_to_its_exit() {
        for tool in ["nasm", "ld", "gdb"] {
            if !crate::process::is_available(Path::new(tool)) {
                eprintln!("skipping: {tool} not installed");
                return;
            }
        }
        let dir = tempfile::tempdir().expect("temp dir");
        let mut app = app_for(dir.path());
        app.settings.debugger.record = true;
        std::fs::write(
            app.project.entry_path(),
            "global _start\n_start:\n    mov eax, 60\n    mov edi, 3\n    syscall\n",
        )
        .expect("write");

        let mut session = None;
        let (mut terminal, _events) = start_test_session(&mut app, &mut session).await;
        assert!(app.recording, "{}", app.status.text);

        settle(&mut app, &mut session, Effect::DebugContinue).await;
        assert!(app.at_exit, "{}", app.status.text);
        assert_ne!(app.status.severity, crate::app::Severity::Error);

        settle(&mut app, &mut session, Effect::DebugContinue).await;
        assert!(session.is_none(), "{}", app.status.text);
        assert!(app.status.text.contains('3'), "{}", app.status.text);
        terminal.abort();
    }

    #[tokio::test]
    async fn a_debugged_program_can_read_from_its_terminal() {
        for tool in ["nasm", "ld", "gdb"] {
            if !crate::process::is_available(Path::new(tool)) {
                eprintln!("skipping: {tool} not installed");
                return;
            }
        }

        let dir = tempfile::tempdir().expect("temp dir");
        let mut app = app_for(dir.path());
        app.settings.debugger.record = false;
        std::fs::write(
            app.project.entry_path(),
            "section .data\n    label db 'Got: '\n    label_len equ $-label\n\
             section .bss\n    input resb 16\n\
             section .text\n    global _start\n_start:\n\
             mov eax, 0\n    mov edi, 0\n    mov rsi, input\n    mov edx, 16\n    syscall\n\
             mov r12, rax\n    mov eax, 1\n    mov edi, 1\n    mov rsi, label\n\
             mov edx, label_len\n    syscall\n    mov eax, 1\n    mov rsi, input\n\
             mov rdx, r12\n    syscall\n    mov eax, 60\n    xor edi, edi\n    syscall\n",
        )
        .expect("write");

        let mut session = None;
        let (mut terminal_runtime, mut terminal_events) =
            start_test_session(&mut app, &mut session).await;
        assert!(session.is_some(), "session: {}", app.status.text);
        let input = terminal_runtime
            .control
            .as_ref()
            .expect("terminal input")
            .clone();
        let send_input = tokio::spawn(async move {
            tokio::time::sleep(Duration::from_millis(50)).await;
            input
                .send(PtyControl::Input(b"Ada\r".to_vec()))
                .expect("inferior terminal");
        });

        settle(&mut app, &mut session, Effect::DebugContinue).await;
        send_input.await.expect("input task");
        assert!(
            session.is_none(),
            "the program should have exited: {} ({})",
            app.status.text,
            app.debugger.state()
        );
        assert!(terminal_runtime.request_stop());

        let mut output = Vec::new();
        loop {
            let event = tokio::time::timeout(Duration::from_secs(2), terminal_events.recv())
                .await
                .expect("terminal should close")
                .expect("terminal event");
            match event {
                PtyEvent::Output(bytes) => output.extend(bytes),
                PtyEvent::Closed => break,
                PtyEvent::Finished(_) => panic!("debug endpoints do not own the inferior"),
            }
        }
        terminal_runtime.abort();

        let output = String::from_utf8_lossy(&output);
        assert!(output.contains("Got: Ada"), "{output:?}");
    }
}