pite-editor 0.3.0

Visual game editor for Pite (egui/eframe): viewport, tree, inspector, and LSP code pane.
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
// SPDX-License-Identifier: MIT OR Apache-2.0
//! External Python language server over stdio (pyright-family).
//!
//! `pite-editor` never embeds a server: it spawns `pyright-langserver
//! --stdio` (or `PITE_LSP_CMD`), syncs the code pane with
//! `didOpen`/`didChange`, and surfaces completion, hover, signature
//! help, and `publishDiagnostics`. The shipped `pite.pyi` stubs go on
//! the server's path so `import pite` resolves. No DAP, no bundled binary.
//!
//! The protocol core is transport-agnostic: [`Bridge`] speaks JSON-RPC
//! over any [`RpcTransport`]. Production uses [`StdioTransport`] (real
//! child stdio); tests drive the same [`Bridge`] with a mock server.

use std::collections::{HashMap, VecDeque};
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::sync::mpsc::{self, Receiver};
use std::time::{Duration, Instant};

use anyhow::{Context, Result};
use serde_json::Value;

/// Documented prerequisite; keep in sync with `docs/lsp.md`.
pub const PINNED_PYRIGHT: &str = "1.1.411";
/// Default server command; [`ENV_CMD_OVERRIDE`] replaces it.
pub const SERVER_CMD: &str = "pyright-langserver";
/// Args for the default command.
pub const SERVER_ARGS: &[&str] = &["--stdio"];
/// Env override for the server command (a binary name or path).
pub const ENV_CMD_OVERRIDE: &str = "PITE_LSP_CMD";
/// Shipped stubs file; its parent dir goes on the server's `extraPaths`.
pub const STUBS_FILE: &str = "pite.pyi";
/// How long the background starter waits for `initialize`.
const INIT_TIMEOUT: Duration = Duration::from_secs(20);

/// Loud message when no server is installed. Editing continues without LSP.
pub fn missing_server_message(cmd: &str) -> String {
    format!(
        "LSP unavailable: `{cmd}` not found on PATH. Install the pinned server \
         (`pip install \"pyright=={PINNED_PYRIGHT}\"` ships `{SERVER_CMD}`) or point \
         `{ENV_CMD_OVERRIDE}` at one. Editing continues without completion, hover, \
         signature help, or server diagnostics."
    )
}

/// Best-effort `file://` URI for a path. Falls back to the raw path text
/// when the current dir is unknown; servers only need it as a document key.
pub fn path_to_uri(path: &Path) -> String {
    let abs = if path.is_absolute() {
        path.to_path_buf()
    } else {
        std::env::current_dir()
            .unwrap_or_else(|_| PathBuf::from("."))
            .join(path)
    };
    uri_from_path_text(&abs.to_string_lossy())
}

/// Build a `file://` URI from an absolute path *string*, on any platform.
/// Windows needs `file:///D:/dir/file.py` — forward slashes and a leading
/// slash before the drive letter. Emitting `file://D:\dir\file.py` (naive
/// concatenation) makes the server report the directory as nonexistent, so
/// the conversion is explicit rather than string-pasted.
pub fn uri_from_path_text(path: &str) -> String {
    let normalized = path.replace('\\', "/");
    let mut out = String::with_capacity(normalized.len() + 8);
    out.push_str("file://");
    if !normalized.starts_with('/') {
        out.push('/');
    }
    for c in normalized.chars() {
        match c {
            ' ' => out.push_str("%20"),
            '#' => out.push_str("%23"),
            '?' => out.push_str("%3F"),
            '%' => out.push_str("%25"),
            other => out.push(other),
        }
    }
    out
}

/// Byte offset of a char offset (egui cursors count chars).
pub fn byte_offset_of_char(text: &str, char_offset: usize) -> usize {
    text.char_indices()
        .map(|(b, _)| b)
        .nth(char_offset)
        .unwrap_or(text.len())
}

/// `(line, character)` for an LSP position. Lines are 0-based;
/// characters count UTF-16 code units per the protocol.
pub fn offset_to_position(text: &str, byte_offset: usize) -> (u32, u32) {
    let at = byte_offset.min(text.len());
    let mut line = 0u32;
    let mut units = 0u32;
    for (b, c) in text.char_indices() {
        if b >= at {
            break;
        }
        if c == '\n' {
            line += 1;
            units = 0;
        } else {
            units += c.len_utf16() as u32;
        }
    }
    (line, units)
}

/// Byte offset of the start of 1-based `line` (clamped to end of text).
pub fn line_start_byte(text: &str, line: usize) -> usize {
    if line <= 1 {
        return 0;
    }
    let mut seen = 1usize;
    for (b, c) in text.char_indices() {
        if c == '\n' {
            seen += 1;
            if seen >= line {
                return b + 1;
            }
        }
    }
    text.len()
}

/// Start byte offset of the identifier ending at `byte_offset`
/// (letters, digits, `_`); completion replaces from here.
pub fn word_start_before(text: &str, byte_offset: usize) -> usize {
    let mut start = byte_offset.min(text.len());
    while start > 0 {
        match text[..start].chars().next_back() {
            Some(c) if c.is_alphanumeric() || c == '_' => start -= c.len_utf8(),
            _ => break,
        }
    }
    start
}

/// End byte offset of the identifier starting at `byte_offset`
/// (letters, digits, `_`); accepting mid-word replaces up to here.
pub fn word_end_after(text: &str, byte_offset: usize) -> usize {
    let mut end = byte_offset.min(text.len());
    for c in text[end..].chars() {
        if c.is_alphanumeric() || c == '_' {
            end += c.len_utf8();
        } else {
            break;
        }
    }
    end
}

/// First `major.minor.patch` in free-form `--version` output.
pub fn parse_version(text: &str) -> Option<(u64, u64, u64)> {
    let mut digits = String::new();
    for c in text.chars() {
        if c.is_ascii_digit() || c == '.' {
            digits.push(c);
        } else if !digits.is_empty() {
            break;
        }
    }
    let mut parts = digits.split('.');
    Some((
        parts.next()?.parse().ok()?,
        parts.next()?.parse().ok()?,
        parts.next()?.parse().ok()?,
    ))
}

/// Numeric triple comparison against the pin.
pub fn version_at_least(have: (u64, u64, u64), want: (u64, u64, u64)) -> bool {
    have >= want
}

fn pin_triple() -> (u64, u64, u64) {
    let mut parts = PINNED_PYRIGHT.split('.');
    (
        parts.next().and_then(|p| p.parse().ok()).unwrap_or(0),
        parts.next().and_then(|p| p.parse().ok()).unwrap_or(0),
        parts.next().and_then(|p| p.parse().ok()).unwrap_or(0),
    )
}

