strop-engine 0.25.0

strop editor engine: documents, grammar dispatch, services, sessions โ€” no terminal
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
use super::attach::{AttachDecision, AttachRecord};
use super::*;
use crate::editor::{document::Document, events::AppEvent, Key};
use strop_core::worker::WorkerId;
use strop_core::{
    id::{BufferRevision, ByteColumn, LineIndex},
    Buffer,
};
use strop_lsp::protocol::{Diag, ResolvedDiag, Severity};
use strop_lsp::{
    LspEvent, PositionEncoding, ReplyContext, RequestId, RequestKind, RequestStamp, ServerColumn,
    ServerId, ServerPosition, WireVersion,
};

fn editor(text: &str) -> Editor {
    let mut buffer = Buffer::from_text(text);
    buffer.path = Some(PathBuf::from("/workspace/origin.txt"));
    Editor::new_in(buffer, PathBuf::from("/workspace"))
}

fn attach_key(e: &Editor, language: &str) -> super::attach::AttachKey {
    super::attach::AttachKey {
        target: strop_workspace::Filesystem::Local,
        language: language.into(),
        path: e.buf().path.clone().unwrap(),
    }
}

fn diag_key(path: &std::path::Path) -> strop_workspace::ResourceLocation {
    strop_workspace::ResourceLocation::local(path.to_path_buf())
}

fn arm(e: &mut Editor, id: u64, kind: RequestKind, encoding: PositionEncoding) -> ReplyContext {
    let document = e.current();
    let revision = e.buf().revision();
    let server = ServerId::new(7);
    let path = e.buf().path.clone().unwrap();
    e.lsp_state.bindings.insert(
        document,
        state::Binding {
            server,
            revision,
            path,
            root: PathBuf::from("/workspace"),
            language: "rust".into(),
            target: strop_workspace::Filesystem::Local,
        },
    );
    let stamp = RequestStamp {
        request: RequestId::new(id),
        server,
        document,
        revision,
    };
    if kind == RequestKind::Hover {
        e.lsp_state.hover = Some(stamp);
    } else {
        e.lsp_state.navigation = Some(stamp);
    }
    ReplyContext {
        stamp,
        encoding,
        kind,
    }
}

fn hover(e: &mut Editor, context: ReplyContext, text: &str) {
    e.handle_app_event(AppEvent::Lsp(LspEvent::HoverText {
        context,
        text: text.into(),
    }));
}

fn diagnostics(
    e: &mut Editor,
    context: ReplyContext,
    encoding: PositionEncoding,
    diags: Vec<Diag>,
) {
    let path = e.buf().path.clone().unwrap();
    e.handle_app_event(AppEvent::Lsp(LspEvent::Diagnostics {
        context: strop_lsp::DiagnosticContext {
            server: context.stamp.server,
            document: context.stamp.document,
            revision: context.stamp.revision,
            encoding,
            version: Some(WireVersion::new(1)),
        },
        doc: diag_key(&path),
        diags,
    }));
}

#[test]
fn older_hover_cannot_overwrite_newer_reply_at_revision_zero() {
    let mut e = editor("let x = 1;\n");
    assert_eq!(e.buf().revision(), BufferRevision::new(0));
    let old = arm(&mut e, 0, RequestKind::Hover, PositionEncoding::Utf8);
    let new = arm(&mut e, 1, RequestKind::Hover, PositionEncoding::Utf8);
    hover(&mut e, new, "new answer");
    hover(&mut e, old, "old answer");
    assert_eq!(e.hover_card.as_deref(), Some("new answer"));
}

#[test]
fn equal_revision_documents_do_not_share_hover_ownership() {
    let mut e = editor("a\n");
    e.feed_text("ix");
    e.feed(Key::Esc);
    let old = arm(&mut e, 0, RequestKind::Hover, PositionEncoding::Utf8);
    let mut buffer = Buffer::from_text("b\n");
    buffer.path = Some(PathBuf::from("/workspace/other.txt"));
    let other = e.docs.insert(Document::new(buffer));
    e.switch_to(other);
    e.feed_text("iy");
    e.feed(Key::Esc);
    let new = arm(&mut e, 1, RequestKind::Hover, PositionEncoding::Utf8);
    assert_eq!(old.stamp.revision, new.stamp.revision);
    assert_ne!(old.stamp.document, new.stamp.document);
    hover(&mut e, old, "wrong document");
    assert!(e.hover_card.is_none());
    hover(&mut e, new, "right document");
    assert_eq!(e.hover_card.as_deref(), Some("right document"));
}

