wsb-daemon 0.275.7622

wsb's daemon: the workbench, the GitHub mirror's schedule and peer continuity, for every workspace on the machine
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
//! Code intelligence for a worktree's editor: omnicode's language server, bridged to the page.
//!
//! The page edits files in its editor and asks about them — what a name is, where it is
//! defined and used, what is wrong with the file. The daemon answers from `omni lsp`, one
//! server per analysis root ([`wsb::omnicode::roots`]): a worktree is a fleet of repositories,
//! and omnicode analyzes one at a time.
//!
//! - **Which files.** The languages `omni` answers for, with the features each is served with,
//!   come from `omni` itself ([`wsb::omnicode::locate`]); a file of another language is
//!   answered with why it is not served, and nothing is started for it.
//! - **Servers.** Started on the first file of their root a page opens; shut down once no page
//!   has a file of it open for [`IDLE`]; never started again behind anyone's back when they
//!   exit — the page is told how one ended, and starts it again by asking.
//! - **Text.** Every page's copy of an open file is kept, and the server's copy follows the
//!   page that last edited or asked ([`documents`]). An answer is always about the asking
//!   page's text, or a refusal that says the text moved on.
//! - **Pushes.** Diagnostics, progress and messages reach the page on the worktree's event
//!   stream, as `code` events ([`CodeEvent`]).
//! - **Paths.** Pages name files by their path in the worktree; the server by `file://` URI.
//!   Locations outside the worktree (a dependency's source) are named by a token the page can
//!   read through the daemon, and only those the server named are readable.

pub mod documents;
pub mod framing;
pub mod session;
pub mod text;

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};

use serde::Serialize;
use serde_json::{Value, json};
use tokio::sync::{Mutex, broadcast, mpsc};

use wsb::omnicode::locate::{self, Omni, Unavailable};
use wsb::omnicode::roots::{AnalysisRoot, Fleet};

use documents::{ClientId, Outgoing, Registry, SyncError};
use session::{Inbound, RequestFailure, Session, State};

/// How long a root's server outlives the last file of it a page had open.
pub const IDLE: Duration = Duration::from_secs(10 * 60);

/// How long a page that lost its event stream keeps its files open: long enough to reconnect.
pub const CLIENT_GRACE: Duration = Duration::from_secs(30);

/// What the page is told, on the worktree's event stream.
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum CodeEvent {
    /// Where a root's server stands.
    Status { root: String, status: RootStatus },
    /// A file's diagnostics, for the server's copy of it at `version` (`digest` is its text's).
    Diagnostics { path: String, version: i32, digest: String, diagnostics: Vec<Value> },
    /// The published analysis's diagnostics of a root's files, by worktree path, replacing
    /// what was said of that root before.
    AnalysisDiagnostics { root: String, files: BTreeMap<String, Vec<Value>> },
    /// Something the server wants a person told.
    Message { level: String, text: String },
}

/// A root and where its server stands.
#[derive(Debug, Clone, Serialize)]
pub struct RootStatus {
    /// Relative to the worktree (`.` for its own root).
    pub root: String,
    #[serde(flatten)]
    pub state: State,
}

/// Why a question about a file has no answer.
#[derive(Debug, Clone, PartialEq)]
pub enum AskError {
    /// The page's text moved on, or the server says the document changed: ask again.
    Stale(String),
    /// The page's copy and the daemon's disagree: the page must send its whole text.
    Resync(String),
    /// The file is not one this can be asked about, or the feature is not served for it.
    NotServed(String),
    /// The server cannot answer now (starting, failed, ended).
    Unavailable(String),
    /// The server answered with an error.
    Failed(String),
}

impl std::fmt::Display for AskError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Stale(m) | Self::Resync(m) | Self::NotServed(m) | Self::Unavailable(m) | Self::Failed(m) => {
                f.write_str(m)
            }
        }
    }
}

impl From<SyncError> for AskError {
    fn from(e: SyncError) -> Self {
        match e {
            SyncError::Stale { .. } => Self::Stale(e.to_string()),
            _ => Self::Resync(e.to_string()),
        }
    }
}

/// What a page is told about a file it opened.
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "served", rename_all = "snake_case")]
pub enum Opened {
    /// Served: by which root's server, as which language, with which features.
    Yes { root: String, language: String, features: Vec<String> },
    /// Not served, and why.
    No { reason: String },
}

