From 9decda5f61384740d71bc070b4291a60c1102e8b Mon Sep 17 00:00:00 2001 From: l0ng-ai <24760907+l0ng-ai@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:20:08 +0800 Subject: [PATCH] feat(lsp): stop a language server from the status bar popup Running, busy and starting servers get a Stop button next to Restart. The server shuts down and stays idle until a file it serves is opened again; a notification says it will restart when needed. --- crates/ide-host/src/ops/lsp.rs | 7 +++++ crates/ide-lsp/src/lib.rs | 15 ++++++++++ crates/ide-lsp/tests/mock_server.rs | 23 +++++++++++++++ src-tauri/tests/commands.snap | 1 + src/bindings.ts | 2 ++ .../code-insight/ServerStatus.test.tsx | 17 +++++++++++ src/features/code-insight/ServerStatus.tsx | 21 ++++++++++++-- src/features/code-insight/servers.test.ts | 20 ++++++++++++- src/features/code-insight/servers.ts | 28 +++++++++++++++++++ src/platform/locales/text/es.json | 4 +++ src/platform/locales/text/fr.json | 4 +++ src/platform/locales/text/ko.json | 4 +++ src/platform/locales/text/pl.json | 4 +++ src/platform/locales/text/pt.json | 4 +++ src/platform/locales/text/ru.json | 4 +++ src/platform/locales/text/tr.json | 4 +++ src/platform/locales/text/zh-TW.json | 4 +++ src/platform/locales/text/zh.json | 4 +++ 18 files changed, 167 insertions(+), 3 deletions(-) diff --git a/crates/ide-host/src/ops/lsp.rs b/crates/ide-host/src/ops/lsp.rs index 87cda40032..844603af17 100644 --- a/crates/ide-host/src/ops/lsp.rs +++ b/crates/ide-host/src/ops/lsp.rs @@ -2097,6 +2097,12 @@ pub async fn lsp_restart(host: &Host, window: &str, server: ServerId) -> IdeResu Ok(()) } +/// Stops a language server; it starts again when a file it serves is opened. +#[command(trust = trusted)] +pub async fn lsp_stop(host: &Host, window: &str, server: ServerId) -> IdeResult<()> { + host.project(window)?.lsp.stop(server).await +} + /// Restarts the language servers named `name` in every open project, so a tool installed or /// updated from one window is what all of them run (not only that window's project). pub async fn lsp_restart_named(host: &Host, name: &str) -> IdeResult<()> { @@ -3306,6 +3312,7 @@ ide_command::domain!( lsp_resolve_command, lsp_resolve_completion, lsp_restart, + lsp_stop, lsp_semantic_tokens, lsp_servers, lsp_signature_help, diff --git a/crates/ide-lsp/src/lib.rs b/crates/ide-lsp/src/lib.rs index f52d444827..9dc06e242e 100644 --- a/crates/ide-lsp/src/lib.rs +++ b/crates/ide-lsp/src/lib.rs @@ -4523,6 +4523,21 @@ impl LspManager { } } + /// Stops `server` on request. It stays down until a document it serves is opened again, + /// which starts it like any first start. + pub async fn stop(&self, server: ide_core::ServerId) -> IdeResult<()> { + let _reconfigure = self.reconfigure_lock.lock().await; + let s = self + .servers + .lock() + .iter() + .find(|s| s.id == server) + .cloned() + .ok_or_else(|| IdeError::not_found(format!("unknown language server {server}")))?; + self.stop_instance(&s, true).await; + Ok(()) + } + /// Gracefully stops the current instance (`shutdown` + `exit`, then kill). async fn stop_instance(&self, server: &Arc, final_stop: bool) { let Some(run) = server.begin_stop(&self.sink, final_stop) else { diff --git a/crates/ide-lsp/tests/mock_server.rs b/crates/ide-lsp/tests/mock_server.rs index 281d8d2cc9..4c7aa8189b 100644 --- a/crates/ide-lsp/tests/mock_server.rs +++ b/crates/ide-lsp/tests/mock_server.rs @@ -4990,6 +4990,29 @@ async fn features_limit_what_a_server_is_used_for() { assert!(!h.events.lock().iter().any(|e| matches!(e, IdeEvent::Diagnostics { source, .. } if source == "rope"))); } +#[tokio::test(flavor = "multi_thread")] +async fn a_stopped_server_starts_again_when_a_file_it_serves_opens() { + let h = harness(&[("mock", incremental_caps())]); + let (_, a) = h.open("a.mk", "x"); + h.wait_status("mock", ServerStatus::Ready).await; + let s = h.launcher.state("mock"); + let id = h.mgr.servers()[0].id; + tokio::time::timeout(Duration::from_secs(5), h.mgr.stop(id)).await.unwrap().unwrap(); + assert_eq!(s.requested("shutdown").len(), 1); + assert_eq!(s.notified("exit").len(), 1); + assert_eq!(h.statuses("mock").last(), Some(&ServerStatus::Stopped)); + tokio::time::sleep(Duration::from_millis(100)).await; + assert_eq!(s.launches.load(Ordering::SeqCst), 1, "stays down until needed"); + + let (_, b) = h.open("b.mk", "y"); + h.wait_status("mock", ServerStatus::Ready).await; + assert_eq!(s.launches.load(Ordering::SeqCst), 2); + let opened: Vec = + s.notified("textDocument/didOpen").iter().map(|p| p["textDocument"]["uri"].clone()).collect(); + assert!(opened.contains(&json!(uri_of(&a))) && opened.contains(&json!(uri_of(&b))), "{opened:?}"); + h.mgr.shutdown_all().await; +} + #[tokio::test(flavor = "multi_thread")] async fn shutdown_all_stops_gracefully() { let h = harness(&[("mock", incremental_caps())]); diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index 3246fb8bfd..e2009ed96a 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -450,6 +450,7 @@ lsp_signature_info trusted project_host bin lsp_snapshot_completion trusted project_host bindings async lsp_snapshot_diagnostics trusted project_host bindings async lsp_source_action_text trusted project_host bindings async +lsp_stop trusted project_host bindings async lsp_type_hierarchy trusted project_host bindings async lsp_virtual_document trusted project_host bindings async lsp_workspace_symbols trusted project_host bindings async diff --git a/src/bindings.ts b/src/bindings.ts index cee9d58861..58f61043e7 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -1180,6 +1180,8 @@ export const commands = { lspSnapshotCompletion: (path: string, text: string, pos: Pos, request: RequestId) => typedError(__TAURI_INVOKE("lsp_snapshot_completion", { path, text, pos, request })), lspSnapshotDiagnostics: (path: string, text: string, request: RequestId) => typedError(__TAURI_INVOKE("lsp_snapshot_diagnostics", { path, text, request })), lspSourceActionText: (path: string, text: string, kind: string, request: RequestId) => typedError(__TAURI_INVOKE("lsp_source_action_text", { path, text, kind, request })), + /** Stops a language server; it starts again when a file it serves is opened. */ + lspStop: (server: ServerId) => typedError(__TAURI_INVOKE("lsp_stop", { server })), lspTypeHierarchy: (doc: DocId, pos: Pos, direction: HierarchyDirection) => typedError(__TAURI_INVOKE("lsp_type_hierarchy", { doc, pos, direction })), /** * Contents of a read-only language-server document, including JDT library diff --git a/src/features/code-insight/ServerStatus.test.tsx b/src/features/code-insight/ServerStatus.test.tsx index d3600596d8..d32ee6b2c0 100644 --- a/src/features/code-insight/ServerStatus.test.tsx +++ b/src/features/code-insight/ServerStatus.test.tsx @@ -57,4 +57,21 @@ describe("Language server status popup", () => { fireEvent.click(screen.getByRole("button", { name: /Language servers/ })); expect(screen.getByRole("button", { name: "Restart jdtls" })).toBeEnabled(); }); + + it("offers Stop only for a server that is up or starting", () => { + for (const [status, stoppable] of [ + ["ready", true], + ["busy", true], + ["starting", true], + ["stopped", false], + ["crashed", false], + ["missing", false], + ] as const) { + useServers.setState({ servers: new Map([[1 as never, server(status, null)]]) }); + const { unmount } = render(); + fireEvent.click(screen.getByRole("button", { name: /Language servers/ })); + expect(!!screen.queryByRole("button", { name: "Stop jdtls" }), status).toBe(stoppable); + unmount(); + } + }); }); diff --git a/src/features/code-insight/ServerStatus.tsx b/src/features/code-insight/ServerStatus.tsx index f6115f2cee..be5bea54e2 100644 --- a/src/features/code-insight/ServerStatus.tsx +++ b/src/features/code-insight/ServerStatus.tsx @@ -1,11 +1,20 @@ -/** Status bar widget listing language servers, with a popup to restart or configure them. */ +/** Status bar widget listing language servers, with a popup to stop, restart or configure them. */ import { useMemo, useRef, useState } from "react"; import clsx from "clsx"; import { getAction, executeAction } from "@/platform/actions"; import { BarButton, Button, IconButton, Popup, T } from "@/ui"; import { downloadJdkActions } from "@/platform/jdk"; import { relativePath, useProject } from "@/platform/project"; -import { STATUS_LABEL, restartServer, servedByOther, serverLabel, serversSummary, useServers } from "./servers"; +import { + STATUS_LABEL, + canStop, + restartServer, + servedByOther, + serverLabel, + serversSummary, + stopServer, + useServers, +} from "./servers"; import styles from "./ServerStatus.module.css"; import { tx } from "@/platform/i18n"; @@ -84,6 +93,14 @@ export function ServerStatus() { Install )} + {canStop(s.status) && ( + void stopServer(s.id)} + /> + )} {/* A missing server may have been installed outside the IDE since; restarting looks for it again. */} { pending.push((data) => resolve({ status: "ok", data })); }), lspRestart: () => Promise.resolve({ status: "error", error: { kind: "unavailable", message: "not found" } }), + lspStop: () => Promise.resolve({ status: "ok", data: null }), }, }; }); @@ -23,7 +24,7 @@ vi.mock("@/platform/ipc", async (importOriginal) => { const { emitLocalIdeEvent } = await import("@/platform/ipc"); const { useProject } = await import("@/platform/project"); const { provideNotificationService } = await import("@/workbench/contributions"); -const { BUSY_SHOW_DELAY_MS, installServerEvents, linterCovers, restartServer, serversSummary, useServers } = +const { BUSY_SHOW_DELAY_MS, installServerEvents, linterCovers, restartServer, serversSummary, stopServer, useServers } = await import("./servers"); describe("server status", () => { @@ -41,6 +42,23 @@ describe("server status", () => { useServers.setState({ servers: new Map() }); }); + it("says a stopped server comes back when it is needed", async () => { + const id = 8 as ServerId; + const entry: ServerEntry = { id, name: "gopls", status: "ready", languages: ["go"], root: null, message: null }; + useServers.setState({ servers: new Map([[id, entry]]) }); + const notify = vi.fn(); + provideNotificationService({ notify } as never); + await stopServer(id); + expect(notify).toHaveBeenCalledWith( + expect.objectContaining({ + level: "info", + title: "gopls server stopped", + body: "The server will restart automatically when needed", + }), + ); + useServers.setState({ servers: new Map() }); + }); + it("keeps a status that arrived after the snapshot was requested", async () => { useProject.setState({ project: { name: "p", root: "/p", trusted: true, isGit: false, settings: {} } as never }); dispose = installServerEvents(); diff --git a/src/features/code-insight/servers.ts b/src/features/code-insight/servers.ts index 6bb2436b90..3b710fd764 100644 --- a/src/features/code-insight/servers.ts +++ b/src/features/code-insight/servers.ts @@ -124,6 +124,34 @@ export async function restartServer(id: ServerId) { } } +/** Stops a server until it is needed again: opening a file it serves starts it. */ +export async function stopServer(id: ServerId) { + const entry = useServers.getState().servers.get(id); + const name = entry ? serverLabel(entry) : String(id); + try { + await call(commands.lspStop(id)); + } catch (e) { + notifications().notify({ + group: "lsp", + level: "error", + title: "Failed to stop language server", + body: e instanceof Error ? e.message : String(e), + }); + return; + } + notifications().notify({ + group: "lsp", + level: "info", + title: tx`${name} server stopped`, + body: tx("The server will restart automatically when needed"), + }); +} + +/** A server that is up (or coming up) and can be stopped. */ +export function canStop(status: ServerStatus): boolean { + return status === "ready" || status === "busy" || status === "starting"; +} + export function installServerEvents(): () => void { const off = onIdeEvent("languageServer", (e) => { const known = useServers.getState().servers.has(e.server); diff --git a/src/platform/locales/text/es.json b/src/platform/locales/text/es.json index 260815cbca..7f316646fa 100644 --- a/src/platform/locales/text/es.json +++ b/src/platform/locales/text/es.json @@ -840,6 +840,7 @@ "FIXME comment": "Comentario FIXME", "Failed": "Falló", "Failed to restart language server": "Error al reiniciar el servidor de lenguaje", + "Failed to stop language server": "Error al detener el servidor de lenguaje", "Fallback font": "Fuente de respaldo", "Fallback font:": "Fuente de respaldo:", "Fetch": "Fetch", @@ -4004,6 +4005,9 @@ "Language servers: {text}": "Servidores de lenguaje: {text}", "Install {name}": "Instalar {name}", "Restart {name}": "Reiniciar {name}", + "Stop {name}": "Detener {name}", + "{name} server stopped": "Servidor {name} detenido", + "The server will restart automatically when needed": "El servidor se reiniciará automáticamente cuando sea necesario", "{count} error": "{count} error", "{count} errors": "{count} errores", "{count} warning": "{count} advertencia", diff --git a/src/platform/locales/text/fr.json b/src/platform/locales/text/fr.json index a3e264919d..7c46baa51f 100644 --- a/src/platform/locales/text/fr.json +++ b/src/platform/locales/text/fr.json @@ -779,6 +779,7 @@ "FIXME comment": "Commentaire FIXME", "Failed": "Échec", "Failed to restart language server": "Échec du redémarrage du serveur de langage", + "Failed to stop language server": "Échec de l'arrêt du serveur de langage", "Fallback font": "Police de secours", "Fallback font:": "Police de secours :", "Fetch": "Fetch", @@ -3873,6 +3874,9 @@ "Language servers: {text}": "Serveurs de langage : {text}", "Install {name}": "Installer {name}", "Restart {name}": "Redémarrer {name}", + "Stop {name}": "Arrêter {name}", + "{name} server stopped": "Serveur {name} arrêté", + "The server will restart automatically when needed": "Le serveur redémarrera automatiquement si nécessaire", "{count} error": "{count} erreur", "{count} errors": "{count} erreurs", "{count} warning": "{count} avertissement", diff --git a/src/platform/locales/text/ko.json b/src/platform/locales/text/ko.json index d9b2c7c49d..2716f866fb 100644 --- a/src/platform/locales/text/ko.json +++ b/src/platform/locales/text/ko.json @@ -877,6 +877,7 @@ "FIXME comment": "FIXME 주석", "Failed": "실패", "Failed to restart language server": "언어 서버를 다시 시작하지 못했습니다", + "Failed to stop language server": "언어 서버를 중지하지 못했습니다", "Fallback font": "대체 글꼴", "Fallback font:": "대체 글꼴:", "Fetch": "페치", @@ -4064,6 +4065,9 @@ "Language servers: {text}": "언어 서버: {text}", "Install {name}": "{name} 설치", "Restart {name}": "{name} 다시 시작", + "Stop {name}": "{name} 중지", + "{name} server stopped": "{name} 서버가 중지되었습니다", + "The server will restart automatically when needed": "필요할 때 서버가 자동으로 다시 시작됩니다", "{count} error": "오류 {count}개", "{count} errors": "오류 {count}개", "{count} warning": "경고 {count}개", diff --git a/src/platform/locales/text/pl.json b/src/platform/locales/text/pl.json index 4391bea243..053c2f0f4e 100644 --- a/src/platform/locales/text/pl.json +++ b/src/platform/locales/text/pl.json @@ -832,6 +832,7 @@ "FIXME comment": "Komentarz FIXME", "Failed": "Nie powiodło się", "Failed to restart language server": "Nie udało się zrestartować serwera językowego", + "Failed to stop language server": "Nie udało się zatrzymać serwera językowego", "Fallback font": "Czcionka zastępcza", "Fallback font:": "Czcionka zastępcza:", "Fetch": "Pobierz dane (Fetch)", @@ -3964,6 +3965,9 @@ "Language servers: {text}": "Serwery językowe: {text}", "Install {name}": "Zainstaluj {name}", "Restart {name}": "Uruchom ponownie {name}", + "Stop {name}": "Zatrzymaj {name}", + "{name} server stopped": "Serwer {name} zatrzymany", + "The server will restart automatically when needed": "Serwer uruchomi się ponownie automatycznie, gdy będzie potrzebny", "{count} error": "{count} błąd", "{count} errors": "Liczba błędów: {count}", "{count} warning": "{count} ostrzeżenie", diff --git a/src/platform/locales/text/pt.json b/src/platform/locales/text/pt.json index 789520ae9a..3ed42fc0d7 100644 --- a/src/platform/locales/text/pt.json +++ b/src/platform/locales/text/pt.json @@ -832,6 +832,7 @@ "FIXME comment": "Comentário FIXME", "Failed": "Falhou", "Failed to restart language server": "Falha ao reiniciar o servidor de linguagem", + "Failed to stop language server": "Falha ao parar o servidor de linguagem", "Fallback font": "Fonte reserva", "Fallback font:": "Fonte reserva:", "Fetch": "Fetch", @@ -3970,6 +3971,9 @@ "Language servers: {text}": "Servidores de linguagem: {text}", "Install {name}": "Instalar {name}", "Restart {name}": "Reiniciar {name}", + "Stop {name}": "Parar {name}", + "{name} server stopped": "Servidor {name} parado", + "The server will restart automatically when needed": "O servidor será reiniciado automaticamente quando necessário", "{count} error": "{count} erro", "{count} errors": "{count} erros", "{count} warning": "{count} aviso", diff --git a/src/platform/locales/text/ru.json b/src/platform/locales/text/ru.json index 89618d2397..55fa9da0b9 100644 --- a/src/platform/locales/text/ru.json +++ b/src/platform/locales/text/ru.json @@ -1921,6 +1921,7 @@ "FIXME comment": "Комментарий FIXME", "Failed": "Сбой", "Failed to restart language server": "Не удалось перезапустить языковой сервер", + "Failed to stop language server": "Не удалось остановить языковой сервер", "Fallback font": "Резервный шрифт", "Fallback font:": "Резервный шрифт:", "Fetch": "Получить", @@ -5456,6 +5457,9 @@ "Language servers: {text}": "Языковые серверы: {text}", "Install {name}": "Установить {name}", "Restart {name}": "Перезапустить {name}", + "Stop {name}": "Остановить {name}", + "{name} server stopped": "Сервер {name} остановлен", + "The server will restart automatically when needed": "Сервер автоматически перезапустится при необходимости", "Check for {name} again": "Проверить наличие {name} снова", "{name} is still not installed": "{name} всё ещё не установлен", "{count} error": "{count} ошибка", diff --git a/src/platform/locales/text/tr.json b/src/platform/locales/text/tr.json index 3a81b26e5f..8f76cb278e 100644 --- a/src/platform/locales/text/tr.json +++ b/src/platform/locales/text/tr.json @@ -3602,6 +3602,7 @@ "FIXME comment": "FIXME yorumu", "Failed": "Başarısız", "Failed to restart language server": "Dil sunucusu yeniden başlatılamadı", + "Failed to stop language server": "Dil sunucusu durdurulamadı", "Fallback font": "Yedek yazı tipi", "Fallback font:": "Yedek yazı tipi:", "Fetch": "Getir", @@ -6669,6 +6670,9 @@ "Language servers: {text}": "Dil sunucuları: {text}", "Install {name}": "{name} Yükle", "Restart {name}": "{name} Yeniden Başlat", + "Stop {name}": "{name} durdur", + "{name} server stopped": "{name} sunucusu durduruldu", + "The server will restart automatically when needed": "Sunucu gerektiğinde otomatik olarak yeniden başlatılacak", "{count} error": "{count} hata", "{count} errors": "{count} hata", "{count} warning": "{count} uyarı", diff --git a/src/platform/locales/text/zh-TW.json b/src/platform/locales/text/zh-TW.json index b7473a22e4..eef3125244 100644 --- a/src/platform/locales/text/zh-TW.json +++ b/src/platform/locales/text/zh-TW.json @@ -1537,6 +1537,7 @@ "FIXME comment": "FIXME 註解", "Failed": "失敗", "Failed to restart language server": "重啟語言伺服器失敗", + "Failed to stop language server": "停止語言伺服器失敗", "Fallback font": "備用字型", "Fallback font:": "備用字型:", "Fetch": "取得", @@ -5022,6 +5023,9 @@ "Language servers: {text}": "語言伺服器:{text}", "Install {name}": "安裝 {name}", "Restart {name}": "重啟 {name}", + "Stop {name}": "停止 {name}", + "{name} server stopped": "{name} 伺服器已停止", + "The server will restart automatically when needed": "需要時伺服器會自動重新啟動", "Check for {name} again": "重新檢測 {name}", "{name} is still not installed": "{name} 仍未安裝", "{count} error": "{count} 個錯誤", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index c6c9b2d3df..07d5b18979 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -2076,6 +2076,7 @@ "FIXME comment": "FIXME 注释", "Failed": "失败", "Failed to restart language server": "重启语言服务器失败", + "Failed to stop language server": "停止语言服务器失败", "Fallback font": "备用字体", "Fallback font:": "备用字体:", "Fetch": "获取", @@ -5778,6 +5779,9 @@ "Language servers: {text}": "语言服务器:{text}", "Install {name}": "安装 {name}", "Restart {name}": "重启 {name}", + "Stop {name}": "停止 {name}", + "{name} server stopped": "{name} 服务器已停止", + "The server will restart automatically when needed": "需要时服务器会自动重启", "Check for {name} again": "重新检测 {name}", "{name} is still not installed": "{name} 仍未安装", "{count} error": "{count} 个错误",