#[test]
fn a_hover_card_arriving_mid_insert_swallows_no_keystroke() {
    // field report: "esc from insert sometimes needs a second press" โ€”
    // an async hover reply opened its card over insert mode and the next
    // key died dismissing it. Now the card dismisses AND the key lands.
    let mut e = editor("a\n");
    e.feed_text("i");
    assert_eq!(e.mode, crate::editor::Mode::Insert);
    e.hover_card = Some("late answer".into());
    e.feed(Key::Esc);
    assert!(e.hover_card.is_none(), "card dismissed");
    assert_eq!(
        e.mode,
        crate::editor::Mode::Normal,
        "esc still exits insert"
    );
    // a typed char dismisses the card and still inserts
    e.feed_text("i");
    e.hover_card = Some("late again".into());
    e.feed_text("z");
    assert_eq!(e.buf().text().to_string(), "za\n");
    assert!(e.hover_card.is_none());
}

#[test]
fn revision_zero_is_valid_but_does_not_bypass_edit_rejection() {
    let mut e = editor("a\n");
    let zero = arm(&mut e, 0, RequestKind::SwitchHeader, PositionEncoding::Utf8);
    e.handle_lsp_event(LspEvent::Note {
        context: zero,
        text: "valid zero".into(),
    });
    assert_eq!(e.message, "valid zero");
    let stale = arm(&mut e, 1, RequestKind::SwitchHeader, PositionEncoding::Utf8);
    e.feed_text("ix");
    e.feed(Key::Esc);
    assert_ne!(e.buf().revision(), stale.stamp.revision);
    e.message = "after edit".into();
    e.handle_lsp_event(LspEvent::Note {
        context: stale,
        text: "stale zero".into(),
    });
    assert_eq!(e.message, "after edit");
}

#[test]
fn close_reopen_same_path_rejects_old_incarnation_reply() {
    let mut e = editor("old disk text\n");
    let old = arm(&mut e, 0, RequestKind::Hover, PositionEncoding::Utf8);
    let path = e.buf().path.clone().unwrap();
    let mut other = Buffer::from_text("keep editor alive\n");
    other.path = Some(PathBuf::from("/workspace/other.txt"));
    e.docs.insert(Document::new(other));
    assert!(e.close_buffer(true));
    let mut reopened = Buffer::from_text("externally replaced content\n");
    reopened.path = Some(path);
    let replacement = e.docs.insert(Document::new(reopened));
    e.switch_to(replacement);
    let new = arm(&mut e, 1, RequestKind::Hover, PositionEncoding::Utf8);
    assert_ne!(old.stamp.document, new.stamp.document);
    assert_eq!(old.stamp.revision, new.stamp.revision);
    hover(&mut e, old, "closed document");
    assert!(e.hover_card.is_none());
    hover(&mut e, new, "fresh document");
    assert_eq!(e.hover_card.as_deref(), Some("fresh document"));
    assert_eq!(e.buf().text().to_string(), "externally replaced content\n");
}

#[test]
fn old_server_reply_is_not_accepted_by_replacement_binding() {
    let mut e = editor("a\n");
    let old = arm(&mut e, 0, RequestKind::Hover, PositionEncoding::Utf8);
    e.lsp_state
        .bindings
        .get_mut(&old.stamp.document)
        .unwrap()
        .server = ServerId::new(8);
    hover(&mut e, old, "dead connection");
    assert!(e.hover_card.is_none());
}

/// A cpp binding at a custom root, mirroring arm().
fn arm_cpp(e: &mut Editor, id: u64, server_id: u64, root: &str) -> ReplyContext {
    let document = e.current();
    let revision = e.buf().revision();
    let server = ServerId::new(server_id);
    let path = e.buf().path.clone().unwrap();
    e.lsp_state.bindings.insert(
        document,
        state::Binding {
            server,
            revision,
            path,
            root: PathBuf::from(root),
            language: "cpp".into(),
            target: strop_workspace::Filesystem::Local,
        },
    );
    let stamp = RequestStamp {
        request: RequestId::new(id),
        server,
        document,
        revision,
    };
    e.lsp_state.navigation = Some(stamp);
    ReplyContext {
        stamp,
        encoding: PositionEncoding::Utf8,
        kind: RequestKind::Goto,
    }
}

fn cpp_editor() -> Editor {
    let mut buffer = Buffer::from_text("#include <vector.hpp>\n");
    buffer.path = Some(PathBuf::from("/proj/main.cpp"));
    Editor::new_in(buffer, PathBuf::from("/proj"))
}

