chronogit 0.9.0

A terminal UI for Git history, diffs, and source code
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
//! Bounded profile/workspace session ownership and URI containment.

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};

use futures_util::future::join_all;
use tokio::sync::{Mutex, watch};
use url::Url;

use crate::domain::{
    DocumentSymbol, RepoPath, RepositoryRoot, SemanticNavigationKind, SourcePosition,
};
use crate::lsp::config::LspConfig;
use crate::lsp::session::{RawLocation, Session, WireRange};
use crate::lsp::{LspError, LspOperationId, PositionEncoding};

const MAX_SESSIONS: usize = 4;
const MAX_DISPLAY_URI_CHARACTERS: usize = 256;

/// A repository-contained wire location awaiting safe document conversion.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct WireRepositoryLocation {
    pub(crate) path: RepoPath,
    pub(crate) selection: WireRange,
    pub(crate) encoding: PositionEncoding,
}

/// A normalized result that never treats a non-repository URI as a path.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) enum WireNavigationTarget {
    Repository(WireRepositoryLocation),
    External { display_uri: String },
}

#[derive(Clone, Debug, Eq, Hash, PartialEq)]
struct SessionKey {
    profile: String,
    workspace_root: PathBuf,
}

#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
struct SessionUseOrder(u64);

impl SessionUseOrder {
    fn advance(&mut self) -> Self {
        self.0 = self.0.saturating_add(1);
        *self
    }
}

struct SessionEntry {
    session: Arc<Session>,
    last_used: SessionUseOrder,
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
enum ManagerLifecycle {
    #[default]
    Running,
    ShuttingDown,
}

#[derive(Default)]
struct ManagerState {
    sessions: HashMap<SessionKey, SessionEntry>,
    clock: SessionUseOrder,
    lifecycle: ManagerLifecycle,
}

/// Lazily starts and independently owns bounded language-server sessions.
///
/// Sessions are keyed by profile and detected workspace root. At most four are
/// retained; starting a fifth cleanly evicts the least recently used session.
#[derive(Clone)]
pub struct LspManager {
    repository: RepositoryRoot,
    config: LspConfig,
    cache_dir: PathBuf,
    state: Arc<Mutex<ManagerState>>,
    startup: Arc<Mutex<()>>,
    latest_request: Arc<AtomicU64>,
    status: watch::Sender<Option<String>>,
}

impl std::fmt::Debug for LspManager {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("LspManager")
            .field("repository", &self.repository)
            .field("profiles", &self.config.profiles().len())
            .finish_non_exhaustive()
    }
}

impl LspManager {
    /// Creates an idle manager. No external process is started by construction.
    #[must_use]
    pub fn new(repository: RepositoryRoot, config: LspConfig) -> Self {
        let (status, _status_receiver) = watch::channel(None);
        Self {
            repository,
            config,
            cache_dir: cache_dir(),
            state: Arc::new(Mutex::new(ManagerState::default())),
            startup: Arc::new(Mutex::new(())),
            latest_request: Arc::new(AtomicU64::new(0)),
            status,
        }
    }

    /// Reports whether the user enabled no profiles.
    #[must_use]
    pub fn is_disabled(&self) -> bool {
        self.config.is_disabled()
    }

    pub(crate) fn subscribe_status(&self) -> watch::Receiver<Option<String>> {
        self.status.subscribe()
    }

    pub(crate) async fn navigate(
        &self,
        request_id: LspOperationId,
        kind: SemanticNavigationKind,
        path: &RepoPath,
        text: &str,
        position: SourcePosition,
    ) -> Result<Vec<WireNavigationTarget>, LspError> {
        let (key, session) = self.session_for(request_id, path).await?;
        // Several input tasks can wait behind one expensive initialization, but
        // only the newest intent may send a request after that wait finishes.
        if self.latest_request.load(Ordering::Acquire) != request_id.value() {
            return Ok(Vec::new());
        }
        let document_path = self.repository.as_path().join(path.to_os_string());
        let response = session
            .navigate(request_id, kind, &document_path, text, position)
            .await;
        if matches!(
            response,
            Err(LspError::Process(_) | LspError::Protocol(_) | LspError::Timeout(_))
        ) {
            self.remove_if_same(&key, &session).await;
        }
        let locations = response?;
        Ok(locations
            .into_iter()
            .map(|location| self.contain(location, session.encoding()))
            .collect())
    }

