lspf 0.2.1

A Rust framework for building extensible LSP language servers
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
//! End-to-end coverage for post-mutation document hooks (issue #49).
//!
//! `textDocument/didOpen`, `didChange`, and `didClose` are protocol built-ins:
//! the engine decodes and mutates the connection-owned [`Documents`]
//! serially, and only then does the user's registered hook enter the Service
//! stack. These tests drive a connection-owned [`Server`] over an in-memory
//! transport and prove the hook observes post-mutation state through the
//! read-only `DocumentsView`, cannot suppress or roll back the built-in, and is
//! skipped — without ending the connection — when decode or built-in validation
//! fails. `didSave` has no built-in mutation in 0.2, so it stays an ordinary
//! typed notification route.

use std::borrow::Cow;
use std::str::FromStr;
use std::sync::{Arc, Mutex};
use std::time::Duration;

use bytes::Bytes;
use serde::{Deserialize, Serialize};
use serde_json::json;
use tokio::sync::mpsc;

use lspf::types::notification::{
    DidChangeTextDocument, DidCloseTextDocument, DidOpenTextDocument, DidSaveTextDocument,
};
use lspf::types::request::Request;
use lspf::types::{
    DidChangeTextDocumentParams, DidCloseTextDocumentParams, DidOpenTextDocumentParams,
    DidSaveTextDocumentParams, Position, Uri,
};
use lspf::{
    BuildError, CancellationToken, Context, LspError, RawMessage, RequestId, Server, Transport,
    TransportError, TransportReader, TransportWriter,
};

// --- What each hook observed -------------------------------------------------

/// One hook invocation, recorded as the state the hook saw *after* the built-in
/// mutation ran. Every field is read through `ctx.documents()`, so the record is
/// exactly what a user handler can observe.
#[derive(Debug, PartialEq, Eq)]
enum Seen {
    Open {
        text: Option<String>,
        version: Option<i32>,
    },
    Change {
        text: Option<String>,
        version: Option<i32>,
    },
    Close {
        still_present: bool,
    },
    Save {
        still_present: bool,
    },
}

type Log = Arc<Mutex<Vec<Seen>>>;

struct AppState {
    seen: Log,
}

fn uri(s: &str) -> Uri {
    Uri::from_str(s).expect("test URIs are valid")
}

async fn on_did_open(state: Arc<AppState>, ctx: Context, params: DidOpenTextDocumentParams) {
    let doc = ctx.documents().get(&params.text_document.uri);
    state.seen.lock().unwrap().push(Seen::Open {
        text: doc.as_ref().map(|d| d.text()),
        version: doc.as_ref().map(|d| d.version()),
    });
}

async fn on_did_change(state: Arc<AppState>, ctx: Context, params: DidChangeTextDocumentParams) {
    let doc = ctx.documents().get(&params.text_document.uri);
    state.seen.lock().unwrap().push(Seen::Change {
        text: doc.as_ref().map(|d| d.text()),
        version: doc.as_ref().map(|d| d.version()),
    });
}

async fn on_did_close(state: Arc<AppState>, ctx: Context, params: DidCloseTextDocumentParams) {
    let still_present = ctx.documents().get(&params.text_document.uri).is_some();
    state
        .seen
        .lock()
        .unwrap()
        .push(Seen::Close { still_present });
}

async fn on_did_save(state: Arc<AppState>, ctx: Context, params: DidSaveTextDocumentParams) {
    let still_present = ctx.documents().get(&params.text_document.uri).is_some();
    state
        .seen
        .lock()
        .unwrap()
        .push(Seen::Save { still_present });
}

// --- A custom request that reads the documents through the view --------------

#[derive(Debug, Serialize, Deserialize)]
struct ProbeParams {
    uri: String,
    /// Optional position to convert with the connection's negotiated encoding.
    #[serde(default)]
    position: Option<Position>,
}

#[derive(Debug, Serialize, Deserialize)]
struct ProbeResult {
    text: Option<String>,
    version: Option<i32>,
    offset: Option<usize>,
    utf8_encoding: bool,
}

/// A custom request whose only job is to report what `ctx.documents()` sees, so
/// a test can observe the documents from a message that arrives *after* the
/// document notifications.
enum Probe {}

impl Request for Probe {
    type Params = ProbeParams;
    type Result = ProbeResult;
    const METHOD: &'static str = "custom/probe";
}