fn insert_target(e: &mut Editor, path: &str, text: &str) -> strop_core::id::DocumentId {
    let mut buffer = Buffer::from_text(text);
    buffer.path = Some(PathBuf::from(path));
    e.docs.insert(Document::new(buffer))
}

fn at_origin() -> ServerPosition {
    ServerPosition {
        line: LineIndex::new(0),
        column: ServerColumn::new(0),
    }
}

#[test]
fn external_header_keeps_the_originating_server() {
    // 0049 ยง4: gd out of the working tree retains the replying server;
    // the second gd resolves through the carried binding.
    let mut e = cpp_editor();
    let context = arm_cpp(&mut e, 0, 7, "/proj");
    let target = insert_target(&mut e, "/usr/include/vector.hpp", "// vector\n");
    e.finish_lsp_jump(target, at_origin(), context);
    let carried = e
        .lsp_state
        .jump_contexts
        .get(&target)
        .expect("the jump carried the originating server's context");
    assert_eq!(carried.server, ServerId::new(7));
    assert_eq!(carried.root, PathBuf::from("/proj"));
    assert_eq!(carried.language, "cpp");
    assert!(
        !e.lsp_state.bindings.contains_key(&target),
        "a carried context is a routing hint, not open state โ€” didOpen follows"
    );
    let resolved = e.lsp_server_for(
        target,
        Path::new("/usr/include/vector.hpp"),
        "cpp",
        &strop_workspace::Filesystem::Local,
    );
    assert_eq!(resolved, Some((ServerId::new(7), PathBuf::from("/proj"))));
    assert!(
        e.docs.get(target).unwrap().buf.readonly,
        "outside-root content stays read-only"
    );
}

#[test]
fn extensionless_header_inherits_the_navigation_language() {
    let mut e = cpp_editor();
    let context = arm_cpp(&mut e, 0, 7, "/proj");
    let target = insert_target(&mut e, "/usr/include/vector", "// no extension\n");
    e.finish_lsp_jump(target, at_origin(), context);
    assert_eq!(
        e.lsp_state
            .jump_contexts
            .get(&target)
            .map(|c| c.language.as_str()),
        Some("cpp"),
        "extensionless inherits the jump's language (0049 ยง4.4)"
    );
    assert_eq!(
        e.lsp_doc_language(target, Path::new("/usr/include/vector"))
            .as_deref(),
        Some("cpp")
    );
}

#[test]
fn ambiguous_c_header_inherits_cpp_context() {
    let mut e = cpp_editor();
    let context = arm_cpp(&mut e, 0, 7, "/proj");
    let target = insert_target(&mut e, "/usr/include/legacy.h", "// c header\n");
    e.finish_lsp_jump(target, at_origin(), context);
    assert_eq!(
        e.lsp_state
            .jump_contexts
            .get(&target)
            .map(|c| c.language.as_str()),
        Some("cpp"),
        "an ambiguous .h keeps the cpp navigation context (0049 ยง4.4)"
    );
}

#[test]
fn a_second_project_never_switches_an_existing_binding() {
    // 0049 ยง4.5: the shared header reached from project B keeps the
    // context project A established โ€” no silent switch.
    let mut e = cpp_editor();
    let first = insert_target(&mut e, "/usr/include/vector.hpp", "// shared\n");
    e.lsp_state.bindings.insert(
        first,
        state::Binding {
            server: ServerId::new(9),
            revision: e.docs.get(first).unwrap().buf.revision(),
            path: PathBuf::from("/usr/include/vector.hpp"),
            root: PathBuf::from("/proj-a"),
            language: "cpp".into(),
            target: strop_workspace::Filesystem::Local,
        },
    );
    e.switch_to(e.current()); // no-op clarity: current is the target
    let origin = e.current();
    // jump from the /proj (server 7) document into the shared header
    e.switch_to(origin);
    let context = arm_cpp(&mut e, 0, 7, "/proj");
    e.finish_lsp_jump(first, at_origin(), context);
    assert_eq!(
        e.lsp_state.bindings.get(&first).map(|b| b.server),
        Some(ServerId::new(9)),
        "the first project's context stands"
    );
    assert!(
        !e.lsp_state.jump_contexts.contains_key(&first),
        "and no second context queues behind it"
    );
}