    pub(crate) async fn hover(
        &self,
        request_id: LspOperationId,
        path: &RepoPath,
        text: &str,
        position: SourcePosition,
    ) -> Result<Option<String>, LspError> {
        let (key, session) = self.session_for(request_id, path).await?;
        if self.latest_request.load(Ordering::Acquire) != request_id.value() {
            return Ok(None);
        }
        let document_path = self.repository.as_path().join(path.to_os_string());
        let response = session
            .hover(request_id, &document_path, text, position)
            .await;
        if matches!(
            response,
            Err(LspError::Process(_) | LspError::Protocol(_) | LspError::Timeout(_))
        ) {
            self.remove_if_same(&key, &session).await;
        }
        response
    }

    pub(crate) async fn document_symbols(
        &self,
        request_id: LspOperationId,
        path: &RepoPath,
        text: &str,
    ) -> Result<Vec<DocumentSymbol>, LspError> {
        let (key, session) = self.session_for(request_id, path).await?;
        if self.latest_request.load(Ordering::Acquire) != request_id.value() {
            return Ok(Vec::new());
        }
        let document_path = self.repository.as_path().join(path.to_os_string());
        let response = session
            .document_symbols(request_id, &document_path, text)
            .await;
        if matches!(
            response,
            Err(LspError::Process(_) | LspError::Protocol(_) | LspError::Timeout(_))
        ) {
            self.remove_if_same(&key, &session).await;
        }
        response
    }

    pub(crate) async fn cancel_obsolete(&self, request_id: LspOperationId) {
        let sessions = self
            .state
            .lock()
            .await
            .sessions
            .values()
            .map(|entry| Arc::clone(&entry.session))
            .collect::<Vec<_>>();
        join_all(
            sessions
                .iter()
                .map(|session| session.cancel_obsolete(request_id)),
        )
        .await;
    }

    /// Cleanly stops every resident server, killing children after a deadline.
    pub async fn shutdown(&self) {
        {
            let mut state = self.state.lock().await;
            state.lifecycle = ManagerLifecycle::ShuttingDown;
        }
        // Wait for a process currently between spawn and insertion. Queued
        // Startups observe the lifecycle state and return without spawning.
        let _startup = self.startup.lock().await;
        let sessions = {
            let mut state = self.state.lock().await;
            state
                .sessions
                .drain()
                .map(|(_, entry)| entry.session)
                .collect::<Vec<_>>()
        };
        join_all(sessions.iter().map(|session| session.shutdown())).await;
    }

    async fn ensure_running(&self) -> Result<(), LspError> {
        if self.state.lock().await.lifecycle == ManagerLifecycle::ShuttingDown {
            Err(LspError::Process(
                "language-server manager is shutting down".to_owned(),
            ))
        } else {
            Ok(())
        }
    }

    async fn session_for(
        &self,
        request_id: LspOperationId,
        path: &RepoPath,
    ) -> Result<(SessionKey, Arc<Session>), LspError> {
        self.latest_request
            .fetch_max(request_id.value(), Ordering::Release);
        self.ensure_running().await?;
        let profile = self.config.profile_for_path(path)?;
        let workspace_root = profile.workspace_root(&self.repository, path);
        let key = SessionKey {
            profile: profile.id().to_owned(),
            workspace_root: workspace_root.clone(),
        };
        if let Some(session) = self.existing_session(&key).await {
            return Ok((key, session));
        }
        // Startup is serialized so rapid intents cannot temporarily create an
        // unbounded number of heavyweight external processes.
        let _startup = self.startup.lock().await;
        self.ensure_running().await?;
        if let Some(session) = self.existing_session(&key).await {
            return Ok((key, session));
        }
        self.make_room().await;
        self.status
            .send_replace(Some(format!("starting {}", profile.id())));
        let started = Session::start(
            profile,
            workspace_root,
            &self.cache_dir,
            self.status.clone(),
        )
        .await?;
        let session = self.insert_session(key.clone(), started).await;
        Ok((key, session))
    }