/// One root: its server, if running, and what the pages have open of it.
struct Root {
    root: AnalysisRoot,
    session: Option<Arc<Session>>,
    /// Why there is no server, when it ended or never started.
    ended: Option<State>,
    registry: Registry,
    /// Diagnostics of the server's copies, by worktree path.
    live: BTreeMap<String, (i32, String, Vec<Value>)>,
    /// The published analysis's diagnostics, by worktree path.
    analysis: BTreeMap<String, Vec<Value>>,
    /// When the last of its files was closed.
    idle_since: Option<Instant>,
}

#[derive(Default)]
struct Inner {
    /// By the root's directory.
    roots: BTreeMap<PathBuf, Root>,
    /// Event streams open per page.
    streams: BTreeMap<ClientId, usize>,
    /// Files outside the worktree the servers named, by token.
    external: BTreeMap<String, PathBuf>,
}

/// A worktree's code intelligence.
pub struct CodeIntel {
    /// Canonical.
    worktree: PathBuf,
    inner: Mutex<Inner>,
    events: broadcast::Sender<CodeEvent>,
    inbound: mpsc::UnboundedSender<(PathBuf, Inbound)>,
}

impl std::fmt::Debug for CodeIntel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CodeIntel").field("worktree", &self.worktree).finish_non_exhaustive()
    }
}

/// The text of a file under the worktree, or why there is none.
fn read_text(path: &Path) -> Result<String, String> {
    std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))
}

impl CodeIntel {
    /// The code intelligence of the worktree at `worktree`, and the task that handles what its
    /// servers push. Nothing is started until a page opens a file.
    pub fn new(worktree: &Path) -> Result<Arc<Self>, String> {
        let worktree = wsb::platform::canonicalize(worktree).map_err(|e| format!("{}: {e}", worktree.display()))?;
        let (events, _) = broadcast::channel(512);
        let (inbound, mut rx) = mpsc::unbounded_channel::<(PathBuf, Inbound)>();
        let intel = Arc::new(Self { worktree, inner: Mutex::new(Inner::default()), events, inbound });
        {
            let weak = Arc::downgrade(&intel);
            tokio::spawn(async move {
                while let Some((dir, pushed)) = rx.recv().await {
                    let Some(intel) = weak.upgrade() else { break };
                    intel.on_inbound(&dir, pushed).await;
                }
            });
        }
        {
            let weak = Arc::downgrade(&intel);
            tokio::spawn(async move {
                let mut every = tokio::time::interval(Duration::from_secs(60));
                loop {
                    every.tick().await;
                    let Some(intel) = weak.upgrade() else { break };
                    intel.stop_idle().await;
                }
            });
        }
        Ok(intel)
    }

    pub fn subscribe(&self) -> broadcast::Receiver<CodeEvent> {
        self.events.subscribe()
    }

    fn label(&self, dir: &Path) -> String {
        match dir.strip_prefix(&self.worktree) {
            Ok(rel) if rel.as_os_str().is_empty() => ".".to_owned(),
            Ok(rel) => rel.to_string_lossy().replace('\\', "/"),
            Err(_) => dir.display().to_string(),
        }
    }

    /// The absolute path of a worktree path, refusing one that leaves the worktree.
    fn absolute(&self, path: &str) -> Result<PathBuf, String> {
        let rel = Path::new(path);
        if rel.is_absolute() || rel.components().any(|c| !matches!(c, std::path::Component::Normal(_))) {
            return Err(format!("{path} is not a path inside the worktree"));
        }
        Ok(self.worktree.join(rel))
    }

    fn uri_of(&self, path: &str) -> Result<String, String> {
        session::file_uri(&self.absolute(path)?)
    }

    /// The worktree path a `file://` URI names, if it is inside the worktree.
    fn path_of(&self, uri: &str) -> Option<String> {
        let path = url::Url::parse(uri).ok()?.to_file_path().ok()?;
        let rel = path.strip_prefix(&self.worktree).ok()?;
        Some(rel.to_string_lossy().replace('\\', "/"))
    }

    /// The `omni` to use, or why there is none.
    pub fn omni(&self) -> Result<Omni, Unavailable> {
        locate::find()
    }