#[test]
fn manual_external_open_names_the_context_route() {
    // 0049 ยง4.6: a server exists but doesn't cover this path โ€” the
    // message says so and names the way in, no install red herring.
    let mut e = Editor::new_in(Buffer::from_text("int main() {}\n"), PathBuf::from("/proj"));
    e.buf_mut().path = Some(PathBuf::from("/usr/include/lonely.hpp"));
    e.lsp_state.attach.attached.push(super::attach::Attachment {
        language: "cpp".into(),
        root: PathBuf::from("/proj"),
        server: ServerId::new(7),
        target: strop_workspace::Filesystem::Local,
    });
    e.lsp_request(RequestKind::Goto);
    assert!(
        e.message.contains("no language context"),
        "truthful context route, got: {}",
        e.message
    );
    // And with no server at all, the install advice is the honest one.
    let mut e = Editor::new_in(Buffer::from_text("int main() {}\n"), PathBuf::from("/proj"));
    e.buf_mut().path = Some(PathBuf::from("/usr/include/lonely.hpp"));
    e.lsp_request(RequestKind::Goto);
    assert!(
        e.message.contains("no language server"),
        "install advice only when nothing serves the language: {}",
        e.message
    );
}

#[test]
fn document_symbols_open_a_picker_and_accepting_jumps() {
    // 0047 ยง1: the reply becomes picker rows; Enter lands on the
    // symbol and records a jumplist entry for ctrl-o.
    let mut e = editor("struct Foo;\nimpl Foo { fn bar() {} }\nfn main() {}\n");
    e.feed_text("G"); // cursor to line 3, so the jump back is observable
    let origin = e.head();
    let context = arm(
        &mut e,
        0,
        RequestKind::DocumentSymbols,
        PositionEncoding::Utf8,
    );
    e.handle_lsp_event(LspEvent::Symbols {
        context,
        symbols: vec![
            strop_lsp::protocol::ProtoSymbol {
                name: "Foo".into(),
                container: String::new(),
                kind: "Struct".into(),
                location: strop_lsp::ServerLocation {
                    doc: strop_workspace::ResourceLocation::local(PathBuf::from(
                        "/workspace/origin.txt",
                    )),
                    position: ServerPosition {
                        line: LineIndex::new(0),
                        column: ServerColumn::new(7),
                    },
                },
            },
            strop_lsp::protocol::ProtoSymbol {
                name: "bar".into(),
                container: "Foo".into(),
                kind: "Method".into(),
                location: strop_lsp::ServerLocation {
                    doc: strop_workspace::ResourceLocation::local(PathBuf::from(
                        "/workspace/origin.txt",
                    )),
                    position: ServerPosition {
                        line: LineIndex::new(1),
                        column: ServerColumn::new(16),
                    },
                },
            },
        ],
    });
    let glue = e.picker.as_ref().expect("the symbols picker opened");
    assert_eq!(glue.picker.kind, strop_picker::Kind::Symbols);
    let texts: Vec<&str> = glue.picker.items.iter().map(|i| i.text.as_str()).collect();
    assert_eq!(texts.len(), 2);
    assert!(texts[0].contains("Foo") && texts[0].contains("Struct") && texts[0].contains(":1"));
    assert!(texts[1].contains("bar") && texts[1].contains("Foo") && texts[1].contains(":2"));
    e.wait_picker();
    e.feed(Key::Enter);
    assert!(!e.picker_open());
    assert_eq!(e.head(), 7, "landed on the struct identifier");
    e.feed(Key::CtrlO);
    assert_eq!(e.head(), origin, "ctrl-o returns to the pre-jump spot");
}

#[test]
fn document_symbols_empty_reply_names_the_document() {
    let mut e = editor("x\n");
    let context = arm(
        &mut e,
        0,
        RequestKind::DocumentSymbols,
        PositionEncoding::Utf8,
    );
    e.handle_lsp_event(LspEvent::Symbols {
        context,
        symbols: Vec::new(),
    });
    assert!(!e.picker_open(), "an empty reply opens nothing");
    assert_eq!(e.message, "no symbols in this document");
}

#[test]
fn goto_completion_uses_target_encoding_and_records_original_jump() {
    let mut e = editor("origin text\n");
    e.feed_text("$");
    let origin = (e.current(), e.head());
    let context = arm(&mut e, 0, RequestKind::Goto, PositionEncoding::Utf8);
    let mut target = Buffer::from_text("a๐Ÿ˜€z\n");
    target.path = Some(PathBuf::from("/workspace/target.txt"));
    let target = e.docs.insert(Document::new(target));
    e.finish_lsp_jump(
        target,
        ServerPosition {
            line: LineIndex::new(0),
            column: ServerColumn::new(5),
        },
        context,
    );
    assert_eq!(e.current(), target);
    assert_eq!(e.head(), 5);
    e.jump_back();
    assert_eq!((e.current(), e.head()), origin);
}