fn version_output(cmd: &str) -> Option<String> {
    let out = Command::new(cmd).arg("--version").output().ok()?;
    if !out.status.success() {
        return None;
    }
    Some(String::from_utf8_lossy(&out.stdout).into_owned())
}

/// `pyright-langserver` speaks only stdio, so ask its `pyright` sibling.
fn sibling_version(cmd: &str) -> Option<String> {
    if Path::new(cmd).file_name().and_then(|s| s.to_str()) != Some(SERVER_CMD) {
        return None;
    }
    let sibling = match Path::new(cmd).parent() {
        Some(parent) if !parent.as_os_str().is_empty() => {
            parent.join("pyright").to_string_lossy().into_owned()
        }
        _ => "pyright".to_string(),
    };
    version_output(&sibling)
}

/// Best-effort version probe: `(version, warning)`. Never fails; a missing
/// binary surfaces later at spawn with the loud message.
pub fn probe_server_version(cmd: &str) -> (Option<String>, Option<String>) {
    let text = version_output(cmd).or_else(|| sibling_version(cmd));
    let Some(text) = text else {
        return (
            None,
            Some(format!(
                "LSP: `{cmd} --version` failed; proceeding without a version check."
            )),
        );
    };
    match parse_version(&text) {
        Some(have) => {
            let label = format!("{}.{}.{}", have.0, have.1, have.2);
            if version_at_least(have, pin_triple()) {
                (Some(label), None)
            } else {
                (
                    Some(label.clone()),
                    Some(format!(
                        "LSP: server is {label} but {PINNED_PYRIGHT} is pinned; \
                         consider upgrading (`pip install \"pyright=={PINNED_PYRIGHT}\"`)."
                    )),
                )
            }
        }
        None => (
            None,
            Some(format!(
                "LSP: could not parse server version from {text:?}; proceeding."
            )),
        ),
    }
}

/// Walk up from `start` looking for `python/pite/pite.pyi` (or a bare
/// `pite.pyi`); return the dir containing it — what goes on `extraPaths`
/// so `import pite` resolves to the shipped stubs.
pub fn find_stubs_dir(start: &Path) -> Option<PathBuf> {
    let mut dir = if start.is_file() {
        start.parent()?.to_path_buf()
    } else {
        start.to_path_buf()
    };
    loop {
        let nested = dir.join("python").join("pite").join(STUBS_FILE);
        if nested.is_file() {
            return Some(dir.join("python").join("pite"));
        }
        if dir.join(STUBS_FILE).is_file() {
            return Some(dir);
        }
        if !dir.pop() {
            return None;
        }
    }
}

/// Stubs baked into the editor binary (`python/pite/` at build time), so
/// `import pite` resolves even where no checkout exists — installed bundles
/// never shipped these files, and the walk-up search above finds nothing
/// there. `pite.py` is the source sibling the checker needs beside `pite.pyi`
/// (the real module is native via PyO3); types always come from the stubs.
const EMBEDDED_STUBS: &str = include_str!("../python/pite.pyi");
const EMBEDDED_SOURCE: &str = include_str!("../python/pite.py");

/// Write the embedded stubs into `dir`, skipping files that already match.
/// Returns the dir for `extraPaths`.
pub fn write_stubs_to(dir: &Path) -> Result<PathBuf> {
    for (name, contents) in [(STUBS_FILE, EMBEDDED_STUBS), ("pite.py", EMBEDDED_SOURCE)] {
        let path = dir.join(name);
        let current = std::fs::read_to_string(&path).unwrap_or_default();
        if current != contents {
            if let Some(parent) = path.parent() {
                std::fs::create_dir_all(parent)?;
            }
            std::fs::write(&path, contents)?;
        }
    }
    Ok(dir.to_path_buf())
}

/// Versioned scratch dir for the embedded stubs; the last resort behind
/// `find_stubs_dir`, so a checkout's own stubs always win.
pub fn materialized_stubs_dir() -> Option<PathBuf> {
    let dir = std::env::temp_dir().join(format!("pite-{}", env!("CARGO_PKG_VERSION")));
    write_stubs_to(&dir).ok()
}

/// Frame a JSON-RPC value with `Content-Length` headers.
pub fn encode_message(body: &Value) -> Vec<u8> {
    let text = serde_json::to_string(body).expect("LSP body serializes");
    let mut out = format!("Content-Length: {}\r\n\r\n", text.len()).into_bytes();
    out.extend_from_slice(text.as_bytes());
    out
}

/// Parse `Content-Length`-framed messages from any buffered reader.
pub struct FramingReader<R: BufRead> {
    inner: R,
}

impl<R: BufRead> FramingReader<R> {
    pub fn new(inner: R) -> Self {
        Self { inner }
    }

    pub fn read_message(&mut self) -> Result<Value> {
        let mut len: Option<usize> = None;
        loop {
            let mut line = String::new();
            let n = self
                .inner
                .read_line(&mut line)
                .context("server closed stdio")?;
            if n == 0 {
                anyhow::bail!("server closed stdio");
            }
            let line = line.trim();
            if line.is_empty() {
                break;
            }
            if let Some(rest) = line.strip_prefix("Content-Length:") {
                len = Some(rest.trim().parse().context("bad Content-Length")?);
            }
        }
        let len = len.context("message without Content-Length")?;
        let mut buf = vec![0u8; len];
        self.inner
            .read_exact(&mut buf)
            .context("server closed stdio")?;
        serde_json::from_slice(&buf).context("server sent invalid JSON")
    }
}

fn request(id: i64, method: &str, params: Value) -> Value {
    serde_json::json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params})
}

fn notification(method: &str, params: Value) -> Value {
    serde_json::json!({"jsonrpc": "2.0", "method": method, "params": params})
}

/// `initialize` carrying the project root. Settings travel separately via
/// `didChangeConfiguration` (and `workspace/configuration` answers).
///
/// `workspaceFolders` is mandatory, not decorative: a server that only sees
/// `rootUri` falls back to a synthetic `<default workspace root>`, finds no
/// files there, and then never re-analyzes an edited document — which is
/// exactly what pyright logs when the root is missing.
pub fn initialize_request(id: i64, root_uri: Option<&str>) -> Value {
    let folders: Value = root_uri
        .map(|uri| serde_json::json!([{"uri": uri, "name": "pite"}]))
        .unwrap_or_else(|| serde_json::json!([]));
    request(
        id,
        "initialize",
        serde_json::json!({
            "processId": std::process::id(),
            "rootUri": root_uri,
            "workspaceFolders": folders,
            "capabilities": {
                "workspace": {"configuration": true},
                "textDocument": {"publishDiagnostics": {}},
            },
        }),
    )
}

