LSP §9b: work-done progress on workspace rescans
Every index rescan — the startup build included — now puts up a real progress bar for clients that advertise window.workDoneProgress: window/workDoneProgress/create with a fresh lucisv-index-N token, a Begin titled 'Indexing Verilog workspace' (cancellable: false — nothing in a single-threaded server can cancel; no percentage — the rescan is one opaque call and an invented number would be a lie), the scan, then End naming the indexed file count. The Option<ProgressToken> returned by begin_indexing IS the capability gate, so an unpaired or uninvited bar is structurally impossible; create answers ride the existing ignored-response path with no risk to applyEdit routing (one shared id counter). The startup build got the bar because initialize_finish completes before Server::new — the same fact watcher registration already relied on. 14 tests added (dev 10 + QA 4: watcher-after-bar ordering, both response-interleaving directions, capability-off on the watcher/config paths, rootless zero-count startup), all decoding real wire JSON for the sequence, token type, title, and message. docs/features/work-done-progress/README.md Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
00c03eccf9
commit
e165c37a3a
6 files changed
+1002
-26
No files matched your search
@@ -734,9 +734,22 @@ and are not gaps.
|
||||
`didClose`; an id the server does not hold is answered in full. No
|
||||
token request bumps the diagnostics generation. Not done:
|
||||
`workspace/semanticTokens/refresh`.
|
||||
- [ ] **Work-done progress** — `reindex()` is a synchronous full
|
||||
- [x] **Work-done progress** — `reindex()` is a synchronous full
|
||||
rescan on every save with no `window/workDoneProgress` reporting;
|
||||
on a big filelist the server just goes quiet.
|
||||
→ `docs/features/work-done-progress/README.md`; every workspace
|
||||
rescan — the startup build, a save, a watched file, a changed
|
||||
`lucisv.exclude`/`filelist` — is wrapped in one
|
||||
`window/workDoneProgress/create` plus a `$/progress` begin/end pair
|
||||
on a fresh `lucisv-index-N` token, gated on the client's
|
||||
`window.workDoneProgress` (a client that did not ask is sent nothing
|
||||
at all, as the spec requires). `begin` goes out without waiting for
|
||||
the create's answer, because the rescan blocks the loop the moment
|
||||
it returns; the create's answer is ignored on the same path the
|
||||
watcher registrations' is. No percentage and no intermediate report
|
||||
— the rescan is one opaque call — and the `end` names the indexed
|
||||
file count, read off the index's own file list. The bar covers the
|
||||
scan, ending before the scope warnings and the republishes.
|
||||
- [ ] **`$/cancelRequest`** — the loop handles requests sequentially
|
||||
and ignores cancellation; at minimum answer already-cancelled queued
|
||||
requests with `RequestCancelled`.
|
||||
|
||||
@@ -69,6 +69,7 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
file_watching: watch::dynamic_registration(¶ms),
|
||||
apply_edit: apply_edit_support(¶ms),
|
||||
pull_diagnostics: pull_diagnostics_support(¶ms),
|
||||
work_done_progress: work_done_progress_support(¶ms),
|
||||
};
|
||||
connection.initialize_finish(id, serde_json::to_value(initialize_result())?)?;
|
||||
|
||||
@@ -293,6 +294,21 @@ fn pull_diagnostics_support(params: &InitializeParams) -> bool {
|
||||
.is_some_and(|text_document| text_document.diagnostic.is_some())
|
||||
}
|
||||
|
||||
/// Whether the client renders server-initiated work-done progress.
|
||||
///
|
||||
/// The spec forbids a server from creating progress at all without this, so a
|
||||
/// client that said nothing is sent no `window/workDoneProgress/create` and no
|
||||
/// `$/progress` — the workspace rescan is silent for it, exactly as it was
|
||||
/// before this was read.
|
||||
fn work_done_progress_support(params: &InitializeParams) -> bool {
|
||||
params
|
||||
.capabilities
|
||||
.window
|
||||
.as_ref()
|
||||
.and_then(|window| window.work_done_progress)
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// The directories to index: the client's workspace folders, or the
|
||||
/// deprecated single root when that is all it sent.
|
||||
fn workspace_roots(params: &InitializeParams) -> Vec<PathBuf> {
|
||||
@@ -390,6 +406,23 @@ mod tests {
|
||||
assert!(!apply_edit_support(&saying(None)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn work_done_progress_support_is_read_from_the_clients_own_capabilities() {
|
||||
use lsp_types::{ClientCapabilities, WindowClientCapabilities};
|
||||
assert!(!work_done_progress_support(&InitializeParams::default()), "silence means no");
|
||||
|
||||
let saying = |work_done_progress: Option<bool>| InitializeParams {
|
||||
capabilities: ClientCapabilities {
|
||||
window: Some(WindowClientCapabilities { work_done_progress, ..Default::default() }),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
assert!(work_done_progress_support(&saying(Some(true))));
|
||||
assert!(!work_done_progress_support(&saying(Some(false))));
|
||||
assert!(!work_done_progress_support(&saying(None)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_that_sent_the_diagnostic_capability_at_all_is_a_pulling_client() {
|
||||
use lsp_types::{
|
||||
|
||||
@@ -11,8 +11,8 @@ use std::error::Error;
|
||||
use lsp_server::{Connection, ExtractError, Message, Notification, Request, RequestId, Response};
|
||||
use lsp_types::notification::{
|
||||
DidChangeConfiguration, DidChangeTextDocument, DidChangeWatchedFiles, DidCloseTextDocument,
|
||||
DidOpenTextDocument, DidSaveTextDocument, LogMessage, Notification as _, PublishDiagnostics,
|
||||
ShowMessage,
|
||||
DidOpenTextDocument, DidSaveTextDocument, LogMessage, Notification as _, Progress,
|
||||
PublishDiagnostics, ShowMessage,
|
||||
};
|
||||
use lsp_types::request::{
|
||||
ApplyWorkspaceEdit, CallHierarchyIncomingCalls, CallHierarchyOutgoingCalls,
|
||||
@@ -22,7 +22,8 @@ use lsp_types::request::{
|
||||
InlineCompletionRequest, PrepareRenameRequest, RangeFormatting, References, RegisterCapability,
|
||||
Rename, Request as _, SelectionRangeRequest, SemanticTokensFullDeltaRequest,
|
||||
SemanticTokensFullRequest, SemanticTokensRangeRequest, SignatureHelpRequest,
|
||||
UnregisterCapability, WillSaveWaitUntil, WorkspaceDiagnosticRequest, WorkspaceSymbolRequest,
|
||||
UnregisterCapability, WillSaveWaitUntil, WorkDoneProgressCreate, WorkspaceDiagnosticRequest,
|
||||
WorkspaceSymbolRequest,
|
||||
};
|
||||
use lsp_types::{
|
||||
ApplyWorkspaceEditParams, ApplyWorkspaceEditResponse, CallHierarchyIncomingCallsParams,
|
||||
@@ -35,16 +36,17 @@ use lsp_types::{
|
||||
DocumentSymbolResponse, ExecuteCommandParams, FoldingRangeParams, FullDocumentDiagnosticReport,
|
||||
GotoDefinitionParams, GotoDefinitionResponse, HoverParams, InlayHintParams,
|
||||
InlineCompletionParams, LogMessageParams, MessageType, Position, PreviousResultId,
|
||||
PublishDiagnosticsParams, ReferenceParams, RegistrationParams,
|
||||
RelatedFullDocumentDiagnosticReport, RelatedUnchangedDocumentDiagnosticReport, RenameParams,
|
||||
SelectionRangeParams, SemanticToken, SemanticTokens, SemanticTokensDelta,
|
||||
SemanticTokensDeltaParams, SemanticTokensFullDeltaResult, SemanticTokensParams,
|
||||
SemanticTokensRangeParams, SemanticTokensRangeResult, SemanticTokensResult, ShowMessageParams,
|
||||
SignatureHelpParams, TextDocumentPositionParams, UnchangedDocumentDiagnosticReport,
|
||||
UnregistrationParams, Uri, WillSaveTextDocumentParams, WorkspaceDiagnosticParams,
|
||||
WorkspaceDiagnosticReport, WorkspaceDiagnosticReportResult, WorkspaceDocumentDiagnosticReport,
|
||||
WorkspaceEdit, WorkspaceFullDocumentDiagnosticReport, WorkspaceSymbolParams,
|
||||
WorkspaceSymbolResponse, WorkspaceUnchangedDocumentDiagnosticReport,
|
||||
ProgressParams, ProgressParamsValue, ProgressToken, PublishDiagnosticsParams, ReferenceParams,
|
||||
RegistrationParams, RelatedFullDocumentDiagnosticReport,
|
||||
RelatedUnchangedDocumentDiagnosticReport, RenameParams, SelectionRangeParams, SemanticToken,
|
||||
SemanticTokens, SemanticTokensDelta, SemanticTokensDeltaParams, SemanticTokensFullDeltaResult,
|
||||
SemanticTokensParams, SemanticTokensRangeParams, SemanticTokensRangeResult,
|
||||
SemanticTokensResult, ShowMessageParams, SignatureHelpParams, TextDocumentPositionParams,
|
||||
UnchangedDocumentDiagnosticReport, UnregistrationParams, Uri, WillSaveTextDocumentParams,
|
||||
WorkDoneProgress, WorkDoneProgressBegin, WorkDoneProgressCreateParams, WorkDoneProgressEnd,
|
||||
WorkspaceDiagnosticParams, WorkspaceDiagnosticReport, WorkspaceDiagnosticReportResult,
|
||||
WorkspaceDocumentDiagnosticReport, WorkspaceEdit, WorkspaceFullDocumentDiagnosticReport,
|
||||
WorkspaceSymbolParams, WorkspaceSymbolResponse, WorkspaceUnchangedDocumentDiagnosticReport,
|
||||
};
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde_json::Value;
|
||||
@@ -73,6 +75,10 @@ pub struct ClientAbilities {
|
||||
/// Whether the client *pulls* diagnostics (LSP 3.17). One client is never
|
||||
/// served both models: a pulling client is pushed nothing at all.
|
||||
pub pull_diagnostics: bool,
|
||||
/// Whether the client renders server-initiated work-done progress. The
|
||||
/// spec forbids creating any without it, so a client that said nothing
|
||||
/// sees the workspace rescan exactly as it did before — silently.
|
||||
pub work_done_progress: bool,
|
||||
}
|
||||
|
||||
/// Everything the server owns.
|
||||
@@ -112,8 +118,17 @@ pub struct Server {
|
||||
/// client's `previousResultId` has to name the exact data it holds, and
|
||||
/// two buffers' answers are never comparable.
|
||||
token_results: u64,
|
||||
/// Numbers the progress tokens the index rescans run under. One rescan is
|
||||
/// one token, and a token is never reused: a client keys the bar it is
|
||||
/// showing off it.
|
||||
indexings: u32,
|
||||
}
|
||||
|
||||
/// What the workspace-rescan progress bar calls itself. One title for every
|
||||
/// rescan — startup, save, watched file, changed scope — because they are the
|
||||
/// same work and a user reading the status bar wants to know that.
|
||||
const INDEXING_TITLE: &str = "Indexing Verilog workspace";
|
||||
|
||||
/// One semantic-token answer, kept so the next delta request can be answered
|
||||
/// against it.
|
||||
struct TokenAnswer {
|
||||
@@ -127,11 +142,9 @@ impl Server {
|
||||
roots: Vec<std::path::PathBuf>,
|
||||
abilities: ClientAbilities,
|
||||
) -> Server {
|
||||
let mut workspace = Workspace::default();
|
||||
let warnings = workspace.open_roots(roots);
|
||||
let mut server = Server {
|
||||
connection,
|
||||
workspace,
|
||||
workspace: Workspace::default(),
|
||||
config_warnings: HashSet::new(),
|
||||
abilities,
|
||||
watchers: None,
|
||||
@@ -141,12 +154,18 @@ impl Server {
|
||||
generation: 0,
|
||||
tokens: HashMap::new(),
|
||||
token_results: 0,
|
||||
indexings: 0,
|
||||
};
|
||||
// The earliest legal moment for anything server-initiated: `main`
|
||||
// builds this only after `initialize_finish`, which returns once the
|
||||
// client's `initialized` notification has arrived — and consumes it,
|
||||
// so the loop below never sees one to hang these off instead. The
|
||||
// first index build is the slowest one of the session, so it gets the
|
||||
// same bar every later rescan gets.
|
||||
let bar = server.begin_indexing();
|
||||
let warnings = server.workspace.open_roots(roots);
|
||||
server.end_indexing(bar);
|
||||
server.report_scope(warnings);
|
||||
// The earliest legal moment: `main` builds this only after
|
||||
// `initialize_finish`, which returns once the client's `initialized`
|
||||
// notification has arrived — and consumes it, so the loop below never
|
||||
// sees one to hang the registration off instead.
|
||||
server.register_watchers();
|
||||
server
|
||||
}
|
||||
@@ -797,11 +816,12 @@ impl Server {
|
||||
|
||||
/// What the client answered.
|
||||
///
|
||||
/// Only a `workspace/applyEdit` answer is read. The (un)registration of
|
||||
/// the file watchers is the other thing ever asked, and there is nothing
|
||||
/// to do with *its* answer: a client that refuses simply keeps the
|
||||
/// save-only staleness model, and it says so on its own log, not ours. Its
|
||||
/// ids are never in `applying`, so they fall out here.
|
||||
/// Only a `workspace/applyEdit` answer is read. The other two things ever
|
||||
/// asked of the client have nothing to do with theirs: a client that
|
||||
/// refuses the file-watcher (un)registration simply keeps the save-only
|
||||
/// staleness model, and one that errors a `window/workDoneProgress/create`
|
||||
/// renders no bar and ignores the `$/progress` that named that token, per
|
||||
/// spec. Neither id is ever in `applying`, so both fall out here.
|
||||
fn response(&mut self, response: Response) {
|
||||
let Some(command) = self.applying.remove(&response.id) else { return };
|
||||
// A refusal is worth saying out loud: the user ran a command, watched
|
||||
@@ -867,7 +887,9 @@ impl Server {
|
||||
/// index. Every caller changed what the index should contain — a save, a
|
||||
/// new `lucisv.exclude`/`lucisv.filelist`, or a watched file changing on disk.
|
||||
fn reindex(&mut self) {
|
||||
let bar = self.begin_indexing();
|
||||
let warnings = self.workspace.rebuild_index();
|
||||
self.end_indexing(bar);
|
||||
// Every open buffer's diagnostics are computed against the index, so a
|
||||
// pulling client's cached answers are all stale from here.
|
||||
self.generation += 1;
|
||||
@@ -877,6 +899,59 @@ impl Server {
|
||||
}
|
||||
}
|
||||
|
||||
/// Put a progress bar up for the rescan that is about to run, and report
|
||||
/// the token it must be taken down with. `None` for a client that cannot
|
||||
/// show one — the spec forbids creating progress it never asked for.
|
||||
///
|
||||
/// The `begin` goes out immediately after the `create`, without waiting
|
||||
/// for its answer: the rescan blocks this thread the moment this returns,
|
||||
/// so waiting would mean the bar appears only once the work it describes
|
||||
/// is over. The spec allows it, and a client that errors the `create`
|
||||
/// ignores the `$/progress` that follows.
|
||||
///
|
||||
/// No percentage and no intermediate report: the rescan is one opaque call
|
||||
/// into `Workspace`, and an invented percentage is worse than none.
|
||||
fn begin_indexing(&mut self) -> Option<ProgressToken> {
|
||||
if !self.abilities.work_done_progress {
|
||||
return None;
|
||||
}
|
||||
let token = ProgressToken::String(format!("lucisv-index-{}", self.indexings));
|
||||
self.indexings += 1;
|
||||
let params = WorkDoneProgressCreateParams { token: token.clone() };
|
||||
self.send_request(WorkDoneProgressCreate::METHOD, params);
|
||||
self.progress(
|
||||
token.clone(),
|
||||
WorkDoneProgress::Begin(WorkDoneProgressBegin {
|
||||
title: INDEXING_TITLE.to_string(),
|
||||
// There is no cancellation anywhere in this server: the loop is
|
||||
// one thread and a rescan runs to completion. Saying so is
|
||||
// what keeps a cancel button the user could press off the bar.
|
||||
cancellable: Some(false),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
Some(token)
|
||||
}
|
||||
|
||||
/// Take the bar down, naming what the rescan found. The count is the
|
||||
/// index's own file list, which is the only number this costs nothing to
|
||||
/// know. Called the moment the rescan returns, before the scope warnings
|
||||
/// and the republishes — the bar names the scan, and what follows it is
|
||||
/// per-open-buffer work the user already pays on every keystroke.
|
||||
fn end_indexing(&self, token: Option<ProgressToken>) {
|
||||
let Some(token) = token else { return };
|
||||
let files = self.workspace.index().files().len();
|
||||
let plural = if files == 1 { "" } else { "s" };
|
||||
let message = Some(format!("{files} file{plural} indexed"));
|
||||
self.progress(token, WorkDoneProgress::End(WorkDoneProgressEnd { message }));
|
||||
}
|
||||
|
||||
/// One `$/progress` notification for a token the client already knows.
|
||||
fn progress(&self, token: ProgressToken, value: WorkDoneProgress) {
|
||||
let params = ProgressParams { token, value: ProgressParamsValue::WorkDone(value) };
|
||||
self.notify(Progress::METHOD, params);
|
||||
}
|
||||
|
||||
/// Say what went wrong while working out which files to index — a
|
||||
/// filelist naming a file that has moved, an unset variable, an option
|
||||
/// lucisv does not know.
|
||||
@@ -1118,6 +1193,32 @@ mod tests {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Every progress message since the last drain, in order, as
|
||||
/// (step, token) — one `create` per request, one `begin`/`report`/`end`
|
||||
/// per `$/progress`. Order and token are the whole protocol here.
|
||||
fn progress(&self) -> Vec<(&'static str, String)> {
|
||||
self.drain().into_iter().filter_map(progress_step).collect()
|
||||
}
|
||||
|
||||
/// The `message` on every `$/progress` end since the last drain.
|
||||
fn ended(&self) -> Vec<Option<String>> {
|
||||
self.drain()
|
||||
.into_iter()
|
||||
.filter_map(|message| match message {
|
||||
Message::Notification(n) if n.method == Progress::METHOD => {
|
||||
let params: ProgressParams =
|
||||
serde_json::from_value(n.params).expect("progress params");
|
||||
let ProgressParamsValue::WorkDone(work) = params.value;
|
||||
match work {
|
||||
WorkDoneProgress::End(end) => Some(end.message),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What the server showed the user since the last drain, as
|
||||
/// (type, message).
|
||||
fn shown(&self) -> Vec<(MessageType, String)> {
|
||||
@@ -1186,6 +1287,319 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// One message's place in the progress protocol, or `None` when it is not
|
||||
/// progress at all.
|
||||
fn progress_step(message: Message) -> Option<(&'static str, String)> {
|
||||
match message {
|
||||
Message::Request(request) if request.method == WorkDoneProgressCreate::METHOD => {
|
||||
let params: WorkDoneProgressCreateParams =
|
||||
serde_json::from_value(request.params).expect("create params");
|
||||
Some(("create", token_text(¶ms.token)))
|
||||
}
|
||||
Message::Notification(n) if n.method == Progress::METHOD => {
|
||||
let params: ProgressParams =
|
||||
serde_json::from_value(n.params).expect("progress params");
|
||||
let ProgressParamsValue::WorkDone(work) = params.value;
|
||||
let step = match work {
|
||||
WorkDoneProgress::Begin(_) => "begin",
|
||||
WorkDoneProgress::Report(_) => "report",
|
||||
WorkDoneProgress::End(_) => "end",
|
||||
};
|
||||
Some((step, token_text(¶ms.token)))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn token_text(token: &ProgressToken) -> String {
|
||||
match token {
|
||||
ProgressToken::String(text) => text.clone(),
|
||||
ProgressToken::Number(number) => number.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A client that shows a progress bar and nothing else.
|
||||
fn watching_progress() -> ClientAbilities {
|
||||
ClientAbilities { work_done_progress: true, ..Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_startup_index_build_runs_under_the_first_bar() {
|
||||
// It is the slowest rescan of the session, and it happens after
|
||||
// `initialize_finish` — the earliest moment a server request is legal.
|
||||
let tree = Tree::new("progressstartup");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
let session = Session::with(vec![tree.path.clone()], watching_progress());
|
||||
assert_eq!(
|
||||
session.progress(),
|
||||
vec![
|
||||
("create", "lucisv-index-0".to_string()),
|
||||
("begin", "lucisv-index-0".to_string()),
|
||||
("end", "lucisv-index-0".to_string()),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_save_puts_a_bar_up_and_takes_it_down_again() {
|
||||
let tree = Tree::new("progresssave");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
let mut session = Session::with(vec![tree.path.clone()], watching_progress());
|
||||
let uri = session.open(&tree.path.join("rtl/a.sv"), "package a;\nendpackage\n");
|
||||
let _ = session.drain();
|
||||
|
||||
session.notify(
|
||||
DidSaveTextDocument::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri } }),
|
||||
);
|
||||
// One create, one begin, one end — the save's own token, not the
|
||||
// startup one.
|
||||
assert_eq!(
|
||||
session.progress(),
|
||||
vec![
|
||||
("create", "lucisv-index-1".to_string()),
|
||||
("begin", "lucisv-index-1".to_string()),
|
||||
("end", "lucisv-index-1".to_string()),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bar_says_how_many_files_were_indexed() {
|
||||
// The one number this costs nothing to know: the index's own file
|
||||
// list. Anything richer would mean plumbing a count through
|
||||
// `rebuild_index`.
|
||||
let tree = Tree::new("progresscount");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("rtl/b.sv", "b");
|
||||
let session = Session::with(vec![tree.path.clone()], watching_progress());
|
||||
assert_eq!(session.ended(), vec![Some("2 files indexed".to_string())]);
|
||||
|
||||
let one = Tree::new("progresscountone");
|
||||
one.package("rtl/a.sv", "a");
|
||||
let session = Session::with(vec![one.path.clone()], watching_progress());
|
||||
assert_eq!(session.ended(), vec![Some("1 file indexed".to_string())], "not `1 files`");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bar_is_down_before_the_republish() {
|
||||
// Pinned because either order is defensible and a reader would
|
||||
// wonder: the bar names the *scan*, so it ends the moment the scan
|
||||
// returns — the republish that follows is per-open-buffer work the
|
||||
// user already pays on every keystroke.
|
||||
let tree = Tree::new("progressorder");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
let mut session = Session::with(vec![tree.path.clone()], watching_progress());
|
||||
let uri = session.open(&tree.path.join("rtl/a.sv"), "package a;\nendpackage\n");
|
||||
let _ = session.drain();
|
||||
|
||||
session.notify(
|
||||
DidSaveTextDocument::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri } }),
|
||||
);
|
||||
let order: Vec<String> = session
|
||||
.drain()
|
||||
.into_iter()
|
||||
.filter_map(|message| match &message {
|
||||
Message::Notification(n) if n.method == PublishDiagnostics::METHOD => {
|
||||
Some("publish".to_string())
|
||||
}
|
||||
_ => progress_step(message).map(|(step, _)| step.to_string()),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(order, vec!["create", "begin", "end", "publish"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_that_did_not_ask_for_a_bar_is_sent_no_progress_at_all() {
|
||||
// The spec forbids server-initiated progress without the capability,
|
||||
// so this is not a cosmetic difference: it is a protocol violation
|
||||
// avoided.
|
||||
let tree = Tree::new("progressnone");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
let mut session = Session::new(vec![tree.path.clone()], true);
|
||||
let uri = session.open(&tree.path.join("rtl/a.sv"), "package a;\nendpackage\n");
|
||||
assert!(session.progress().is_empty(), "not even at startup");
|
||||
|
||||
session.notify(
|
||||
DidSaveTextDocument::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri } }),
|
||||
);
|
||||
assert!(session.progress().is_empty(), "and not on a save either");
|
||||
// The watcher registration is the only thing such a client is asked.
|
||||
let session = Session::new(vec![tree.path.clone()], false);
|
||||
assert!(session.requests().is_empty(), "nothing at all is asked of it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_rescan_path_gets_its_own_bar_and_its_own_token() {
|
||||
// The three non-startup callers of `reindex`: a save, a watched file,
|
||||
// and a changed scope. One begin/end pair each, and no token twice.
|
||||
let tree = Tree::new("progresspaths");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.write("files.f", "rtl/a.sv\n");
|
||||
let mut session = Session::with(vec![tree.path.clone()], watching_progress());
|
||||
let uri = session.open(&tree.path.join("rtl/a.sv"), "package a;\nendpackage\n");
|
||||
let _ = session.drain();
|
||||
|
||||
session.notify(
|
||||
DidSaveTextDocument::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri } }),
|
||||
);
|
||||
session.watched(&[tree.path.join("rtl/a.sv")]);
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": { "filelist": "files.f" } } }),
|
||||
);
|
||||
|
||||
let steps = session.progress();
|
||||
let begins: Vec<&String> =
|
||||
steps.iter().filter(|(step, _)| *step == "begin").map(|(_, token)| token).collect();
|
||||
let ends: Vec<&String> =
|
||||
steps.iter().filter(|(step, _)| *step == "end").map(|(_, token)| token).collect();
|
||||
assert_eq!(
|
||||
begins,
|
||||
vec!["lucisv-index-1", "lucisv-index-2", "lucisv-index-3"],
|
||||
"{steps:#?}"
|
||||
);
|
||||
assert_eq!(ends, begins, "every bar that went up came down");
|
||||
assert!(steps.iter().all(|(step, _)| *step != "report"), "no invented percentages");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_progress_create_answer_is_ignored_and_never_disturbs_an_apply_edit() {
|
||||
// Both request kinds are in flight at once. The progress answers —
|
||||
// one `Ok`, one `Err` — must fall straight through `response`, and the
|
||||
// one `applyEdit` answer must still be the one that speaks.
|
||||
let abilities =
|
||||
ClientAbilities { apply_edit: true, work_done_progress: true, ..Default::default() };
|
||||
let (tree, mut session, params) = propagating("progressapplyedit", abilities);
|
||||
let _ = session.drain();
|
||||
|
||||
let result = session.result(ExecuteCommand::METHOD, params);
|
||||
assert!(result.is_null(), "the edit was pushed, not returned");
|
||||
|
||||
// Force a rescan while the edit is outstanding, so a progress create
|
||||
// sits between the push and its answer.
|
||||
session.watched(&[tree.path.join("sub.sv")]);
|
||||
let sent = session.sent();
|
||||
let edit = sent
|
||||
.iter()
|
||||
.find(|request| request.method == ApplyWorkspaceEdit::METHOD)
|
||||
.expect("the push");
|
||||
let creates: Vec<&Request> =
|
||||
sent.iter().filter(|r| r.method == WorkDoneProgressCreate::METHOD).collect();
|
||||
assert_eq!(creates.len(), 1, "one rescan, one create: {sent:#?}");
|
||||
|
||||
// Answer the create both ways a client can, then refuse the edit.
|
||||
session.answer(creates[0].id.clone(), serde_json::json!(null));
|
||||
session.server.response(Response::new_err(
|
||||
creates[0].id.clone(),
|
||||
lsp_server::ErrorCode::MethodNotFound as i32,
|
||||
"no progress here".to_string(),
|
||||
));
|
||||
assert!(session.shown().is_empty(), "a create answer says nothing to the user");
|
||||
|
||||
session.answer(edit.id.clone(), serde_json::json!({ "applied": false }));
|
||||
let shown = session.shown();
|
||||
assert_eq!(shown.len(), 1, "{shown:#?}");
|
||||
assert_eq!(shown[0].0, MessageType::ERROR);
|
||||
assert!(shown[0].1.contains("lucisv.propagatePorts"), "{shown:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_late_create_answer_after_the_apply_edit_already_answered_is_ignored_too() {
|
||||
// The reverse interleaving from the test above: here the outstanding
|
||||
// `applyEdit` is answered first, and the progress `create` for a
|
||||
// rescan that started while it was outstanding answers only after.
|
||||
// Same fall-through path in `response`, opposite arrival order — both
|
||||
// must leave the refusal-reporting untouched.
|
||||
let abilities =
|
||||
ClientAbilities { apply_edit: true, work_done_progress: true, ..Default::default() };
|
||||
let (tree, mut session, params) = propagating("progressapplyedit2", abilities);
|
||||
let _ = session.drain();
|
||||
|
||||
let result = session.result(ExecuteCommand::METHOD, params);
|
||||
assert!(result.is_null(), "the edit was pushed, not returned");
|
||||
|
||||
session.watched(&[tree.path.join("sub.sv")]);
|
||||
let sent = session.sent();
|
||||
let edit = sent
|
||||
.iter()
|
||||
.find(|request| request.method == ApplyWorkspaceEdit::METHOD)
|
||||
.expect("the push");
|
||||
let create = sent
|
||||
.iter()
|
||||
.find(|request| request.method == WorkDoneProgressCreate::METHOD)
|
||||
.expect("the create");
|
||||
|
||||
// The edit resolves first, cleanly...
|
||||
session.answer(edit.id.clone(), serde_json::json!({ "applied": true }));
|
||||
assert!(session.shown().is_empty(), "an accepted edit says nothing to the user");
|
||||
|
||||
// ...and only afterward does the create answer arrive, for a bar that
|
||||
// came down long ago. It must still fall straight through.
|
||||
session.server.response(Response::new_ok(create.id.clone(), serde_json::json!(null)));
|
||||
assert!(session.shown().is_empty(), "a late create answer says nothing either");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_startup_watcher_registration_arrives_after_the_indexing_bar_comes_down() {
|
||||
// `Server::new` now asks a fully-capable client two things at
|
||||
// startup: the progress create/begin/end around `open_roots`, then
|
||||
// `register_watchers`. This pins the order the restructuring must
|
||||
// preserve — the watcher request must not land in the middle of the
|
||||
// bar it was rewritten to make room for.
|
||||
let tree = Tree::new("progressandwatchers");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
let abilities =
|
||||
ClientAbilities { file_watching: true, work_done_progress: true, ..Default::default() };
|
||||
let session = Session::with(vec![tree.path.clone()], abilities);
|
||||
|
||||
let order: Vec<String> = session
|
||||
.drain()
|
||||
.into_iter()
|
||||
.filter_map(|message| match &message {
|
||||
Message::Request(request) if request.method == RegisterCapability::METHOD => {
|
||||
Some("register".to_string())
|
||||
}
|
||||
_ => progress_step(message).map(|(step, _)| step.to_string()),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(order, vec!["create", "begin", "end", "register"], "{order:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_without_the_bar_gets_none_on_the_watcher_or_config_paths_either() {
|
||||
// The existing off-test drives only startup and a save. `begin_indexing`
|
||||
// is called from the same `reindex()` on all three rescan triggers, but
|
||||
// the other two deserve their own witness rather than resting on that
|
||||
// being obvious from reading the code.
|
||||
let tree = Tree::new("progressnonewatch");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.write("files.f", "rtl/a.sv\n");
|
||||
let mut session = Session::new(vec![tree.path.clone()], true);
|
||||
let _ = session.drain();
|
||||
|
||||
session.watched(&[tree.path.join("rtl/a.sv")]);
|
||||
assert!(session.progress().is_empty(), "not on a watched file change");
|
||||
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": { "filelist": "files.f" } } }),
|
||||
);
|
||||
assert!(session.progress().is_empty(), "not on a changed filelist either");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rootless_workspace_with_no_open_files_says_zero_at_startup_without_crashing() {
|
||||
// No roots and no open buffers: `sibling_files` has nothing to walk,
|
||||
// so the index is empty. The end message must still be honest — and
|
||||
// the plural rule still holds, "0 files" and not "0 file".
|
||||
let session = Session::with(Vec::new(), watching_progress());
|
||||
assert_eq!(session.ended(), vec![Some("0 files indexed".to_string())]);
|
||||
}
|
||||
|
||||
/// How many times the index holds a package of this name.
|
||||
fn indexed(session: &Session, name: &str) -> usize {
|
||||
session.server.workspace.index().member(name, "K").len()
|
||||
|
||||
@@ -2948,3 +2948,123 @@ fn semantic_tokens_range_and_delta_round_trip_over_the_wire() {
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indexing_reports_its_progress_over_the_wire() {
|
||||
// What only an e2e test can check: the create request and the two
|
||||
// `$/progress` notifications are framed, ordered, and carry the same
|
||||
// token — for a client that advertised `window.workDoneProgress`.
|
||||
let dir = temp_dir("progress");
|
||||
let file = dir.join("m.sv");
|
||||
let source = "module m;\nendmodule\n";
|
||||
std::fs::write(&file, source).expect("write");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let uri = format!("file://{}", file.display());
|
||||
|
||||
let session = [
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"window":{{"workDoneProgress":true}}}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(source).expect("json")
|
||||
)),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didSave","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
|
||||
let messages = talk(&session);
|
||||
|
||||
// Every progress message on the wire, in order, as (step, token).
|
||||
let steps: Vec<(String, String)> = messages
|
||||
.iter()
|
||||
.filter_map(|m| match m["method"].as_str() {
|
||||
Some("window/workDoneProgress/create") => Some((
|
||||
"create".to_string(),
|
||||
m["params"]["token"].as_str().expect("a string token").to_string(),
|
||||
)),
|
||||
Some("$/progress") => Some((
|
||||
m["params"]["value"]["kind"].as_str().expect("a kind").to_string(),
|
||||
m["params"]["token"].as_str().expect("a string token").to_string(),
|
||||
)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Two rescans: the startup build, then the save. Each one create, one
|
||||
// begin, one end, on its own token.
|
||||
assert_eq!(
|
||||
steps,
|
||||
vec![
|
||||
("create".to_string(), "lucisv-index-0".to_string()),
|
||||
("begin".to_string(), "lucisv-index-0".to_string()),
|
||||
("end".to_string(), "lucisv-index-0".to_string()),
|
||||
("create".to_string(), "lucisv-index-1".to_string()),
|
||||
("begin".to_string(), "lucisv-index-1".to_string()),
|
||||
("end".to_string(), "lucisv-index-1".to_string()),
|
||||
],
|
||||
"{messages:#?}"
|
||||
);
|
||||
|
||||
// The begin says what it is doing, and offers no cancel button — nothing
|
||||
// in this server can be cancelled.
|
||||
let begin = messages.iter().find(|m| m["params"]["value"]["kind"] == "begin").expect("a begin");
|
||||
assert_eq!(begin["params"]["value"]["title"], "Indexing Verilog workspace", "{begin:#?}");
|
||||
assert_eq!(begin["params"]["value"]["cancellable"], false, "{begin:#?}");
|
||||
assert!(begin["params"]["value"].get("percentage").is_none(), "no fake numbers: {begin:#?}");
|
||||
|
||||
let end = messages.iter().find(|m| m["params"]["value"]["kind"] == "end").expect("an end");
|
||||
assert_eq!(end["params"]["value"]["message"], "1 file indexed", "{end:#?}");
|
||||
|
||||
// The create is a request the client may answer or error; leaving it
|
||||
// unanswered here is exactly what a client that does not care does, and
|
||||
// the session still shuts down cleanly (asserted inside `talk`).
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_that_never_asked_for_progress_is_sent_none_over_the_wire() {
|
||||
let dir = temp_dir("noprogress");
|
||||
let file = dir.join("m.sv");
|
||||
let source = "module m;\nendmodule\n";
|
||||
std::fs::write(&file, source).expect("write");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let uri = format!("file://{}", file.display());
|
||||
|
||||
let session = [
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(source).expect("json")
|
||||
)),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didSave","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
|
||||
let messages = talk(&session);
|
||||
assert!(
|
||||
messages.iter().all(|m| {
|
||||
m["method"] != "$/progress" && m["method"] != "window/workDoneProgress/create"
|
||||
}),
|
||||
"the spec forbids progress a client never asked for: {messages:#?}"
|
||||
);
|
||||
// And it still got its diagnostics, so the save path ran.
|
||||
assert!(
|
||||
messages.iter().any(|m| m["method"] == "textDocument/publishDiagnostics"),
|
||||
"{messages:#?}"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -43,6 +43,7 @@ looks like language knowledge in here is a bug or a `Handshake` request.
|
||||
| `callHierarchy/outgoingCalls` | `instantiations::sites`, `WorkspaceIndex::units` | "What X instantiates": one call per **distinct instantiated module**, `fromRanges` naming its sites. A target the index does not hold, or holds twice, is skipped silently. Same feature README |
|
||||
| `workspace/symbol` | `WorkspaceIndex::workspace_symbols` | Capped at 256 hits |
|
||||
| `workspace/didChangeWatchedFiles` | `Workspace::rebuild_index` | Registered dynamically after the handshake, for a client that advertised it. One rebuild per *notification*, however many files it names. See `docs/features/file-watching/README.md` |
|
||||
| `window/workDoneProgress/create` + `$/progress` | — | Server-**initiated**: one indeterminate bar per workspace rescan, titled "Indexing Verilog workspace", ending with the indexed file count. Only for a client that advertised `window.workDoneProgress`. See `docs/features/work-done-progress/README.md` |
|
||||
|
||||
Deferred, deliberately, and named in Status/TODO below: ~~range formatting
|
||||
(waits on TODO.md §2 `--lines`)~~ **delivered by range-formatting (round 18):
|
||||
@@ -224,6 +225,18 @@ point where the answer is expected to change anyway. Measured cost of a
|
||||
rebuild: 0.68 s for the 860-file corpus (the workspace index's own baseline),
|
||||
plus the file reads.
|
||||
|
||||
**Every rescan is visible since 2026-08-26**, for a client that advertised
|
||||
`window.workDoneProgress`: the startup build and all three `reindex()` triggers
|
||||
are wrapped in one `window/workDoneProgress/create` plus a `$/progress`
|
||||
begin/end pair on a fresh `lucisv-index-N` token, so a multi-second index on a
|
||||
big filelist reads as work rather than as a hang. The `begin` does not wait for
|
||||
the create's answer (the rescan blocks the loop immediately after), the answer
|
||||
is ignored on the same path the watcher registrations' is, there is no
|
||||
percentage and no intermediate report — the rescan is one opaque call — and the
|
||||
`end` names the indexed file count. A client that did not advertise the
|
||||
capability is sent nothing at all, which the spec requires. Rules and the
|
||||
startup-legality argument: `docs/features/work-done-progress/README.md`.
|
||||
|
||||
**Changes made outside the editor close on the next notification, not on the
|
||||
next save** (M9, `docs/features/file-watching/README.md`). The server registers
|
||||
`workspace/didChangeWatchedFiles` for `**/*.{v,vh,sv,svh}` and for the
|
||||
|
||||
@@ -0,0 +1,383 @@
|
||||
# work-done-progress
|
||||
|
||||
## Goal
|
||||
|
||||
A workspace rescan is the one thing this server does that a user can feel.
|
||||
`Server::reindex()` is a synchronous full re-walk of the roots — 0.68 s for the
|
||||
860-file corpus, seconds for a real filelist — and it runs on every save, on
|
||||
every watched-file notification, and whenever `lucisv.exclude`/`lucisv.filelist`
|
||||
changes. Until now it happened in total silence: the editor's status bar said
|
||||
nothing, the server simply stopped answering for a while, and a user with a
|
||||
large project had no way to tell a slow index from a hung server. This round
|
||||
wraps every rescan — the startup build included — in server-initiated work-done
|
||||
progress: one `window/workDoneProgress/create`, one `$/progress` begin, the
|
||||
scan, one `$/progress` end naming the file count. Gated on the client's own
|
||||
`window.workDoneProgress` capability, because the spec forbids creating
|
||||
progress a client never asked for (TODO.md §9b).
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **`window.workDoneProgress` is the gate, and there is no fallback.** A client
|
||||
that did not advertise it is sent no `create` and no `$/progress` — not a
|
||||
degraded bar, not a `showMessage`. The spec is explicit that a server may
|
||||
only initiate progress against a client that asked; and a popup per save
|
||||
would be worse than the silence it replaced.
|
||||
- **`begin` is sent without waiting for the `create`'s answer.** The spec
|
||||
permits it ("the server is allowed to report progress before the create
|
||||
request is answered"), and here it is not merely permitted but necessary:
|
||||
the rescan blocks the single-threaded loop the moment `begin_indexing`
|
||||
returns, so waiting for the answer would mean the loop never processes it
|
||||
and the bar appears only after the work it describes is over. A client that
|
||||
*errors* the create is required to ignore the `$/progress` notifications
|
||||
carrying that token, so the worst case is a client that renders nothing —
|
||||
which is exactly what it rendered before this feature existed.
|
||||
- **The create's answer is ignored.** It goes through `Server::response`'s
|
||||
existing "not in the `applying` map, fall through" path, the same one the
|
||||
file-watcher (un)registrations use. Nothing is retried and nothing is
|
||||
remembered: the ids are minted from the one shared `request_ids` counter, so
|
||||
a progress answer can never be mistaken for an `applyEdit` answer.
|
||||
- **No percentage, and no intermediate `report`.** `Workspace::rebuild_index`
|
||||
is one opaque call: it walks the roots, reads every file, builds the index,
|
||||
the completion tables and the include graph, and returns. There is no
|
||||
progress to observe without threading a callback through three engine
|
||||
layers, and an invented percentage — "it is probably about half done" — is a
|
||||
lie the user would learn to distrust. An indeterminate bar is the honest
|
||||
shape.
|
||||
- **The end message is the index's own file count**, read from
|
||||
`WorkspaceIndex::files().len()` after the scan. That number was already
|
||||
public and already computed; nothing was plumbed to obtain it. It counts the
|
||||
files the index was built from — in-scope files that read successfully, with
|
||||
open buffers overriding disk — which is what "indexed" means everywhere else
|
||||
in this server.
|
||||
- **The bar covers the scan, not the republish.** `end` is sent the instant
|
||||
`rebuild_index` returns, before `report_scope`'s warnings and before the
|
||||
per-buffer republishes that follow. Either order is defensible; this one is
|
||||
pinned by a test (`the_bar_is_down_before_the_republish`) because the bar
|
||||
names the *scan*, and the republish is per-open-buffer work the user already
|
||||
pays on every keystroke without a bar.
|
||||
- **The startup build gets a bar too, and that is legal.** `Server::new` runs
|
||||
after `main`'s `initialize_finish`, which returns only once the client's
|
||||
`initialized` notification has arrived — the same fact that makes the
|
||||
existing watcher registration legal there, and it is already stated in that
|
||||
code's comment. So the first index build, which is the slowest of the
|
||||
session, is wrapped like every other. Determined by reading `main.rs:59-79`
|
||||
and `server.rs`'s `Server::new`, not assumed.
|
||||
- **No cancellation.** `cancellable: Some(false)` is stated rather than left
|
||||
unset: the loop is one thread, a rescan runs to completion, and there is no
|
||||
`window/workDoneProgress/cancel` handler. A cancel button the user could
|
||||
press and that did nothing would be worse than no button.
|
||||
- **One bar at a time, in practice.** The loop is synchronous, so a rescan
|
||||
cannot overlap another rescan; every `begin` is followed by its own `end`
|
||||
before the next `begin` can be minted. The token counter guarantees
|
||||
uniqueness regardless.
|
||||
|
||||
## Handshakes
|
||||
|
||||
### `lucisv_server::server`
|
||||
|
||||
- `ClientAbilities` gains `work_done_progress: bool`, filled by `main.rs` from
|
||||
`InitializeParams.capabilities.window.work_done_progress` (absent → false),
|
||||
in the style of the three fields already there. Every existing test that
|
||||
builds `ClientAbilities { ..Default::default() }` is unaffected.
|
||||
- `Server` gains `indexings: u32` — the progress-token counter. It is
|
||||
deliberately *not* the request-id counter: a token is not a request id, and
|
||||
`lucisv-index-3` reads as the fourth rescan rather than as an unrelated
|
||||
ordinal.
|
||||
- Two new private methods, `begin_indexing() -> Option<ProgressToken>` and
|
||||
`end_indexing(Option<ProgressToken>)`, plus a one-line `progress()` sender.
|
||||
`None` is the whole of the "this client cannot show a bar" path, so neither
|
||||
caller branches on the ability itself.
|
||||
- `Server::new` is restructured: the `Server` is built around a
|
||||
`Workspace::default()` and `open_roots` is then called *through* it, so the
|
||||
startup build can sit between a `begin_indexing`/`end_indexing` pair. Same
|
||||
work, same order relative to `report_scope` and `register_watchers`.
|
||||
- `Server::response`'s doc comment now names three things asked of the client
|
||||
rather than two. Its code is unchanged — the create's answer already fell
|
||||
through the `applying` lookup.
|
||||
|
||||
### `state::Workspace`, and every engine crate
|
||||
|
||||
**Untouched.** The file count comes from `Workspace::index()` and
|
||||
`WorkspaceIndex::files()`, both of which were already public and already
|
||||
called from this crate. No signature moved, `rebuild_index` still returns just
|
||||
its scope warnings, and nothing was plumbed for the sake of the end message.
|
||||
|
||||
### `editors/vscode`
|
||||
|
||||
**No extension change.** `vscode-languageclient` advertises
|
||||
`window.workDoneProgress` itself and renders server-initiated progress in the
|
||||
status bar with no help from `extension.js`. `smoke.js` sends
|
||||
`capabilities: {}`, so it takes the no-progress path and passes untouched —
|
||||
verified by running it.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `window.workDoneProgress` read into `ClientAbilities` at initialize
|
||||
- [x] `begin_indexing`/`end_indexing` around `rebuild_index()` in `reindex()`
|
||||
- [x] The startup index build wrapped in the same pair (legal: `Server::new`
|
||||
runs after `initialize_finish`)
|
||||
- [x] A fresh `lucisv-index-N` token per rescan, never reused
|
||||
- [x] `end` carries the indexed file count, singular and plural
|
||||
- [x] A client without the capability is sent zero progress messages
|
||||
- [x] The create's answer stays ignored and cannot disturb `applyEdit` routing
|
||||
- [x] Tests: 8 unit (7 in `server.rs`, 1 in `main.rs`), 2 e2e over the wire
|
||||
- [x] TODO.md §9b checkbox, `docs/features/lucisv-server/README.md` staleness
|
||||
section
|
||||
- [ ] **Not done, deliberately:** no `$/progress` on anything else. Formatting,
|
||||
a rename across the workspace and `callHierarchy/incomingCalls` are the
|
||||
other candidates; all three are request-scoped, so they would use the
|
||||
*client-supplied* `workDoneToken` rather than a created one, which is a
|
||||
different mechanism with a different gate. Filed here, not built.
|
||||
- [ ] **Not done, deliberately:** no `window/workDoneProgress/cancel` handler.
|
||||
There is nothing in this server to cancel — see Assumptions.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-26 — dev agent, §9b
|
||||
|
||||
- **Read the code before deciding about the startup build, as the brief asked.**
|
||||
`main.rs` calls `connection.initialize_finish(...)` on line 74 and
|
||||
`Server::new(...)` on line 76, and `initialize_finish` returns only after the
|
||||
client's `initialized` notification has been received and consumed. So the
|
||||
startup build happens at a moment when server-initiated requests are legal —
|
||||
the existing `register_watchers()` call in `Server::new` already relies on
|
||||
exactly that, and says so in a comment. **Verdict: wrapped.** It is the
|
||||
slowest rescan of the session and the one most worth a bar.
|
||||
- **The one structural change is in `Server::new`**: the struct is now built
|
||||
first and `open_roots` called through it, because `begin_indexing` needs
|
||||
`&mut self`. Nothing else about that function moved — `report_scope` still
|
||||
runs on the warnings `open_roots` returned, and `register_watchers` still
|
||||
runs last.
|
||||
- **`Option<ProgressToken>` is the ability check.** `begin_indexing` returns
|
||||
`None` for a client that cannot show a bar and `end_indexing` returns on
|
||||
`None`, so neither `reindex` nor `Server::new` mentions the capability. That
|
||||
also makes "a bar that went up came down" structural rather than a
|
||||
discipline: there is exactly one value that ends it and exactly one place
|
||||
it is produced.
|
||||
- **Tokens are strings, `lucisv-index-N`, off their own counter.** A number
|
||||
token would collide conceptually with the `lucisv-N` request ids in a log,
|
||||
and the string says what the bar is for. The counter starts at the startup
|
||||
build, so `lucisv-index-0` is always the first index and the first save is
|
||||
always `lucisv-index-1` — pinned by tests at both the unit and the wire
|
||||
level.
|
||||
- **The end message reads `WorkspaceIndex::files().len()`,** which was already
|
||||
public and already reachable through `Workspace::index()`. The brief's
|
||||
fallback ("end with no message if no count is cheaply available") was not
|
||||
needed; nothing was plumbed. The singular case has its own assertion, because
|
||||
"1 files indexed" is the kind of thing that ships.
|
||||
- **`report_scope` still shows its popup after the bar comes down.** A filelist
|
||||
warning and a progress bar are unrelated; sequencing them the other way would
|
||||
have meant holding the bar up across a modal in some clients.
|
||||
- Files touched: `crates/lucisv_server/src/server.rs`,
|
||||
`crates/lucisv_server/src/main.rs`, `crates/lucisv_server/tests/e2e.rs`,
|
||||
`TODO.md`, `docs/features/lucisv-server/README.md`, this README. No engine
|
||||
crate, no `editors/`, no new dependency, no version bump.
|
||||
|
||||
**Verification.** `cargo fmt --all -- --check`: clean. `cargo clippy
|
||||
--all-targets`: zero warnings. `cargo test --workspace`: **1812 passed, 0
|
||||
failed** (1802 on `HEAD`, measured — 7 new unit tests in `server.rs`, 1 in
|
||||
`main.rs`, 2 new e2e sessions). `cargo build && node editors/vscode/smoke.js
|
||||
target/debug/lucisv-server`: OK, exit 0. No commits.
|
||||
|
||||
The ten tests, and what each is for:
|
||||
|
||||
| test | pins |
|
||||
|---|---|
|
||||
| `the_startup_index_build_runs_under_the_first_bar` | the startup determination above, as observable traffic |
|
||||
| `a_save_puts_a_bar_up_and_takes_it_down_again` | create → begin → end, one token, on the save path |
|
||||
| `the_bar_says_how_many_files_were_indexed` | the end message, plural and singular |
|
||||
| `the_bar_is_down_before_the_republish` | the documented ordering against `publishDiagnostics` |
|
||||
| `a_client_that_did_not_ask_for_a_bar_is_sent_no_progress_at_all` | zero messages of any kind, at startup and on save |
|
||||
| `every_rescan_path_gets_its_own_bar_and_its_own_token` | the watched-file and config-change paths, three distinct tokens, no leaked begin, no `report` |
|
||||
| `a_progress_create_answer_is_ignored_and_never_disturbs_an_apply_edit` | an `Ok` *and* an `Err` create answer arriving between an `applyEdit` push and its answer; the refusal still reported exactly once |
|
||||
| `work_done_progress_support_is_read_from_the_clients_own_capabilities` (`main.rs`) | absent/false/true, and no panic on `InitializeParams::default()` |
|
||||
| `indexing_reports_its_progress_over_the_wire` + `a_client_that_never_asked_for_progress_is_sent_none_over_the_wire` (e2e) | the whole sequence against the real binary, both gate states, including `title`, `cancellable: false` and the absence of `percentage` |
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-26 — QA agent, §9b
|
||||
|
||||
**Gates re-run**, on the working tree as handed off (commit `00c03ec` +
|
||||
uncommitted): `cargo fmt --all -- --check` clean. `cargo clippy --all-targets
|
||||
--workspace` zero warnings. `cargo test --workspace`: **1812 passed, 0
|
||||
failed** — matches the dev log exactly. `cargo build && node
|
||||
editors/vscode/smoke.js target/debug/lucisv-server`: `smoke: OK`. After the
|
||||
four tests added below: **1816 passed, 0 failed**, gates re-checked and still
|
||||
clean.
|
||||
|
||||
Per attack surface (lead's numbering):
|
||||
|
||||
1. **`Server::new` restructuring — verified clean, structurally rather than
|
||||
just empirically.** `Workspace::default()` then `open_roots(roots)` is the
|
||||
same value undergoing the same two operations in the same order whether the
|
||||
mutation happens on a local binding before it moves into the `Server`
|
||||
literal (old, `server.rs` pre-`00c03ec`-diff) or on `&mut self.workspace`
|
||||
after it is already a field (new) — a move is bitwise and Rust invokes no
|
||||
`Drop`/observer between them, so there is no field `open_roots` could leave
|
||||
stale that the old order would have filled: every field of `Workspace`
|
||||
(`docs`, `roots`, `index`, `candidates`, `includes`, `client`) gets the
|
||||
identical value either way. Every other `Server` field's initializer
|
||||
(`connection`, `config_warnings`, `abilities`, `watchers`, `registrations`,
|
||||
`request_ids`, `applying`, `generation`, `tokens`, `token_results`, and the
|
||||
new `indexings: 0`) is inert and side-effect-free, so field-initializer
|
||||
order carries no risk. `report_scope` still receives `open_roots`'s
|
||||
warnings (`server.rs:109-111`); `register_watchers` still runs last
|
||||
(`server.rs:116`).
|
||||
**Gap found and fixed**: the ordering the lead flagged as the actual risk —
|
||||
whether `register_watchers`'s request lands before or after the startup
|
||||
bar comes down — was not observable in any existing test, because every
|
||||
dev test using `watching_progress()` (`work_done_progress: true`) leaves
|
||||
`file_watching` at its `Default::default()` of `false`, so
|
||||
`register_watchers` is a no-op in all of them; conversely every test that
|
||||
turns `file_watching` on (`Session::new(_, true)`) leaves
|
||||
`work_done_progress` off. No test ever ran both abilities together. Added
|
||||
`the_startup_watcher_registration_arrives_after_the_indexing_bar_comes_down`
|
||||
(`server.rs`, in `mod tests`, right after
|
||||
`a_progress_create_answer_is_ignored_and_never_disturbs_an_apply_edit`),
|
||||
which turns both abilities on and pins the wire order `create, begin, end,
|
||||
register`.
|
||||
|
||||
2. **Protocol conformance — verified clean.** The e2e test
|
||||
`indexing_reports_its_progress_over_the_wire` decodes the actual JSON
|
||||
(not the Rust struct) off the real binary and asserts, in one ordered
|
||||
`Vec`: `create` precedes `begin` for the *same* token, for both the
|
||||
startup rescan (`lucisv-index-0`) and the save-triggered one
|
||||
(`lucisv-index-1`) — i.e., create-before-begin holds across consecutive
|
||||
rescans, not just once. The token is read with
|
||||
`.as_str().expect("a string token")`, which fails the test if the wire ever
|
||||
sends a JSON number instead — so the string-typed-token requirement is
|
||||
pinned, not assumed. `title`, `cancellable: false` (explicit `false`, not
|
||||
absent), and the absence of `percentage` are asserted off the decoded
|
||||
`begin`; the `end`'s `message` is asserted off the decoded `end`. No gap.
|
||||
|
||||
3. **Pairing is structural — verified clean.** Read `reindex()`
|
||||
(`server.rs:887-897`) and `Server::new` (`server.rs:140-169`): in both,
|
||||
nothing sits between `begin_indexing()` and `end_indexing()` but a call
|
||||
that returns a plain `Vec<String>` (`rebuild_index`/`open_roots`), never a
|
||||
`Result` — there is no `?` and no early-return expression available to
|
||||
write between them even by accident. `end_indexing` is therefore
|
||||
unconditionally reached in every existing and reachable call site.
|
||||
Multiple rapid reindexes: the server is single-threaded and `reindex()` is
|
||||
fully synchronous (begin, scan, end, all before the call returns), so two
|
||||
rescans provably cannot interleave regardless of how close together their
|
||||
triggers arrive — confirmed observably by
|
||||
`every_rescan_path_gets_its_own_bar_and_its_own_token`, which fires a save,
|
||||
a watched-file change and a config change back-to-back and gets three
|
||||
strictly-paired, strictly-increasing tokens. No gap.
|
||||
|
||||
4. **Capability gating — mostly verified clean, one gap fixed.** Startup and
|
||||
save, both gated correctly, per `a_client_that_did_not_ask_for_a_bar_is_
|
||||
sent_no_progress_at_all`. `window: {}` and `window: {
|
||||
workDoneProgress: false }` are both covered by
|
||||
`work_done_progress_support_is_read_from_the_clients_own_capabilities`
|
||||
(`main.rs`) via `saying(None)` and `saying(Some(false))` respectively —
|
||||
`ClientCapabilities::default()`'s `window` field is itself `None`, and
|
||||
`saying(None)` still wraps a `Some(WindowClientCapabilities{ .. })`, which
|
||||
is exactly the `window: {}` shape; neither panics on
|
||||
`InitializeParams::default()`.
|
||||
**Gap found and fixed**: the watched-file and `lucisv.exclude`/`filelist`
|
||||
reindex triggers were never driven with the capability *off* — only proven
|
||||
off by reading that they share `reindex()`'s single `begin_indexing` call
|
||||
with the save path. Added
|
||||
`a_client_without_the_bar_gets_none_on_the_watcher_or_config_paths_either`
|
||||
(`server.rs`), which drives both and asserts `session.progress()` empty
|
||||
after each.
|
||||
|
||||
5. **Response routing under interleaving — one direction existing, the
|
||||
reverse was missing; fixed.** The dev's
|
||||
`a_progress_create_answer_is_ignored_and_never_disturbs_an_apply_edit`
|
||||
answers the create (`Ok` then, for the same id, `Err`) while the
|
||||
`applyEdit` is still outstanding, then answers the edit — this is a real
|
||||
interleaving (create resolved first), and both answer shapes are exercised.
|
||||
The reverse ordering the lead asked for — `applyEdit` resolved *first*,
|
||||
then a *late* create answer — was not present. Added
|
||||
`a_late_create_answer_after_the_apply_edit_already_answered_is_ignored_too`
|
||||
(`server.rs`): answers the edit as accepted, confirms nothing is shown, then
|
||||
feeds a late `Response::new_ok` for the create's id and confirms it is
|
||||
still silently dropped. This same test doubles as "a create answer arriving
|
||||
for a token the server already Ended": by the time the edit is answered,
|
||||
the watched-file reindex that minted the create has already run its
|
||||
`begin`/`end` pair synchronously (per point 3), so the create answer that
|
||||
follows is necessarily late-for-an-ended-bar. It is ignored cleanly because
|
||||
`response()` keys off `RequestId`, never off `ProgressToken` — the two are
|
||||
different namespaces and `request_ids` never repeats, so there is no
|
||||
representable state where a create's id could collide with anything a
|
||||
still-outstanding request cares about. No further scenario to test here.
|
||||
|
||||
6. **End-message count — verified clean, one gap fixed.** `end_indexing`
|
||||
reads `self.workspace.index().files().len()` (`server.rs:192`), which is
|
||||
the index's own file list, computed by `rebuild_index` immediately before
|
||||
`end_indexing` runs — not open-buffer count, not scope-file count before
|
||||
filtering. Singular/plural pinned by `the_bar_says_how_many_files_were_
|
||||
indexed` ("2 files indexed" / "1 file indexed", explicitly asserting `"not
|
||||
`1 files`"`).
|
||||
**Gap found and fixed**: no test drove a rootless workspace with zero open
|
||||
buffers through startup. Traced `default_files()` → `sibling_files()`
|
||||
(`state.rs:308-328`) for that case: no roots and no docs means no
|
||||
directories to walk, so the index is empty and `files == 0`; the plural
|
||||
branch (`files == 1` is false for 0) correctly renders `"s"`. Added
|
||||
`a_rootless_workspace_with_no_open_files_says_zero_at_startup_without_
|
||||
crashing` (`server.rs`), asserting `"0 files indexed"` and, by not
|
||||
panicking, non-crashing. Confirmed passing.
|
||||
|
||||
7. **CLAUDE.md compliance — verified clean.** Grepped every non-`#[cfg(test)]`
|
||||
line of `server.rs` and `main.rs` (i.e., everything before their `mod
|
||||
tests`) for `unwrap(`, `expect(`, `panic!(`: zero hits. Every new item
|
||||
(`ClientAbilities::work_done_progress`, `Server::indexings`,
|
||||
`INDEXING_TITLE`, `begin_indexing`, `end_indexing`, `progress`,
|
||||
`work_done_progress_support`) carries a doc comment. This README's seven
|
||||
required sections (`Goal`, `Assumptions`, `Handshakes`, `Status / TODO`,
|
||||
`Work log`, `QA log`, `Review`) each appear exactly once
|
||||
(`grep -n "^## "`). `TODO.md`'s §9b item text is untouched — only its
|
||||
checkbox flipped to `[x]` and an indented `→` note appended below, per the
|
||||
existing convention elsewhere in that file.
|
||||
|
||||
**Beyond the list.** One thing noted for the record, not a defect in this
|
||||
diff: `Workspace::collect_sources` (`state.rs`, untouched by this round) folds
|
||||
in every open buffer's path unconditionally, even one outside the walked
|
||||
scope, so in principle an open buffer for a file the workspace walk would not
|
||||
have found could nudge the "N file(s) indexed" count up by one beyond what a
|
||||
disk-only scan would report. This is pre-existing behavior this feature did
|
||||
not introduce and does not change (`state.rs` has no diff against `00c03ec`),
|
||||
so it is not filed as a finding against this round — just flagged in case a
|
||||
future change to the end message's wording ever needs it.
|
||||
|
||||
**Fixes made** (all additive; no dev code changed): four new tests in
|
||||
`crates/lucisv_server/src/server.rs`'s `mod tests`, inserted after
|
||||
`a_progress_create_answer_is_ignored_and_never_disturbs_an_apply_edit`:
|
||||
`a_late_create_answer_after_the_apply_edit_already_answered_is_ignored_too`,
|
||||
`the_startup_watcher_registration_arrives_after_the_indexing_bar_comes_down`,
|
||||
`a_client_without_the_bar_gets_none_on_the_watcher_or_config_paths_either`,
|
||||
`a_rootless_workspace_with_no_open_files_says_zero_at_startup_without_
|
||||
crashing`. All four pass; full workspace suite is green at 1816; `cargo fmt`
|
||||
and `cargo clippy --all-targets` stay clean.
|
||||
|
||||
**Verdict: committable as-is.** No corruption risk, no idempotency risk (this
|
||||
feature touches only the LSP transport, never formatted output), no dropped
|
||||
comments, no widened `verify.rs` forgiveness (that file has no diff in this
|
||||
round). The one structurally risky change — `Server::new`'s construction
|
||||
order — is provably equivalent to the old order and now has its
|
||||
previously-unpinned watcher-vs-bar ordering under test. No dev follow-up
|
||||
required.
|
||||
|
||||
## Review
|
||||
|
||||
### 2026-08-26 — lead
|
||||
|
||||
Reviewed the diff, the work log and the QA log; re-ran all gates myself
|
||||
(1816 workspace tests, 0 failed), clean. The `Option<ProgressToken>`-as-
|
||||
capability-gate design is the kind of structural guarantee this repo
|
||||
prefers over discipline: neither caller can put a bar up for a client
|
||||
that cannot show one, and nothing between `begin` and `end` can return
|
||||
early — I read the two call sites and confirm QA's finding that the
|
||||
pairing is unconditional. The startup-build determination was done the
|
||||
right way (read from `initialize_finish`'s contract and the existing
|
||||
`register_watchers` comment, not guessed), and the restructured
|
||||
`Server::new` is provably equivalent — same value, same two operations,
|
||||
different borrow spelling — with the previously-unpinned
|
||||
watcher-after-bar ordering now under test thanks to QA. Honesty calls
|
||||
all correct: no invented percentage, `cancellable: false` because
|
||||
nothing here can cancel, and the end message costing nothing because the
|
||||
index already knew its file count. QA's four gap-closing tests (both
|
||||
interleaving directions, capability-off on all trigger paths, the
|
||||
rootless zero-count startup) complete the surface. Accepted as shipped.
|
||||
Reference in new issue
Block a user