#[test]
fn navigation_changed_during_load_does_not_switch_or_consume_new_request() {
    let mut e = editor("origin text\n");
    let old = arm(&mut e, 0, RequestKind::Goto, PositionEncoding::Utf8);
    let current = arm(&mut e, 1, RequestKind::Goto, PositionEncoding::Utf8);
    let target = e.docs.insert(Document::new(Buffer::from_text("target\n")));
    let before = (e.current(), e.head());
    e.finish_lsp_jump(
        target,
        ServerPosition {
            line: LineIndex::new(0),
            column: ServerColumn::new(2),
        },
        old,
    );
    assert_eq!((e.current(), e.head()), before);
    assert!(e.lsp_reply_fresh(&current));
}

#[test]
fn diagnostics_resolve_utf8_columns_in_place() {
    let mut e = editor("a๐Ÿ˜€z\n");
    let owner = arm(&mut e, 0, RequestKind::Hover, PositionEncoding::Utf8);
    diagnostics(
        &mut e,
        owner,
        PositionEncoding::Utf8,
        vec![Diag {
            line: LineIndex::new(0),
            col: ServerColumn::new(5),
            end_line: LineIndex::new(0),
            end_col: ServerColumn::new(6),
            severity: Severity::Error,
            message: "z".into(),
        }],
    );
    let diagnostics = e.diags_for(e.current()).unwrap();
    assert_eq!(
        (diagnostics[0].col.get(), diagnostics[0].end_col.get()),
        (5, 6)
    );
    assert_eq!(diagnostics[0].severity, Severity::Error);
}

#[test]
fn diagnostics_resolve_utf16_columns_against_the_rope() {
    let mut e = editor("a๐Ÿ˜€z\n");
    let owner = arm(&mut e, 0, RequestKind::Hover, PositionEncoding::Utf8);
    // UTF-16 units: a=1, emoji=2, z=1. Position 3 begins z;
    // position 4 is the boundary after z.
    diagnostics(
        &mut e,
        owner,
        PositionEncoding::Utf16,
        vec![Diag {
            line: LineIndex::new(0),
            col: ServerColumn::new(3),
            end_line: LineIndex::new(0),
            end_col: ServerColumn::new(4),
            severity: Severity::Warning,
            message: "mid-emoji".into(),
        }],
    );
    let diagnostics = e.diags_for(e.current()).unwrap();
    assert_eq!(
        (diagnostics[0].col.get(), diagnostics[0].end_col.get()),
        (5, 6)
    );
    assert_eq!(diagnostics[0].severity_char(), 'W');
}

#[test]
fn diagnostics_beyond_the_document_clamp_instead_of_panicking() {
    let mut e = editor("single line");
    let owner = arm(&mut e, 0, RequestKind::Hover, PositionEncoding::Utf8);
    diagnostics(
        &mut e,
        owner,
        PositionEncoding::Utf16,
        vec![Diag {
            line: LineIndex::new(9),
            col: ServerColumn::new(2),
            end_line: LineIndex::new(12),
            end_col: ServerColumn::new(4),
            severity: Severity::Information,
            message: "stale server range".into(),
        }],
    );
    let diagnostics = e.diags_for(e.current()).unwrap();
    assert_eq!(diagnostics[0].line.get(), 0);
    assert_eq!(diagnostics[0].end_line.get(), 0);
    // "single line": utf16 == bytes, col 2 stays 2.
    assert_eq!(diagnostics[0].col.get(), 2);
}