pub fn initialized_notification() -> Value {
    notification("initialized", serde_json::json!({}))
}

/// `extraPaths` + basic type-checking mode so the shipped stubs resolve.
pub fn did_change_configuration(stubs_dir: Option<&Path>) -> Value {
    let extra: Vec<String> = stubs_dir
        .map(|d| vec![d.to_string_lossy().into_owned()])
        .unwrap_or_default();
    notification(
        "workspace/didChangeConfiguration",
        serde_json::json!({"settings": {
            "python": {"analysis": {
                "extraPaths": extra,
                "typeCheckingMode": "basic",
            }},
        }}),
    )
}

/// Answer a server `workspace/configuration` pull. The answer is the
/// requested SECTION VALUE (`result[0]` pairs with `items[0]`): for section
/// `"python"` that is the `{"analysis": ...}` object itself — NOT wrapped in
/// another `"python"` layer, which the server would read as a section with
/// no `analysis` and silently drop (that exact shape starved `import pite`
/// of its stubs). Anything else gets an empty object (defaults hold).
pub fn configuration_response(id: i64, section: &str, stubs_dir: Option<&Path>) -> Value {
    let extra: Vec<String> = stubs_dir
        .map(|d| vec![d.to_string_lossy().into_owned()])
        .unwrap_or_default();
    let result = if section == "python" {
        serde_json::json!({"analysis": {
            "extraPaths": extra,
            "typeCheckingMode": "basic",
        }})
    } else {
        serde_json::json!({})
    };
    serde_json::json!({"jsonrpc": "2.0", "id": id, "result": [result]})
}

pub fn did_open_notification(uri: &str, text: &str) -> Value {
    notification(
        "textDocument/didOpen",
        serde_json::json!({"textDocument": {
            "uri": uri, "languageId": "python", "version": 1, "text": text,
        }}),
    )
}

pub fn did_change_notification(uri: &str, version: i32, text: &str) -> Value {
    notification(
        "textDocument/didChange",
        serde_json::json!({"textDocument": {"uri": uri, "version": version},
            "contentChanges": [{"text": text}]}),
    )
}

fn position_params(uri: &str, line: u32, character: u32) -> Value {
    serde_json::json!({"textDocument": {"uri": uri},
        "position": {"line": line, "character": character}})
}

pub fn completion_request(id: i64, uri: &str, line: u32, character: u32) -> Value {
    request(
        id,
        "textDocument/completion",
        position_params(uri, line, character),
    )
}

pub fn hover_request(id: i64, uri: &str, line: u32, character: u32) -> Value {
    request(
        id,
        "textDocument/hover",
        position_params(uri, line, character),
    )
}

pub fn signature_request(id: i64, uri: &str, line: u32, character: u32) -> Value {
    request(
        id,
        "textDocument/signatureHelp",
        position_params(uri, line, character),
    )
}

/// One server diagnostic (0-based line, protocol severity 1=error..4=hint).
#[derive(Debug, Clone, PartialEq)]
pub struct Diagnostic {
    pub line: u32,
    pub character: u32,
    pub severity: u32,
    pub message: String,
}

/// One completion candidate.
#[derive(Debug, Clone, PartialEq)]
pub struct CompletionItem {
    pub label: String,
    pub detail: String,
}

/// Parse `publishDiagnostics` params into diagnostics (empty when clean).
pub fn parse_publish_diagnostics(params: &Value) -> Vec<Diagnostic> {
    let Some(items) = params.get("diagnostics").and_then(Value::as_array) else {
        return Vec::new();
    };
    items
        .iter()
        .map(|d| Diagnostic {
            line: d
                .pointer("/range/start/line")
                .and_then(Value::as_u64)
                .unwrap_or(0) as u32,
            character: d
                .pointer("/range/start/character")
                .and_then(Value::as_u64)
                .unwrap_or(0) as u32,
            severity: d.get("severity").and_then(Value::as_u64).unwrap_or(1) as u32,
            message: d
                .get("message")
                .and_then(Value::as_str)
                .unwrap_or("")
                .to_string(),
        })
        .collect()
}

/// Parse a completion result (array or `{items}`; null means no candidates).
pub fn parse_completion_items(result: &Value) -> Vec<CompletionItem> {
    let items = match result {
        Value::Array(items) => items.clone(),
        Value::Object(_) => result
            .get("items")
            .and_then(Value::as_array)
            .cloned()
            .unwrap_or_default(),
        _ => Vec::new(),
    };
    items
        .iter()
        .map(|i| CompletionItem {
            label: i
                .get("label")
                .and_then(Value::as_str)
                .unwrap_or("")
                .to_string(),
            detail: i
                .get("detail")
                .and_then(Value::as_str)
                .unwrap_or("")
                .to_string(),
        })
        .filter(|i| !i.label.is_empty())
        .collect()
}

/// Parse a hover result into plain text (markdown fenced content included).
pub fn parse_hover(result: &Value) -> String {
    let contents = match result {
        Value::Null => return String::new(),
        Value::Object(_) => result.get("contents").unwrap_or(&Value::Null),
        other => other,
    };
    match contents {
        Value::String(s) => s.clone(),
        Value::Array(parts) => parts
            .iter()
            .filter_map(|p| {
                p.get("value")
                    .and_then(Value::as_str)
                    .map(str::to_string)
                    .or_else(|| p.as_str().map(str::to_string))
            })
            .collect::<Vec<_>>()
            .join("\n"),
        Value::Object(_) => contents
            .get("value")
            .and_then(Value::as_str)
            .unwrap_or("")
            .to_string(),
        _ => String::new(),
    }
}

/// Parse signature help into one line per overload.
pub fn parse_signature_help(result: &Value) -> Vec<String> {
    result
        .get("signatures")
        .and_then(Value::as_array)
        .map(|sigs| {
            sigs.iter()
                .filter_map(|s| s.get("label").and_then(Value::as_str).map(str::to_string))
                .collect()
        })
        .unwrap_or_default()
}

#[derive(Debug, Clone, Copy, PartialEq)]
enum PendingKind {
    Initialize,
    Completion,
    Hover,
    Signature,
}

/// Byte transport for JSON-RPC values. Production speaks over child
/// stdio; tests substitute a mock server speaking the same messages.
pub trait RpcTransport: Send {
    fn send(&mut self, body: &Value) -> Result<()>;
    fn drain(&mut self) -> Vec<Value>;
    fn alive(&mut self) -> bool;
}

/// Real child-stdio transport: writes go straight to the server's
/// stdin, a reader thread forwards framed replies to a channel.
pub struct StdioTransport {
    stdin: std::process::ChildStdin,
    inbox: Receiver<Value>,
    dead: bool,
}