    /// Every root and where its server stands.
    pub async fn status(&self) -> Vec<RootStatus> {
        let inner = self.inner.lock().await;
        inner.roots.iter().map(|(dir, r)| RootStatus { root: self.label(dir), state: root_state(r) }).collect()
    }

    fn emit(&self, event: CodeEvent) {
        let _ = self.events.send(event);
    }

    /// Send what a registry said to tell the server.
    fn send(&self, session: &Session, outgoing: Vec<Outgoing>) -> Result<(), String> {
        for o in outgoing {
            match o {
                Outgoing::Open { path, language_id, version, text } => session.notify(
                    "textDocument/didOpen",
                    json!({ "textDocument": { "uri": self.uri_of(&path)?, "languageId": language_id, "version": version, "text": text } }),
                )?,
                Outgoing::Edit { path, version, changes } => session.notify(
                    "textDocument/didChange",
                    json!({ "textDocument": { "uri": self.uri_of(&path)?, "version": version }, "contentChanges": changes }),
                )?,
                Outgoing::Replace { path, version, text } => session.notify(
                    "textDocument/didChange",
                    json!({ "textDocument": { "uri": self.uri_of(&path)?, "version": version }, "contentChanges": [{ "text": text }] }),
                )?,
                Outgoing::Close { path } => session.notify(
                    "textDocument/didClose",
                    json!({ "textDocument": { "uri": self.uri_of(&path)? } }),
                )?,
            }
        }
        Ok(())
    }

    /// A page opened `path` with `text` at its `version`.
    pub async fn open(&self, client: &str, path: &str, version: i64, text: &str) -> Result<Opened, String> {
        let omni = match self.omni() {
            Ok(o) => o,
            Err(why) => return Ok(Opened::No { reason: why.to_string() }),
        };
        let file = self.absolute(path)?;
        let Some((language, served)) = omni.language_of(&file) else {
            return Ok(Opened::No {
                reason: format!("omnicode does not analyze {path}: no language it answers for takes this file"),
            });
        };
        let (language, features) = (language.to_owned(), served.features.clone());
        // The file may not exist yet (a new, unsaved file): its directory decides its root.
        let located = match wsb::platform::canonicalize(&file) {
            Ok(f) => f,
            Err(_) => wsb::platform::canonicalize(file.parent().unwrap_or(&self.worktree))
                .map_err(|e| format!("{path}: {e}"))?
                .join(file.file_name().unwrap_or_default()),
        };
        let root = Fleet::discover(&self.worktree)?.analysis_root(&located)?;
        let session = self.session_for(&omni, root.clone()).await?;
        let mut inner = self.inner.lock().await;
        let r = inner.roots.get_mut(&root.dir).ok_or("the root vanished while it was started")?;
        r.idle_since = None;
        let outgoing = r.registry.open(client, path, &language, version, text);
        self.send(&session, outgoing)?;
        Ok(Opened::Yes { root: self.label(&root.dir), language, features })
    }

    /// The running server of `root`, started if it is not and was never started or stopped
    /// for being idle. One that ended unasked stays ended until [`Self::restart`].
    async fn session_for(&self, omni: &Omni, root: AnalysisRoot) -> Result<Arc<Session>, String> {
        {
            let mut inner = self.inner.lock().await;
            let r = inner.roots.entry(root.dir.clone()).or_insert_with(|| Root {
                root: root.clone(),
                session: None,
                ended: None,
                registry: Registry::default(),
                live: BTreeMap::new(),
                analysis: BTreeMap::new(),
                idle_since: None,
            });
            if let Some(s) = r.session.as_ref().filter(|s| s.running()) {
                return Ok(s.clone());
            }
            if let Some(ended @ State::Crashed { .. }) = &r.ended {
                return Err(format!(
                    "the language server of {} ended ({}); start it again to go on",
                    self.label(&root.dir),
                    serde_json::to_string(ended).unwrap_or_default()
                ));
            }
        }
        self.emit(CodeEvent::Status {
            root: self.label(&root.dir),
            status: RootStatus { root: self.label(&root.dir), state: State::Starting },
        });
        let started = Session::start(omni, root.clone(), self.inbound.clone()).await;
        let mut inner = self.inner.lock().await;
        let r = inner.roots.get_mut(&root.dir).ok_or("the root vanished while it was started")?;
        match started {
            Ok(s) => {
                r.session = Some(s.clone());
                r.ended = None;
                // A server started again holds what the pages have open.
                let replay = r.registry.replay();
                self.send(&s, replay)?;
                Ok(s)
            }
            Err(e) => {
                let failed = State::Failed { message: e.clone() };
                r.ended = Some(failed.clone());
                drop(inner);
                self.emit(CodeEvent::Status {
                    root: self.label(&root.dir),
                    status: RootStatus { root: self.label(&root.dir), state: failed },
                });
                Err(e)
            }
        }
    }