#[test]
fn attached_server_diagnostics_survive_full_replay() {
    use crate::editor::trace::{
        drive::{self, Action},
        seed::Seed,
    };
    use strop_trace::replay::{Tape, Tick};
    let mut e = editor("a\n");
    e.buf_mut().path = Some(PathBuf::from("/workspace/origin.rs"));
    e.tape = std::rc::Rc::new(Tape::fixture(|operation, _| match operation {
        "lsp.open" => Ok(serde_json::json!(true)),
        _ => Err(std::io::Error::other("unexpected native observation")),
    }));
    e.tape.seed(&Seed::capture(&e).unwrap()).unwrap();
    e.recorded_action(
        Action::Start {
            directory_picker: false,
            open: None,
        },
        Tick::default(),
    )
    .unwrap();
    let ticket = *e.lsp_state.attach.pending.values().next().unwrap();
    let attach = AttachRecord {
        ticket,
        server: Some(ServerId::new(3)),
        language: "rust".into(),
        name: "rust-analyzer".into(),
        root: PathBuf::from("/workspace"),
        target: strop_workspace::Filesystem::Local,
        outcome: AttachDecision::Attached,
        layers: Vec::new(),
    };
    e.recorded_action(Action::Event(AppEvent::LspAttach(attach)), Tick::default())
        .unwrap();
    let event = LspEvent::Diagnostics {
        context: strop_lsp::DiagnosticContext {
            server: ServerId::new(3),
            document: e.current(),
            revision: e.buf().revision(),
            encoding: PositionEncoding::Utf8,
            version: Some(WireVersion::new(1)),
        },
        doc: diag_key(Path::new("/workspace/origin.rs")),
        diags: vec![Diag {
            line: LineIndex::new(0),
            col: ServerColumn::new(0),
            end_line: LineIndex::new(0),
            end_col: ServerColumn::new(1),
            severity: Severity::Error,
            message: "source diagnostic".into(),
        }],
    };
    e.recorded_action(Action::Event(AppEvent::Lsp(event)), Tick::default())
        .unwrap();
    assert_eq!(e.diag_counts(e.current()), (1, 0));
    e.tape.finish().unwrap();
    let replayed = drive::replay(e.tape.fixture_nodes(), |_, _, _, _| {
        Err(std::io::Error::other(
            "frame action without an installed renderer",
        ))
    })
    .unwrap();
    assert_eq!(replayed.diag_counts(replayed.current()), (1, 0));
}

#[test]
fn stale_attach_completion_is_refused() {
    let mut e = editor("a\n");
    let current = WorkerId::new(2);
    e.lsp_state
        .attach
        .pending
        .insert(attach_key(&e, "rust"), current);
    e.handle_lsp_attach(AttachRecord {
        ticket: WorkerId::new(1),
        server: Some(ServerId::new(3)),
        language: "rust".into(),
        name: "rust-analyzer".into(),
        root: PathBuf::from("/workspace"),
        target: strop_workspace::Filesystem::Local,
        outcome: AttachDecision::Attached,
        layers: Vec::new(),
    });
    assert!(e.lsp_servers.is_empty());
    assert_eq!(
        e.lsp_state.attach.pending.get(&attach_key(&e, "rust")),
        Some(&current)
    );
}

#[test]
fn sticky_refusal_reports_once_but_trust_refusals_repeat() {
    let mut e = editor("a\n");
    let first = WorkerId::new(1);
    e.lsp_state
        .attach
        .pending
        .insert(attach_key(&e, "rust"), first);
    e.handle_lsp_attach(AttachRecord {
        ticket: first,
        server: None,
        language: "rust".into(),
        name: "rust-analyzer".into(),
        root: PathBuf::from("/workspace"),
        target: strop_workspace::Filesystem::Local,
        outcome: AttachDecision::NotExecutable {
            command: "rust-analyzer".into(),
            reason: "not found on PATH".into(),
            hint: "rustup component add rust-analyzer".into(),
        },
        layers: Vec::new(),
    });
    assert!(e.message.contains("not found on PATH"));
    assert!(e.message.contains("rust-analyzer"));
    assert!(e.message.contains("rustup component add rust-analyzer"));
    let second = WorkerId::new(2);
    e.lsp_state
        .attach
        .pending
        .insert(attach_key(&e, "rust"), second);
    e.message = "later state".into();
    e.handle_lsp_attach(AttachRecord {
        ticket: second,
        server: None,
        language: "rust".into(),
        name: "rust-analyzer".into(),
        root: PathBuf::from("/workspace"),
        target: strop_workspace::Filesystem::Local,
        outcome: AttachDecision::NotExecutable {
            command: "rust-analyzer".into(),
            reason: "not found on PATH".into(),
            hint: "rustup component add rust-analyzer".into(),
        },
        layers: Vec::new(),
    });
    assert_eq!(e.message, "later state", "sticky refusals do not repeat");
    // Trust refusals are actionable: they re-report every attempt.
    let third = WorkerId::new(3);
    e.lsp_state
        .attach
        .pending
        .insert(attach_key(&e, "rust"), third);
    e.handle_lsp_attach(AttachRecord {
        ticket: third,
        server: None,
        language: "rust".into(),
        name: "custom-lsp".into(),
        root: PathBuf::from("/workspace"),
        target: strop_workspace::Filesystem::Local,
        outcome: AttachDecision::TrustRequired {
            command: "custom-lsp".into(),
        },
        layers: Vec::new(),
    });
    assert!(e.message.contains(":trust"));
}

