croft-software 0.2.132

VSCode-style TUI written in Rust
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
//! Running notebook cells (#355): one Jupyter kernel per open notebook,
//! driven through `assets/jupyter/bridge.py`, and the edits that write a
//! run's outputs back into the notebook's JSON.
//!
//! The bridge speaks the Jupyter wire protocol through `jupyter_client`,
//! which every `ipykernel` install carries, so croft needs no ZMQ client of
//! its own and any installed kernelspec (not only Python) works. croft and
//! the bridge exchange JSON lines; outputs arrive already in nbformat v4
//! shape. Outputs are written into the buffer as ordinary edits, so Save
//! persists them the way Jupyter does and Undo takes a run back.

use std::path::{Path, PathBuf};
use std::sync::mpsc::{Receiver, Sender, channel};

use serde::{Deserialize, Serialize};
use serde_json::Value;

const BRIDGE: &str = include_str!("../assets/jupyter/bridge.py");

/// The kernel name that asks the bridge for the installed kernels only:
/// one [`Event::Specs`] (or an [`Event::Error`]) and nothing else.
pub const LIST_KERNELS: &str = "--list";

/// What croft asks the kernel to do.
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "op", rename_all = "lowercase")]
pub enum Request {
    Execute {
        id: String,
        code: String,
    },
    /// Runs whose outputs croft no longer keeps, so the bridge can drop
    /// what it tracks for them (#1475).
    Forget {
        ids: Vec<String>,
    },
    Interrupt,
    Restart,
    Shutdown,
}

/// What the kernel reports back.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(tag = "ev", rename_all = "lowercase")]
pub enum Event {
    Ready {
        kernel: String,
        display: String,
    },
    Output {
        id: String,
        output: Value,
    },
    Clear {
        id: String,
    },
    /// An updatable display changed (#1475): output `index` of run `id`,
    /// which may have finished long ago, is now `output`.
    Update {
        id: String,
        index: usize,
        output: Value,
    },
    Done {
        id: String,
        execution_count: Option<u64>,
        status: String,
    },
    Error {
        message: String,
    },
    /// The notebook's kernel is not installed here (#1377): the ones that
    /// are, so the user can pick one.
    Missing {
        kernel: String,
        specs: Vec<KernelSpec>,
    },
    /// The installed kernels, for Notebook: Select Kernel.
    Specs {
        specs: Vec<KernelSpec>,
    },
    /// The bridge exited (#878). Sent by croft itself when the bridge's
    /// output closes, not by the bridge, so a kernel that is gone is known
    /// before a request is handed to it and lost.
    Exited,
}

/// An installed kernelspec, as `jupyter kernelspec list` knows it.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct KernelSpec {
    pub name: String,
    pub display: String,
    #[serde(default)]
    pub language: String,
}

/// A notebook whose kernel is not installed, waiting for the user to pick
/// another: the name it asked for and what this machine has.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KernelChoice {
    pub requested: String,
    pub specs: Vec<KernelSpec>,
}

/// A notebook's kernel. Starting one never blocks: finding a Python with
/// `jupyter_client` and `ipykernel`, and the kernel's own start-up, happen
/// on a worker thread, and requests sent before it is ready wait there.
pub struct KernelSession {
    requests: Sender<Request>,
    events: Receiver<Event>,
}

impl KernelSession {
    pub fn start(workspace: &Path, cwd: &Path, kernel: &str) -> Self {
        let (req_tx, req_rx) = channel::<Request>();
        let (ev_tx, ev_rx) = channel::<Event>();
        let workspace = workspace.to_path_buf();
        let cwd = cwd.to_path_buf();
        let kernel = kernel.to_string();
        std::thread::spawn(move || run_bridge(&workspace, &cwd, &kernel, req_rx, ev_tx));
        Self {
            requests: req_tx,
            events: ev_rx,
        }
    }

    /// A session whose kernel is the test.
    #[cfg(test)]
    pub fn for_test() -> (Self, Sender<Event>, Receiver<Request>) {
        let (req_tx, req_rx) = channel();
        let (ev_tx, ev_rx) = channel();
        let session = Self {
            requests: req_tx,
            events: ev_rx,
        };
        (session, ev_tx, req_rx)
    }

    /// Send `request`; false when the bridge is gone (#878), so nothing
    /// will ever answer it.
    pub fn send(&self, request: Request) -> bool {
        self.requests.send(request).is_ok()
    }

    pub fn try_events(&self) -> Vec<Event> {
        self.events.try_iter().collect()
    }
}

impl Drop for KernelSession {
    fn drop(&mut self) {
        let _ = self.requests.send(Request::Shutdown);
    }
}

/// Pythons worth trying, most specific first: the workspace's own venv
/// (where a project's kernel and its dependencies live), the active venv,
/// then whatever `python3` is on PATH.
pub fn python_candidates(workspace: &Path, virtual_env: Option<&Path>) -> Vec<PathBuf> {
    let mut out: Vec<PathBuf> = [".venv", "venv"]
        .iter()
        .map(|d| workspace.join(d).join("bin").join("python"))
        .filter(|p| p.exists())
        .collect();
    if let Some(v) = virtual_env {
        let p = v.join("bin").join("python");
        if p.exists() && !out.contains(&p) {
            out.push(p);
        }
    }
    out.push(PathBuf::from("python3"));
    out
}

fn has_jupyter(python: &Path) -> bool {
    std::process::Command::new(python)
        .args(["-c", "import jupyter_client, ipykernel"])
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .is_ok_and(|s| s.success())
}

fn run_bridge(
    workspace: &Path,
    cwd: &Path,
    kernel: &str,
    requests: Receiver<Request>,
    events: Sender<Event>,
) {
    use std::io::{BufRead, Write};
    let venv = std::env::var_os("VIRTUAL_ENV").map(PathBuf::from);
    let Some(python) = python_candidates(workspace, venv.as_deref())
        .into_iter()
        .find(|p| has_jupyter(p))
    else {
        let _ = events.send(Event::Error {
            message: "no Python with jupyter_client and ipykernel found (install ipykernel in the project's .venv)".into(),
        });
        return;
    };
    let child = std::process::Command::new(&python)
        .arg("-c")
        .arg(BRIDGE)
        .arg(kernel)
        .arg(cwd)
        .current_dir(cwd)
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::null())
        .spawn();
    let mut child = match child {
        Ok(c) => c,
        Err(e) => {
            let _ = events.send(Event::Error {
                message: format!("cannot start {}: {e}", python.display()),
            });
            return;
        }
    };
    let (Some(mut stdin), Some(stdout)) = (child.stdin.take(), child.stdout.take()) else {
        return;
    };
    let reader_events = events.clone();
    let reader = std::thread::spawn(move || {
        for line in std::io::BufReader::new(stdout).lines() {
            let Ok(line) = line else { break };
            if let Ok(ev) = serde_json::from_str::<Event>(&line)
                && reader_events.send(ev).is_err()
            {
                break;
            }
        }
        let _ = reader_events.send(Event::Exited);
    });
    // The session hanging up (its notebook closed) is a shutdown too.
    for request in requests.iter().chain(std::iter::once(Request::Shutdown)) {
        let stop = matches!(request, Request::Shutdown);
        let Ok(mut line) = serde_json::to_string(&request) else {
            continue;
        };
        line.push('\n');
        if stdin
            .write_all(line.as_bytes())
            .and_then(|_| stdin.flush())
            .is_err()
            || stop
        {
            break;
        }
    }
    drop(stdin);
    let _ = child.wait();
    let _ = reader.join();
}