async fn probe(
    _state: Arc<AppState>,
    ctx: Context,
    params: ProbeParams,
    _ct: CancellationToken,
) -> Result<ProbeResult, LspError> {
    let documents = ctx.documents();
    let uri = uri(&params.uri);
    let doc = documents.get(&uri);
    Ok(ProbeResult {
        text: doc.as_ref().map(|d| d.text()),
        version: doc.as_ref().map(|d| d.version()),
        offset: params
            .position
            .and_then(|position| documents.position_to_offset(&uri, position)),
        utf8_encoding: documents.position_encoding() == lspf::PositionEncoding::Utf8,
    })
}

// --- In-memory transport -----------------------------------------------------

struct ChannelTransport {
    in_rx: mpsc::UnboundedReceiver<RawMessage>,
    out_tx: mpsc::UnboundedSender<RawMessage>,
}

struct ChannelReader {
    in_rx: mpsc::UnboundedReceiver<RawMessage>,
}

struct ChannelWriter {
    out_tx: mpsc::UnboundedSender<RawMessage>,
}

impl Transport for ChannelTransport {
    type Reader = ChannelReader;
    type Writer = ChannelWriter;

    fn split(self) -> (Self::Reader, Self::Writer) {
        (
            ChannelReader { in_rx: self.in_rx },
            ChannelWriter {
                out_tx: self.out_tx,
            },
        )
    }
}

impl TransportReader for ChannelReader {
    async fn recv(&mut self) -> Result<RawMessage, TransportError> {
        self.in_rx.recv().await.ok_or(TransportError::Closed)
    }
}

impl TransportWriter for ChannelWriter {
    async fn send(&mut self, msg: RawMessage) -> Result<(), TransportError> {
        self.out_tx.send(msg).map_err(|_| TransportError::Closed)
    }

    async fn shutdown(self) -> Result<(), TransportError> {
        Ok(())
    }
}

// --- Envelope helpers --------------------------------------------------------

fn request(id: i32, method: &'static str, params: serde_json::Value) -> RawMessage {
    RawMessage::Request {
        id: RequestId::Number(id),
        method: Cow::Borrowed(method),
        params: Bytes::from(serde_json::to_vec(&params).unwrap()),
    }
}

fn initialize_request(id: i32) -> RawMessage {
    request(
        id,
        "initialize",
        json!({ "processId": null, "rootUri": null, "capabilities": {} }),
    )
}

/// An `initialize` whose client offers UTF-8, so the connection negotiates it
/// (ADR 0016) and the view reports byte offsets.
fn initialize_utf8_request(id: i32) -> RawMessage {
    request(
        id,
        "initialize",
        json!({
            "processId": null,
            "rootUri": null,
            "capabilities": { "general": { "positionEncodings": ["utf-8"] } }
        }),
    )
}

fn notification(method: &'static str, params: serde_json::Value) -> RawMessage {
    RawMessage::Notification {
        method: Cow::Borrowed(method),
        params: Bytes::from(serde_json::to_vec(&params).unwrap()),
    }
}

fn did_open(uri: &str, text: &str) -> RawMessage {
    notification(
        "textDocument/didOpen",
        json!({
            "textDocument": {
                "uri": uri,
                "languageId": "plaintext",
                "version": 1,
                "text": text
            }
        }),
    )
}

fn did_change(uri: &str, version: i32, start: u32, end: u32, text: &str) -> RawMessage {
    notification(
        "textDocument/didChange",
        json!({
            "textDocument": { "uri": uri, "version": version },
            "contentChanges": [{
                "range": {
                    "start": { "line": 0, "character": start },
                    "end": { "line": 0, "character": end }
                },
                "text": text
            }]
        }),
    )
}

fn did_close(uri: &str) -> RawMessage {
    notification(
        "textDocument/didClose",
        json!({ "textDocument": { "uri": uri } }),
    )
}

fn did_save(uri: &str) -> RawMessage {
    notification(
        "textDocument/didSave",
        json!({ "textDocument": { "uri": uri } }),
    )
}

fn probe_request(id: i32, uri: &str) -> RawMessage {
    request(id, "custom/probe", json!({ "uri": uri }))
}

// --- Harness -----------------------------------------------------------------