#[test]
fn attach_skips_unknown_languages_without_discovery() {
    let mut e = editor("plain text\n");
    e.lsp_maybe_attach();
    assert!(e.lsp_state.attach.pending.is_empty());
    assert!(e.lsp_servers.is_empty());
}

#[test]
fn refused_attach_messages_are_reported() {
    let mut e = editor("a\n");
    let ticket = WorkerId::new(9);
    e.lsp_state
        .attach
        .pending
        .insert(attach_key(&e, "rust"), ticket);
    e.handle_lsp_attach(AttachRecord {
        ticket,
        server: None,
        language: "rust".into(),
        name: "rust".into(),
        root: PathBuf::from("/workspace"),
        target: strop_workspace::Filesystem::Local,
        outcome: AttachDecision::NoServer,
        layers: Vec::new(),
    });
    assert!(e.message.contains("no language server"));
    assert!(e
        .lsp_state
        .attach
        .refused
        .contains_key(&attach_key(&e, "rust")));
}

/// 0033 ยง2: a malformed layer's diagnostic reaches the modeline with
/// its exact path even though the fallback server attached โ€” and a
/// healthy Ready does not erase it.
#[test]
fn layer_diagnostic_survives_a_healthy_attach_and_ready() {
    let mut e = editor("a\n");
    e.buf_mut().path = Some(PathBuf::from("/workspace/origin.rs"));
    let ticket = WorkerId::new(4);
    e.lsp_state
        .attach
        .pending
        .insert(attach_key(&e, "rust"), ticket);
    e.handle_lsp_attach(AttachRecord {
        ticket,
        server: Some(ServerId::new(5)),
        language: "rust".into(),
        name: "rust-analyzer".into(),
        root: PathBuf::from("/workspace"),
        target: strop_workspace::Filesystem::Local,
        outcome: AttachDecision::Attached,
        layers: vec![strop_lsp::languages::LayerDiagnostic {
            path: PathBuf::from("/home/u/.config/strop/languages.toml"),
            message: "TOML parse error โ€” layer ignored".into(),
            remote: None,
        }],
    });
    // the fallback server attached and the warning is visible with the
    // actual path
    assert_eq!(e.lsp_servers.len(), 1);
    assert_eq!(e.lsp_state.attach.attached.len(), 1);
    assert!(
        e.message.contains("/home/u/.config/strop/languages.toml"),
        "{}",
        e.message
    );
    assert!(e.message.contains("layer ignored"));
    // a healthy Ready must not erase the configuration warning
    e.handle_lsp_event(LspEvent::Ready {
        server: ServerId::new(5),
        name: "rust-analyzer".into(),
    });
    assert!(e.message.contains("ready"));
    assert!(
        e.message.contains("/home/u/.config/strop/languages.toml"),
        "{}",
        e.message
    );
    // a later attach reporting the same layer does not duplicate it
    let again = WorkerId::new(6);
    e.lsp_state
        .attach
        .pending
        .insert(attach_key(&e, "rust"), again);
    e.handle_lsp_attach(AttachRecord {
        ticket: again,
        server: None,
        language: "rust".into(),
        name: "rust-analyzer".into(),
        root: PathBuf::from("/workspace"),
        target: strop_workspace::Filesystem::Local,
        outcome: AttachDecision::NoServer,
        layers: vec![strop_lsp::languages::LayerDiagnostic {
            path: PathBuf::from("/home/u/.config/strop/languages.toml"),
            message: "TOML parse error โ€” layer ignored".into(),
            remote: None,
        }],
    });
    assert_eq!(e.lsp_state.attach.layer_diagnostics.len(), 1);
}

/// 0033 ยง2: several malformed layers report the first with a count,
/// and a refusal still carries them.
#[test]
fn multiple_layer_diagnostics_report_with_a_count() {
    let mut e = editor("a\n");
    e.buf_mut().path = Some(PathBuf::from("/workspace/origin.rs"));
    let ticket = WorkerId::new(7);
    e.lsp_state
        .attach
        .pending
        .insert(attach_key(&e, "rust"), ticket);
    e.handle_lsp_attach(AttachRecord {
        ticket,
        server: None,
        language: "rust".into(),
        name: "rust".into(),
        root: PathBuf::from("/workspace"),
        target: strop_workspace::Filesystem::Local,
        outcome: AttachDecision::NoServer,
        layers: vec![
            strop_lsp::languages::LayerDiagnostic {
                path: PathBuf::from("/xdg/languages.toml"),
                message: "bad โ€” layer ignored".into(),
                remote: None,
            },
            strop_lsp::languages::LayerDiagnostic {
                path: PathBuf::from("/proj/.strop/languages.toml"),
                message: "worse โ€” layer ignored".into(),
                remote: None,
            },
        ],
    });
    assert!(e.message.contains("/xdg/languages.toml"), "{}", e.message);
    assert!(e.message.contains("+1 more"), "{}", e.message);
    assert_eq!(e.lsp_state.attach.layer_diagnostics.len(), 2);
}