/// A notebook's kernel, the cells it still owes answers for, and events
/// that arrived while the notebook was not the active tab.
pub struct NotebookRun {
    session: KernelSession,
    pending: Vec<(String, CellRef)>,
    /// Runs that finished, each cell's latest only, so a display it made
    /// can still be updated from a later cell (#1475).
    finished: Vec<(String, CellRef)>,
    backlog: Vec<Event>,
    /// The kernel's display name, once it is up.
    pub kernel: Option<String>,
    /// Set when the notebook's kernel is not installed: the cells sent so
    /// far wait for the user to pick another (#1377).
    pub choice: Option<KernelChoice>,
    /// Set when the kernel never came up or its bridge exited (#878): this
    /// run answers nothing more and the next run needs a new kernel.
    ended: bool,
    sent: u64,
}

impl NotebookRun {
    pub fn new(session: KernelSession) -> Self {
        Self {
            session,
            pending: Vec::new(),
            finished: Vec::new(),
            backlog: Vec::new(),
            kernel: None,
            choice: None,
            ended: false,
            sent: 0,
        }
    }

    /// A run whose kernel is the test: it reads what croft sends and
    /// speaks for the kernel.
    #[cfg(test)]
    pub fn for_test() -> (Self, Sender<Event>, Receiver<Request>) {
        let (session, ev_tx, req_rx) = KernelSession::for_test();
        (Self::new(session), ev_tx, req_rx)
    }

    /// Send `cell` to the kernel. The kernel runs cells in the order they
    /// were sent, so Run All is simply every cell sent at once.
    pub fn execute(&mut self, cell: CellRef) {
        self.sent += 1;
        let id = format!("{}-{}", cell.index, self.sent);
        // The cell's outputs are about to go: an update to a display from
        // its last run has nothing left to replace.
        self.forget_finished(&cell);
        self.session.send(Request::Execute {
            id: id.clone(),
            code: cell.source.clone(),
        });
        self.pending.push((id, cell));
    }

    /// Send `request` to the kernel; false when its bridge is gone.
    pub fn send(&self, request: Request) -> bool {
        self.session.send(request)
    }

    /// Whether the kernel failed to start or its bridge exited (#878).
    pub fn ended(&self) -> bool {
        self.ended
    }

    /// Run on `session`'s kernel from now on: the old one is shut down and
    /// the cells still waiting are sent again, so a Run All that stopped
    /// on a missing kernel carries on with the chosen one.
    pub fn restart_with(&mut self, session: KernelSession) {
        self.session = session;
        self.kernel = None;
        self.choice = None;
        self.backlog.clear();
        for (id, cell) in &self.pending {
            self.session.send(Request::Execute {
                id: id.clone(),
                code: cell.source.clone(),
            });
        }
    }

    /// Drop `cell`'s earlier finished runs, and tell the bridge, so its
    /// display registrations do not pile up across reruns.
    fn forget_finished(&mut self, cell: &CellRef) {
        let (gone, kept): (Vec<_>, Vec<_>) = std::mem::take(&mut self.finished)
            .into_iter()
            .partition(|(_, done)| same_cell(done, cell));
        self.finished = kept;
        let ids: Vec<String> = gone.into_iter().map(|(id, _)| id).collect();
        if !ids.is_empty() {
            self.session.send(Request::Forget { ids });
        }
    }

    /// Cells running or queued, for the `In [*]` marks.
    pub fn running_indices(&self) -> Vec<usize> {
        self.pending.iter().map(|(_, c)| c.index).collect()
    }

    /// Take what the kernel has said since the last call.
    pub fn collect(&mut self) -> bool {
        let fresh = self.session.try_events();
        let any = !fresh.is_empty() || !self.backlog.is_empty();
        self.backlog.extend(fresh);
        any
    }

    /// Fold the collected events into the notebook's `text`. Returns the
    /// new text when a cell changed, and lines worth showing the user.
    pub fn fold(&mut self, text: &str) -> (Option<String>, Vec<String>) {
        let mut doc = text.to_string();
        let mut changed = false;
        let mut notes = Vec::new();
        for event in std::mem::take(&mut self.backlog) {
            let (id, edit) = match event {
                Event::Ready { display, .. } => {
                    // A second Ready is a restart: the old kernel will never
                    // finish what it had, so nothing still pending can
                    // complete. The bridge settles those cells first; this
                    // is the backstop if it could not.
                    if self.kernel.is_some() {
                        self.pending.clear();
                    } else {
                        // The kernel is up, so the cells waiting for it
                        // start now and their old outputs go now: a kernel
                        // that never starts leaves them as they were (#878).
                        for (_, cell) in &self.pending {
                            if let Some(next) = apply(&doc, cell, CellEdit::Begin) {
                                doc = next;
                                changed = true;
                            }
                        }
                    }
                    notes.push(format!("Kernel ready: {display}"));
                    self.kernel = Some(display);
                    continue;
                }
                Event::Error { message } => {
                    // A kernel that never came up will answer nothing: its
                    // bridge has exited (#878).
                    if self.kernel.is_none() {
                        self.pending.clear();
                        self.ended = true;
                    }
                    notes.push(format!("Kernel: {message}"));
                    continue;
                }
                Event::Exited => {
                    // Nothing will answer the cells still waiting, and a
                    // request sent now would be queued for nobody (#878).
                    self.pending.clear();
                    self.ended = true;
                    if self.kernel.take().is_some() {
                        notes.push(String::from("Kernel exited: the next run starts a new one"));
                    }
                    continue;
                }
                Event::Missing { kernel, specs } => {
                    // The cells stay queued: they run once a kernel is
                    // picked, and are dropped if the user declines.
                    notes.push(format!(
                        "Kernel '{kernel}' is not installed here: select one to run this notebook"
                    ));
                    self.choice = Some(KernelChoice {
                        requested: kernel,
                        specs,
                    });
                    continue;
                }
                Event::Specs { .. } => continue,
                Event::Output { id, output } => (id, CellEdit::Output(output)),
                Event::Clear { id } => (id, CellEdit::Clear),
                Event::Update { id, index, output } => {
                    let cell = self
                        .pending
                        .iter()
                        .chain(&self.finished)
                        .find(|(p, _)| *p == id)
                        .map(|(_, c)| c.clone());
                    if let Some(next) =
                        cell.and_then(|cell| apply(&doc, &cell, CellEdit::Replace(index, output)))
                    {
                        doc = next;
                        changed = true;
                    }
                    continue;
                }
                Event::Done {
                    id,
                    execution_count,
                    ..
                } => (id, CellEdit::Done(execution_count)),
            };
            let Some(pos) = self.pending.iter().position(|(p, _)| *p == id) else {
                continue;
            };
            let cell = if matches!(edit, CellEdit::Done(_)) {
                let (id, cell) = self.pending.remove(pos);
                self.forget_finished(&cell);
                self.finished.push((id, cell.clone()));
                cell
            } else {
                self.pending[pos].1.clone()
            };
            if let Some(next) = apply(&doc, &cell, edit) {
                doc = next;
                changed = true;
            }
        }
        (changed.then_some(doc), notes)
    }
}