impl StdioTransport {
    pub fn spawn(cmd: &str, args: &[&str]) -> Result<(Self, Child)> {
        let mut child = Command::new(cmd)
            .args(args)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::null())
            .spawn()
            .map_err(|e| {
                if e.kind() == std::io::ErrorKind::NotFound {
                    anyhow::anyhow!(missing_server_message(cmd))
                } else {
                    anyhow::anyhow!("cannot start `{cmd}`: {e:#}")
                }
            })?;
        let stdin = child.stdin.take().context("server stdin unavailable")?;
        let stdout = child.stdout.take().context("server stdout unavailable")?;
        let (tx, inbox) = mpsc::channel();
        std::thread::spawn(move || {
            let mut framing = FramingReader::new(BufReader::new(stdout));
            while let Ok(msg) = framing.read_message() {
                if tx.send(msg).is_err() {
                    break;
                }
            }
        });
        Ok((
            Self {
                stdin,
                inbox,
                dead: false,
            },
            child,
        ))
    }
}

impl RpcTransport for StdioTransport {
    fn send(&mut self, body: &Value) -> Result<()> {
        let bytes = encode_message(body);
        self.stdin.write_all(&bytes).context("server stdin closed")
    }

    fn drain(&mut self) -> Vec<Value> {
        let mut out = Vec::new();
        loop {
            match self.inbox.try_recv() {
                Ok(msg) => out.push(msg),
                Err(mpsc::TryRecvError::Empty) => break,
                Err(mpsc::TryRecvError::Disconnected) => {
                    self.dead = true;
                    break;
                }
            }
        }
        out
    }

    fn alive(&mut self) -> bool {
        !self.dead
    }
}

/// Protocol state above a transport: request ids, pending kinds, typed
/// results, and per-document diagnostics.
pub struct Bridge {
    next_id: i64,
    pending: HashMap<i64, PendingKind>,
    responses: HashMap<i64, Value>,
    versions: HashMap<String, i32>,
    completions: VecDeque<(i64, Vec<CompletionItem>)>,
    hovers: VecDeque<(i64, String)>,
    signatures: VecDeque<(i64, Vec<String>)>,
    notices: VecDeque<String>,
    pub diagnostics: HashMap<String, Vec<Diagnostic>>,
}

impl Bridge {
    pub fn new() -> Self {
        Self {
            next_id: 1,
            pending: HashMap::new(),
            responses: HashMap::new(),
            versions: HashMap::new(),
            completions: VecDeque::new(),
            hovers: VecDeque::new(),
            signatures: VecDeque::new(),
            notices: VecDeque::new(),
            diagnostics: HashMap::new(),
        }
    }

    fn call(&mut self, tx: &mut dyn RpcTransport, kind: PendingKind, body: Value) -> Result<i64> {
        let id = self.next_id;
        self.next_id += 1;
        tx.send(&body)?;
        self.pending.insert(id, kind);
        Ok(id)
    }

    pub fn send_initialize(
        &mut self,
        tx: &mut dyn RpcTransport,
        root_uri: Option<&str>,
    ) -> Result<i64> {
        let id = self.next_id;
        let body = initialize_request(id, root_uri);
        self.call(tx, PendingKind::Initialize, body)
    }

    pub fn send_initialized(&mut self, tx: &mut dyn RpcTransport) -> Result<()> {
        tx.send(&initialized_notification())
    }

    pub fn send_configuration(
        &mut self,
        tx: &mut dyn RpcTransport,
        stubs: Option<&Path>,
    ) -> Result<()> {
        tx.send(&did_change_configuration(stubs))
    }

    pub fn did_open(&mut self, tx: &mut dyn RpcTransport, uri: &str, text: &str) -> Result<()> {
        self.versions.insert(uri.to_string(), 1);
        tx.send(&did_open_notification(uri, text))
    }

    pub fn did_change(&mut self, tx: &mut dyn RpcTransport, uri: &str, text: &str) -> Result<()> {
        let version = self.versions.entry(uri.to_string()).or_insert(0);
        *version += 1;
        tx.send(&did_change_notification(uri, *version, text))
    }

    pub fn request_completion(
        &mut self,
        tx: &mut dyn RpcTransport,
        uri: &str,
        line: u32,
        character: u32,
    ) -> Result<i64> {
        let id = self.next_id;
        let body = completion_request(id, uri, line, character);
        self.call(tx, PendingKind::Completion, body)
    }

    pub fn request_hover(
        &mut self,
        tx: &mut dyn RpcTransport,
        uri: &str,
        line: u32,
        character: u32,
    ) -> Result<i64> {
        let id = self.next_id;
        let body = hover_request(id, uri, line, character);
        self.call(tx, PendingKind::Hover, body)
    }

    pub fn request_signature(
        &mut self,
        tx: &mut dyn RpcTransport,
        uri: &str,
        line: u32,
        character: u32,
    ) -> Result<i64> {
        let id = self.next_id;
        let body = signature_request(id, uri, line, character);
        self.call(tx, PendingKind::Signature, body)
    }

    /// Route one incoming message: match responses to pending requests,
    /// answer server requests, file diagnostics notifications.
    pub fn ingest(&mut self, msg: Value, tx: &mut dyn RpcTransport, stubs: Option<&Path>) {
        if let Some(id) = msg.get("id").and_then(Value::as_i64) {
            if msg.get("method").is_some() {
                self.answer_server_request(id, &msg, tx, stubs);
            } else {
                let result = msg.get("result").cloned().unwrap_or(Value::Null);
                match self.pending.remove(&id) {
                    Some(PendingKind::Completion) => {
                        self.completions
                            .push_back((id, parse_completion_items(&result)));
                    }
                    Some(PendingKind::Hover) => {
                        self.hovers.push_back((id, parse_hover(&result)));
                    }
                    Some(PendingKind::Signature) => {
                        self.signatures
                            .push_back((id, parse_signature_help(&result)));
                    }
                    Some(PendingKind::Initialize) => {
                        self.responses.insert(id, result);
                    }
                    None => {}
                }
            }
            return;
        }
        let Some(method) = msg.get("method").and_then(Value::as_str) else {
            return;
        };
        match method {
            "textDocument/publishDiagnostics" => {
                let params = msg.get("params").unwrap_or(&Value::Null);
                let uri = params.get("uri").and_then(Value::as_str).unwrap_or("");
                self.diagnostics
                    .insert(uri.to_string(), parse_publish_diagnostics(params));
            }
            "window/showMessage" | "window/logMessage" => {
                if let Some(text) = msg
                    .get("params")
                    .and_then(|p| p.get("message"))
                    .and_then(Value::as_str)
                {
                    self.notices.push_back(text.to_string());
                }
            }
            _ => {}
        }
    }