    /// Start a root's server again, holding what the pages have open.
    pub async fn restart(&self, root: &str) -> Result<(), String> {
        let omni = self.omni().map_err(|e| e.to_string())?;
        let dir = if root == "." { self.worktree.clone() } else { self.absolute(root)? };
        let dir = wsb::platform::canonicalize(&dir).map_err(|e| format!("{root}: {e}"))?;
        let (old, analysis_root) = {
            let mut inner = self.inner.lock().await;
            let r = inner.roots.get_mut(&dir).ok_or_else(|| format!("{root} is not a root of this worktree's editor"))?;
            r.ended = None;
            (r.session.take(), r.root.clone())
        };
        if let Some(old) = old {
            old.shutdown().await;
        }
        self.session_for(&omni, analysis_root).await.map(|_| ())
    }

    /// The root whose server has `path` open for `client`.
    fn root_of<'a>(inner: &'a mut Inner, worktree: &Path, path: &str) -> Option<&'a mut Root> {
        let file = worktree.join(path);
        inner
            .roots
            .values_mut()
            .filter(|r| file.starts_with(&r.root.dir))
            .max_by_key(|r| r.root.dir.components().count())
    }

    /// A page edited `path`.
    pub async fn change(
        &self,
        client: &str,
        path: &str,
        from: i64,
        to: i64,
        changes: &[text::Change],
    ) -> Result<(), AskError> {
        let mut inner = self.inner.lock().await;
        let worktree = self.worktree.clone();
        let r = Self::root_of(&mut inner, &worktree, path)
            .ok_or_else(|| AskError::Resync(format!("{path} is not open")))?;
        let outgoing = r.registry.change(client, path, from, to, changes)?;
        let session = r.session.clone().filter(|s| s.running());
        if let Some(s) = session {
            self.send(&s, outgoing).map_err(AskError::Unavailable)?;
        }
        Ok(())
    }

    /// A page closed `path`.
    pub async fn close(&self, client: &str, path: &str) {
        let mut inner = self.inner.lock().await;
        let worktree = self.worktree.clone();
        let Some(r) = Self::root_of(&mut inner, &worktree, path) else { return };
        let outgoing = r.registry.close(client, path);
        if outgoing.iter().any(|o| matches!(o, Outgoing::Close { .. })) {
            r.live.remove(path);
        }
        if r.registry.is_empty() {
            r.idle_since = Some(Instant::now());
        }
        if let Some(s) = r.session.clone().filter(|s| s.running()) {
            let _ = self.send(&s, outgoing);
        }
    }

    /// A page's event stream opened.
    pub async fn stream_opened(&self, client: &str) {
        *self.inner.lock().await.streams.entry(client.to_owned()).or_default() += 1;
    }

    /// A page's event stream ended: if it does not come back within [`CLIENT_GRACE`], the
    /// page is gone and its files are closed.
    pub fn stream_closed(self: &Arc<Self>, client: &str) {
        let intel = Arc::downgrade(self);
        let client = client.to_owned();
        tokio::spawn(async move {
            {
                let Some(intel) = intel.upgrade() else { return };
                let mut inner = intel.inner.lock().await;
                let left = inner.streams.entry(client.clone()).or_default();
                *left = left.saturating_sub(1);
            }
            tokio::time::sleep(CLIENT_GRACE).await;
            let Some(intel) = intel.upgrade() else { return };
            let mut inner = intel.inner.lock().await;
            if inner.streams.get(&client).copied().unwrap_or(0) > 0 {
                return;
            }
            inner.streams.remove(&client);
            for r in inner.roots.values_mut() {
                let outgoing = r.registry.close_client(&client);
                for o in &outgoing {
                    if let Outgoing::Close { path } = o {
                        r.live.remove(path);
                    }
                }
                if r.registry.is_empty() && r.idle_since.is_none() {
                    r.idle_since = Some(Instant::now());
                }
                if let Some(s) = r.session.clone().filter(|s| s.running()) {
                    let _ = intel.send(&s, outgoing);
                }
            }
        });
    }

    /// Ask the server about `path` as `client` has it at `version`.
    pub async fn ask(
        &self,
        client: &str,
        path: &str,
        version: i64,
        feature: &str,
        params: Value,
    ) -> Result<Value, AskError> {
        let omni = self.omni().map_err(|e| AskError::NotServed(e.to_string()))?;
        let file = self.absolute(path).map_err(AskError::NotServed)?;
        let (_, served) = omni
            .language_of(&file)
            .ok_or_else(|| AskError::NotServed(format!("omnicode does not analyze {path}")))?;
        if !served.features.iter().any(|f| f == feature) {
            return Err(AskError::NotServed(format!("{feature} is not served for {path}")));
        }
        let method = method_of(feature).ok_or_else(|| AskError::NotServed(format!("{feature} is not a feature")))?;
        let session = {
            let mut inner = self.inner.lock().await;
            let worktree = self.worktree.clone();
            let r = Self::root_of(&mut inner, &worktree, path)
                .ok_or_else(|| AskError::Resync(format!("{path} is not open")))?;
            let session = match (&r.session, &r.ended) {
                (Some(s), _) if s.running() => s.clone(),
                (_, Some(ended)) => {
                    return Err(AskError::Unavailable(format!(
                        "the language server is not running: {}",
                        serde_json::to_string(ended).unwrap_or_default()
                    )));
                }
                _ => return Err(AskError::Unavailable("the language server is not running".into())),
            };
            let outgoing = r.registry.ensure(client, path, version)?;
            self.send(&session, outgoing).map_err(AskError::Unavailable)?;
            session
        };
        let mut params = params;
        params["textDocument"] = json!({ "uri": self.uri_of(path).map_err(AskError::NotServed)? });
        match session.request(method, params).await {
            Ok(result) => Ok(self.rewrite(result).await),
            Err(RequestFailure::Rpc { code, message })
                if code == session::CONTENT_MODIFIED || code == session::REQUEST_CANCELLED =>
            {
                Err(AskError::Stale(message))
            }
            Err(RequestFailure::Rpc { message, .. }) => Err(AskError::Failed(message)),
            Err(other) => Err(AskError::Unavailable(other.to_string())),
        }
    }

    /// A server's answer with its `file://` URIs as the page names files: a worktree path, or
    /// a token for a file outside the worktree.
    async fn rewrite(&self, mut value: Value) -> Value {
        let mut external = BTreeMap::new();
        rewrite_uris(&mut value, &mut |uri: &str| match self.path_of(uri) {
            Some(path) => json!({ "path": path }),
            None => {
                let file = url::Url::parse(uri).ok().and_then(|u| u.to_file_path().ok());
                match file {
                    Some(f) => {
                        let token = text::digest(&f.display().to_string())[..32].to_owned();
                        external.insert(token.clone(), f.clone());
                        json!({ "external": token, "name": f.display().to_string() })
                    }
                    None => json!({ "unreadable": uri }),
                }
            }
        });
        if !external.is_empty() {
            self.inner.lock().await.external.extend(external);
        }
        value
    }

    /// The text of a file outside the worktree a server named.
    pub async fn external(&self, token: &str) -> Result<(String, String), String> {
        let path = self
            .inner
            .lock()
            .await
            .external
            .get(token)
            .cloned()
            .ok_or_else(|| "no language server named a file by this token".to_owned())?;
        Ok((path.display().to_string(), read_text(&path)?))
    }

    /// A page saved `path`.
    pub async fn saved(&self, path: &str) {
        let mut inner = self.inner.lock().await;
        let worktree = self.worktree.clone();
        let Some(r) = Self::root_of(&mut inner, &worktree, path) else { return };
        if r.registry.server_copy(path).is_none() {
            return;
        }
        if let (Some(s), Ok(uri)) = (r.session.clone().filter(|s| s.running()), self.uri_of(path)) {
            let _ = s.notify("textDocument/didSave", json!({ "textDocument": { "uri": uri } }));
        }
    }

    /// Files changed on disk (worktree paths; `deleted` when gone).
    pub async fn disk_changed(&self, changes: &[(String, bool)]) {
        let inner = self.inner.lock().await;
        for r in inner.roots.values() {
            let Some(s) = r.session.clone().filter(|s| s.running()) else { continue };
            let events: Vec<Value> = changes
                .iter()
                .filter(|(p, _)| self.worktree.join(p).starts_with(&r.root.dir))
                .filter_map(|(p, deleted)| Some(json!({ "uri": self.uri_of(p).ok()?, "type": if *deleted { 3 } else { 2 } })))
                .collect();
            if !events.is_empty() {
                let _ = s.notify("workspace/didChangeWatchedFiles", json!({ "changes": events }));
            }
        }
    }

    /// Every diagnostic the editor holds: of the servers' copies, and of the published
    /// analyses, by worktree path.
    pub async fn diagnostics(&self) -> Vec<CodeEvent> {
        let inner = self.inner.lock().await;
        let mut out = Vec::new();
        for (dir, r) in &inner.roots {
            out.push(CodeEvent::AnalysisDiagnostics { root: self.label(dir), files: r.analysis.clone() });
            for (path, (version, digest, diagnostics)) in &r.live {
                out.push(CodeEvent::Diagnostics {
                    path: path.clone(),
                    version: *version,
                    digest: digest.clone(),
                    diagnostics: diagnostics.clone(),
                });
            }
        }
        out
    }

    async fn on_inbound(self: &Arc<Self>, dir: &Path, pushed: Inbound) {
        match pushed {
            Inbound::Diagnostics(params) => {
                let Some(path) = params["uri"].as_str().and_then(|u| self.path_of(u)) else { return };
                let mut inner = self.inner.lock().await;
                let Some(r) = inner.roots.get_mut(dir) else { return };
                let Some((version, text)) = r.registry.server_copy(&path) else {
                    // Closed meanwhile: what it says is about nothing any page has.
                    return;
                };
                // Published for an older copy: the newer one's follow.
                if params["version"].as_i64().is_some_and(|v| v != i64::from(version)) {
                    return;
                }
                let digest = text::digest(text);
                let diagnostics = params["diagnostics"].as_array().cloned().unwrap_or_default();
                r.live.insert(path.clone(), (version, digest.clone(), diagnostics.clone()));
                drop(inner);
                self.emit(CodeEvent::Diagnostics { path, version, digest, diagnostics });
            }
            Inbound::Message { level, text } => self.emit(CodeEvent::Message { level: level.to_owned(), text }),
            Inbound::State(state) => {
                let root = self.label(dir);
                let ready = matches!(state, State::Ready { .. });
                if matches!(state, State::Crashed { .. } | State::Stopped) {
                    let mut inner = self.inner.lock().await;
                    if let Some(r) = inner.roots.get_mut(dir) {
                        r.ended = Some(state.clone());
                        r.session = None;
                        r.live.clear();
                    }
                }
                self.emit(CodeEvent::Status { root: root.clone(), status: RootStatus { root, state } });
                if ready {
                    self.refresh_analysis(dir).await;
                }
            }
            Inbound::Reanalyzed => self.refresh_analysis(dir).await,
        }
    }

    /// Read a root's published diagnostics and tell the page.
    async fn refresh_analysis(self: &Arc<Self>, dir: &Path) {
        let Ok(omni) = self.omni() else { return };
        let worktree = self.worktree.clone();
        let root_dir = dir.to_owned();
        let read = tokio::task::spawn_blocking(move || analysis_diagnostics(&omni, &worktree, &root_dir)).await;
        let files = match read {
            Ok(Ok(files)) => files,
            Ok(Err(e)) => {
                self.emit(CodeEvent::Message {
                    level: "warning".into(),
                    text: format!("the analysis diagnostics of {} cannot be read: {e}", self.label(dir)),
                });
                return;
            }
            Err(e) => {
                tracing::warn!("reading analysis diagnostics panicked: {e}");
                return;
            }
        };
        {
            let mut inner = self.inner.lock().await;
            if let Some(r) = inner.roots.get_mut(dir) {
                r.analysis = files.clone();
            }
        }
        self.emit(CodeEvent::AnalysisDiagnostics { root: self.label(dir), files });
    }

    /// Shut down the servers of roots nothing is open of for [`IDLE`].
    async fn stop_idle(&self) {
        let idle: Vec<Arc<Session>> = {
            let mut inner = self.inner.lock().await;
            inner
                .roots
                .values_mut()
                .filter(|r| r.registry.is_empty() && r.idle_since.is_some_and(|t| t.elapsed() >= IDLE))
                .filter_map(|r| {
                    r.idle_since = None;
                    r.session.take()
                })
                .collect()
        };
        for s in idle {
            s.shutdown().await;
        }
    }
}