/// 0033 ยง3: a spawn failure carries its typed reason to the modeline.
#[test]
fn spawn_failure_refusal_carries_its_reason() {
    let mut e = editor("a\n");
    e.buf_mut().path = Some(PathBuf::from("/workspace/origin.rs"));
    let ticket = WorkerId::new(8);
    e.lsp_state
        .attach
        .pending
        .insert(attach_key(&e, "rust"), ticket);
    e.handle_lsp_attach(AttachRecord {
        ticket,
        server: None,
        language: "rust".into(),
        name: "rust-analyzer".into(),
        root: PathBuf::from("/workspace"),
        target: strop_workspace::Filesystem::Local,
        outcome: AttachDecision::SpawnFailed {
            reason: "cannot build the LSP runtime: boom".into(),
        },
        layers: Vec::new(),
    });
    assert!(e.message.contains("could not start"), "{}", e.message);
    assert!(e.message.contains("runtime"), "{}", e.message);
    assert!(e
        .lsp_state
        .attach
        .refused
        .contains_key(&attach_key(&e, "rust")));
}

/// 0033 ยง3: a terminal Failed event reaches the modeline with the
/// executable-bearing hint and tears the server down; a failure for an
/// already-removed server cannot resurrect a message.
#[test]
fn failed_server_event_names_the_command_and_removes_the_server() {
    let mut e = editor("a\n");
    e.buf_mut().path = Some(PathBuf::from("/workspace/origin.rs"));
    let server = ServerId::new(6);
    e.lsp_servers.push(LspServer {
        id: server,
        client: None,
        rx: std::sync::mpsc::channel().1,
        ready: true,
    });
    e.handle_lsp_event(LspEvent::Failed {
        server,
        name: "pyright".into(),
        hint: "cannot run `pyright-langserver`: No such file or directory \
               (os error 2) โ€” npm i -g pyright"
            .into(),
    });
    assert!(e.message.contains("pyright-langserver"), "{}", e.message);
    assert!(e.message.contains("npm i -g pyright"), "{}", e.message);
    assert!(e.lsp_servers.is_empty());
    // a duplicate failure for the removed server is refused, not shown
    e.message = "later state".into();
    e.handle_lsp_event(LspEvent::Failed {
        server,
        name: "pyright".into(),
        hint: "stale".into(),
    });
    assert_eq!(e.message, "later state");
}

/// window/showMessage reaches the modeline from its owning server;
/// a message for an unknown server is refused, not shown.
#[test]
fn server_message_reaches_the_modeline_from_its_owner() {
    let mut e = editor("a\n");
    e.buf_mut().path = Some(PathBuf::from("/workspace/origin.rs"));
    let server = ServerId::new(6);
    e.lsp_servers.push(LspServer {
        id: server,
        client: None,
        rx: std::sync::mpsc::channel().1,
        ready: true,
    });
    e.handle_lsp_event(LspEvent::ServerMessage {
        server,
        name: "pyright".into(),
        text: "stubPath is not a valid directory".into(),
    });
    assert_eq!(e.message, "lsp: pyright: stubPath is not a valid directory");
    e.message = "later state".into();
    e.handle_lsp_event(LspEvent::ServerMessage {
        server: ServerId::new(99),
        name: "ghost".into(),
        text: "stale".into(),
    });
    assert_eq!(e.message, "later state");
}

#[test]
fn resolved_diag_round_trips_serde() {
    let diag = ResolvedDiag {
        line: LineIndex::new(2),
        col: ByteColumn::new(7),
        end_line: LineIndex::new(2),
        end_col: ByteColumn::new(11),
        severity: Severity::Warning,
        message: "unused".into(),
    };
    let bytes = serde_json::to_vec(&diag).unwrap();
    let back: ResolvedDiag = serde_json::from_slice(&bytes).unwrap();
    assert_eq!(diag, back);
}

mod remote;