/// Every document hook plus the probe request, so one server can observe all
/// four notifications.
fn observing_server(seen: &Log) -> Server<AppState> {
    Server::builder(AppState {
        seen: Arc::clone(seen),
    })
    .notification::<DidOpenTextDocument, _, _>(on_did_open)
    .notification::<DidChangeTextDocument, _, _>(on_did_change)
    .notification::<DidCloseTextDocument, _, _>(on_did_close)
    .notification::<DidSaveTextDocument, _, _>(on_did_save)
    .request::<Probe, _, _>(probe)
    .build()
    .expect("one hook per built-in notification is a valid registration set")
}

/// Serve `server` over an in-memory transport, feeding `messages` one at a time
/// and awaiting each request's response before sending the next, so ordering is
/// observable. Closing the peer end then drains the connection.
async fn drive(server: Server<AppState>, messages: Vec<RawMessage>) -> Vec<RawMessage> {
    let (in_tx, in_rx) = mpsc::unbounded_channel::<RawMessage>();
    let (out_tx, mut out_rx) = mpsc::unbounded_channel::<RawMessage>();
    let transport = ChannelTransport { in_rx, out_tx };

    let handle = tokio::spawn(async move { server.serve(transport).await });

    let mut outbox = Vec::new();
    for msg in messages {
        let response_id = msg.id().cloned();
        in_tx.send(msg).unwrap();
        if let Some(response_id) = response_id {
            let response = tokio::time::timeout(Duration::from_secs(2), out_rx.recv())
                .await
                .expect("response arrived within 2s")
                .expect("writer remained open");
            assert_eq!(response.id(), Some(&response_id));
            outbox.push(response);
        }
    }
    drop(in_tx); // peer disconnect → serve drains and returns

    tokio::time::timeout(Duration::from_secs(2), handle)
        .await
        .expect("serve returned within 2s")
        .expect("server task did not panic")
        .expect("serve ended cleanly");

    outbox.extend(std::iter::from_fn(|| out_rx.try_recv().ok()));
    outbox
}

fn ok_result<T: serde::de::DeserializeOwned>(outbox: &[RawMessage], id: i32) -> T {
    let response = outbox
        .iter()
        .find(
            |m| matches!(m, RawMessage::Response { id: rid, .. } if *rid == RequestId::Number(id)),
        )
        .expect("the request was answered");
    match response {
        RawMessage::Response {
            result: Ok(bytes), ..
        } => serde_json::from_slice(bytes).expect("the result decodes"),
        other => panic!("expected a success response, got {other:?}"),
    }
}

fn probed(outbox: &[RawMessage], id: i32) -> ProbeResult {
    ok_result(outbox, id)
}