fn root_state(r: &Root) -> State {
    match (&r.session, &r.ended) {
        (Some(s), _) => s.state(),
        (None, Some(ended)) => ended.clone(),
        (None, None) => State::Stopped,
    }
}

/// The request a feature is asked as.
pub fn method_of(feature: &str) -> Option<&'static str> {
    Some(match feature {
        "hover" => "textDocument/hover",
        "definition" => "textDocument/definition",
        "references" => "textDocument/references",
        "document_symbols" => "textDocument/documentSymbol",
        "semantic_tokens" => "textDocument/semanticTokens/full",
        "completion" => "textDocument/completion",
        "signature_help" => "textDocument/signatureHelp",
        "inlay_hints" => "textDocument/inlayHint",
        _ => return None,
    })
}

/// Every `uri` and `targetUri` in a protocol value, replaced with what `name` makes of it.
fn rewrite_uris(value: &mut Value, name: &mut dyn FnMut(&str) -> Value) {
    match value {
        Value::Object(map) => {
            for (key, v) in map.iter_mut() {
                match (key.as_str(), &*v) {
                    ("uri" | "targetUri", Value::String(uri)) => {
                        let uri = uri.clone();
                        *v = name(&uri);
                    }
                    _ => rewrite_uris(v, name),
                }
            }
        }
        Value::Array(items) => {
            for v in items {
                rewrite_uris(v, name);
            }
        }
        _ => {}
    }
}