    async fn existing_session(&self, key: &SessionKey) -> Option<Arc<Session>> {
        let mut state = self.state.lock().await;
        let tick = state.clock.advance();
        let entry = state.sessions.get_mut(key)?;
        entry.last_used = tick;
        Some(Arc::clone(&entry.session))
    }

    async fn insert_session(&self, key: SessionKey, started: Arc<Session>) -> Arc<Session> {
        let evicted;
        let result;
        {
            let mut state = self.state.lock().await;
            let tick = state.clock.advance();
            if let Some(existing) = state.sessions.get_mut(&key) {
                existing.last_used = tick;
                result = Arc::clone(&existing.session);
                evicted = Some(started);
            } else {
                evicted = if state.sessions.len() >= MAX_SESSIONS {
                    let oldest = state
                        .sessions
                        .iter()
                        .min_by_key(|(_, entry)| entry.last_used)
                        .map(|(key, _)| key.clone());
                    oldest.and_then(|key| state.sessions.remove(&key).map(|entry| entry.session))
                } else {
                    None
                };
                state.sessions.insert(
                    key,
                    SessionEntry {
                        session: Arc::clone(&started),
                        last_used: tick,
                    },
                );
                result = started;
            }
        }
        if let Some(session) = evicted {
            tokio::spawn(async move { session.shutdown().await });
        }
        result
    }

    async fn make_room(&self) {
        let removed = {
            let mut state = self.state.lock().await;
            if state.sessions.len() < MAX_SESSIONS {
                None
            } else {
                let oldest = state
                    .sessions
                    .iter()
                    .min_by_key(|(_, entry)| entry.last_used)
                    .map(|(key, _)| key.clone());
                oldest.and_then(|key| state.sessions.remove(&key).map(|entry| entry.session))
            }
        };
        if let Some(session) = removed {
            session.shutdown().await;
        }
    }

    async fn remove_if_same(&self, key: &SessionKey, failed: &Arc<Session>) {
        let removed = {
            let mut state = self.state.lock().await;
            if state
                .sessions
                .get(key)
                .is_some_and(|entry| Arc::ptr_eq(&entry.session, failed))
            {
                state.sessions.remove(key).map(|entry| entry.session)
            } else {
                None
            }
        };
        if let Some(session) = removed {
            tokio::spawn(async move { session.shutdown().await });
        }
    }

    fn contain(&self, location: RawLocation, encoding: PositionEncoding) -> WireNavigationTarget {
        let RawLocation { uri, selection } = location;
        let external = || WireNavigationTarget::External {
            display_uri: sanitize_uri(&uri),
        };
        let Ok(uri) = Url::parse(&uri) else {
            return external();
        };
        if uri.scheme() != "file" {
            return external();
        }
        let Ok(path) = uri.to_file_path() else {
            return external();
        };
        let Ok(relative) = path.strip_prefix(self.repository.as_path()) else {
            return external();
        };
        let Some(path) = repo_path(relative) else {
            return external();
        };
        WireNavigationTarget::Repository(WireRepositoryLocation {
            path,
            selection,
            encoding,
        })
    }
}

#[cfg(unix)]
fn repo_path(path: &Path) -> Option<RepoPath> {
    use std::os::unix::ffi::OsStrExt;

    RepoPath::from_bytes(path.as_os_str().as_bytes().to_vec()).ok()
}

#[cfg(not(unix))]
fn repo_path(path: &Path) -> Option<RepoPath> {
    let value = path.to_str()?.replace('\\', "/");
    RepoPath::from_bytes(value.into_bytes()).ok()
}

fn sanitize_uri(uri: &str) -> String {
    uri.chars()
        .filter(|character| !character.is_control())
        .take(MAX_DISPLAY_URI_CHARACTERS)
        .collect()
}

