feat(code-insight): compact Language Services status widget for the current file (#7562)

The status item is a compact icon whose badge reflects the active file's servers; the popup lists the current file's servers first, then the project's others, keeping restart, log and update actions.

Fixes #7489
Цей коміт міститься в:
l0ng-ai authored and GitHub committed 2026-12-02 23:23:37 +08:00
1 джерело 37f2dd3ced
коміт 18f28cd804
9 files changed
+239 -97

No files matched your search

+6
Переглянути файл
@@ -2188,6 +2188,11 @@ pub fn lsp_servers(host: &Host, window: &str) -> IdeResult<Vec<ServerInfo>> {
Ok(host.project(window)?.lsp.servers())
}
#[command(trust = always)]
pub fn lsp_document_servers(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec<ServerId>> {
Ok(host.project(window)?.lsp.document_servers(doc))
}
/// Answers a server's `window/showMessageRequest` question (`null`: dismissed). It runs where the
/// language server runs: the question waits in that process, a remote project's server included.
#[command(trust = trusted)]
@@ -3462,6 +3467,7 @@ ide_command::domain!(
lsp_stop,
lsp_semantic_tokens,
lsp_servers,
lsp_document_servers,
lsp_signature_help,
lsp_signature_info,
lsp_type_hierarchy,
+5
Переглянути файл
@@ -4746,6 +4746,11 @@ impl LspManager {
.collect()
}
/// Servers associated with this open document, including ones still starting or stopped.
pub fn document_servers(&self, doc: DocId) -> Vec<ide_core::ServerId> {
self.docs.lock().get(&doc).map(|d| d.servers.iter().map(|a| a.server.id).collect()).unwrap_or_default()
}
pub async fn restart(&self, server: ide_core::ServerId) -> IdeResult<()> {
let s = {
// Only the restart itself holds the lock: a start can take minutes (a Gradle or
+1
Переглянути файл
@@ -443,6 +443,7 @@ lsp_completion trusted project_host bin
lsp_document_colors trusted project_host bindings async
lsp_document_highlights trusted project_host bindings async
lsp_document_links trusted project_host bindings async
lsp_document_servers always project_host bindings sync
lsp_edit_argument trusted project_host bindings async
lsp_editable_arguments trusted project_host bindings async
lsp_exception_class_at trusted project_host bindings async
+1
Переглянути файл
@@ -1131,6 +1131,7 @@ export const commands = {
lspDocumentHighlights: (doc: DocId, pos: Pos) => typedError<Highlight[], IdeError>(__TAURI_INVOKE("lsp_document_highlights", { doc, pos })),
/** Links in a document (`href`s, Markdown links, `#include`s…) from its language servers. */
lspDocumentLinks: (doc: DocId) => typedError<DocumentLink[], IdeError>(__TAURI_INVOKE("lsp_document_links", { doc })),
lspDocumentServers: (doc: DocId) => typedError<ServerId[], IdeError>(__TAURI_INVOKE("lsp_document_servers", { doc })),
/**
* Sets an argument of the call at `pos`; the edit reaches the document as the server's
* `workspace/applyEdit`, undoable like any other.
+30 -4
Переглянути файл
@@ -11,7 +11,7 @@
background: var(--success);
}
.busy {
background: var(--accent);
background: var(--warning);
animation: pulse 1.2s var(--ease) infinite alternate;
}
.error {
@@ -31,11 +31,35 @@
}
}
.panel {
width: 340px;
padding: 6px 0;
width: min(340px, calc(100vw - 2 * var(--space-3)));
max-height: min(60vh, 440px);
overflow-y: auto;
padding: var(--space-1-5) 0;
font-family: var(--font-ui);
font-size: var(--fs-ui);
}
.widgetIcons {
position: relative;
display: inline-flex;
align-items: center;
gap: var(--space-0-5);
}
.indicator {
position: absolute;
right: -2px;
bottom: -1px;
margin: 0;
box-shadow: 0 0 0 1px var(--bg-frame);
}
.section + .section {
border-top: 1px solid var(--border-popup);
margin-top: var(--space-1);
padding-top: var(--space-1);
}
.empty {
padding: var(--space-1) var(--space-3);
color: var(--fg-subtle);
}
.header {
padding: 2px 12px 6px;
font-size: var(--fs-small);
@@ -55,7 +79,9 @@
}
.name {
color: var(--fg-emphasis);
margin-right: 8px;
margin-right: var(--space-2);
min-width: 0;
overflow-wrap: anywhere;
}
.status {
color: var(--fg-subtle);
+45 -1
Переглянути файл
@@ -1,10 +1,18 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen } from "@testing-library/react";
import { act, fireEvent, render, screen, within } from "@testing-library/react";
import { registerAction } from "@/platform/actions";
import { useEditorRegistry } from "@/editor/api";
import { useProject } from "@/platform/project";
import { ServerStatus } from "./ServerStatus";
import { useServers, type ServerEntry } from "./servers";
import { useToolUpdates } from "@/workbench/contributions";
const documentServers = vi.hoisted(() => vi.fn(async (_doc: number) => ({ status: "ok", data: [1] })));
vi.mock("@/platform/ipc", async (original) => {
const ipc = await original<typeof import("@/platform/ipc")>();
return { ...ipc, isTauri: () => true, commands: { ...ipc.commands, lspDocumentServers: documentServers } };
});
const ISSUE_49 =
"jdtls needs JDK 25 or newer to run (found JDK 8, 17, 21). Download JDK 25, or pick an installed one in Settings › Languages & Frameworks › Java › Language Server › JDK (it restarts automatically); the project can still target an older Java version.";
@@ -14,9 +22,45 @@ const server = (status: ServerEntry["status"], message: string | null): ServerEn
afterEach(() => {
useServers.setState({ servers: new Map() });
useToolUpdates.setState({ latest: {} });
useEditorRegistry.setState({ active: null });
useProject.setState({ project: null });
});
describe("Language server status popup", () => {
it("puts attached servers first and keeps the status widget compact across editor switches", async () => {
useProject.setState({ project: { root: "/work" } as never });
const file = (doc: number, path: string) => ({ ctx: { doc, path, language: "java" } }) as never;
useEditorRegistry.setState({ active: file(10, "/work/First.java") });
useServers.setState({
servers: new Map([
[1 as never, server("ready", null)],
[2 as never, { ...server("crashed", null), id: 2 as never, name: "java-analyzer" }],
]),
});
documentServers.mockImplementation(async (doc) => ({ status: "ok", data: [doc === 10 ? 1 : 2] }));
render(<ServerStatus />);
const button = await screen.findByRole("button", { name: "Language servers: jdtls" });
expect(button).toHaveTextContent(/^$/);
fireEvent.click(button);
expect(within(screen.getByRole("region", { name: "Running on Current File" })).getByText("jdtls")).toBeVisible();
expect(
within(screen.getByRole("region", { name: "Running on Other Files" })).getByText("java-analyzer"),
).toBeVisible();
act(() => useEditorRegistry.setState({ active: file(11, "/work/Second.java") }));
expect(await screen.findByRole("button", { name: "Language servers: java-analyzer" })).toBeVisible();
expect(
within(screen.getByRole("region", { name: "Running on Current File" })).getByText("java-analyzer"),
).toBeVisible();
act(() => useEditorRegistry.setState({ active: null }));
expect(screen.getByRole("button", { name: "Language servers" })).toHaveTextContent(/^$/);
expect(
within(screen.getByRole("region", { name: "Running on Current File" })).getByText("No language servers"),
).toBeVisible();
});
it("marks a server with a newer version and updates it from its row (#7365)", () => {
const install = vi.fn();
const off = registerAction({ id: "tools.install", title: "Install", run: ({ arg }) => install(arg) });
+145 -92
Переглянути файл
@@ -1,8 +1,10 @@
/** Status bar widget listing language servers, with a popup to stop, restart or configure them. */
import { useMemo, useRef, useState } from "react";
import { useEffect, useMemo, useRef, useState } from "react";
import clsx from "clsx";
import { getAction, executeAction } from "@/platform/actions";
import { BarButton, Button, Icon, IconButton, Popup, T } from "@/ui";
import { BarButton, Button, Icon, IconButton, Popup, T, fileIconName } from "@/ui";
import { useEditorRegistry } from "@/editor/api";
import { call, commands, isTauri, type ServerId } from "@/platform/ipc";
import { downloadJdkActions } from "@/platform/jdk";
import { relativePath, useProject } from "@/platform/project";
import {
@@ -19,31 +21,70 @@ import styles from "./ServerStatus.module.css";
import { tx } from "@/platform/i18n";
import { useToolUpdates } from "@/workbench/contributions";
const MAX_WIDGET_ICONS = 4;
export function ServerStatus() {
const map = useServers((s) => s.servers);
const servers = useMemo(() => [...map.values()].sort((a, b) => serverLabel(a).localeCompare(serverLabel(b))), [map]);
const root = useProject((s) => s.project?.root ?? "");
const [open, setOpen] = useState(false);
const ref = useRef<HTMLButtonElement>(null);
const summary = serversSummary(servers);
const active = useEditorRegistry((s) => s.active?.ctx);
const [association, setAssociation] = useState<{ file: typeof active; root: string; ids: Set<ServerId> }>();
useEffect(() => {
if (!root || !active || !isTauri()) return;
let current = true;
void call(commands.lspDocumentServers(active.doc)).then(
(ids) => {
if (current) setAssociation({ file: active, root, ids: new Set(ids) });
},
() => {
if (current) setAssociation(undefined);
},
);
return () => {
current = false;
};
}, [active, root, map]);
const ids = association?.file === active && association?.root === root ? association.ids : undefined;
const current = servers.filter((s) => ids?.has(s.id));
const others = servers.filter((s) => !ids?.has(s.id));
const summary = serversSummary(current.length ? current : servers);
const currentSummary = current.length ? summary : null;
const shown = current.length > MAX_WIDGET_ICONS ? MAX_WIDGET_ICONS - 1 : current.length;
// features/tools owns installing; without it, fall back to the manual hint text.
const canInstall = !!getAction("tools.install");
const canConfigure = !!getAction("tools.languageServers");
const latestVersions = useToolUpdates((s) => s.latest);
// Installed servers with a newer version; the same tool can back several servers.
const updatable = canInstall ? servers.filter((s) => latestVersions[s.name]) : [];
if (!summary) return null;
if (!root && !servers.length) return null;
return (
<>
<BarButton
ref={ref}
aria-expanded={open}
aria-label={tx`Language servers: ${summary.text}`}
aria-label={currentSummary ? tx`Language servers: ${currentSummary.text}` : tx("Language servers")}
tooltip="Language servers"
onClick={() => setOpen((v) => !v)}
>
<span className={clsx(styles.dot, styles[summary.tone])} aria-hidden />
{summary.text}
<span className={styles.widgetIcons} aria-hidden>
{current.length ? (
current
.slice(0, shown)
.map((server, index) => (
<Icon
key={server.id}
name={index === 0 && active ? fileIconName(active.path) : "file-json"}
size={14}
/>
))
) : (
<Icon name="file-json" size={14} />
)}
{summary && <span className={clsx(styles.dot, styles.indicator, styles[summary.tone])} />}
</span>
{current.length > shown && <span aria-hidden>+{current.length - shown}</span>}
{updatable.length > 0 && (
<Icon
name="arrow-up"
@@ -62,104 +103,116 @@ export function ServerStatus() {
aria-label="Language servers"
>
<div className={styles.panel}>
<div className={styles.header}>
<T>Language Servers</T>
</div>
{servers.map((s) => {
// jdtls without a JDK new enough to run it: "Download JDK 25".
const [jdkFix] = s.status === "misconfigured" ? downloadJdkActions(s.message) : [];
const latest = latestVersions[s.name];
return (
<div key={s.id} className={styles.server}>
<div className={styles.line}>
<span
className={clsx(
styles.dot,
styles[s.status === "missing" && servedByOther(s, servers) ? "idle" : toneOf(s.status)],
)}
aria-hidden
/>
<span className={styles.name}>{serverLabel(s)}</span>
<span className={styles.status}>{STATUS_LABEL[s.status]}</span>
<span className={styles.spacer} />
{jdkFix ? (
<Button
size="small"
onClick={() => {
setOpen(false);
jdkFix.run();
}}
>
{jdkFix.label}
</Button>
) : (
<>
{latest && updatable.includes(s) && (
{[
{ label: tx("Running on Current File"), entries: current },
{ label: tx("Running on Other Files"), entries: others },
].map(({ label, entries }) => (
<section key={label} aria-label={label} className={styles.section}>
<div className={styles.header}>{label}</div>
{entries.length === 0 && (
<div className={styles.empty}>
<T>No language servers</T>
</div>
)}
{entries.map((s) => {
// jdtls without a JDK new enough to run it: "Download JDK 25".
const [jdkFix] = s.status === "misconfigured" ? downloadJdkActions(s.message) : [];
const latest = latestVersions[s.name];
return (
<div key={s.id} className={styles.server}>
<div className={styles.line}>
<span
className={clsx(
styles.dot,
styles[s.status === "missing" && servedByOther(s, servers) ? "idle" : toneOf(s.status)],
)}
aria-hidden
/>
<span className={styles.name}>{serverLabel(s)}</span>
<span className={styles.status}>{STATUS_LABEL[s.status]}</span>
<span className={styles.spacer} />
{jdkFix ? (
<Button
size="small"
aria-label={tx`Update ${s.name}`}
title={tx`Version ${latest} is available.`}
onClick={() => {
setOpen(false);
void executeAction("tools.install", s.name);
jdkFix.run();
}}
>
<T>Update</T>
{jdkFix.label}
</Button>
) : (
<>
{latest && updatable.includes(s) && (
<Button
size="small"
aria-label={tx`Update ${s.name}`}
title={tx`Version ${latest} is available.`}
onClick={() => {
setOpen(false);
void executeAction("tools.install", s.name);
}}
>
<T>Update</T>
</Button>
)}
{s.status === "missing" && canInstall && (
<Button
size="small"
aria-label={tx`Install ${s.name}`}
onClick={() => {
setOpen(false);
void executeAction("tools.install", s.name);
}}
>
<T>Install</T>
</Button>
)}
{canStop(s.status) && (
<IconButton
icon="stop"
size="small"
title={tx`Stop ${serverLabel(s)}`}
onClick={() => void stopServer(s.id)}
/>
)}
{/* A missing server may have been installed outside the IDE since; restarting looks for it again. */}
<IconButton
icon="refresh"
size="small"
title={
s.status === "missing" ? tx`Check for ${s.name} again` : tx`Restart ${serverLabel(s)}`
}
onClick={() => void restartServer(s.id)}
/>
</>
)}
{s.status === "missing" && canInstall && (
<Button
size="small"
aria-label={tx`Install ${s.name}`}
onClick={() => {
setOpen(false);
void executeAction("tools.install", s.name);
}}
>
<T>Install</T>
</Button>
)}
{canStop(s.status) && (
{canConfigure && (
<IconButton
icon="stop"
icon="settings"
size="small"
title={tx`Stop ${serverLabel(s)}`}
onClick={() => void stopServer(s.id)}
title={tx`Configure ${serverLabel(s)}…`}
onClick={() => {
setOpen(false);
void executeAction("tools.languageServers", s.name);
}}
/>
)}
{/* A missing server may have been installed outside the IDE since; restarting looks for it again. */}
<IconButton
icon="refresh"
size="small"
title={s.status === "missing" ? tx`Check for ${s.name} again` : tx`Restart ${serverLabel(s)}`}
onClick={() => void restartServer(s.id)}
/>
</>
)}
{canConfigure && (
<IconButton
icon="settings"
size="small"
title={tx`Configure ${serverLabel(s)}…`}
onClick={() => {
setOpen(false);
void executeAction("tools.languageServers", s.name);
}}
/>
)}
</div>
{(s.languages.length > 0 || s.root) && (
<div className={styles.meta}>
{s.languages.join(", ")}
{s.root && s.root !== root ? ` · ${relativePath(root, s.root) || s.root}` : ""}
</div>
{(s.languages.length > 0 || s.root) && (
<div className={styles.meta}>
{s.languages.join(", ")}
{s.root && s.root !== root ? ` · ${relativePath(root, s.root) || s.root}` : ""}
</div>
)}
{s.message && (
<div className={clsx(styles.message, s.status === "missing" && styles.install)}>{s.message}</div>
)}
</div>
)}
{s.message && (
<div className={clsx(styles.message, s.status === "missing" && styles.install)}>{s.message}</div>
)}
</div>
);
})}
);
})}
</section>
))}
</div>
</Popup>
</>
+3
Переглянути файл
@@ -5222,6 +5222,9 @@
"Package {id} {version} is deprecated ({reasons}); use {alternative} instead": "Package {id} {version} is deprecated ({reasons}); use {alternative} instead",
"Package {id} {version} is deprecated ({reasons})": "Package {id} {version} is deprecated ({reasons})",
"Audit NuGet Packages": "Audit NuGet Packages",
"Running on Current File": "Running on Current File",
"Running on Other Files": "Running on Other Files",
"No language servers": "No language servers",
"Deployed": "Deployed",
"Deploying…": "Deploying…",
"Undeploying…": "Undeploying…",
+3
Переглянути файл
@@ -12121,6 +12121,9 @@
"Package {id} {version} is deprecated ({reasons}); use {alternative} instead": "包 {id} {version} 已弃用({reasons}),请改用 {alternative}",
"Package {id} {version} is deprecated ({reasons})": "包 {id} {version} 已弃用({reasons})",
"Audit NuGet Packages": "审计 NuGet 包",
"Running on Current File": "在当前文件中运行",
"Running on Other Files": "在其他文件中运行",
"No language servers": "没有语言服务器",
"Deployed": "已部署",
"Deploying…": "正在部署…",
"Undeploying…": "正在取消部署…",