/// The kernel a notebook asks for (`metadata.kernelspec.name`).
pub fn kernel_name(doc_text: &str) -> String {
    serde_json::from_str::<Value>(doc_text)
        .ok()
        .and_then(|d| {
            d.pointer("/metadata/kernelspec/name")
                .and_then(Value::as_str)
                .map(str::to_string)
        })
        .unwrap_or_else(|| "python3".into())
}

/// The notebook's language (`metadata.kernelspec.language`, else
/// `metadata.language_info.name`), lowercased.
pub fn notebook_language(doc_text: &str) -> Option<String> {
    let doc = serde_json::from_str::<Value>(doc_text).ok()?;
    [
        "/metadata/kernelspec/language",
        "/metadata/language_info/name",
    ]
    .iter()
    .find_map(|p| doc.pointer(p).and_then(Value::as_str))
    .filter(|l| !l.is_empty())
    .map(str::to_lowercase)
}

/// The kernel a picker opens on: `current` when it is installed, else the
/// first one for the notebook's `language`, else the first.
pub fn preferred_kernel(specs: &[KernelSpec], current: &str, language: Option<&str>) -> usize {
    specs
        .iter()
        .position(|s| s.name == current)
        .or_else(|| {
            let language = language?;
            specs
                .iter()
                .position(|s| s.language.eq_ignore_ascii_case(language))
        })
        .unwrap_or(0)
}

/// `doc_text` with `metadata.kernelspec` naming `spec`, as Jupyter writes
/// it when a kernel is changed; other metadata is kept.
pub fn set_kernelspec(doc_text: &str, spec: &KernelSpec) -> Option<String> {
    let mut doc: Value = serde_json::from_str(doc_text).ok()?;
    let root = doc.as_object_mut()?;
    let metadata = root
        .entry("metadata")
        .or_insert_with(|| Value::Object(Default::default()))
        .as_object_mut()?;
    let ks = metadata
        .entry("kernelspec")
        .or_insert_with(|| Value::Object(Default::default()));
    if !ks.is_object() {
        *ks = Value::Object(Default::default());
    }
    let ks = ks.as_object_mut()?;
    ks.insert("name".into(), Value::from(spec.name.clone()));
    ks.insert("display_name".into(), Value::from(spec.display.clone()));
    if !spec.language.is_empty() {
        ks.insert("language".into(), Value::from(spec.language.clone()));
    }
    Some(render(&doc))
}

/// A code cell as sent to the kernel: where it is and what it says.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CellRef {
    /// Position in `cells` when the run was asked for.
    pub index: usize,
    /// nbformat 4.5's cell id, when the file has one: it finds the cell
    /// again after cells above it were added or removed mid-run.
    pub cell_id: Option<String>,
    pub source: String,
}

/// Every code cell, in order: what Run All sends.
pub fn code_cells(doc_text: &str) -> Vec<CellRef> {
    let Ok(doc) = serde_json::from_str::<Value>(doc_text) else {
        return Vec::new();
    };
    doc["cells"]
        .as_array()
        .map(|cells| {
            cells
                .iter()
                .enumerate()
                .filter(|(_, c)| c["cell_type"] == "code")
                .map(|(i, c)| cell_ref(i, c))
                .collect()
        })
        .unwrap_or_default()
}

/// The code cell at `index`.
pub fn code_cell(doc_text: &str, index: usize) -> Option<CellRef> {
    let doc = serde_json::from_str::<Value>(doc_text).ok()?;
    let cell = doc["cells"].get(index)?;
    (cell["cell_type"] == "code").then(|| cell_ref(index, cell))
}

fn cell_ref(index: usize, cell: &Value) -> CellRef {
    CellRef {
        index,
        cell_id: cell["id"].as_str().map(str::to_string),
        source: joined(&cell["source"]),
    }
}

/// nbformat stores multi-line strings as a list of lines.
fn joined(v: &Value) -> String {
    match v {
        Value::String(s) => s.clone(),
        Value::Array(parts) => parts.iter().filter_map(Value::as_str).collect(),
        _ => String::new(),
    }
}

/// Split text into nbformat's list-of-lines form, each line keeping its
/// newline, as Jupyter writes it.
fn lines_of(text: &str) -> Value {
    Value::Array(
        text.split_inclusive('\n')
            .map(|l| Value::String(l.to_string()))
            .collect(),
    )
}

/// An output as the kernel sent it, with its text fields in the form
/// Jupyter saves.
fn stored(mut output: Value) -> Value {
    if let Some(text) = output
        .get("text")
        .and_then(Value::as_str)
        .map(str::to_string)
    {
        output["text"] = lines_of(&text);
    }
    if let Some(data) = output.get_mut("data").and_then(Value::as_object_mut) {
        for (mime, value) in data.iter_mut() {
            let textual = mime.starts_with("text/") || mime == "application/javascript";
            if textual && let Some(text) = value.as_str().map(str::to_string) {
                *value = lines_of(&text);
            }
        }
    }
    output
}

/// Whether two runs were of the same cell: by nbformat id when it has one,
/// else by position.
fn same_cell(a: &CellRef, b: &CellRef) -> bool {
    match (&a.cell_id, &b.cell_id) {
        (Some(x), Some(y)) => x == y,
        _ => a.index == b.index,
    }
}

/// A change a kernel event makes to one cell.
pub enum CellEdit {
    /// The run is starting: old outputs and count go.
    Begin,
    Output(Value),
    /// Output `index` takes this one's data and metadata, when the cell
    /// still has it (#1475).
    Replace(usize, Value),
    Clear,
    Done(Option<u64>),
}