fn cache_dir() -> PathBuf {
    std::env::var_os("XDG_CACHE_HOME")
        .filter(|value| !value.is_empty())
        .map(PathBuf::from)
        .or_else(|| {
            std::env::var_os("HOME")
                .filter(|value| !value.is_empty())
                .map(PathBuf::from)
                .map(|home| home.join(".cache"))
        })
        .unwrap_or_else(std::env::temp_dir)
        .join("chronogit/lsp")
}

#[cfg(test)]
mod tests {
    use std::fs;
    use std::path::PathBuf;

    use super::LspManager;
    use crate::domain::{RepoPath, RepositoryRoot, SemanticNavigationKind, SourcePosition};
    use crate::lsp::session::{RawLocation, WirePosition, WireRange};
    use crate::lsp::{LspConfig, LspOperationId};

    fn manager() -> LspManager {
        LspManager::new(
            RepositoryRoot::new(PathBuf::from("/repo"))
                .unwrap_or_else(|error| panic!("root: {error}")),
            LspConfig::disabled(),
        )
    }

    const fn operation(value: u64) -> LspOperationId {
        LspOperationId::new(value)
    }

    fn location(uri: &str) -> RawLocation {
        RawLocation {
            uri: uri.to_owned(),
            selection: WireRange {
                start: WirePosition {
                    line: 1,
                    character: 2,
                },
                end: WirePosition {
                    line: 1,
                    character: 3,
                },
            },
        }
    }

    #[test]
    fn contains_only_repository_file_uris() {
        let manager = manager();
        assert!(matches!(
            manager.contain(
                location("file:///repo/src/main.rs"),
                crate::lsp::PositionEncoding::Utf16
            ),
            super::WireNavigationTarget::Repository(_)
        ));
        for uri in [
            "file:///outside/main.rs",
            "jdt://contents/String.class",
            "https://example.test/x",
        ] {
            assert!(matches!(
                manager.contain(location(uri), crate::lsp::PositionEncoding::Utf16),
                super::WireNavigationTarget::External { .. }
            ));
        }
    }

    #[tokio::test]
    async fn shutdown_rejects_late_navigation_without_starting_a_server() {
        let manager = manager();
        manager.shutdown().await;
        let path = RepoPath::from_bytes(b"src/main.rs".to_vec())
            .unwrap_or_else(|error| panic!("path: {error}"));
        assert!(matches!(
            manager
                .navigate(
                    operation(1),
                    SemanticNavigationKind::Definition,
                    &path,
                    "fn main() {}\n",
                    SourcePosition::new(0, 3),
                )
                .await,
            Err(crate::lsp::LspError::Process(_))
        ));
    }

    #[tokio::test]
    async fn missing_server_is_a_recoverable_request_error() {
        let directory = tempfile::tempdir().unwrap_or_else(|error| panic!("temp: {error}"));
        let config_path = directory.path().join("lsp.toml");
        fs::write(
            &config_path,
            "[servers.missing]\nlanguage_id='missing'\nextensions=['missing']\ncommand=['/definitely/missing/chronogit-language-server']\n",
        )
        .unwrap_or_else(|error| panic!("config: {error}"));
        let config = LspConfig::load(&["missing".to_owned()], Some(&config_path))
            .unwrap_or_else(|error| panic!("profile: {error}"));
        let root =
            fs::canonicalize(directory.path()).unwrap_or_else(|error| panic!("root: {error}"));
        let mut manager = LspManager::new(
            RepositoryRoot::new(root).unwrap_or_else(|error| panic!("root value: {error}")),
            config,
        );
        manager.cache_dir = directory.path().join("cache");
        let path = RepoPath::from_bytes(b"main.missing".to_vec())
            .unwrap_or_else(|error| panic!("path: {error}"));
        let error = match manager
            .navigate(
                operation(1),
                SemanticNavigationKind::Definition,
                &path,
                "symbol\n",
                SourcePosition::new(0, 0),
            )
            .await
        {
            Err(error) => error,
            Ok(targets) => panic!("missing executable unexpectedly returned {targets:?}"),
        };
        assert!(matches!(error, crate::lsp::LspError::Process(_)));
    }