    fn answer_server_request(
        &mut self,
        id: i64,
        msg: &Value,
        tx: &mut dyn RpcTransport,
        stubs: Option<&Path>,
    ) {
        let method = msg.get("method").and_then(Value::as_str).unwrap_or("");
        let reply = match method {
            "workspace/configuration" => {
                let section = msg
                    .pointer("/params/items/0/section")
                    .and_then(Value::as_str)
                    .unwrap_or("");
                configuration_response(id, section, stubs)
            }
            _ => serde_json::json!({"jsonrpc": "2.0", "id": id, "result": null}),
        };
        let _ = tx.send(&reply);
    }

    /// Drain the transport into protocol state. Returns `false` once the
    /// server is gone (caller reports loudly and drops the client).
    pub fn poll(&mut self, tx: &mut dyn RpcTransport, stubs: Option<&Path>) -> bool {
        for msg in tx.drain() {
            self.ingest(msg, tx, stubs);
        }
        tx.alive()
    }

    /// Block (via transport polls) until a response id arrives or timeout.
    /// Used only by the background starter for `initialize`.
    pub fn await_response(
        &mut self,
        tx: &mut dyn RpcTransport,
        id: i64,
        stubs: Option<&Path>,
        timeout: Duration,
    ) -> Result<Value> {
        let start = Instant::now();
        loop {
            for msg in tx.drain() {
                self.ingest(msg, tx, stubs);
            }
            if let Some(result) = self.responses.remove(&id) {
                return Ok(result);
            }
            if !tx.alive() {
                anyhow::bail!("server exited during initialize");
            }
            if start.elapsed() > timeout {
                anyhow::bail!("server did not answer initialize in time");
            }
            std::thread::sleep(Duration::from_millis(10));
        }
    }

    pub fn take_completion(&mut self) -> Option<(i64, Vec<CompletionItem>)> {
        self.completions.pop_front()
    }

    pub fn take_hover(&mut self) -> Option<(i64, String)> {
        self.hovers.pop_front()
    }

    pub fn take_signature(&mut self) -> Option<(i64, Vec<String>)> {
        self.signatures.pop_front()
    }

    pub fn take_notice(&mut self) -> Option<String> {
        self.notices.pop_front()
    }
}

impl Default for Bridge {
    fn default() -> Self {
        Self::new()
    }
}

/// Owns the child process; killing on drop so no server outlives the editor.
pub struct ChildGuard(Child);

impl ChildGuard {
    pub fn new(child: Child) -> Self {
        Self(child)
    }
}

impl Drop for ChildGuard {
    fn drop(&mut self) {
        let _ = self.0.kill();
        let _ = self.0.wait();
    }
}

/// A ready-to-use server connection for one editor session.
pub struct LspClient {
    bridge: Bridge,
    transport: Box<dyn RpcTransport>,
    _child: Option<ChildGuard>,
    stubs_dir: Option<PathBuf>,
    dead_reported: bool,
    pub server_version: Option<String>,
}

impl LspClient {
    fn new(
        transport: Box<dyn RpcTransport>,
        child: Option<ChildGuard>,
        stubs_dir: Option<PathBuf>,
        server_version: Option<String>,
    ) -> Self {
        Self {
            bridge: Bridge::new(),
            transport,
            _child: child,
            stubs_dir,
            dead_reported: false,
            server_version,
        }
    }

    /// Poll the server; returns an error string once when it dies.
    pub fn poll(&mut self) -> Option<String> {
        let stubs = self.stubs_dir.clone();
        if !self.bridge.poll(&mut *self.transport, stubs.as_deref()) && !self.dead_reported {
            self.dead_reported = true;
            return Some("LSP: language server exited; editing continues without it.".to_string());
        }
        None
    }

    pub fn did_open(&mut self, uri: &str, text: &str) -> Result<()> {
        self.bridge.did_open(&mut *self.transport, uri, text)
    }

    pub fn did_change(&mut self, uri: &str, text: &str) -> Result<()> {
        self.bridge.did_change(&mut *self.transport, uri, text)
    }

    pub fn request_completion(&mut self, uri: &str, line: u32, character: u32) -> Result<i64> {
        self.bridge
            .request_completion(&mut *self.transport, uri, line, character)
    }

    pub fn request_hover(&mut self, uri: &str, line: u32, character: u32) -> Result<i64> {
        self.bridge
            .request_hover(&mut *self.transport, uri, line, character)
    }

    pub fn request_signature(&mut self, uri: &str, line: u32, character: u32) -> Result<i64> {
        self.bridge
            .request_signature(&mut *self.transport, uri, line, character)
    }

    pub fn take_completion(&mut self) -> Option<(i64, Vec<CompletionItem>)> {
        self.bridge.take_completion()
    }

    pub fn take_hover(&mut self) -> Option<(i64, String)> {
        self.bridge.take_hover()
    }

    pub fn take_signature(&mut self) -> Option<(i64, Vec<String>)> {
        self.bridge.take_signature()
    }

    pub fn take_notice(&mut self) -> Option<String> {
        self.bridge.take_notice()
    }

    pub fn diagnostics_for_uri(&self, uri: &str) -> &[Diagnostic] {
        self.bridge
            .diagnostics
            .get(uri)
            .map(Vec::as_slice)
            .unwrap_or(&[])
    }

    pub fn diagnostic_count(&self) -> usize {
        self.bridge.diagnostics.values().map(Vec::len).sum()
    }
}

/// Starter outcome delivered to the UI thread.
pub enum LspOutcome {
    Ready {
        client: LspClient,
        warning: Option<String>,
    },
    Failed(String),
}

/// Spawn the server in the background and run the `initialize` handshake
/// there (cold starts take seconds). The receiver gets exactly one outcome;
/// a missing binary fails fast and loudly, never silently.
pub fn spawn_lsp(root_dir: Option<PathBuf>, script: &Path) -> Receiver<LspOutcome> {
    let (tx, rx) = mpsc::channel();
    let script = script.to_path_buf();
    std::thread::spawn(move || {
        let outcome = start_blocking(root_dir.as_deref(), &script);
        let _ = tx.send(outcome);
    });
    rx
}