/// `doc_text` with `edit` applied to `cell`, or `None` when the cell can no
/// longer be found (deleted mid-run) or the buffer is not valid JSON.
pub fn apply(doc_text: &str, cell: &CellRef, edit: CellEdit) -> Option<String> {
    let mut doc: Value = serde_json::from_str(doc_text).ok()?;
    let cells = doc.get_mut("cells")?.as_array_mut()?;
    let at = match &cell.cell_id {
        Some(id) => cells.iter().position(|c| c["id"] == id.as_str())?,
        None => cell.index,
    };
    let target = cells.get_mut(at)?.as_object_mut()?;
    if target.get("cell_type").and_then(Value::as_str) != Some("code") {
        return None;
    }
    let outputs = target
        .entry("outputs")
        .or_insert_with(|| Value::Array(Vec::new()));
    match edit {
        CellEdit::Begin => {
            *outputs = Value::Array(Vec::new());
            target.insert("execution_count".into(), Value::Null);
        }
        CellEdit::Output(output) => {
            if let Some(list) = outputs.as_array_mut() {
                list.push(stored(output));
            }
        }
        CellEdit::Replace(index, output) => {
            // Only the display's data and metadata change, as in Jupyter:
            // an `execute_result` keeps its type and execution count.
            let slot = outputs
                .as_array_mut()
                .and_then(|list| list.get_mut(index))
                .and_then(Value::as_object_mut)?;
            let mut output = stored(output);
            for field in ["data", "metadata"] {
                slot.insert(field.into(), output[field].take());
            }
        }
        CellEdit::Clear => *outputs = Value::Array(Vec::new()),
        CellEdit::Done(count) => {
            target.insert(
                "execution_count".into(),
                count.map_or(Value::Null, Value::from),
            );
        }
    }
    Some(render(&doc))
}