    #[tokio::test]
    #[ignore = "requires rust-analyzer on PATH and is an optional interoperability smoke test"]
    async fn rust_analyzer_definition_smoke_test() {
        let repository = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        let config_dir = tempfile::tempdir().unwrap_or_else(|error| panic!("temp: {error}"));
        let config_path = config_dir.path().join("lsp.toml");
        fs::write(&config_path, "[servers]\n").unwrap_or_else(|error| panic!("config: {error}"));
        let config = LspConfig::load(&["rust-analyzer".to_owned()], Some(&config_path))
            .unwrap_or_else(|error| panic!("profile: {error}"));
        let mut manager = LspManager::new(
            RepositoryRoot::new(repository.clone()).unwrap_or_else(|error| panic!("root: {error}")),
            config,
        );
        manager.cache_dir = config_dir.path().join("cache");
        let path = RepoPath::from_bytes(b"src/main.rs".to_vec())
            .unwrap_or_else(|error| panic!("path: {error}"));
        let source = fs::read_to_string(repository.join("src/main.rs"))
            .unwrap_or_else(|error| panic!("source: {error}"));
        let (line, byte_column) = source
            .lines()
            .enumerate()
            .find_map(|(line, source_line)| {
                source_line
                    .find("LspConfig::load")
                    .map(|column| (line, column))
            })
            .unwrap_or_else(|| panic!("could not find smoke-test symbol"));
        let mut targets = Vec::new();
        for request_id in 1..=20 {
            match manager
                .navigate(
                    operation(request_id),
                    SemanticNavigationKind::Definition,
                    &path,
                    &source,
                    SourcePosition::new(u32::try_from(line).unwrap_or(u32::MAX), byte_column),
                )
                .await
            {
                Ok(found) => targets = found,
                Err(error) => panic!("definition: {error}"),
            }
            if !targets.is_empty() {
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(500)).await;
        }
        assert!(
            targets
                .iter()
                .any(|target| matches!(target, super::WireNavigationTarget::Repository(_))),
            "unexpected targets: {targets:?}"
        );
        let hover = manager
            .hover(
                operation(21),
                &path,
                &source,
                SourcePosition::new(u32::try_from(line).unwrap_or(u32::MAX), byte_column),
            )
            .await
            .unwrap_or_else(|error| panic!("hover: {error}"));
        assert!(
            hover.is_some(),
            "rust-analyzer returned no hover information"
        );
        manager.shutdown().await;
    }

    #[tokio::test]
    #[ignore = "requires pyright-langserver on PATH and is an optional interoperability smoke test"]
    async fn pyright_definition_smoke_test() {
        let repository = tempfile::tempdir().unwrap_or_else(|error| panic!("temp: {error}"));
        fs::write(
            repository.path().join("pyrightconfig.json"),
            "{\"include\":[\".\"]}\n",
        )
        .unwrap_or_else(|error| panic!("pyright config: {error}"));
        fs::write(
            repository.path().join("helper.py"),
            "def greeting(name: str) -> str:\n    return f\"Hello, {name}\"\n",
        )
        .unwrap_or_else(|error| panic!("helper: {error}"));
        let source = "from helper import greeting\n\nprint(greeting(\"ChronoGit\"))\n";
        fs::write(repository.path().join("main.py"), source)
            .unwrap_or_else(|error| panic!("main: {error}"));
        let config_path = repository.path().join("lsp.toml");
        fs::write(&config_path, "[servers]\n").unwrap_or_else(|error| panic!("config: {error}"));
        let config = LspConfig::load(&["pyright".to_owned()], Some(&config_path))
            .unwrap_or_else(|error| panic!("profile: {error}"));
        let root =
            fs::canonicalize(repository.path()).unwrap_or_else(|error| panic!("root: {error}"));
        let mut manager = LspManager::new(
            RepositoryRoot::new(root).unwrap_or_else(|error| panic!("root value: {error}")),
            config,
        );
        manager.cache_dir = repository.path().join("cache");
        let path = RepoPath::from_bytes(b"main.py".to_vec())
            .unwrap_or_else(|error| panic!("path: {error}"));
        let byte_column = source
            .lines()
            .nth(2)
            .and_then(|line| line.find("greeting"))
            .unwrap_or_else(|| panic!("could not find smoke-test symbol"));
        let mut targets = Vec::new();
        for request_id in 1..=20 {
            targets = manager
                .navigate(
                    operation(request_id),
                    SemanticNavigationKind::Definition,
                    &path,
                    source,
                    SourcePosition::new(2, byte_column),
                )
                .await
                .unwrap_or_else(|error| panic!("definition: {error}"));
            if targets.iter().any(|target| {
                matches!(
                    target,
                    super::WireNavigationTarget::Repository(location)
                        if location.path.as_bytes() == b"helper.py"
                )
            }) {
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(250)).await;
        }
        assert!(
            targets.iter().any(|target| {
                matches!(
                    target,
                    super::WireNavigationTarget::Repository(location)
                        if location.path.as_bytes() == b"helper.py"
                )
            }),
            "unexpected targets: {targets:?}"
        );
        let hover = manager
            .hover(
                operation(21),
                &path,
                source,
                SourcePosition::new(2, byte_column),
            )
            .await
            .unwrap_or_else(|error| panic!("hover: {error}"));
        assert!(hover.is_some(), "Pyright returned no hover information");
        manager.shutdown().await;
    }