// --- Tests -------------------------------------------------------------------

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn each_document_hook_observes_the_post_mutation_documents() {
    let seen: Log = Arc::default();
    drive(
        observing_server(&seen),
        vec![
            initialize_request(1),
            did_open("file:///hooks.txt", "hello world"),
            did_change("file:///hooks.txt", 2, 6, 11, "lspf"),
            did_save("file:///hooks.txt"),
            did_close("file:///hooks.txt"),
        ],
    )
    .await;

    assert_eq!(
        *seen.lock().unwrap(),
        vec![
            Seen::Open {
                text: Some("hello world".to_string()),
                version: Some(1),
            },
            Seen::Change {
                text: Some("hello lspf".to_string()),
                version: Some(2),
            },
            // didSave has no built-in mutation in 0.2, so the document is
            // untouched and still open when the ordinary route runs.
            Seen::Save {
                still_present: true
            },
            Seen::Close {
                still_present: false
            },
        ],
        "every hook runs once, in receipt order, observing post-mutation state"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn the_built_in_mutation_runs_without_any_registered_hook() {
    let seen: Log = Arc::default();
    // Only the probe request is registered — no document hook at all.
    let server = Server::builder(AppState {
        seen: Arc::clone(&seen),
    })
    .request::<Probe, _, _>(probe)
    .build()
    .expect("a lone custom request builds");

    let outbox = drive(
        server,
        vec![
            initialize_request(1),
            did_open("file:///no-hook.txt", "hello world"),
            did_change("file:///no-hook.txt", 2, 6, 11, "lspf"),
            probe_request(2, "file:///no-hook.txt"),
        ],
    )
    .await;

    let probed = probed(&outbox, 2);
    assert_eq!(
        probed.text.as_deref(),
        Some("hello lspf"),
        "document mutation is a built-in, not something a hook opts into"
    );
    assert_eq!(probed.version, Some(2));
    assert!(
        seen.lock().unwrap().is_empty(),
        "no hook was registered, so nothing was observed"
    );
}

/// A hook cannot suppress the built-in: it runs strictly after the mutation has
/// landed, and even a panicking hook — isolated by the framework's outermost
/// Layer — leaves the documents mutated and the connection able to serve later
/// messages.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_panicking_hook_cannot_suppress_or_roll_back_the_mutation() {
    async fn panicking_hook(
        _state: Arc<AppState>,
        _ctx: Context,
        _params: DidOpenTextDocumentParams,
    ) {
        panic!("a hook must not be able to undo the built-in mutation");
    }

    let server = Server::builder(AppState {
        seen: Arc::default(),
    })
    .notification::<DidOpenTextDocument, _, _>(panicking_hook)
    .request::<Probe, _, _>(probe)
    .build()
    .expect("server builds");

    let outbox = drive(
        server,
        vec![
            initialize_request(1),
            did_open("file:///panics.txt", "still here"),
            probe_request(2, "file:///panics.txt"),
        ],
    )
    .await;

    assert_eq!(
        probed(&outbox, 2).text.as_deref(),
        Some("still here"),
        "the mutation survives a hook that panics after it"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn malformed_document_params_skip_the_hook_and_later_messages_still_run() {
    let seen: Log = Arc::default();
    let outbox = drive(
        observing_server(&seen),
        vec![
            initialize_request(1),
            // `version` must be an integer, so these params never decode.
            notification(
                "textDocument/didOpen",
                json!({
                    "textDocument": {
                        "uri": "file:///malformed.txt",
                        "languageId": "plaintext",
                        "version": "not-a-number",
                        "text": "ignored"
                    }
                }),
            ),
            did_open("file:///after.txt", "later work still happens"),
            probe_request(2, "file:///malformed.txt"),
        ],
    )
    .await;

    assert_eq!(
        *seen.lock().unwrap(),
        vec![Seen::Open {
            text: Some("later work still happens".to_string()),
            version: Some(1),
        }],
        "a decode failure skips the hook; the next notification still runs it"
    );
    assert_eq!(
        probed(&outbox, 2).text,
        None,
        "nothing was opened for the malformed notification"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn an_invalid_change_skips_the_hook_and_leaves_the_document_intact() {
    let seen: Log = Arc::default();
    let outbox = drive(
        observing_server(&seen),
        vec![
            initialize_request(1),
            did_open("file:///invalid-change.txt", "hello world"),
            // A range whose end precedes its start fails built-in validation.
            did_change("file:///invalid-change.txt", 2, 11, 6, "lspf"),
            probe_request(2, "file:///invalid-change.txt"),
        ],
    )
    .await;

    assert_eq!(
        *seen.lock().unwrap(),
        vec![Seen::Open {
            text: Some("hello world".to_string()),
            version: Some(1),
        }],
        "built-in validation failure skips the change hook"
    );
    let probed = probed(&outbox, 2);
    assert_eq!(
        probed.text.as_deref(),
        Some("hello world"),
        "a rejected change leaves the document as it was"
    );
    assert_eq!(
        probed.version,
        Some(1),
        "a rejected change does not advance the version"
    );
}

/// A rejected change in the middle of a batch must not leave a half-applied
/// revision behind: the whole notification is refused, so the document stays at
/// the revision the last accepted notification produced.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_change_batch_applies_all_or_nothing() {
    let seen: Log = Arc::default();
    let outbox = drive(
        observing_server(&seen),
        vec![
            initialize_request(1),
            did_open("file:///batch.txt", "hello world"),
            // The first edit is applicable on its own; the second is reversed.
            notification(
                "textDocument/didChange",
                json!({
                    "textDocument": { "uri": "file:///batch.txt", "version": 2 },
                    "contentChanges": [
                        {
                            "range": {
                                "start": { "line": 0, "character": 6 },
                                "end": { "line": 0, "character": 11 }
                            },
                            "text": "lspf"
                        },
                        {
                            "range": {
                                "start": { "line": 0, "character": 5 },
                                "end": { "line": 0, "character": 0 }
                            },
                            "text": "!"
                        }
                    ]
                }),
            ),
            probe_request(2, "file:///batch.txt"),
        ],
    )
    .await;

    assert_eq!(
        *seen.lock().unwrap(),
        vec![Seen::Open {
            text: Some("hello world".to_string()),
            version: Some(1),
        }],
        "a rejected batch skips the change hook"
    );
    let probed = probed(&outbox, 2);
    assert_eq!(
        probed.text.as_deref(),
        Some("hello world"),
        "the batch's first edit is rolled back with the rest of it"
    );
    assert_eq!(
        probed.version,
        Some(1),
        "a rejected batch does not advance the version"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_change_batch_composes_its_edits_in_order() {
    let seen: Log = Arc::default();
    drive(
        observing_server(&seen),
        vec![
            initialize_request(1),
            did_open("file:///compose.txt", "hello world"),
            notification(
                "textDocument/didChange",
                json!({
                    "textDocument": { "uri": "file:///compose.txt", "version": 2 },
                    "contentChanges": [
                        // "hello world" -> "hello lspf"
                        {
                            "range": {
                                "start": { "line": 0, "character": 6 },
                                "end": { "line": 0, "character": 11 }
                            },
                            "text": "lspf"
                        },
                        // "hello lspf" -> "hi lspf", ranged against the result
                        // of the edit before it.
                        {
                            "range": {
                                "start": { "line": 0, "character": 0 },
                                "end": { "line": 0, "character": 5 }
                            },
                            "text": "hi"
                        }
                    ]
                }),
            ),
        ],
    )
    .await;

    assert_eq!(
        seen.lock().unwrap()[1],
        Seen::Change {
            text: Some("hi lspf".to_string()),
            version: Some(2),
        },
        "the hook observes the whole batch applied in receipt order, once"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn closing_a_document_that_was_never_opened_still_runs_the_hook() {
    let seen: Log = Arc::default();
    drive(
        observing_server(&seen),
        vec![
            initialize_request(1),
            did_close("file:///never-opened.txt"),
            did_open("file:///opened.txt", "x"),
            did_close("file:///opened.txt"),
        ],
    )
    .await;

    assert_eq!(
        *seen.lock().unwrap(),
        vec![
            // Nothing was there to remove, so the hook observes the same
            // absence a real close would have left behind.
            Seen::Close {
                still_present: false
            },
            Seen::Open {
                text: Some("x".to_string()),
                version: Some(1),
            },
            Seen::Close {
                still_present: false
            },
        ],
        "a close with nothing to remove is not a validation failure"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn the_view_converts_positions_with_the_negotiated_encoding() {
    let seen: Log = Arc::default();
    let outbox = drive(
        observing_server(&seen),
        vec![
            initialize_utf8_request(1),
            // "héllo" — 'é' is two UTF-8 bytes, so byte 3 is the second 'l'
            // under UTF-8 but would be character 4 under UTF-16.
            did_open("file:///encoded.txt", "héllo"),
            request(
                2,
                "custom/probe",
                json!({
                    "uri": "file:///encoded.txt",
                    "position": { "line": 0, "character": 3 }
                }),
            ),
        ],
    )
    .await;

    let probed = probed(&outbox, 2);
    assert!(
        probed.utf8_encoding,
        "the view reports the encoding the connection negotiated"
    );
    assert_eq!(
        probed.offset,
        Some(3),
        "under UTF-8 `character` is a byte offset within the line"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn initialize_advertises_the_built_in_incremental_document_sync() {
    let seen: Log = Arc::default();
    // No document hook is registered: the sync capability describes the
    // protocol built-in the engine always performs, not a user registration.
    let server = Server::builder(AppState {
        seen: Arc::clone(&seen),
    })
    .build()
    .expect("an empty server builds");
    let outbox = drive(server, vec![initialize_request(1)]).await;

    let init: lspf::types::InitializeResult = ok_result(&outbox, 1);
    assert_eq!(
        init.capabilities.text_document_sync,
        Some(lspf::types::TextDocumentSyncCapability::Kind(
            lspf::types::TextDocumentSyncKind::INCREMENTAL
        )),
        "a client only sends didOpen/didChange/didClose to a server that \
         advertises the sync kind the engine's built-ins implement"
    );
}

#[test]
fn duplicate_document_hook_registration_fails_during_build() {
    let err = Server::builder(AppState {
        seen: Arc::default(),
    })
    .notification::<DidOpenTextDocument, _, _>(on_did_open)
    .notification::<DidOpenTextDocument, _, _>(on_did_open)
    .build()
    .err()
    .expect("a built-in notification takes at most one hook");
    assert_eq!(
        err,
        BuildError::DuplicateMethod("textDocument/didOpen".to_string())
    );
}