lspf 0.9.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
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
//! Typed outgoing request helpers on `ClientHandle` (issues #104, #105, #106, #107).
//!
//! `show_document`, `show_message_request`, and `apply_edit` are thin wrappers
//! over the generic typed request broker, as are the client-owned workspace
//! queries `configuration` and `workspace_folders`, the dynamic capability
//! announcements `register_capability` and `unregister_capability`, and the
//! five stable workspace refresh helpers `code_lens_refresh`,
//! `diagnostic_refresh`, `inlay_hint_refresh`, `inline_value_refresh`, and
//! `semantic_tokens_refresh`. With the `proposed` Cargo feature the same
//! coverage extends to the proposed `refresh_folding_ranges` and
//! `refresh_text_document_content` helpers (issue #108). These
//! wire-level tests run each helper inside a real handler over an in-memory
//! transport, pin the outgoing request's method and parameter shape against
//! the fixtures under `tests/fixtures/`, and then complete it through every
//! documented path: success, a remote JSON-RPC error, an invalid success
//! result, caller abandonment, and connection disconnect. A final integration
//! test proves that dynamic registration never makes an otherwise absent
//! local route dispatchable.

use std::borrow::Cow;
use std::sync::{Arc, Mutex};

use bytes::Bytes;
use lspf::types::request::Request;
use lspf::types::{
    ApplyWorkspaceEditResponse, MessageActionItem, ShowDocumentResult, WorkspaceFolder,
};
use lspf::{
    CancellationToken, ClientError, ClientHandle, RawMessage, RequestId, Server, ServerContext,
    Transport, TransportError, TransportReader, TransportWriter,
};
use serde_json::json;
use tokio::sync::mpsc;

const SHOW_DOCUMENT_FIXTURE: &str = include_str!("fixtures/show_document_request.json");
const SHOW_MESSAGE_REQUEST_FIXTURE: &str = include_str!("fixtures/show_message_request.json");
const APPLY_EDIT_FIXTURE: &str = include_str!("fixtures/apply_edit_request.json");
const CONFIGURATION_FIXTURE: &str = include_str!("fixtures/configuration_request.json");
const WORKSPACE_FOLDERS_FIXTURE: &str = include_str!("fixtures/workspace_folders_request.json");
const REGISTER_CAPABILITY_FIXTURE: &str = include_str!("fixtures/register_capability_request.json");
const UNREGISTER_CAPABILITY_FIXTURE: &str =
    include_str!("fixtures/unregister_capability_request.json");
const CODE_LENS_REFRESH_FIXTURE: &str = include_str!("fixtures/code_lens_refresh_request.json");
const DIAGNOSTIC_REFRESH_FIXTURE: &str = include_str!("fixtures/diagnostic_refresh_request.json");
const INLAY_HINT_REFRESH_FIXTURE: &str = include_str!("fixtures/inlay_hint_refresh_request.json");
const INLINE_VALUE_REFRESH_FIXTURE: &str =
    include_str!("fixtures/inline_value_refresh_request.json");
const SEMANTIC_TOKENS_REFRESH_FIXTURE: &str =
    include_str!("fixtures/semantic_tokens_refresh_request.json");

// --- Registrations -----------------------------------------------------------

/// A probe request whose handler runs one outgoing helper call. The trigger's
/// params are the helper's params as JSON; its result is the handler's marker
/// string, which synchronizes the test with the read loop.
enum Trigger {}

impl Request for Trigger {
    type Params = serde_json::Value;
    type Result = String;
    const METHOD: &'static str = "test/trigger";
}

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

struct ChannelTransport {
    incoming: mpsc::UnboundedReceiver<RawMessage>,
    outgoing: mpsc::UnboundedSender<RawMessage>,
}

struct ChannelReader(mpsc::UnboundedReceiver<RawMessage>);
struct ChannelWriter(mpsc::UnboundedSender<RawMessage>);

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

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

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

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

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

struct Session {
    in_tx: mpsc::UnboundedSender<RawMessage>,
    out_rx: mpsc::UnboundedReceiver<RawMessage>,
    serve: tokio::task::JoinHandle<lspf::Result<lspf::Outcome>>,
}