    #[tokio::test]
    #[ignore = "requires jdtls on PATH and is an optional interoperability smoke test"]
    async fn jdtls_definition_smoke_test() {
        let repository = tempfile::tempdir().unwrap_or_else(|error| panic!("temp: {error}"));
        fs::write(
            repository.path().join("Helper.java"),
            "final class Helper { static String greeting() { return \"hello\"; } }\n",
        )
        .unwrap_or_else(|error| panic!("helper: {error}"));
        let source = "final class Main { String value = Helper.greeting(); }\n";
        fs::write(repository.path().join("Main.java"), source)
            .unwrap_or_else(|error| panic!("main: {error}"));
        let config_path = repository.path().join("lsp.toml");
        fs::write(&config_path, "[servers]\n").unwrap_or_else(|error| panic!("config: {error}"));
        let config = LspConfig::load(&["jdtls".to_owned()], Some(&config_path))
            .unwrap_or_else(|error| panic!("profile: {error}"));
        let root =
            fs::canonicalize(repository.path()).unwrap_or_else(|error| panic!("root: {error}"));
        let mut manager = LspManager::new(
            RepositoryRoot::new(root).unwrap_or_else(|error| panic!("root value: {error}")),
            config,
        );
        manager.cache_dir = repository.path().join("cache");
        let path = RepoPath::from_bytes(b"Main.java".to_vec())
            .unwrap_or_else(|error| panic!("path: {error}"));
        let byte_column = source
            .lines()
            .next()
            .and_then(|line| line.find("Helper"))
            .unwrap_or_else(|| panic!("could not find smoke-test symbol"));
        let mut targets = Vec::new();
        for request_id in 1..=30 {
            targets = manager
                .navigate(
                    operation(request_id),
                    SemanticNavigationKind::Definition,
                    &path,
                    source,
                    SourcePosition::new(0, byte_column),
                )
                .await
                .unwrap_or_else(|error| panic!("definition: {error}"));
            if targets.iter().any(|target| {
                matches!(
                    target,
                    super::WireNavigationTarget::Repository(location)
                        if location.path.as_bytes() == b"Helper.java"
                )
            }) {
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(500)).await;
        }
        assert!(
            targets.iter().any(|target| {
                matches!(
                    target,
                    super::WireNavigationTarget::Repository(location)
                        if location.path.as_bytes() == b"Helper.java"
                )
            }),
            "unexpected targets: {targets:?}"
        );
        let hover = manager
            .hover(
                operation(31),
                &path,
                source,
                SourcePosition::new(0, byte_column),
            )
            .await
            .unwrap_or_else(|error| panic!("hover: {error}"));
        assert!(hover.is_some(), "JDT LS returned no hover information");
        manager.shutdown().await;
    }
}