fn start_blocking(root_dir: Option<&Path>, script: &Path) -> LspOutcome {
    let cmd = std::env::var(ENV_CMD_OVERRIDE).unwrap_or_else(|_| SERVER_CMD.to_string());
    let (server_version, mut warning) = probe_server_version(&cmd);
    let stubs_dir = root_dir
        .and_then(find_stubs_dir)
        .or_else(|| find_stubs_dir(script))
        .or_else(|| find_stubs_dir(Path::new(".")))
        .or_else(materialized_stubs_dir);
    if stubs_dir.is_none() {
        let w = "LSP: shipped pite.pyi stubs not found; `import pite` may not resolve.".to_string();
        warning = Some(match warning {
            Some(prev) => format!("{prev} {w}"),
            None => w,
        });
    }
    let (mut transport, child) = match StdioTransport::spawn(&cmd, SERVER_ARGS) {
        Ok(pair) => pair,
        Err(e) => return LspOutcome::Failed(format!("LSP unavailable: {e:#}")),
    };
    let root_uri = root_dir.map(path_to_uri);
    let mut bridge = Bridge::new();
    let init_id = match bridge.send_initialize(&mut transport, root_uri.as_deref()) {
        Ok(id) => id,
        Err(e) => return LspOutcome::Failed(format!("LSP: cannot talk to server: {e:#}")),
    };
    let stubs = stubs_dir.clone();
    match bridge.await_response(&mut transport, init_id, stubs.as_deref(), INIT_TIMEOUT) {
        Ok(_) => {}
        Err(e) => {
            return LspOutcome::Failed(format!(
                "LSP: initialize failed ({e:#}); editing continues without it."
            ))
        }
    }
    let stubs_ref = stubs_dir.clone();
    if bridge.send_initialized(&mut transport).is_err()
        || bridge
            .send_configuration(&mut transport, stubs_ref.as_deref())
            .is_err()
    {
        return LspOutcome::Failed("LSP: server went quiet after initialize.".to_string());
    }
    let mut client = LspClient::new(
        Box::new(transport),
        Some(ChildGuard::new(child)),
        stubs_dir,
        server_version,
    );
    client.bridge = bridge;
    LspOutcome::Ready { client, warning }
}

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

    /// In-test mock server: canned answers + diagnostics on open/change.
    struct MockServer {
        opened: HashMap<String, String>,
    }

    impl MockServer {
        fn new() -> Self {
            Self {
                opened: HashMap::new(),
            }
        }

        fn handle(&mut self, msg: &Value) -> Vec<Value> {
            let method = msg.get("method").and_then(Value::as_str).unwrap_or("");
            if msg.get("id").is_some() {
                let id = msg.get("id").cloned().unwrap();
                let result = match method {
                    "initialize" => serde_json::json!({"capabilities": {}}),
                    "textDocument/completion" => serde_json::json!([
                        {"label": "position", "detail": "tuple[float, float]"},
                        {"label": "pressed", "detail": "def pressed"},
                    ]),
                    "textDocument/hover" => serde_json::json!({"contents": {
                        "kind": "markdown", "value": "**position**: tuple"}}),
                    "textDocument/signatureHelp" => serde_json::json!({"signatures": [
                        {"label": "play(path, volume)"},
                    ]}),
                    "shutdown" => Value::Null,
                    _ => Value::Null,
                };
                return vec![serde_json::json!({"jsonrpc": "2.0", "id": id, "result": result})];
            }
            match method {
                "textDocument/didOpen" | "textDocument/didChange" => {
                    let doc = msg.get("params").and_then(|p| p.get("textDocument"));
                    let uri = doc
                        .and_then(|d| d.get("uri"))
                        .and_then(Value::as_str)
                        .unwrap_or("");
                    let text = if method.ends_with("didOpen") {
                        msg.pointer("/params/textDocument/text")
                            .and_then(Value::as_str)
                            .unwrap_or("")
                    } else {
                        msg.pointer("/params/contentChanges/0/text")
                            .and_then(Value::as_str)
                            .unwrap_or("")
                    };
                    self.opened.insert(uri.to_string(), text.to_string());
                    let diagnostics = if text.contains("oops") {
                        serde_json::json!([{"range": {"start": {"line": 0, "character": 0},
                            "end": {"line": 0, "character": 4}},
                            "severity": 1, "message": "mock: undefined name"}])
                    } else {
                        serde_json::json!([])
                    };
                    vec![serde_json::json!({"jsonrpc": "2.0",
                        "method": "textDocument/publishDiagnostics",
                        "params": {"uri": uri, "diagnostics": diagnostics}})]
                }
                _ => Vec::new(),
            }
        }
    }

    struct MockTransport {
        pub outbox: Vec<Value>,
        inbox: VecDeque<Value>,
        server: MockServer,
    }

    impl MockTransport {
        fn new() -> Self {
            Self {
                outbox: Vec::new(),
                inbox: VecDeque::new(),
                server: MockServer::new(),
            }
        }
    }

    impl RpcTransport for MockTransport {
        fn send(&mut self, body: &Value) -> Result<()> {
            self.outbox.push(body.clone());
            self.inbox.extend(self.server.handle(body));
            Ok(())
        }

        fn drain(&mut self) -> Vec<Value> {
            self.inbox.drain(..).collect()
        }

        fn alive(&mut self) -> bool {
            true
        }
    }

    #[test]
    fn framing_round_trip() {
        let body = serde_json::json!({"jsonrpc": "2.0", "id": 7, "method": "x", "params": {}});
        let bytes = encode_message(&body);
        assert!(bytes.starts_with(b"Content-Length: "));
        let mut reader = FramingReader::new(Cursor::new(bytes));
        assert_eq!(reader.read_message().unwrap(), body);
    }

    #[test]
    fn framing_rejects_garbage_loudly() {
        let mut reader = FramingReader::new(Cursor::new(b"not a frame".to_vec()));
        assert!(reader.read_message().is_err());
        let mut reader = FramingReader::new(Cursor::new(b"Content-Length: 5\r\n\r\n###".to_vec()));
        assert!(reader.read_message().is_err());
    }

    #[test]
    fn builders_carry_params() {
        let open = did_open_notification("file:///a.py", "import pite\n");
        assert_eq!(
            open.pointer("/params/textDocument/uri").unwrap(),
            "file:///a.py"
        );
        let change = did_change_notification("file:///a.py", 7, "x = 1\n");
        assert_eq!(
            change.pointer("/params/contentChanges/0/text").unwrap(),
            "x = 1\n"
        );
        assert_eq!(change.pointer("/params/textDocument/version").unwrap(), 7);
        let req = completion_request(3, "file:///a.py", 4, 9);
        assert_eq!(req.get("id").unwrap(), 3);
        assert_eq!(req.pointer("/params/position/line").unwrap(), 4);
        let init = initialize_request(1, Some("file:///proj"));
        assert_eq!(init.pointer("/params/rootUri").unwrap(), "file:///proj");
        assert_eq!(
            init.pointer("/params/workspaceFolders/0/uri").unwrap(),
            "file:///proj"
        );
        assert_eq!(
            init.pointer("/params/capabilities/workspace/configuration"),
            Some(&Value::Bool(true))
        );
        let bare = initialize_request(1, None);
        assert_eq!(
            bare.pointer("/params/workspaceFolders").unwrap(),
            &serde_json::json!([])
        );
        let cfg = did_change_configuration(Some(Path::new("/stubs")));
        assert_eq!(
            cfg.pointer("/params/settings/python/analysis/extraPaths/0")
                .unwrap(),
            "/stubs"
        );
    }

    #[test]
    fn mock_round_trip_open_change_completion_diagnostics() {
        let mut bridge = Bridge::new();
        let mut tx = MockTransport::new();
        let uri = "file:///proj/scripts/player.py";

        bridge
            .did_open(&mut tx, uri, "import pite\noops\n")
            .unwrap();
        assert!(bridge.poll(&mut tx, None));
        let diags = bridge.diagnostics.get(uri).cloned().unwrap_or_default();
        assert_eq!(diags.len(), 1);
        assert_eq!(diags[0].line, 0);
        assert!(diags[0].message.contains("undefined name"));

        bridge.did_change(&mut tx, uri, "import pite\n").unwrap();
        assert!(bridge.poll(&mut tx, None));
        assert!(bridge
            .diagnostics
            .get(uri)
            .cloned()
            .unwrap_or_default()
            .is_empty());
        let versions: Vec<i64> = tx
            .outbox
            .iter()
            .filter(|m| m.get("method").and_then(Value::as_str) == Some("textDocument/didChange"))
            .filter_map(|m| {
                m.pointer("/params/textDocument/version")
                    .and_then(Value::as_i64)
            })
            .collect();
        assert_eq!(versions, vec![2]);

        let id = bridge.request_completion(&mut tx, uri, 1, 2).unwrap();
        assert!(bridge.poll(&mut tx, None));
        let (got_id, items) = bridge.take_completion().expect("completion arrives");
        assert_eq!(got_id, id);
        assert_eq!(items.len(), 2);
        assert_eq!(items[0].label, "position");

        bridge.request_hover(&mut tx, uri, 1, 2).unwrap();
        assert!(bridge.poll(&mut tx, None));
        let (_, hover) = bridge.take_hover().expect("hover arrives");
        assert!(hover.contains("position"));

        bridge.request_signature(&mut tx, uri, 1, 2).unwrap();
        assert!(bridge.poll(&mut tx, None));
        let (_, sigs) = bridge.take_signature().expect("signature arrives");
        assert_eq!(sigs, vec!["play(path, volume)"]);

        // Every request carried a JSON-RPC id; notifications did not.
        assert!(tx
            .outbox
            .iter()
            .any(|m| m.get("method").unwrap() == "textDocument/didOpen"));
    }

    #[test]
    fn server_requests_get_answers() {
        let mut bridge = Bridge::new();
        let mut tx = MockTransport::new();
        bridge.ingest(
            serde_json::json!({"jsonrpc": "2.0", "id": 9,
                "method": "workspace/configuration",
                "params": {"items": [{"scopeUri": "file:///proj", "section": "python"}]}}),
            &mut tx,
            Some(Path::new("/stubs")),
        );
        let reply = tx.outbox.last().expect("server request answered");
        assert_eq!(reply.get("id").unwrap(), 9);
        assert_eq!(
            reply.pointer("/result/0/analysis/extraPaths/0").unwrap(),
            "/stubs"
        );
    }

    #[test]
    fn missing_server_fails_loudly() {
        let err = StdioTransport::spawn("definitely-not-a-pite-lsp-server", SERVER_ARGS)
            .err()
            .expect("missing server must fail");
        let msg = format!("{err:#}");
        assert!(msg.contains("not found on PATH"), "got: {msg}");
        assert!(msg.contains(PINNED_PYRIGHT), "got: {msg}");
        assert!(msg.contains(ENV_CMD_OVERRIDE), "got: {msg}");
    }

    #[test]
    fn version_parse_and_compare() {
        assert_eq!(parse_version("pyright 1.1.411"), Some((1, 1, 411)));
        assert_eq!(parse_version("1.1.398"), Some((1, 1, 398)));
        assert_eq!(parse_version("no version here"), None);
        assert!(version_at_least((1, 1, 411), (1, 1, 411)));
        assert!(version_at_least((1, 1, 412), (1, 1, 411)));
        assert!(!version_at_least((1, 1, 400), (1, 1, 411)));
    }

    #[test]
    fn configuration_answers_section_values() {
        // `workspace/configuration` pulls `items[0].section`; the answer is
        // the section VALUE — a wrapped `{"python": ...}` reads as a section
        // with no `analysis` and is silently dropped by the server.
        let py = configuration_response(7, "python", Some(Path::new("/stubs")));
        assert_eq!(
            py.pointer("/result/0/analysis/extraPaths/0").unwrap(),
            "/stubs"
        );
        assert!(py.pointer("/result/0/python").is_none());
        let other = configuration_response(8, "pyright", Some(Path::new("/stubs")));
        assert_eq!(other.pointer("/result/0").unwrap(), &serde_json::json!({}));
    }

    #[test]
    fn stubs_found_beside_layout() {
        let dir = std::env::temp_dir().join(format!("pite-lsp-stubs-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let stubs = dir.join("python").join("pite");
        std::fs::create_dir_all(&stubs).unwrap();
        std::fs::write(stubs.join(STUBS_FILE), "x: int\n").unwrap();
        let script = dir.join("scripts").join("a.py");
        assert_eq!(find_stubs_dir(&script), Some(stubs));
        assert!(find_stubs_dir(Path::new("/definitely/not/here")).is_none());

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn uris_are_well_formed_on_every_platform() {
        assert_eq!(
            uri_from_path_text("/home/dev/pite/scripts/a.py"),
            "file:///home/dev/pite/scripts/a.py"
        );
        // Windows: backslashes and drive letter need normalizing, else the
        // server reports the project directory as nonexistent.
        assert_eq!(
            uri_from_path_text(r"D:\Projects\Pite\pite\examples\minimal-2d"),
            "file:///D:/Projects/Pite/pite/examples/minimal-2d"
        );
        assert_eq!(
            uri_from_path_text("D:/Projects/Pite/pite/scripts/a.py"),
            "file:///D:/Projects/Pite/pite/scripts/a.py"
        );
        assert_eq!(
            uri_from_path_text("/home/dev/my game/a b.py"),
            "file:///home/dev/my%20game/a%20b.py"
        );
        assert_eq!(path_to_uri(Path::new("/tmp/a.py")), "file:///tmp/a.py");
    }

    #[test]
    fn positions_and_word_starts() {
        let text = "ab\ncλd\n";
        assert_eq!(offset_to_position(text, 0), (0, 0));
        assert_eq!(offset_to_position(text, 3), (1, 0));
        // λ is one char but two UTF-16 units? No: U+03BB is one UTF-16 unit.
        assert_eq!(offset_to_position(text, 4), (1, 1));
        assert_eq!(byte_offset_of_char(text, 0), 0);
        assert_eq!(byte_offset_of_char(text, 4), 4);
        assert_eq!(word_start_before("self.position", 13), 5);
        assert_eq!(word_start_before("self.position", 4), 0);
        assert_eq!(word_start_before("x = 1", 4), 4);
        assert_eq!(word_start_before("x = 1", 5), 4);
        assert_eq!(word_end_after("self.position", 5), 13);
        assert_eq!(word_end_after("self.position", 0), 4);
        assert_eq!(word_end_after("x = 1", 4), 5);
        assert_eq!(word_end_after("x = 1", 5), 5);
    }

    #[test]
    fn line_starts_land() {
        let text = "a\nbb\n\nc";
        assert_eq!(line_start_byte(text, 0), 0);
        assert_eq!(line_start_byte(text, 1), 0);
        assert_eq!(line_start_byte(text, 2), 2);
        assert_eq!(line_start_byte(text, 3), 5);
        assert_eq!(line_start_byte(text, 4), 6);
        assert_eq!(line_start_byte(text, 99), text.len());
    }

    #[test]
    fn embedded_stubs_materialize_and_repair() {
        let dir = std::env::temp_dir().join(format!("pite-lsp-stubtest-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let back = write_stubs_to(&dir).unwrap();
        assert_eq!(back, dir);
        assert_eq!(
            std::fs::read_to_string(dir.join(STUBS_FILE)).unwrap(),
            EMBEDDED_STUBS
        );
        assert_eq!(
            std::fs::read_to_string(dir.join("pite.py")).unwrap(),
            EMBEDDED_SOURCE
        );
        std::fs::write(dir.join(STUBS_FILE), "stale").unwrap();
        write_stubs_to(&dir).unwrap();
        assert_eq!(
            std::fs::read_to_string(dir.join(STUBS_FILE)).unwrap(),
            EMBEDDED_STUBS
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn null_results_are_empty() {
        assert!(parse_completion_items(&Value::Null).is_empty());
        assert!(parse_hover(&Value::Null).is_empty());
        assert!(parse_signature_help(&Value::Null).is_empty());
        assert!(parse_publish_diagnostics(&Value::Null).is_empty());
    }

    #[cfg(unix)]
    #[test]
    fn framing_survives_real_fds() {
        use std::os::unix::net::UnixStream;
        let (a, b) = UnixStream::pair().unwrap();
        let body = serde_json::json!({"jsonrpc": "2.0", "method": "ping"});
        let bytes = encode_message(&body);
        let mut writer = a;
        writer.write_all(&bytes).unwrap();
        let mut reader = FramingReader::new(BufReader::new(b));
        assert_eq!(reader.read_message().unwrap(), body);
    }

    /// Live-server smoke: real pyright over stdio on the dogfood script
    /// (open → completion, change → session still serving). Runs only with
    /// `PITE_LSP_SMOKE=1` (CI sets it after installing the pin); otherwise
    /// it skips so plain `cargo test` needs no server.
    #[test]
    fn live_pyright_smoke_open_completion_change() {
        if std::env::var("PITE_LSP_SMOKE").is_err() {
            eprintln!("skipped: set PITE_LSP_SMOKE=1 for the live pyright smoke");
            return;
        }
        let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("..")
            .join("examples")
            .join("minimal-2d");
        let script = root.join("scripts").join("player.py");
        let text = std::fs::read_to_string(&script).expect("dogfood script exists");
        let rx = spawn_lsp(Some(root), &script);
        let mut client = match rx
            .recv_timeout(Duration::from_secs(180))
            .expect("starter answers")
        {
            LspOutcome::Ready { client, warning } => {
                if let Some(w) = warning {
                    eprintln!("smoke warning: {w}");
                }
                assert_eq!(client.server_version.as_deref(), Some(PINNED_PYRIGHT));
                client
            }
            LspOutcome::Failed(msg) => panic!("smoke server failed: {msg}"),
        };
        let uri = path_to_uri(&script);
        client.did_open(&uri, &text).expect("didOpen sends");

        // The server must adopt our project root: without `workspaceFolders`
        // it logs a synthetic `<default workspace root>`, finds no files, and
        // silently analyzes nothing.
        while let Some(notice) = client.take_notice() {
            assert!(
                !notice.contains("<default workspace root>"),
                "smoke: server ignored the project root: {notice}"
            );
        }

        // Completion inside `self.` — proves the open + completion round-trip.
        let (dot_line, dot_col) = text
            .lines()
            .enumerate()
            .find_map(|(l, line)| {
                let col = line.find("self.")? + 5;
                Some((l as u32, col as u32))
            })
            .expect("smoke script contains `self.`");
        let found = smoke_await_completion(&mut client, &uri, dot_line, dot_col);
        assert!(!found.is_empty(), "smoke: completion came back empty");
        assert!(
            found.iter().any(|i| i.label == "position"),
            "smoke: expected `position`, got {:?}",
            found.iter().map(|i| &i.label).collect::<Vec<_>>()
        );

        // Change, then prove the session still serves: `didChange` syncs the
        // server buffer only; the dogfood file on disk is never touched.
        let broken = format!("{text}\nundefined_smoke_name_xyz\n");
        client.did_change(&uri, &broken).expect("didChange sends");
        let after = smoke_await_completion(&mut client, &uri, dot_line, dot_col);
        assert!(
            after.iter().any(|i| i.label == "position"),
            "smoke: completion broke after didChange, got {:?}",
            after.iter().map(|i| &i.label).collect::<Vec<_>>()
        );
    }

    /// Poll until the server answers a completion request, failing loudly if
    /// it dies or the request goes unanswered. Returns the labels' items.
    fn smoke_await_completion(
        client: &mut LspClient,
        uri: &str,
        line: u32,
        character: u32,
    ) -> Vec<CompletionItem> {
        client
            .request_completion(uri, line, character)
            .expect("completion sends");
        let deadline = Instant::now() + Duration::from_secs(120);
        loop {
            if let Some(msg) = client.poll() {
                panic!("smoke: server died ({msg})");
            }
            if let Some((_, items)) = client.take_completion() {
                return items;
            }
            if Instant::now() > deadline {
                panic!("smoke: no completion arrived");
            }
            std::thread::sleep(Duration::from_millis(100));
        }
    }
}