fn inbound_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 success_response(id: i32, result: serde_json::Value) -> RawMessage {
    RawMessage::Response {
        id: RequestId::Number(id),
        result: Ok(Bytes::from(serde_json::to_vec(&result).unwrap())),
    }
}

fn error_response(
    id: i32,
    code: i32,
    message: &'static str,
    data: Option<serde_json::Value>,
) -> RawMessage {
    RawMessage::Response {
        id: RequestId::Number(id),
        result: Err(lspf::JsonRpcError {
            code,
            message: message.to_string(),
            data,
        }),
    }
}

fn exit() -> RawMessage {
    RawMessage::Notification {
        method: Cow::Borrowed("exit"),
        params: Bytes::from_static(b"null"),
    }
}

async fn receive(outgoing: &mut mpsc::UnboundedReceiver<RawMessage>) -> RawMessage {
    tokio::time::timeout(std::time::Duration::from_secs(2), outgoing.recv())
        .await
        .expect("server output before watchdog timeout")
        .expect("server output channel remains open")
}

async fn start(server: Server<()>) -> Session {
    let (in_tx, incoming) = mpsc::unbounded_channel();
    let (outgoing, out_rx) = mpsc::unbounded_channel();
    let serve = tokio::spawn(server.serve(ChannelTransport { incoming, outgoing }));
    Session {
        in_tx,
        out_rx,
        serve,
    }
}

async fn init(session: &mut Session) {
    session
        .in_tx
        .send(inbound_request(
            1,
            "initialize",
            json!({ "processId": null, "rootUri": null, "capabilities": {} }),
        ))
        .unwrap();
    let response = receive(&mut session.out_rx).await;
    assert_eq!(response.id(), Some(&RequestId::Number(1)));
}

async fn finish(session: Session) {
    session.in_tx.send(exit()).unwrap();
    session
        .serve
        .await
        .expect("serve task did not panic")
        .expect("serve ended cleanly");
}