/// A root's published diagnostics, as protocol diagnostics by worktree path. A diagnostic
/// about content no longer on disk is left out: its position would point into other text.
fn analysis_diagnostics(
    omni: &Omni,
    worktree: &Path,
    dir: &Path,
) -> Result<BTreeMap<String, Vec<Value>>, String> {
    let out = wsb::git_backend::command_without_repo_scope(&omni.path)
        .args(["--json", "diagnostics", "-C"])
        .arg(dir)
        .output()
        .map_err(|e| format!("cannot run {}: {e}", omni.path.display()))?;
    let v: Value = serde_json::from_slice(&out.stdout).map_err(|e| format!("not JSON: {e}"))?;
    if !out.status.success() {
        return Err(v["message"].as_str().unwrap_or("omni diagnostics failed").to_owned());
    }
    let items = v.as_array().ok_or("omni diagnostics answered with no list")?;
    let mut files: BTreeMap<String, Vec<Value>> = BTreeMap::new();
    let mut texts: BTreeMap<String, Option<String>> = BTreeMap::new();
    for d in items {
        let primary = &d["primary"];
        let Some(rel) = primary["path"].as_str() else { continue };
        let abs = dir.join(rel);
        let text = texts.entry(rel.to_owned()).or_insert_with(|| {
            let bytes = std::fs::read(&abs).ok()?;
            let hex = format!("{:x}", <sha2::Sha256 as sha2::Digest>::digest(&bytes));
            let wanted = primary["content_hash"].as_str().unwrap_or("").trim_start_matches("sha256:");
            (hex == wanted).then(|| String::from_utf8(bytes).ok()).flatten()
        });
        let Some(text) = text.as_deref() else { continue };
        let (Some(a), Some(b)) = (primary["range_utf8"][0].as_u64(), primary["range_utf8"][1].as_u64()) else { continue };
        let (Ok(start), Ok(end)) = (text::position(text, a as usize), text::position(text, b as usize)) else { continue };
        let Ok(path) = abs.strip_prefix(worktree).map(|p| p.to_string_lossy().replace('\\', "/")) else { continue };
        files.entry(path).or_default().push(json!({
            "range": { "start": start, "end": end },
            "severity": match d["severity"].as_str() { Some("error") => 1, Some("warning") => 2, Some("info") => 3, _ => 4 },
            "code": d["code"],
            "source": format!("omnicode/{}", d["source"].as_str().unwrap_or("")),
            "message": d["message"],
        }));
    }
    Ok(files)
}

#[cfg(test)]
#[path = "mod_tests.rs"]
mod tests;