Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions rust/contracts/application-boundary.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,12 @@ this lifecycle protection; actual symbol computation remains upstream-owned.
| Modules | stable IDs, manifests, enabled state, lifecycle snapshots, dependencies, capabilities, and contributions | native factories, processes, timers, PTY/ConPTY, watchers, connections, and UI rendering |
| Updates | normalized release metadata, state names, validated `stable|autobuild` preference, explicit rolling consent, and stable error codes | update feeds, package verification, download, installation, restart, and native UI |

Language-server workspace edits preserve explicit LSP document versions.
Core rejects edits for stale or unknown versioned documents. A native host checks
that its editor snapshots still match those versions before touching files or
buffers, and stops pending work when Core revokes a delivered request. The
[Core commands reference](rust-core-api.md#commands) specifies the event and reply shapes.

### Application update channels

A missing saved channel selects `stable` for Stable and legacy shared-identity builds;
Expand Down
83 changes: 72 additions & 11 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -699,6 +699,7 @@ or removing a command fails until the table changes in the same commit.
| `lsp.functionProvider` | Select a registered function provider strictly inside one workspace |
| `lsp.configureFunctionRelay` | Replace the enabled plugins and live workspace contexts Core's plugin-to-plugin function relay checks calls against |
| `lsp.hostResponse` | Answer one host-service request a plugin backend sent |
| `lsp.applyEditResponse` | Answer one server-initiated `workspace/applyEdit` request with whether the host applied it |
| `lsp.hostNotify` | Send one host notification to a plugin backend that negotiated it |
| `lsp.pluginServerRequest` | Send one request of a plugin backend to the plugin's own language server, under the plugin's declared session policy |
| `lsp.pluginServerNotify` | Send one notification of a plugin backend to the plugin's own language server |
Expand Down Expand Up @@ -3445,21 +3446,30 @@ explicit `plugin.function.*` error.
callee does not register the function within 30 seconds.

`lsp.request` accepts a semantic `operation` plus
the operation-specific URI, position, range, diagnostics, item, action, or
the operation-specific URI, position, range, diagnostics, item, action, hint, or
command fields, and returns `{ operationId }`. Supported operations include
completion and resolve, hover, definition/declaration/type-definition, references,
completion and resolve, hover, signature help (`signatureHelp`), definition/declaration/type-definition, references,
implementation, rename, formatting, range formatting, document symbols, code actions and resolve, execute command,
inlay hints, full-document semantic tokens, folding ranges, document links
inlay hints and resolve (`inlayHints`, `resolveInlayHint`), full-document semantic tokens, folding ranges, document links
(`documentLinks`, result `{ links: [{ range, target, tooltip }] }`; `target` is null
until a server supplies it, and entries without a range are dropped), workspace
symbols (`workspaceSymbols`, see below), code lens, and provider virtual documents.
For code actions, `diagnostics` contains the original `LspClientDiagnostic`
objects returned by Core: nullable integer `severity`, `tags`, and
`relatedInformation` remain intact, and every range uses zero-based `line` /
`utf16Column` positions. A platform's display severity or marker projection is
`utf16Column` positions. Optional `codeActionContext` accepts `{ only?: string[], triggerKind?: 1 | 2 }`
(`1` invoked, `2` automatic). Disabled actions are omitted, titles are normalized
to single-line bounded text (512 bytes), each action carries a deterministic
`group` (`"quickfix"`, `"refactor"`, `"source"`, or `"other"`), and Core sorts
actions stably with `isPreferred` first and then `quickfix`, `refactor`, `source`,
`other` (up to 256 actions). `resolveCodeAction` strips Core-only `group` before
sending `codeAction/resolve`. A code action with an unsupported or stale workspace
edit is omitted. Normalized edits preserve the optional `documentVersions` map
described below. A platform's display severity or marker projection is
not a diagnostic request model. Non-LSP markers may request actions with a range
and an empty diagnostic context. The round-trip fixture is
`rust/fixtures/lsp/diagnostic-code-actions-v1.json`.
and an empty diagnostic context. The round-trip fixtures are
`rust/fixtures/lsp/diagnostic-code-actions-v1.json` and
`rust/fixtures/lsp/editor-actions-hints-v1.json`.

Deadline cancellations are written by a separate session-owned worker. The
deadline monitor never writes to stdin. A background write that exceeds
Expand Down Expand Up @@ -3492,6 +3502,7 @@ typed events. Hosts should use `waitEvents` so idle sessions do not poll.
Event types
include `stateChanged`, `featuresChanged`, `diagnostics`,
`requestCompleted`, `requestProgress`, `functionsChanged`, `hostRequest`,
`workspaceApplyEdit`, `workspaceApplyEditCancelled`, `inlayHintsRefresh`, `semanticTokensRefresh`,
`serverInfoChanged`, and `log`. Every request completes at
most once with either `result` or a structured runtime error containing
provider/session, stage, optional method/document/request, stable code, and
Expand Down Expand Up @@ -5575,7 +5586,57 @@ The `featuresChanged` event carries `completionOptions:
`completionProvider` and its dynamic `textDocument/completion` registrations
(empty arrays when none are declared). The event is re-sent when registrations
change them. Hosts use it, not a hard-coded list, to send
`completionContext.triggerKind = 2`.
`completionContext.triggerKind = 2`. Whenever `signatureHelp` is offered,
`featuresChanged` likewise carries `signatureHelpOptions:
{ triggerCharacters: string[], retriggerCharacters: string[] }`, aggregated across
`signatureHelpProvider` and dynamic `textDocument/signatureHelp` registrations.

Operation `signatureHelp` (`textDocument/signatureHelp`) requires `uri` and
`position` and accepts optional `signatureHelpContext` (`triggerKind` `1`..`3`,
one-character `triggerCharacter` when `triggerKind = 2`, `isRetrigger`, and
`activeSignatureHelp`, which may be a previously normalized Core `SignatureHelp`
result). Its normalized result is `{ signatureHelp: null }` when no signature is active, or
`{ signatureHelp: { signatures, activeSignature, activeParameter } }` (capped at 32 signatures,
128 parameters per signature, 512-character single-line labels, and 2048-byte
documentation). Each parameter is normalized from either a substring label or
UTF-16 `[start, end]` offsets into
`{ label, utf16Start, utf16End, byteStart, byteEnd, documentation, isMarkdown }`,
and the original `activeSignature` / `activeParameter` selections are mapped to
the retained entries. Missing or out-of-range indices select the first retained
entry when one exists. The legacy top-level `activeParameter` is used only for
the active signature when that signature has no `activeParameter` of its own.

Operation `inlayHints` (`textDocument/inlayHint`) sorts hints stably by
`(line, utf16Column)`, trims labels to single-line text of at most 48 characters
(with `…`), caps tooltips at 2048 bytes, and keeps at most 8 hints per line and
512 hints per viewport request. When a static or dynamically registered provider
advertises `resolveProvider`,
`featuresChanged` includes `inlayHintResolve` and `resolveInlayHint` (`inlayHint/resolve`)
resolves a single hint (`{ hint }`). Pass back the normalized hint with its optional
`resolvePayload` for this operation. Core uses that bounded original hint (at most 16 KiB)
to keep the language server's original label parts, position and data. Hints that
exceed the resolve limit are displayable without a resolve payload. Core advertises `workspace.inlayHint.refreshSupport`
and forwards `workspace/inlayHint/refresh` as the `inlayHintsRefresh` event after
acknowledging the request with JSON-RPC `null`. Repeated refreshes coalesce until
the host drains the queued event.

When a language server sends `workspace/applyEdit`, Core validates its edit payload,
immediately replies `{ applied: false, failureReason }` for stale versioned targets,
invalid positions or replacement text, non-file URIs, snippet or annotated
edits, or `create`/`rename`/`delete` resource operations. The valid payload is
bounded to 256 target files, 4096 edits and 4 MiB of replacement text. Numeric
versions must match the session's current open documents. Core preserves them in
`documentVersions`, keyed by the same target paths as `changes`. The event is
`workspaceApplyEdit` with `result: { applyEditId, label, changes, documentVersions }`.
The native host rechecks the supplied versions against the synchronized editor
snapshots and validates workspace boundaries. It applies or rejects the edit
using `lsp.planWorkspaceEdit` and `lsp.applyTextEdits`, then answers with
`lsp.applyEditResponse` (`{ sessionId, applyEditId, applied, failureReason? }`).
Eight requests per session may await the host within the session request timeout.
If cancelled or expired before delivery, Core removes the queued edit. After
delivery, `workspaceApplyEditCancelled` carries `result: { applyEditId }` and the
host stops pending work for that ID. The server receives cancellation, timeout,
or shutdown settlement without waiting for a late host response.

Operation `documentSymbols` (`textDocument/documentSymbol`) needs only the
document `uri` and is offered, as the `documentSymbols` feature, when the server
Expand Down Expand Up @@ -7245,10 +7306,10 @@ replacement fails atomically. Invalid requests return `invalid_request` with sta
`source_too_large`, `source_too_large_or_invalid`, `replacement_too_large`, `too_many_matches`.
Source, query and replacement are never included in errors or diagnostic logs.

`editor.preferences.resolve` accepts optional `lineNumbers`, `whitespace`, `cursorStyle`
(`line`, `block`, `underline`), `cursorBlink` and `autoSaveDelayMilliseconds`. It returns
actual values and minimum/maximum delay. Defaults: true, false, line, true, 1500 ms;
unknown styles resolve to line and delay clamps to 250–60,000 ms.
`editor.preferences.resolve` accepts optional `lineNumbers`, `whitespace`, `inlayHints`,
`cursorStyle` (`line`, `block`, `underline`), `cursorBlink` and `autoSaveDelayMilliseconds`.
It returns actual values and minimum/maximum delay. Defaults: true, false, true, line,
true, 1500 ms; unknown styles resolve to line and delay clamps to 250–60,000 ms.

`editor.recent.reduce` accepts `entries`, optional `event:{kind,path,name,line,column}`,
`query` and `onlyEdited`. It returns bounded `entries` and filtered `results`. Paths are
Expand Down
4 changes: 4 additions & 0 deletions rust/crates/core/src/protocol/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -703,6 +703,8 @@ pub enum LspCommand {
ConfigureFunctionRelay,
/// Answers a plugin backend's host-service request (`lsp.hostResponse`).
HostResponse,
/// Answers a language server's `workspace/applyEdit` request (`lsp.applyEditResponse`).
ApplyEditResponse,
/// Sends a plugin backend one host notification (`lsp.hostNotify`).
HostNotify,
/// Sends a plugin-owned language server one request of its backend (`lsp.pluginServerRequest`).
Expand Down Expand Up @@ -1426,6 +1428,7 @@ impl CoreCommand {
"lsp.functionProvider" => Some(Self::Lsp(LspCommand::FunctionProvider)),
"lsp.configureFunctionRelay" => Some(Self::Lsp(LspCommand::ConfigureFunctionRelay)),
"lsp.hostResponse" => Some(Self::Lsp(LspCommand::HostResponse)),
"lsp.applyEditResponse" => Some(Self::Lsp(LspCommand::ApplyEditResponse)),
"lsp.hostNotify" => Some(Self::Lsp(LspCommand::HostNotify)),
"lsp.pluginServerRequest" => Some(Self::Lsp(LspCommand::PluginServerRequest)),
"lsp.pluginServerNotify" => Some(Self::Lsp(LspCommand::PluginServerNotify)),
Expand Down Expand Up @@ -1743,6 +1746,7 @@ mod tests {
"lsp.functionRequest",
"lsp.configureFunctionRelay",
"lsp.hostResponse",
"lsp.applyEditResponse",
"lsp.hostNotify",
"lsp.pluginServerRequest",
"lsp.pluginServerNotify",
Expand Down
15 changes: 15 additions & 0 deletions rust/crates/core/src/runtime/dispatcher/lsp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,21 @@ pub(super) fn dispatch(command: LspCommand, id: Option<String>, payload: Value)
Err(error) => CoreResponse::failure(id, error),
}
}
LspCommand::ApplyEditResponse => {
match serde_json::from_value::<lithe_lsp_engine::ApplyEditResponseRequest>(payload)
.map_err(|error| {
CoreError::new(
ErrorCode::InvalidRequest,
"Invalid workspace apply-edit response",
)
.with_details(error.to_string())
})
.and_then(lithe_lsp_engine::apply_edit_response)
{
Ok(()) => CoreResponse::success(id, json!({})),
Err(error) => CoreResponse::failure(id, error),
}
}
LspCommand::HostNotify => {
match serde_json::from_value::<lithe_lsp_engine::PluginHostNotification>(payload)
.map_err(|error| {
Expand Down
1 change: 1 addition & 0 deletions rust/crates/core/src/runtime/request_trace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,7 @@ pub(crate) fn is_hot(method: &str) -> bool {
| "lsp.waitEvents"
| "lsp.cancelOperation"
| "lsp.hostResponse"
| "lsp.applyEditResponse"
| "lsp.hostNotify"
| "debug.receive"
| "debug.transport.handle"
Expand Down
5 changes: 2 additions & 3 deletions rust/crates/core/src/tests/toolchain_definitions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,8 @@ fn tool_definitions_declare_settings_category_and_audience() {
tagged["audience"] = json!("plugin");
let mut plugin = manifest("dev.lithe.fixture.compiler", tagged);
// The fields are toolDefinitions 1, so a host that supports only 0 never installs it.
let rejected = validate_manifest_value(plugin.clone())
.err()
.expect("version 0 refuses settings categories");
let rejected =
validate_manifest_value(plugin.clone()).expect_err("version 0 refuses settings categories");
assert_eq!(rejected.field.as_deref(), Some("requires.toolDefinitions"));
plugin["requires"]["toolDefinitions"] = json!(1);
assert!(validate_manifest_value(plugin.clone()).is_ok());
Expand Down
6 changes: 5 additions & 1 deletion rust/crates/editor/src/preferences.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use serde_json::{json, Value};
struct Stored {
line_numbers: Option<bool>,
whitespace: Option<bool>,
inlay_hints: Option<bool>,
cursor_style: Option<String>,
cursor_blink: Option<bool>,
auto_save_delay_milliseconds: Option<u64>,
Expand All @@ -27,6 +28,7 @@ pub fn resolve_command(payload: Value) -> Result<Value, CoreError> {
Ok(json!({
"lineNumbers":stored.line_numbers.unwrap_or(true),
"whitespace":stored.whitespace.unwrap_or(false),
"inlayHints":stored.inlay_hints.unwrap_or(true),
"cursorStyle":style,
"cursorBlink":stored.cursor_blink.unwrap_or(true),
"autoSaveDelayMilliseconds":stored.auto_save_delay_milliseconds.unwrap_or(1500).clamp(250,60_000),
Expand All @@ -43,14 +45,16 @@ mod tests {
let value = resolve_command(json!({})).unwrap();
assert_eq!(value["lineNumbers"], true);
assert_eq!(value["whitespace"], false);
assert_eq!(value["inlayHints"], true);
assert_eq!(value["cursorStyle"], "line");
assert_eq!(value["cursorBlink"], true);
assert_eq!(value["autoSaveDelayMilliseconds"], 1500);
}
#[test]
fn corrupted_values_are_bounded_without_replacing_valid_choices() {
let value = resolve_command(json!({"lineNumbers":false,"cursorStyle":"unknown","cursorBlink":false,"autoSaveDelayMilliseconds":1})).unwrap();
let value = resolve_command(json!({"lineNumbers":false,"inlayHints":false,"cursorStyle":"unknown","cursorBlink":false,"autoSaveDelayMilliseconds":1})).unwrap();
assert_eq!(value["lineNumbers"], false);
assert_eq!(value["inlayHints"], false);
assert_eq!(value["cursorStyle"], "line");
assert_eq!(value["cursorBlink"], false);
assert_eq!(value["autoSaveDelayMilliseconds"], 250);
Expand Down
6 changes: 6 additions & 0 deletions rust/crates/lsp-client/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ mod requests;
mod results;
mod server_messages;
mod validation;
mod workspace_edits;

pub use capabilities::*;
pub(crate) use diagnostics::*;
Expand All @@ -23,6 +24,7 @@ pub(crate) use requests::*;
pub(crate) use results::*;
pub use server_messages::*;
pub(crate) use validation::*;
use workspace_edits::{parse_bounded_text_edit, parse_workspace_apply_edit, WorkspaceEdit};

#[cfg(test)]
mod semantic_tests {
Expand Down Expand Up @@ -134,6 +136,7 @@ mod formatting_and_completion_tests {
command: None,
formatting_options: options,
include_declaration: None,
..Default::default()
}
}

Expand Down Expand Up @@ -206,6 +209,7 @@ mod formatting_and_completion_tests {
"range": {"start": {"line": 0, "character": 0}, "end": {"line": 0, "character": 1}},
"newText": "x"
}])),
&Default::default(),
)
.unwrap();
assert_eq!(result["edits"][0]["newText"], "x");
Expand All @@ -221,6 +225,7 @@ mod formatting_and_completion_tests {
let result = lsp_feature_result_for_method(
Some("textDocument/documentSymbol"),
Some(&case["serverResult"]),
&Default::default(),
)
.unwrap();
assert_eq!(result, case["expected"], "case {}", case["name"]);
Expand Down Expand Up @@ -276,6 +281,7 @@ mod formatting_and_completion_tests {
let result = lsp_feature_result_for_method(
Some("textDocument/completion"),
Some(&json!({"isIncomplete": true, "items": [{"label": "a"}]})),
&Default::default(),
)
.unwrap();
assert_eq!(result["isIncomplete"], true);
Expand Down
Loading
Loading