/// One-space indentation, sorted keys and a trailing newline: nbformat's
/// own layout, so a notebook Jupyter wrote keeps its shape.
fn render(doc: &Value) -> String {
    let mut out = Vec::new();
    let fmt = serde_json::ser::PrettyFormatter::with_indent(b" ");
    let mut ser = serde_json::Serializer::with_formatter(&mut out, fmt);
    if doc.serialize(&mut ser).is_err() {
        return String::new();
    }
    let mut text = String::from_utf8(out).unwrap_or_default();
    text.push('\n');
    text
}

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

    const NB: &str = "{\n \"cells\": [\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# t\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 7,\n   \"id\": \"c-a\",\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"old\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"print(1+1)\\n\",\n    \"40+2\"\n   ]\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"Python 3\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n";

    #[test]
    fn code_cells_and_the_kernel_come_from_the_notebook() {
        assert_eq!(kernel_name(NB), "python3");
        assert_eq!(kernel_name("{\"cells\": []}"), "python3");
        let cells = code_cells(NB);
        assert_eq!(cells.len(), 1);
        assert_eq!(cells[0].index, 1);
        assert_eq!(cells[0].cell_id.as_deref(), Some("c-a"));
        assert_eq!(cells[0].source, "print(1+1)\n40+2");
        assert_eq!(code_cell(NB, 1), Some(cells[0].clone()));
        assert_eq!(code_cell(NB, 0), None, "a markdown cell does not run");
    }

    #[test]
    fn a_run_replaces_outputs_and_count_in_jupyter_layout() {
        let cell = code_cell(NB, 1).unwrap();
        let t = apply(NB, &cell, CellEdit::Begin).unwrap();
        assert!(!t.contains("old"));
        let t = apply(
            &t,
            &cell,
            CellEdit::Output(
                serde_json::json!({"output_type": "stream", "name": "stdout", "text": "2\n"}),
            ),
        )
        .unwrap();
        let t = apply(
            &t,
            &cell,
            CellEdit::Output(serde_json::json!({"output_type": "execute_result", "execution_count": 1, "data": {"text/plain": "42"}, "metadata": {}})),
        )
        .unwrap();
        let t = apply(&t, &cell, CellEdit::Done(Some(1))).unwrap();
        let expected = NB
            .replace("\"execution_count\": 7", "\"execution_count\": 1")
            .replace(
                "   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"old\\n\"\n     ]\n    }\n   ],",
                "   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"2\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"42\"\n      ]\n     },\n     \"execution_count\": 1,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],",
            );
        assert_eq!(t, expected);
    }

    #[test]
    fn a_cell_is_found_by_id_after_cells_move_and_lost_when_deleted() {
        let cell = code_cell(NB, 1).unwrap();
        // A cell inserted above: index 1 is now the new cell, id still finds ours.
        let moved = NB.replacen(
            "  {\n   \"cell_type\": \"markdown\"",
            "  {\n   \"cell_type\": \"code\", \"id\": \"new\", \"metadata\": {}, \"outputs\": [], \"source\": [], \"execution_count\": null\n  },\n  {\n   \"cell_type\": \"markdown\"",
            1,
        );
        let t = apply(&moved, &cell, CellEdit::Done(Some(9))).unwrap();
        let doc: Value = serde_json::from_str(&t).unwrap();
        assert_eq!(doc["cells"][2]["execution_count"], 9);
        assert_eq!(doc["cells"][0]["execution_count"], Value::Null);
        let gone = r#"{"cells": [{"cell_type": "markdown", "source": []}]}"#;
        assert!(apply(gone, &cell, CellEdit::Done(Some(1))).is_none());
    }

    #[test]
    fn candidates_prefer_the_workspace_venv() {
        let dir = tempfile::tempdir().unwrap();
        let py = dir.path().join(".venv/bin/python");
        std::fs::create_dir_all(py.parent().unwrap()).unwrap();
        std::fs::write(&py, "").unwrap();
        let c = python_candidates(dir.path(), None);
        assert_eq!(c, vec![py, PathBuf::from("python3")]);
    }

    /// Runs a real kernel. Set `CROFT_TEST_JUPYTER_PYTHON` to the `python`
    /// of a venv with ipykernel; the test links that whole venv in as the
    /// workspace's `.venv` (a venv's python moved out of its venv is the
    /// bare base interpreter).
    #[test]
    #[ignore = "needs a Python with ipykernel; set CROFT_TEST_JUPYTER_PYTHON"]
    fn a_real_kernel_runs_prints_and_survives_an_interrupt() {
        let python = PathBuf::from(std::env::var("CROFT_TEST_JUPYTER_PYTHON").unwrap());
        let dir = tempfile::tempdir().unwrap();
        let venv = python.parent().and_then(Path::parent).unwrap();
        std::os::unix::fs::symlink(venv, dir.path().join(".venv")).unwrap();
        let k = KernelSession::start(dir.path(), dir.path(), "python3");
        let wait = |pred: &dyn Fn(&Event) -> bool| -> Vec<Event> {
            let end = std::time::Instant::now() + std::time::Duration::from_secs(60);
            let mut seen = Vec::new();
            while std::time::Instant::now() < end {
                for ev in k.try_events() {
                    assert!(!matches!(ev, Event::Error { .. }), "{ev:?}");
                    let hit = pred(&ev);
                    seen.push(ev);
                    if hit {
                        return seen;
                    }
                }
                std::thread::sleep(std::time::Duration::from_millis(20));
            }
            panic!("timed out; saw {seen:?}");
        };
        k.send(Request::Execute {
            id: "a".into(),
            code: "print(1+1)".into(),
        });
        let seen = wait(&|e| matches!(e, Event::Done { .. }));
        assert!(matches!(seen[0], Event::Ready { .. }), "{seen:?}");
        assert!(
            seen.iter()
                .any(|e| matches!(e, Event::Output { output, .. } if output["text"] == "2\n"))
        );
        k.send(Request::Execute {
            id: "b".into(),
            code: "import time\nwhile True: time.sleep(0.05)".into(),
        });
        std::thread::sleep(std::time::Duration::from_millis(800));
        k.send(Request::Interrupt);
        let seen = wait(&|e| matches!(e, Event::Done { .. }));
        assert!(seen.iter().any(
            |e| matches!(e, Event::Done { id, status, .. } if id == "b" && status == "error")
        ));
        k.send(Request::Execute {
            id: "c".into(),
            code: "6*7".into(),
        });
        let seen = wait(&|e| matches!(e, Event::Done { .. }));
        assert!(seen.iter().any(
            |e| matches!(e, Event::Output { output, .. } if output["data"]["text/plain"] == "42")
        ));
    }

    fn spec(name: &str, display: &str, language: &str) -> KernelSpec {
        KernelSpec {
            name: name.into(),
            display: display.into(),
            language: language.into(),
        }
    }

    fn installed() -> Vec<KernelSpec> {
        vec![
            spec("ir", "R", "R"),
            spec("python3", "Python 3 (ipykernel)", "python"),
        ]
    }

    #[test]
    fn a_missing_kernel_keeps_the_cells_until_another_is_chosen() {
        let (mut run, _kernel, _old) = NotebookRun::for_test();
        run.execute(code_cell(NB, 1).unwrap());
        run.backlog = vec![Event::Missing {
            kernel: "conda-env-ds-py".into(),
            specs: installed(),
        }];
        let (text, notes) = run.fold(NB);
        assert!(text.is_none());
        assert_eq!(
            notes,
            vec![
                "Kernel 'conda-env-ds-py' is not installed here: select one to run this notebook"
                    .to_string()
            ]
        );
        assert_eq!(
            run.choice,
            Some(KernelChoice {
                requested: "conda-env-ds-py".into(),
                specs: installed(),
            })
        );
        assert_eq!(
            run.running_indices(),
            vec![1],
            "the cell waits for a kernel"
        );
        // The chosen kernel gets the cell that was waiting.
        let (session, _events, requests) = KernelSession::for_test();
        run.restart_with(session);
        assert!(run.choice.is_none());
        match requests.try_iter().collect::<Vec<_>>().as_slice() {
            [Request::Execute { code, .. }] => assert_eq!(code, "print(1+1)\n40+2"),
            other => panic!("expected the waiting cell, got {other:?}"),
        }
        assert_eq!(run.running_indices(), vec![1]);
    }

    #[test]
    fn the_picker_opens_on_the_notebooks_kernel_or_its_language() {
        let specs = installed();
        assert_eq!(preferred_kernel(&specs, "ir", Some("python")), 0);
        assert_eq!(
            preferred_kernel(&specs, "conda-env-ds-py", Some("python")),
            1
        );
        assert_eq!(preferred_kernel(&specs, "conda-env-ds-py", Some("r")), 0);
        // Negative: nothing matches, so the first row.
        assert_eq!(preferred_kernel(&specs, "julia-1.10", Some("julia")), 0);
        assert_eq!(preferred_kernel(&specs, "gone", None), 0);
        let nb = r#"{"metadata":{"kernelspec":{"name":"conda-env-ds-py","language":"Python"}},"cells":[]}"#;
        assert_eq!(notebook_language(nb).as_deref(), Some("python"));
        let info = r#"{"metadata":{"language_info":{"name":"python"}},"cells":[]}"#;
        assert_eq!(notebook_language(info).as_deref(), Some("python"));
        assert_eq!(notebook_language(r#"{"cells":[]}"#), None);
    }

    #[test]
    fn choosing_a_kernel_writes_it_into_the_notebook_metadata() {
        let nb = NB.replace("\"name\": \"python3\"", "\"name\": \"conda-env-ds-py\"");
        let out = set_kernelspec(&nb, &spec("python3", "Python 3 (ipykernel)", "python")).unwrap();
        let doc: Value = serde_json::from_str(&out).unwrap();
        assert_eq!(doc["metadata"]["kernelspec"]["name"], "python3");
        assert_eq!(
            doc["metadata"]["kernelspec"]["display_name"],
            "Python 3 (ipykernel)"
        );
        assert_eq!(doc["metadata"]["kernelspec"]["language"], "python");
        assert_eq!(kernel_name(&out), "python3");
        // Negative: the cells and the rest of the file are untouched.
        assert_eq!(
            doc["cells"],
            serde_json::from_str::<Value>(NB).unwrap()["cells"]
        );
        assert_eq!(doc["nbformat_minor"], 5);
        // A notebook with no metadata gets one.
        let bare = set_kernelspec(r#"{"cells":[]}"#, &spec("ir", "R", "R")).unwrap();
        assert_eq!(kernel_name(&bare), "ir");
    }

    fn run_without_kernel() -> NotebookRun {
        NotebookRun::for_test().0
    }

    #[test]
    fn folding_events_writes_outputs_and_clears_the_running_mark() {
        let mut run = run_without_kernel();
        let cell = code_cell(NB, 1).unwrap();
        run.execute(cell);
        assert_eq!(run.running_indices(), vec![1]);
        let id = run.pending[0].0.clone();
        run.backlog = vec![
            Event::Ready {
                kernel: "python3".into(),
                display: "Python 3".into(),
            },
            Event::Output {
                id: id.clone(),
                output: serde_json::json!({"output_type": "stream", "name": "stdout", "text": "2\n"}),
            },
            Event::Output {
                id: "someone-else".into(),
                output: serde_json::json!({"output_type": "stream", "name": "stdout", "text": "stray\n"}),
            },
            Event::Done {
                id,
                execution_count: Some(3),
                status: "ok".into(),
            },
        ];
        let (text, notes) = run.fold(NB);
        let doc: Value = serde_json::from_str(&text.unwrap()).unwrap();
        assert_eq!(doc["cells"][1]["execution_count"], 3);
        let outputs = doc["cells"][1]["outputs"].as_array().unwrap();
        assert_eq!(
            outputs.len(),
            1,
            "the kernel coming up cleared the old output; no stray: {outputs:?}"
        );
        assert_eq!(outputs[0]["text"][0], "2\n");
        assert_eq!(notes, vec!["Kernel ready: Python 3".to_string()]);
        assert!(run.running_indices().is_empty());
        assert_eq!(run.kernel.as_deref(), Some("Python 3"));
    }

    #[test]
    fn a_kernel_that_never_starts_leaves_nothing_running() {
        let mut run = run_without_kernel();
        run.execute(code_cell(NB, 1).unwrap());
        run.backlog = vec![Event::Error {
            message: "no Python".into(),
        }];
        let (text, notes) = run.fold(NB);
        assert!(text.is_none(), "the cell keeps its outputs and count");
        assert_eq!(notes, vec!["Kernel: no Python".to_string()]);
        assert!(run.running_indices().is_empty());
        assert!(run.ended(), "#878: the next run needs a new kernel");
        // Negative: a failed request on a kernel that is up is not a
        // failed start; the kernel keeps serving.
        let mut up = run_without_kernel();
        up.backlog = vec![
            Event::Ready {
                kernel: "python3".into(),
                display: "Python 3".into(),
            },
            Event::Error {
                message: "restart: Invalid Signature".into(),
            },
        ];
        up.fold(NB);
        assert!(!up.ended());
        // A bridge that exits after its kernel came up ends the run too:
        // the cells it owed stop waiting and the next run starts afresh.
        up.execute(code_cell(NB, 1).unwrap());
        up.backlog = vec![Event::Exited];
        let (_, notes) = up.fold(NB);
        assert!(up.ended());
        assert!(up.running_indices().is_empty());
        assert_eq!(
            notes,
            vec!["Kernel exited: the next run starts a new one".to_string()]
        );
    }

    #[test]
    fn a_restart_settles_cells_the_old_kernel_was_running() {
        let mut run = run_without_kernel();
        let ready = || Event::Ready {
            kernel: "python3".into(),
            display: "Python 3".into(),
        };
        run.backlog = vec![ready()];
        run.fold(NB);
        run.execute(code_cell(NB, 1).unwrap());
        assert_eq!(run.running_indices(), vec![1]);
        // The restarted kernel announces itself; the old one never answers.
        run.backlog = vec![ready()];
        run.fold(NB);
        assert!(
            run.running_indices().is_empty(),
            "no cell stays at In [*] across a restart"
        );
        // The first Ready of a run is not a restart: it clears nothing.
        let mut fresh = run_without_kernel();
        fresh.execute(code_cell(NB, 1).unwrap());
        fresh.backlog = vec![ready()];
        fresh.fold(NB);
        assert_eq!(fresh.running_indices(), vec![1]);
    }

    /// A stand-in for `jupyter_client` (#1477): it records which threads
    /// touch the kernel client, and with `FAKE_RESTART_FAIL` set fails the
    /// restart's `wait_for_ready` the way a socket race does. A code cell
    /// containing `hang` never finishes, like a runaway loop.
    const FAKE_JUPYTER: &str = r#"# A stand-in for jupyter_client that records which threads touch the
# kernel's sockets, and can fail a restart the way a socket race does.
import json, os, queue, threading, time

touched = set()


class Spec:
    display_name = "Fake"


class Client:
    def __init__(self):
        self.n = 0
        self.msgs = []
        self.up = False
        self.restarted = False

    def mark(self):
        if self.up:
            touched.add(threading.current_thread().name)

    def start_channels(self):
        pass

    def wait_for_ready(self, timeout=None):
        self.mark()
        if self.restarted and os.environ.get("FAKE_RESTART_FAIL"):
            raise RuntimeError("Invalid Signature")
        self.up = True

    def execute(self, code, store_history=True):
        self.mark()
        self.n += 1
        mid = "m%d" % self.n
        # `emit:[[msg_type, content], ...]` plays those iopub messages.
        if code.startswith("emit:"):
            for kind, content in json.loads(code[5:]):
                self.msgs.append({"parent_header": {"msg_id": mid},
                                  "msg_type": kind, "content": content})
        if "hang" not in code:
            self.msgs.append({"parent_header": {"msg_id": mid}, "msg_type": "status",
                              "content": {"execution_state": "idle"}})
        return mid

    def get_iopub_msg(self, timeout=None):
        self.mark()
        if self.msgs:
            return self.msgs.pop(0)
        time.sleep(min(timeout or 0, 0.02))
        raise queue.Empty

    def get_shell_msg(self, timeout=None):
        self.mark()
        time.sleep(min(timeout or 0, 0.02))
        raise queue.Empty

    def stop_channels(self):
        with open(os.environ["FAKE_TOUCHED"], "w") as f:
            json.dump(sorted(touched), f)


class KernelManager:
    def __init__(self, kernel_name=None):
        self.kernel_spec = Spec()
        self.c = Client()

    def start_kernel(self, cwd=None):
        pass

    def client(self):
        return self.c

    def restart_kernel(self, now=False):
        self.c.mark()
        self.c.restarted = True

    def interrupt_kernel(self):
        pass

    def shutdown_kernel(self, now=False):
        pass
"#;

    /// Runs the real bridge against the fake kernel with `requests` as its
    /// stdin; returns what it emitted and the threads that used the client.
    fn bridge_against_fake(requests: &[&str], restart_fails: bool) -> (Vec<Event>, Vec<String>) {
        bridge_run("python3", requests, restart_fails, false)
    }

    /// The installed kernels the fake `jupyter_client` reports (#1377).
    const FAKE_KERNELSPEC: &str = r#"class KernelSpecManager:
    def get_all_specs(self):
        return {
            "python3": {"resource_dir": "", "spec": {"display_name": "Python 3 (ipykernel)", "language": "python"}},
            "ir": {"resource_dir": "", "spec": {"display_name": "R", "language": "R"}},
        }
"#;

    fn bridge_run(
        kernel: &str,
        requests: &[&str],
        restart_fails: bool,
        with_specs: bool,
    ) -> (Vec<Event>, Vec<String>) {
        let tmp = tempfile::tempdir().unwrap();
        let pkg = tmp.path().join("jupyter_client");
        std::fs::create_dir_all(&pkg).unwrap();
        std::fs::write(pkg.join("__init__.py"), "").unwrap();
        std::fs::write(pkg.join("manager.py"), FAKE_JUPYTER).unwrap();
        if with_specs {
            std::fs::write(pkg.join("kernelspec.py"), FAKE_KERNELSPEC).unwrap();
        }
        let touched = tmp.path().join("touched.json");
        let mut cmd = std::process::Command::new("python3");
        cmd.arg("-c")
            .arg(BRIDGE)
            .arg(kernel)
            .arg(tmp.path())
            .env("PYTHONPATH", tmp.path())
            .env("FAKE_TOUCHED", &touched)
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::null());
        if restart_fails {
            cmd.env("FAKE_RESTART_FAIL", "1");
        }
        let mut child = cmd.spawn().unwrap();
        {
            use std::io::Write;
            let mut stdin = child.stdin.take().unwrap();
            // A bridge that already exited (a missing kernel, a listing)
            // reads none of it.
            for r in requests {
                let _ = writeln!(stdin, "{r}");
            }
            // Let the bridge work through them before it is told to stop.
            std::thread::sleep(std::time::Duration::from_millis(800));
            let _ = writeln!(stdin, r#"{{"op":"shutdown"}}"#);
        }
        let out = child.wait_with_output().unwrap();
        let events = String::from_utf8_lossy(&out.stdout)
            .lines()
            .filter_map(|l| serde_json::from_str(l).ok())
            .collect();
        let touched: Vec<String> = std::fs::read_to_string(&touched)
            .ok()
            .and_then(|t| serde_json::from_str(&t).ok())
            .unwrap_or_default();
        (events, touched)
    }

    const RUN_HANG_RESTART_RUN: [&str; 4] = [
        r#"{"op":"execute","id":"a","code":"x = 1"}"#,
        r#"{"op":"execute","id":"h","code":"hang"}"#,
        r#"{"op":"restart"}"#,
        r#"{"op":"execute","id":"b","code":"print('after')"}"#,
    ];

    fn done_status(events: &[Event], cell: &str) -> Option<String> {
        events.iter().find_map(|e| match e {
            Event::Done { id, status, .. } if id == cell => Some(status.clone()),
            _ => None,
        })
    }

    #[test]
    fn one_thread_owns_the_kernel_sockets_across_a_restart() {
        if !crate::lsp::manager::is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let (events, touched) = bridge_against_fake(&RUN_HANG_RESTART_RUN, false);
        // zmq sockets are not thread-safe: a second reader is what lost the
        // restart's reply and left cells at In [*].
        assert_eq!(
            touched.len(),
            1,
            "threads that used the client: {touched:?}"
        );
        let readies = events
            .iter()
            .filter(|e| matches!(e, Event::Ready { .. }))
            .count();
        assert_eq!(
            readies, 2,
            "the restart must announce the new kernel: {events:?}"
        );
        assert_eq!(
            done_status(&events, "b").as_deref(),
            Some("ok"),
            "{events:?}"
        );
    }

    #[test]
    fn a_failed_restart_still_settles_the_cells_it_lost() {
        if !crate::lsp::manager::is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let (events, _) = bridge_against_fake(&RUN_HANG_RESTART_RUN, true);
        assert_eq!(
            done_status(&events, "h").as_deref(),
            Some("error"),
            "the runaway cell must not stay at In [*]: {events:?}"
        );
        assert!(
            events.iter().any(|e| matches!(
                e,
                Event::Error { message } if message.starts_with("restart:")
            )),
            "the failure is reported: {events:?}"
        );
        // The bridge keeps serving after it.
        assert_eq!(
            done_status(&events, "b").as_deref(),
            Some("ok"),
            "{events:?}"
        );
    }

    /// Negative: without a restart, a finished cell is reported once, as ok,
    /// and nothing is settled as failed.
    #[test]
    fn cells_without_a_restart_finish_ok() {
        if !crate::lsp::manager::is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let (events, _) = bridge_against_fake(
            &[
                r#"{"op":"execute","id":"a","code":"x = 1"}"#,
                r#"{"op":"execute","id":"b","code":"y = 2"}"#,
            ],
            false,
        );
        assert_eq!(done_status(&events, "a").as_deref(), Some("ok"));
        assert_eq!(done_status(&events, "b").as_deref(), Some("ok"));
        assert!(
            !events.iter().any(|e| matches!(e, Event::Error { .. })),
            "{events:?}"
        );
    }

    /// An iopub message of `kind` for the fake kernel's `emit:` cells.
    fn iopub(kind: &str, text: &str, display_id: Option<&str>) -> Value {
        let mut content = serde_json::json!({"data": {"text/plain": text}, "metadata": {}});
        if let Some(id) = display_id {
            content["transient"] = serde_json::json!({ "display_id": id });
        }
        serde_json::json!([kind, content])
    }

    fn emitting(id: &str, msgs: &[Value]) -> String {
        let code = format!("emit:{}", Value::Array(msgs.to_vec()));
        serde_json::json!({"op": "execute", "id": id, "code": code}).to_string()
    }

    fn updates(events: &[Event]) -> Vec<(String, usize, String)> {
        events
            .iter()
            .filter_map(|e| match e {
                Event::Update { id, index, output } => Some((
                    id.clone(),
                    *index,
                    output["data"]["text/plain"]
                        .as_str()
                        .unwrap_or("")
                        .to_string(),
                )),
                _ => None,
            })
            .collect()
    }

    /// #1475: `display(..., display_id=True)` then `.update()` reaches croft
    /// as an update of that output, from its own cell or a later one.
    #[test]
    fn the_bridge_turns_display_updates_into_replacements() {
        if !crate::lsp::manager::is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let stream = serde_json::json!(["stream", {"name": "stdout", "text": "done\n"}]);
        let a = emitting(
            "a",
            &[
                iopub("display_data", "download: 0%", Some("bar")),
                stream,
                iopub("update_display_data", "download: 50%", Some("bar")),
            ],
        );
        let b = emitting(
            "b",
            &[iopub(
                "update_display_data",
                "download: verified",
                Some("bar"),
            )],
        );
        let (events, _) = bridge_against_fake(&[&a, &b], false);
        assert_eq!(
            updates(&events),
            vec![
                ("a".to_string(), 0, "download: 50%".to_string()),
                ("a".to_string(), 0, "download: verified".to_string()),
            ],
            "{events:?}"
        );
        let first = events.iter().find_map(|e| match e {
            Event::Output { id, output } if id == "a" => Some(output.clone()),
            _ => None,
        });
        assert_eq!(first.unwrap()["data"]["text/plain"], "download: 0%");
    }

    /// #1475 negative: an update for a display nobody made, or for one its
    /// cell has since cleared, changes nothing.
    #[test]
    fn an_unknown_or_cleared_display_is_not_updated() {
        if !crate::lsp::manager::is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let clear = serde_json::json!(["clear_output", {"wait": false}]);
        let a = emitting(
            "a",
            &[
                iopub("update_display_data", "ghost", Some("nobody")),
                iopub("display_data", "plain", None),
                iopub("display_data", "old", Some("gone")),
                clear,
                iopub("update_display_data", "new", Some("gone")),
            ],
        );
        let (events, _) = bridge_against_fake(&[&a], false);
        assert!(updates(&events).is_empty(), "{events:?}");
        assert_eq!(done_status(&events, "a").as_deref(), Some("ok"));
    }

    fn display(text: &str) -> Value {
        serde_json::json!({"output_type": "display_data", "data": {"text/plain": text}, "metadata": {}})
    }

    /// #1475: an update replaces the output in place, even once its cell
    /// finished and another cell sent the update, and is saved that way.
    #[test]
    fn an_update_replaces_a_finished_cells_display() {
        let mut run = run_without_kernel();
        let cell = code_cell(NB, 1).unwrap();
        let doc = apply(NB, &cell, CellEdit::Begin).unwrap();
        run.execute(cell);
        let id = run.pending[0].0.clone();
        run.backlog = vec![
            Event::Output {
                id: id.clone(),
                output: display("download: 0%"),
            },
            Event::Output {
                id: id.clone(),
                output: serde_json::json!({"output_type": "stream", "name": "stdout", "text": "done\n"}),
            },
            Event::Done {
                id: id.clone(),
                execution_count: Some(1),
                status: "ok".into(),
            },
        ];
        let doc = run.fold(&doc).0.unwrap();
        // The cell is done; the update comes from a later run.
        run.backlog = vec![Event::Update {
            id,
            index: 0,
            output: display("download: verified"),
        }];
        let doc: Value = serde_json::from_str(&run.fold(&doc).0.unwrap()).unwrap();
        let outputs = doc["cells"][1]["outputs"].as_array().unwrap();
        assert_eq!(outputs.len(), 2, "{outputs:?}");
        assert_eq!(outputs[0]["data"]["text/plain"][0], "download: verified");
        assert_eq!(outputs[1]["text"][0], "done\n");
    }

    /// #1475 negative: once the cell runs again its old display is gone, so
    /// an update to it (or to an output the cell no longer has) is dropped.
    #[test]
    fn an_update_after_a_rerun_or_past_the_outputs_changes_nothing() {
        let mut run = run_without_kernel();
        let cell = code_cell(NB, 1).unwrap();
        let doc = apply(NB, &cell, CellEdit::Begin).unwrap();
        run.execute(cell.clone());
        let old = run.pending[0].0.clone();
        run.backlog = vec![
            Event::Output {
                id: old.clone(),
                output: display("first run"),
            },
            Event::Done {
                id: old.clone(),
                execution_count: Some(1),
                status: "ok".into(),
            },
        ];
        let doc = run.fold(&doc).0.unwrap();
        run.backlog = vec![Event::Update {
            id: old.clone(),
            index: 5,
            output: display("nowhere"),
        }];
        assert!(run.fold(&doc).0.is_none(), "no output 5 to replace");
        run.execute(cell);
        run.backlog = vec![Event::Update {
            id: old,
            index: 0,
            output: display("stale"),
        }];
        assert!(run.fold(&doc).0.is_none(), "the rerun owns the cell now");
    }

    /// #1475: an update to an `execute_result` changes its data and
    /// metadata only; it stays an `execute_result` with its count.
    #[test]
    fn an_update_keeps_an_execute_results_type_and_count() {
        let mut run = run_without_kernel();
        let cell = code_cell(NB, 1).unwrap();
        let doc = apply(NB, &cell, CellEdit::Begin).unwrap();
        run.execute(cell);
        let id = run.pending[0].0.clone();
        run.backlog = vec![
            Event::Output {
                id: id.clone(),
                output: serde_json::json!({"output_type": "execute_result", "execution_count": 4,
                    "data": {"text/plain": "0%"}, "metadata": {}}),
            },
            Event::Update {
                id,
                index: 0,
                output: serde_json::json!({"output_type": "display_data",
                    "data": {"text/plain": "100%"}, "metadata": {"done": true}}),
            },
        ];
        let doc: Value = serde_json::from_str(&run.fold(&doc).0.unwrap()).unwrap();
        let out = &doc["cells"][1]["outputs"][0];
        assert_eq!(out["output_type"], "execute_result", "{out}");
        assert_eq!(out["execution_count"], 4, "{out}");
        assert_eq!(out["data"]["text/plain"][0], "100%");
        assert_eq!(out["metadata"]["done"], true);
    }

    /// #1475: rerunning a cell tells the bridge to forget its last run, so
    /// display registrations do not pile up across reruns.
    #[test]
    fn a_rerun_tells_the_bridge_to_forget_the_last_run() {
        let (mut run, _events, requests) = NotebookRun::for_test();
        let cell = code_cell(NB, 1).unwrap();
        run.execute(cell.clone());
        let old = run.pending[0].0.clone();
        run.backlog = vec![Event::Done {
            id: old.clone(),
            execution_count: Some(1),
            status: "ok".into(),
        }];
        run.fold(NB);
        run.execute(cell);
        let forgets: Vec<_> = requests
            .try_iter()
            .filter_map(|r| match r {
                Request::Forget { ids } => Some(ids),
                _ => None,
            })
            .collect();
        assert_eq!(forgets, vec![vec![old]]);
    }

    /// #1475: once croft forgets a run, the bridge stops sending updates
    /// for its displays, while other runs' displays still update.
    #[test]
    fn the_bridge_drops_displays_of_forgotten_runs() {
        if !crate::lsp::manager::is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let a = emitting("a", &[iopub("display_data", "a", Some("bar"))]);
        let b = emitting("b", &[iopub("display_data", "b", Some("bar"))]);
        let forget = r#"{"op":"forget","ids":["a"]}"#;
        let c = emitting("c", &[iopub("update_display_data", "new", Some("bar"))]);
        let (events, _) = bridge_against_fake(&[&a, &b, forget, &c], false);
        assert_eq!(
            updates(&events),
            vec![("b".to_string(), 0, "new".to_string())],
            "{events:?}"
        );
    }

    /// A long Run All behind a silent cell: the bridge must not wait on
    /// iopub between queued requests, or each one costs the poll timeout
    /// and an Interrupt or Restart queued after them is held back.
    #[test]
    fn queued_requests_do_not_each_wait_on_a_silent_kernel() {
        if !crate::lsp::manager::is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let mut requests: Vec<String> = (0..250)
            .map(|i| format!(r#"{{"op":"execute","id":"h{i}","code":"hang"}}"#))
            .collect();
        requests.push(r#"{"op":"execute","id":"a","code":"x = 1"}"#.into());
        let requests: Vec<&str> = requests.iter().map(String::as_str).collect();
        let start = std::time::Instant::now();
        let (events, _) = bridge_against_fake(&requests, false);
        let took = start.elapsed();
        assert_eq!(done_status(&events, "a").as_deref(), Some("ok"));
        // Waiting per queued cell would add 250 polls (5s) on top of the
        // helper's 0.8s pause.
        assert!(
            took < std::time::Duration::from_secs(3),
            "queued requests were slowed by iopub polls: {took:?}"
        );
    }

    fn fake_specs() -> Vec<KernelSpec> {
        vec![
            KernelSpec {
                name: "ir".into(),
                display: "R".into(),
                language: "R".into(),
            },
            KernelSpec {
                name: "python3".into(),
                display: "Python 3 (ipykernel)".into(),
                language: "python".into(),
            },
        ]
    }

    #[test]
    fn a_kernel_this_machine_lacks_is_reported_with_the_installed_ones() {
        if !crate::lsp::manager::is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let (events, _) = bridge_run(
            "conda-env-ds-py",
            &[r#"{"op":"execute","id":"a","code":"x = 1"}"#],
            false,
            true,
        );
        assert_eq!(
            events,
            vec![Event::Missing {
                kernel: "conda-env-ds-py".into(),
                specs: fake_specs(),
            }],
            "no kernel is started and nothing runs"
        );
    }

    /// Negative: a notebook naming an installed kernel starts it with no
    /// question, as before.
    #[test]
    fn an_installed_kernel_starts_without_asking() {
        if !crate::lsp::manager::is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let (events, _) = bridge_run(
            "python3",
            &[r#"{"op":"execute","id":"a","code":"x = 1"}"#],
            false,
            true,
        );
        assert!(
            matches!(events.first(), Some(Event::Ready { .. })),
            "{events:?}"
        );
        assert!(
            !events.iter().any(|e| matches!(e, Event::Missing { .. })),
            "{events:?}"
        );
        assert_eq!(done_status(&events, "a").as_deref(), Some("ok"));
    }

    #[test]
    fn the_bridge_lists_the_installed_kernels() {
        if !crate::lsp::manager::is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let (events, _) = bridge_run("--list", &[], false, true);
        assert_eq!(
            events,
            vec![Event::Specs {
                specs: fake_specs()
            }]
        );
    }
}