fn result_string(response: &RawMessage) -> String {
    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 assert_wire_request(message: &RawMessage, fixture: &str) {
    let RawMessage::Request { method, params, .. } = message else {
        panic!("expected a request, got {message:?}")
    };
    let wire = json!({
        "method": method.as_ref(),
        "params": serde_json::from_slice::<serde_json::Value>(params)
            .expect("the params are valid JSON"),
    });
    let expected: serde_json::Value =
        serde_json::from_str(fixture).expect("the fixture is valid JSON");
    assert_eq!(wire, expected, "the wire shape must match the fixture");
}

/// The numeric ID of an outbound request, which is how the mock peer answers
/// it and how a `$/cancelRequest` names it.
fn outbound_number_id(message: &RawMessage) -> i32 {
    match message {
        RawMessage::Request { id, .. } => match id {
            RequestId::Number(n) => *n,
            _ => panic!("expected a numeric outbound request id"),
        },
        other => panic!("expected a request, got {other:?}"),
    }
}

fn take_outcome<T>(outcome: &Arc<Mutex<Option<T>>>) -> T {
    outcome
        .lock()
        .unwrap()
        .take()
        .expect("the handler recorded an outcome")
}

/// Poll for an outcome recorded by a detached task, which survives the
/// session close that completes the pending request.
async fn await_outcome<T>(outcome: &Arc<Mutex<Option<T>>>) -> T {
    tokio::time::timeout(std::time::Duration::from_secs(3), async {
        loop {
            if let Some(value) = outcome.lock().unwrap().take() {
                return value;
            }
            tokio::time::sleep(std::time::Duration::from_millis(5)).await;
        }
    })
    .await
    .expect("the detached task recorded an outcome within the watchdog")
}

// --- Per-helper behavior tests ----------------------------------------------

/// Instantiate the five wire-level behavior tests for one helper. Each test
/// module gets:
///
/// - `success_matches_the_wire_fixture_and_decodes_the_result`
/// - `remote_error_preserves_code_message_and_data`
/// - `invalid_success_result_reports_deserialize`
/// - `abandoning_the_future_cancels_the_request_on_the_wire`
/// - `connection_disconnect_resolves_the_pending_request_as_cancelled`
///
/// `call` is an expression producing the helper future given a `ClientHandle` and
/// the trigger params as `serde_json::Value`. It is invoked three ways: awaited
/// inside the trigger handler, dropped without awaiting after a short delay
/// (abandonment), and awaited on a detached task that survives session close.
macro_rules! helper_wire_tests {
    (
        $name:ident,
        result = $result:ty,
        params = $params:expr,
        fixture = $fixture:ident,
        call = $call:expr,
        success_reply = $success_reply:expr,
        success_assert = $success_assert:expr,
        invalid_reply = $invalid_reply:expr $(,)?
    ) => {
        mod $name {
            use super::*;

            /// The helper awaited to completion inside the trigger handler.
            fn awaited_call(
                client: ClientHandle,
                params: serde_json::Value,
            ) -> impl std::future::Future<Output = Result<$result, ClientError>> {
                async move { ($call)(client, params).await }
            }

            /// The helper's future created and dropped without being awaited.
            async fn abandoned_call(client: ClientHandle, params: serde_json::Value) {
                let fut = ($call)(client, params);
                tokio::select! {
                    _ = fut => {}
                    _ = tokio::time::sleep(std::time::Duration::from_millis(50)) => {}
                }
            }

            fn roundtrip_server(
                outcome: &Arc<Mutex<Option<Result<$result, ClientError>>>>,
            ) -> Server<()> {
                let outcome = Arc::clone(outcome);
                Server::builder(())
                    .request::<Trigger, _, _>(move |_state: Arc<()>,
                                                 ctx: ServerContext,
                                                 params: serde_json::Value,
                                                 _ct: CancellationToken| {
                        let outcome = Arc::clone(&outcome);
                        async move {
                            let result = awaited_call(ctx.client(), params).await;
                            *outcome.lock().unwrap() = Some(result);
                            Ok("triggered".to_string())
                        }
                    })
                    .build()
                    .expect("the outgoing-request server builds")
            }

            fn abandon_server() -> Server<()> {
                Server::builder(())
                    .request::<Trigger, _, _>(move |_state: Arc<()>,
                                                 ctx: ServerContext,
                                                 params: serde_json::Value,
                                                 _ct: CancellationToken| {
                        async move {
                            abandoned_call(ctx.client(), params).await;
                            Ok("abandoned".to_string())
                        }
                    })
                    .build()
                    .expect("the outgoing-request server builds")
            }

            fn detached_server(
                outcome: &Arc<Mutex<Option<Result<$result, ClientError>>>>,
            ) -> Server<()> {
                let outcome = Arc::clone(outcome);
                Server::builder(())
                    .request::<Trigger, _, _>(move |_state: Arc<()>,
                                                 ctx: ServerContext,
                                                 params: serde_json::Value,
                                                 _ct: CancellationToken| {
                        let outcome = Arc::clone(&outcome);
                        async move {
                            tokio::spawn(async move {
                                let result = awaited_call(ctx.client(), params).await;
                                *outcome.lock().unwrap() = Some(result);
                            });
                            Ok("spawned".to_string())
                        }
                    })
                    .build()
                    .expect("the outgoing-request server builds")
            }

            /// Send the trigger, return the outbound request the helper put on
            /// the wire (with its wire shape pinned against the fixture).
            async fn trigger_request(session: &mut Session) -> i32 {
                session
                    .in_tx
                    .send(inbound_request(2, Trigger::METHOD, $params))
                    .unwrap();
                let outbound = receive(&mut session.out_rx).await;
                assert_wire_request(&outbound, $fixture);
                outbound_number_id(&outbound)
            }

            #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
            async fn success_matches_the_wire_fixture_and_decodes_the_result() {
                let outcome = Arc::new(Mutex::new(None));
                let mut session = start(roundtrip_server(&outcome)).await;
                init(&mut session).await;

                let id = trigger_request(&mut session).await;
                session
                    .in_tx
                    .send(success_response(id, $success_reply))
                    .unwrap();
                let response = receive(&mut session.out_rx).await;
                assert_eq!(response.id(), Some(&RequestId::Number(2)));
                assert_eq!(result_string(&response), "triggered");
                finish(session).await;

                let value = take_outcome(&outcome).expect("the helper succeeded");
                ($success_assert)(value);
            }

            #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
            async fn remote_error_preserves_code_message_and_data() {
                let outcome = Arc::new(Mutex::new(None));
                let mut session = start(roundtrip_server(&outcome)).await;
                init(&mut session).await;

                let id = trigger_request(&mut session).await;
                session
                    .in_tx
                    .send(error_response(
                        id,
                        -32001,
                        "test error",
                        Some(json!({ "detail": "transient" })),
                    ))
                    .unwrap();
                let response = receive(&mut session.out_rx).await;
                assert_eq!(response.id(), Some(&RequestId::Number(2)));
                finish(session).await;

                let err = take_outcome(&outcome).unwrap_err();
                match err {
                    ClientError::Remote(e) => {
                        assert_eq!(e.code, -32001);
                        assert_eq!(e.message, "test error");
                        assert_eq!(e.data, Some(json!({ "detail": "transient" })));
                    }
                    other => panic!("expected ClientError::Remote, got {other:?}"),
                }
            }

            #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
            async fn invalid_success_result_reports_deserialize() {
                let outcome = Arc::new(Mutex::new(None));
                let mut session = start(roundtrip_server(&outcome)).await;
                init(&mut session).await;

                let id = trigger_request(&mut session).await;
                session
                    .in_tx
                    .send(success_response(id, $invalid_reply))
                    .unwrap();
                let response = receive(&mut session.out_rx).await;
                assert_eq!(response.id(), Some(&RequestId::Number(2)));
                finish(session).await;

                let err = take_outcome(&outcome).unwrap_err();
                assert!(
                    matches!(err, ClientError::Deserialize(_)),
                    "expected ClientError::Deserialize, got {err:?}"
                );
            }

            #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
            async fn abandoning_the_future_cancels_the_request_on_the_wire() {
                let mut session = start(abandon_server()).await;
                init(&mut session).await;

                session
                    .in_tx
                    .send(inbound_request(2, Trigger::METHOD, $params))
                    .unwrap();
                let outbound = receive(&mut session.out_rx).await;
                let id = outbound_number_id(&outbound);

                // Dropping the future emits exactly one typed $/cancelRequest
                // naming the abandoned request's ID.
                let cancel = receive(&mut session.out_rx).await;
                match cancel {
                    RawMessage::Notification { method, params } => {
                        assert_eq!(&*method, "$/cancelRequest");
                        let params: serde_json::Value =
                            serde_json::from_slice(&params).unwrap();
                        assert_eq!(params["id"], serde_json::json!(id));
                    }
                    other => panic!("expected a $/cancelRequest notification, got {other:?}"),
                }

                // The handler still completes normally.
                let response = receive(&mut session.out_rx).await;
                assert_eq!(response.id(), Some(&RequestId::Number(2)));
                assert_eq!(result_string(&response), "abandoned");
                finish(session).await;
            }

            #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
            async fn connection_disconnect_resolves_the_pending_request_as_cancelled() {
                let outcome = Arc::new(Mutex::new(None));
                let mut session = start(detached_server(&outcome)).await;
                init(&mut session).await;

                session
                    .in_tx
                    .send(inbound_request(2, Trigger::METHOD, $params))
                    .unwrap();
                // The trigger response may race the detached task's request;
                // skip it until the request itself appears on the wire, which
                // proves it is pending when the connection drops.
                loop {
                    match receive(&mut session.out_rx).await {
                        RawMessage::Request { .. } => break,
                        _ => {}
                    }
                }

                // Close the transport without answering: the pending request
                // must complete with Cancelled, and serving must not hang.
                drop(session.in_tx);
                tokio::time::timeout(std::time::Duration::from_secs(3), session.serve)
                    .await
                    .expect("serve returned within the watchdog")
                    .expect("serve task did not panic")
                    .expect("serve ended cleanly");

                let err = await_outcome(&outcome).await.unwrap_err();
                assert!(
                    matches!(err, ClientError::Cancelled),
                    "expected ClientError::Cancelled, got {err:?}"
                );
            }
        }
    };
}

helper_wire_tests!(
    show_document,
    result = ShowDocumentResult,
    params = json!({ "uri": "file:///guide.md", "takeFocus": true }),
    fixture = SHOW_DOCUMENT_FIXTURE,
    call = |client: ClientHandle, params: serde_json::Value| async move {
        client
            .show_document(serde_json::from_value(params).unwrap())
            .await
    },
    success_reply = json!({ "success": true }),
    success_assert =
        |value: ShowDocumentResult| assert_eq!(value, ShowDocumentResult { success: true }),
    invalid_reply = json!({ "success": "yes" }),
);

helper_wire_tests!(
    show_message_request,
    result = Option<MessageActionItem>,
    params = json!({
        "type": 3,
        "message": "save before closing?",
        "actions": [{ "title": "Save" }, { "title": "Discard" }],
    }),
    fixture = SHOW_MESSAGE_REQUEST_FIXTURE,
    call = |client: ClientHandle, params: serde_json::Value| async move {
        client
            .show_message_request(serde_json::from_value(params).unwrap())
            .await
    },
    success_reply = json!({ "title": "Save" }),
    success_assert = |value: Option<MessageActionItem>| {
        let item = value.expect("the user picked an action");
        assert_eq!(item.title, "Save");
        assert!(item.properties.is_empty());
    },
    invalid_reply = json!({ "title": 42 }),
);

helper_wire_tests!(
    apply_edit,
    result = ApplyWorkspaceEditResponse,
    params = json!({
        "label": "rename symbol",
        "edit": {
            "changes": {
                "file:///main.rs": [
                    {
                        "range": {
                            "start": { "line": 0, "character": 4 },
                            "end": { "line": 0, "character": 7 },
                        },
                        "newText": "renamed",
                    },
                ],
            },
        },
    }),
    fixture = APPLY_EDIT_FIXTURE,
    call = |client: ClientHandle, params: serde_json::Value| async move {
        client
            .apply_edit(serde_json::from_value(params).unwrap())
            .await
    },
    success_reply = json!({ "applied": true }),
    success_assert = |value: ApplyWorkspaceEditResponse| {
        assert_eq!(
            value,
            ApplyWorkspaceEditResponse {
                applied: true,
                failure_reason: None,
                failed_change: None,
            }
        );
    },
    invalid_reply = json!({ "applied": "yes" }),
);

helper_wire_tests!(
    configuration,
    result = Vec<serde_json::Value>,
    params = json!({
        "items": [
            { "section": "editor" },
            { "scopeUri": "file:///workspace/main.rs", "section": "lspf.language" },
        ],
    }),
    fixture = CONFIGURATION_FIXTURE,
    call = |client: ClientHandle, params: serde_json::Value| async move {
        client.configuration(serde_json::from_value(params).unwrap()).await
    },
    // The reply mixes a filled value, a null, and an extra entry: the result
    // must keep the client's order and length exactly, filling nothing in and
    // truncating nothing out.
    success_reply = json!([{ "tabSize": 4 }, null, { "extra": true }]),
    success_assert = |value: Vec<serde_json::Value>| {
        assert_eq!(
            value,
            vec![json!({ "tabSize": 4 }), serde_json::Value::Null, json!({ "extra": true })],
            "the client's order and length are preserved exactly"
        );
    },
    invalid_reply = json!({ "not": "an array" }),
);

helper_wire_tests!(
    workspace_folders,
    result = Option<Vec<WorkspaceFolder>>,
    params = json!(null),
    fixture = WORKSPACE_FOLDERS_FIXTURE,
    call = |client: ClientHandle, _params: serde_json::Value| async move { client.workspace_folders().await },
    success_reply = json!([
        { "uri": "file:///a", "name": "a" },
        { "uri": "file:///b", "name": "b" },
    ]),
    success_assert = |value: Option<Vec<WorkspaceFolder>>| {
        let folders = value.expect("the client answered with folders");
        assert_eq!(folders.len(), 2, "the client's order and length are preserved");
        assert_eq!(folders[0].uri.as_str(), "file:///a");
        assert_eq!(folders[0].name, "a");
        assert_eq!(folders[1].uri.as_str(), "file:///b");
        assert_eq!(folders[1].name, "b");
    },
    invalid_reply = json!([{ "name": "missing uri" }]),
);

helper_wire_tests!(
    register_capability,
    result = (),
    params = json!({
        "registrations": [
            {
                "id": "hover-registration",
                "method": "textDocument/hover",
                "registerOptions": { "documentSelector": [{ "language": "rust" }] },
            },
        ],
    }),
    fixture = REGISTER_CAPABILITY_FIXTURE,
    call = |client: ClientHandle, params: serde_json::Value| async move {
        client
            .register_capability(serde_json::from_value(params).unwrap())
            .await
    },
    success_reply = json!(null),
    success_assert = |value: ()| assert_eq!(value, ()),
    invalid_reply = json!({ "unexpected": true }),
);

helper_wire_tests!(
    unregister_capability,
    result = (),
    params = json!({
        "unregisterations": [
            { "id": "hover-registration", "method": "textDocument/hover" },
        ],
    }),
    fixture = UNREGISTER_CAPABILITY_FIXTURE,
    call = |client: ClientHandle, params: serde_json::Value| async move {
        client
            .unregister_capability(serde_json::from_value(params).unwrap())
            .await
    },
    success_reply = json!(null),
    success_assert = |value: ()| assert_eq!(value, ()),
    invalid_reply = json!({ "unexpected": true }),
);

helper_wire_tests!(
    code_lens_refresh,
    result = (),
    params = json!(null),
    fixture = CODE_LENS_REFRESH_FIXTURE,
    call = |client: ClientHandle, _params: serde_json::Value| async move {
        client.code_lens_refresh().await
    },
    success_reply = json!(null),
    success_assert = |value: ()| assert_eq!(value, ()),
    invalid_reply = json!({ "unexpected": true }),
);

helper_wire_tests!(
    diagnostic_refresh,
    result = (),
    params = json!(null),
    fixture = DIAGNOSTIC_REFRESH_FIXTURE,
    call = |client: ClientHandle, _params: serde_json::Value| async move {
        client.diagnostic_refresh().await
    },
    success_reply = json!(null),
    success_assert = |value: ()| assert_eq!(value, ()),
    invalid_reply = json!({ "unexpected": true }),
);

helper_wire_tests!(
    inlay_hint_refresh,
    result = (),
    params = json!(null),
    fixture = INLAY_HINT_REFRESH_FIXTURE,
    call = |client: ClientHandle, _params: serde_json::Value| async move {
        client.inlay_hint_refresh().await
    },
    success_reply = json!(null),
    success_assert = |value: ()| assert_eq!(value, ()),
    invalid_reply = json!({ "unexpected": true }),
);

helper_wire_tests!(
    inline_value_refresh,
    result = (),
    params = json!(null),
    fixture = INLINE_VALUE_REFRESH_FIXTURE,
    call = |client: ClientHandle, _params: serde_json::Value| async move {
        client.inline_value_refresh().await
    },
    success_reply = json!(null),
    success_assert = |value: ()| assert_eq!(value, ()),
    invalid_reply = json!({ "unexpected": true }),
);

helper_wire_tests!(
    semantic_tokens_refresh,
    result = (),
    params = json!(null),
    fixture = SEMANTIC_TOKENS_REFRESH_FIXTURE,
    call = |client: ClientHandle, _params: serde_json::Value| async move {
        client.semantic_tokens_refresh().await
    },
    success_reply = json!(null),
    success_assert = |value: ()| assert_eq!(value, ()),
    invalid_reply = json!({ "unexpected": true }),
);

// --- Proposed workspace refresh helpers (issue #108) --------------------------
//
// These helpers and their local protocol types exist only when the crate's
// `proposed` Cargo feature is enabled, so the whole module is compiled out of
// default builds.

#[cfg(feature = "proposed")]
mod proposed {
    use super::*;

    const FOLDING_RANGE_REFRESH_FIXTURE: &str =
        include_str!("fixtures/folding_range_refresh_request.json");
    const TEXT_DOCUMENT_CONTENT_REFRESH_FIXTURE: &str =
        include_str!("fixtures/text_document_content_refresh_request.json");

    helper_wire_tests!(
        refresh_folding_ranges,
        result = (),
        params = json!(null),
        fixture = FOLDING_RANGE_REFRESH_FIXTURE,
        call = |client: ClientHandle, _params: serde_json::Value| async move {
            client.refresh_folding_ranges().await
        },
        success_reply = json!(null),
        success_assert = |value: ()| assert_eq!(value, ()),
        invalid_reply = json!({ "unexpected": true }),
    );

    helper_wire_tests!(
        refresh_text_document_content,
        result = (),
        params = json!({ "uri": "file:///main.rs" }),
        fixture = TEXT_DOCUMENT_CONTENT_REFRESH_FIXTURE,
        call = |client: ClientHandle, params: serde_json::Value| async move {
            client
                .refresh_text_document_content(serde_json::from_value(params).unwrap())
                .await
        },
        success_reply = json!(null),
        success_assert = |value: ()| assert_eq!(value, ()),
        invalid_reply = json!({ "unexpected": true }),
    );

    /// The text-document-content refresh params carry only the target
    /// `DocumentUri`: the struct has exactly that one field, so the helper
    /// produces exactly the `uri` wire field.
    #[test]
    fn text_document_content_refresh_params_contain_only_the_uri() {
        let params: lspf::proposed::TextDocumentContentRefreshParams =
            serde_json::from_value(json!({ "uri": "file:///main.rs" })).unwrap();
        assert_eq!(params.uri.as_str(), "file:///main.rs");
        assert_eq!(
            serde_json::to_value(&params).unwrap(),
            json!({ "uri": "file:///main.rs" }),
            "the params serialize to exactly the uri field"
        );
    }
}

// --- Router freeze integration test (issue #106) ----------------------------

/// A dynamic `client/registerCapability` announcement tells the client about
/// a capability; it never adds a route to the connection's frozen Router.
/// Dynamically registering `textDocument/hover` must not make the otherwise
/// absent local hover route dispatchable.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn dynamic_registration_does_not_dispatch_an_absent_route() {
    // The trigger handler announces hover support to the client; the params
    // come from the wire fixture so the announcement is the real thing.
    let fixture: serde_json::Value =
        serde_json::from_str(REGISTER_CAPABILITY_FIXTURE).expect("the fixture is valid JSON");
    let registration_params = fixture["params"].clone();
    let server = Server::builder(())
        .request::<Trigger, _, _>(
            move |_state: Arc<()>,
                  ctx: ServerContext,
                  params: serde_json::Value,
                  _ct: CancellationToken| {
                async move {
                    ctx.client()
                        .register_capability(serde_json::from_value(params).unwrap())
                        .await
                        .expect("the client accepted the registration");
                    Ok("registered".to_string())
                }
            },
        )
        .build()
        .expect("the outgoing-request server builds");
    let mut session = start(server).await;
    init(&mut session).await;

    session
        .in_tx
        .send(inbound_request(2, Trigger::METHOD, registration_params))
        .unwrap();
    let outbound = receive(&mut session.out_rx).await;
    assert_wire_request(&outbound, REGISTER_CAPABILITY_FIXTURE);
    let id = outbound_number_id(&outbound);
    session
        .in_tx
        .send(success_response(id, json!(null)))
        .unwrap();
    let response = receive(&mut session.out_rx).await;
    assert_eq!(response.id(), Some(&RequestId::Number(2)));
    assert_eq!(result_string(&response), "registered");

    // The Router never gained a hover route: dispatch still answers
    // MethodNotFound for the dynamically registered method.
    session
        .in_tx
        .send(inbound_request(
            3,
            "textDocument/hover",
            json!({
                "textDocument": { "uri": "file:///main.rs" },
                "position": { "line": 0, "character": 0 },
            }),
        ))
        .unwrap();
    let response = receive(&mut session.out_rx).await;
    match response {
        RawMessage::Response {
            id: RequestId::Number(3),
            result: Err(e),
        } => assert_eq!(
            e.code, -32601,
            "dynamic registration must not add a local route"
        ),
        other => panic!("expected a MethodNotFound error for id 3, got {other:?}"),
    }
    finish(session).await;
}