Skip to main content

agentmux_srv/server/
lsp_handlers.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::sync::Arc;
5
6use crate::backend::rpc::engine::WshRpcEngine;
7use crate::backend::base::expand_home_dir_safe;
8use crate::backend::rpc_types::{LspSendReq, LspStartReq, LspStartResult, LspStopReq};
9
10use super::AppState;
11
12pub fn register_lsp_handlers(engine: &Arc<WshRpcEngine>, state: &AppState) {
13    // ── LSP RPCs ───────────────────────────────────────────────────
14    // Three handlers backing the editor pane's LSP integration:
15    //   * lspstart — spawn (or attach to) the server for a file
16    //   * lspsend  — forward an LSP JSON-RPC message to the server's stdin
17    //   * lspstop  — refcount-decrement; server exits when count hits 0
18    // Server-pushed notifications (publishDiagnostics, $/progress, …)
19    // arrive via WS event `lsp:message` from the supervisor's reader task.
20    // Spec: docs/specs/SPEC_EDITOR_LSP_AND_THEMES_2026-05-26.md
21
22    let lsp_supervisor_start = state.lsp_supervisor.clone();
23    engine.register_typed(
24        "lspstart",
25        move |cmd: LspStartReq, _ctx| {
26            let supervisor = lsp_supervisor_start.clone();
27            async move {
28                let expanded = expand_home_dir_safe(&cmd.file_path);
29                let workspace_root =
30                    crate::backend::lsp::workspace::detect_workspace_root(expanded.as_path());
31                let result = supervisor
32                    .start(crate::backend::lsp::StartArgs {
33                        language: cmd.language,
34                        workspace_root,
35                        file_path: expanded,
36                    })
37                    .await
38                    .map_err(|e| e.to_wire_string())?;
39                Ok(LspStartResult {
40                    server_id: result.server_id,
41                    workspace_root: result.workspace_root,
42                })
43            }
44        },
45    );
46
47    let lsp_supervisor_send = state.lsp_supervisor.clone();
48    engine.register_typed(
49        "lspsend",
50        move |cmd: LspSendReq, _ctx| {
51            let supervisor = lsp_supervisor_send.clone();
52            async move {
53                let message_json = serde_json::to_string(&cmd.message)
54                    .map_err(|e| format!("lspsend serialize: {e}"))?;
55                supervisor
56                    .send(&cmd.server_id, &message_json)
57                    .await
58                    .map_err(|e| e.to_wire_string())?;
59                Ok(())
60            }
61        },
62    );
63
64    let lsp_supervisor_stop = state.lsp_supervisor.clone();
65    engine.register_typed(
66        "lspstop",
67        move |cmd: LspStopReq, _ctx| {
68            let supervisor = lsp_supervisor_stop.clone();
69            async move {
70                supervisor
71                    .stop(&cmd.server_id)
72                    .await
73                    .map_err(|e| e.to_wire_string())?;
74                Ok(())
75            }
76        },
77    );
78}
79
80#[cfg(test)]
81mod tests {
82    use super::*;
83    use crate::backend::rpc_types::RpcMessage;
84
85    /// All three LSP commands record their request and response types.
86    ///
87    /// Before this, each handler deserialized into a `Cmd` struct declared
88    /// inside its own closure. Those cannot be named, so they could not be
89    /// generated from and the frontend restated every one of them by hand --
90    /// three shapes with nothing connecting them to the Rust they describe.
91    #[tokio::test]
92    async fn register_typed_records_the_three_lsp_commands() {
93        let state = crate::server::tests::test_state();
94        let (engine, _rx) = WshRpcEngine::new();
95        register_lsp_handlers(&engine, &state);
96        let schema = engine.schema_json();
97        let rows = schema.as_array().unwrap();
98        let find = |cmd: &str| {
99            rows.iter()
100                .find(|r| r["command"] == cmd)
101                .unwrap_or_else(|| panic!("{cmd} missing from the schema"))
102        };
103
104        let start = find("lspstart");
105        assert_eq!(start["requestName"], "LspStartReq");
106        assert_eq!(start["responseName"], "LspStartResult");
107
108        // `lspsend` and `lspstop` answer nothing, which is a real response
109        // type rather than an absent one -- the stubs say `Promise<void>` and
110        // the registry should agree rather than recording `Value`.
111        for cmd in ["lspsend", "lspstop"] {
112            let row = find(cmd);
113            assert_eq!(row["responseName"], "()", "{cmd} should answer nothing");
114        }
115        assert_eq!(find("lspsend")["requestName"], "LspSendReq");
116        assert_eq!(find("lspstop")["requestName"], "LspStopReq");
117    }
118
119    /// `lspsend.message` is an opaque passthrough: the backend re-serializes
120    /// it and writes it to the server's stdin without inspecting it. Anything
121    /// that is valid JSON has to survive, including the shapes a narrower
122    /// Rust type would have rejected -- which is why it stays a `Value` and
123    /// generates as `unknown` rather than as a named message type.
124    #[test]
125    fn lspsend_accepts_any_json_message() {
126        for message in [
127            serde_json::json!({ "jsonrpc": "2.0", "id": 1, "method": "initialize" }),
128            serde_json::json!([1, 2, 3]),
129            serde_json::json!("a bare string"),
130            serde_json::Value::Null,
131        ] {
132            let req: LspSendReq = serde_json::from_value(serde_json::json!({
133                "server_id": "srv-1",
134                "message": message.clone(),
135            }))
136            .unwrap_or_else(|e| panic!("{message} should deserialize, got {e}"));
137            assert_eq!(req.message, message, "the proxy must not reshape the payload");
138        }
139    }
140
141    /// A missing `server_id` is an error rather than a silent no-op. The
142    /// untyped handlers answered `lspstop: missing field ...`; `register_typed`
143    /// rejects it before the handler body runs, so the request never reaches
144    /// the supervisor either way.
145    #[tokio::test]
146    async fn a_malformed_request_is_rejected_rather_than_run() {
147        let state = crate::server::tests::test_state();
148        let (engine, mut rx) = WshRpcEngine::new();
149        register_lsp_handlers(&engine, &state);
150
151        engine.handle_message(RpcMessage {
152            command: "lspstop".to_string(),
153            reqid: "req-1".to_string(),
154            data: Some(serde_json::json!({})),
155            ..Default::default()
156        });
157        let resp = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv())
158            .await
159            .unwrap()
160            .unwrap();
161        assert!(
162            resp.error.contains("server_id"),
163            "expected a missing-field error naming the field, got {:?}",
164            resp.error,
165        );
166    }
167}