A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
improvement: lsp status icon and refresh (#8011)
Myles Scolnickfb28793ad585
diff --git a/Makefile b/Makefileindex 94834686f4..bf6310d038 100644--- a/Makefile+++ b/Makefile@@ -54,7 +54,7 @@ marimo/_lsp: $(shell find packages/lsp)./scripts/buildlsp.sh.PHONY: dev-dev:+dev: fe-codegen@echo "Starting development servers..."@# Start both processes, with marimo in background@(trap 'kill %1; exit' INT; \diff --git a/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx b/frontend/src/components/editor/chrome/wrapper/app-chrome.tsxindex e8ea0552bb..abc99270c8 100644--- a/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx+++ b/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx@@ -37,6 +37,7 @@ import {type PanelType,} from "../types";import { BackendConnectionStatus } from "./footer-items/backend-status";+import { LspStatus } from "./footer-items/lsp-status";import { PanelsWrapper } from "./panels";import { PendingAICells } from "./pending-ai-cells";import { useAiPanelTab } from "./useAiPanel";@@ -490,6 +491,7 @@ export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {/><div className="border-l border-border h-4 mx-1" /><BackendConnectionStatus />+ <LspStatus /><div className="flex-1" /><Buttonsize="xs"diff --git a/frontend/src/components/editor/chrome/wrapper/footer-items/lsp-status.tsx b/frontend/src/components/editor/chrome/wrapper/footer-items/lsp-status.tsxnew file mode 100644index 0000000000..871403ac0a--- /dev/null+++ b/frontend/src/components/editor/chrome/wrapper/footer-items/lsp-status.tsx@@ -0,0 +1,178 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { atom, useAtomValue, useSetAtom } from "jotai";+import { AlertCircleIcon, CheckCircle2Icon } from "lucide-react";+import type React from "react";+import { Spinner } from "@/components/icons/spinner";+import { Tooltip } from "@/components/ui/tooltip";+import { toast } from "@/components/ui/use-toast";+import { API } from "@/core/network/api";+import { connectionAtom } from "@/core/network/connection";+import type {+ LspHealthResponse,+ LspRestartRequest,+ LspRestartResponse,+} from "@/core/network/types";+import { isAppConnected } from "@/core/websocket/connection-utils";+import { useAsyncData } from "@/hooks/useAsyncData";+import { useInterval } from "@/hooks/useInterval";++const CHECK_LSP_HEALTH_INTERVAL_MS = 60_000;++export const lspHealthAtom = atom<LspHealthResponse | null>(null);++export const LspStatus: React.FC = () => {+ const connection = useAtomValue(connectionAtom).state;+ const setLspHealth = useSetAtom(lspHealthAtom);++ const { isFetching, data, refetch } = useAsyncData(async () => {+ if (!isAppConnected(connection)) {+ return null;+ }++ try {+ const health = await API.get<LspHealthResponse>("/lsp/health");+ setLspHealth(health);+ return health;+ } catch {+ return null;+ }+ }, [connection]);++ useInterval(refetch, {+ delayMs: isAppConnected(connection) ? CHECK_LSP_HEALTH_INTERVAL_MS : null,+ whenVisible: true,+ });++ const handleRestart = async () => {+ try {+ const result = await API.post<LspRestartRequest, LspRestartResponse>(+ "/lsp/restart",+ {},+ );++ if (result.success) {+ toast({+ title: "LSP Servers Restarted",+ description:+ result.restarted.length > 0+ ? `Restarted: ${result.restarted.join(", ")}`+ : "No servers needed restart",+ });+ } else {+ toast({+ variant: "danger",+ title: "LSP Restart Failed",+ description: Object.entries(result.errors ?? {})+ .map(([k, v]) => `${k}: ${v}`)+ .join("\n"),+ });+ }++ // Refresh health status+ refetch();+ } catch (error) {+ toast({+ variant: "danger",+ title: "LSP Restart Failed",+ description: error instanceof Error ? error.message : "Unknown error",+ });+ }+ };++ // Don't show if no LSP servers are configured+ if (!data || data.servers.length === 0) {+ return null;+ }++ const getStatusIcon = () => {+ if (isFetching) {+ return <Spinner size="small" />;+ }++ if (!data) {+ return <AlertCircleIcon className="w-4 h-4" />;+ }++ switch (data.status) {+ case "healthy":+ return <CheckCircle2Icon className="w-4 h-4 text-(--green-9)" />;+ case "degraded":+ return <AlertCircleIcon className="w-4 h-4 text-(--yellow-11)" />;+ case "unhealthy":+ return <AlertCircleIcon className="w-4 h-4 text-(--yellow-11)" />;+ }+ };++ const getServerStatusDisplay = (+ status: "starting" | "running" | "stopped" | "crashed" | "unresponsive",+ lastPingMs: number | null | undefined,+ ) => {+ switch (status) {+ case "running":+ return `✓ OK${lastPingMs == null ? "" : ` (${lastPingMs.toFixed(0)}ms)`}`;+ case "starting":+ return "⋯ Starting";+ case "stopped":+ return "✗ Stopped";+ case "crashed":+ return "✗ Crashed";+ case "unresponsive":+ return "✗ Not responding";+ }+ };++ const getServerStatusColor = (+ status: "starting" | "running" | "stopped" | "crashed" | "unresponsive",+ ) => {+ switch (status) {+ case "running":+ return "text-(--green-9)";+ case "starting":+ return "text-(--yellow-11)";+ default:+ return "text-(--red-9)";+ }+ };++ const tooltipContent = (+ <div className="text-sm">+ <b>LSP Status</b>+ <div className="mt-1 text-xs space-y-1">+ {data?.servers.map((server) => (+ <div key={server.serverId} className="flex justify-between gap-2">+ <span>{server.serverId}</span>+ <span className={getServerStatusColor(server.status)}>+ {getServerStatusDisplay(server.status, server.lastPingMs)}+ </span>+ </div>+ ))}+ </div>+ {data?.status === "healthy" ? null : (+ <div className="mt-2 text-xs text-muted-foreground">+ Click to restart failed servers+ </div>+ )}+ </div>+ );++ const handleClick = () => {+ if (data?.status !== "healthy") {+ void handleRestart();+ }+ };++ return (+ <Tooltip content={tooltipContent} data-testid="footer-lsp-status">+ <button+ type="button"+ onClick={handleClick}+ className="p-1 hover:bg-accent rounded flex items-center gap-1.5 text-xs text-muted-foreground"+ data-testid="lsp-status"+ >+ {getStatusIcon()}+ <span>LSP</span>+ </button>+ </Tooltip>+ );+};diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.tsindex 977dc2f8a2..3afc580b92 100644--- a/frontend/src/core/network/types.ts+++ b/frontend/src/core/network/types.ts@@ -100,6 +100,10 @@ export type InvokeAiToolRequest = schemas["InvokeAiToolRequest"];export type InvokeAiToolResponse = schemas["InvokeAiToolResponse"];export type ClearCacheRequest = schemas["ClearCacheRequest"];export type GetCacheInfoRequest = schemas["GetCacheInfoRequest"];+export type LspHealthResponse = schemas["LspHealthResponse"];+export type LspRestartRequest = schemas["LspRestartRequest"];+export type LspRestartResponse = schemas["LspRestartResponse"];+export type LspServerHealth = schemas["LspServerHealth"];/*** Requests sent to the BE during run/edit mode.diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.pyindex b48f664b02..200170e4f6 100644--- a/marimo/_cli/development/commands.py+++ b/marimo/_cli/development/commands.py@@ -9,37 +9,32 @@ from pathlib import Pathfrom typing import TYPE_CHECKING, Anyimport click-import msgspec-import msgspec.json-from marimo._cli.print import orangefrom marimo._data.models import DataTypefrom marimo._messaging.errors import Error as MarimoErrorfrom marimo._messaging.notification import NotificationMessagefrom marimo._runtime.commands import CommandMessage-from marimo._session.state.serialize import (- serialize_notebook,- serialize_session_view,-)-from marimo._utils.code import hash_codeif TYPE_CHECKING:import psutildef _generate_server_api_schema() -> dict[str, Any]:+ import msgspec+ import msgspec.jsonfrom starlette.schemas import SchemaGeneratorimport marimo._config.config as configimport marimo._data.models as dataimport marimo._messaging.errors as errors- import marimo._messaging.notification as notification+ import marimo._messaging.notification as notificationsimport marimo._runtime.commands as commandsimport marimo._secrets.models as secrets_modelsimport marimo._server.models.completion as completionimport marimo._server.models.export as exportimport marimo._server.models.files as filesimport marimo._server.models.home as home+ import marimo._server.models.lsp as lspimport marimo._server.models.models as modelsimport marimo._server.models.packages as packagesimport marimo._server.models.secrets as secrets@@ -97,41 +92,41 @@ def _generate_server_api_schema() -> dict[str, Any]:secrets_models.SecretKeysWithProvider,secrets.CreateSecretRequest,# Operations- notification.CellNotification,- notification.HumanReadableStatus,- notification.FunctionCallResultNotification,- notification.UIElementMessageNotification,- notification.RemoveUIElementsNotification,- notification.InterruptedNotification,- notification.CompletedRunNotification,- notification.KernelReadyNotification,- notification.CompletionResultNotification,- notification.AlertNotification,- notification.MissingPackageAlertNotification,- notification.InstallingPackageAlertNotification,- notification.ReconnectedNotification,- notification.BannerNotification,- notification.ReloadNotification,- notification.VariableDeclarationNotification,- notification.VariableValue,- notification.VariablesNotification,- notification.VariableValuesNotification,- notification.DatasetsNotification,- notification.DataColumnPreviewNotification,- notification.SQLTablePreviewNotification,- notification.SQLTableListPreviewNotification,- notification.DataSourceConnectionsNotification,- notification.SecretKeysResultNotification,- notification.CacheClearedNotification,- notification.CacheInfoNotification,- notification.QueryParamsSetNotification,- notification.QueryParamsAppendNotification,- notification.QueryParamsDeleteNotification,- notification.QueryParamsClearNotification,- notification.UpdateCellCodesNotification,- notification.UpdateCellIdsNotification,- notification.FocusCellNotification,- notification.NotificationMessage,+ notifications.CellNotification,+ notifications.HumanReadableStatus,+ notifications.FunctionCallResultNotification,+ notifications.UIElementMessageNotification,+ notifications.RemoveUIElementsNotification,+ notifications.InterruptedNotification,+ notifications.CompletedRunNotification,+ notifications.KernelReadyNotification,+ notifications.CompletionResultNotification,+ notifications.AlertNotification,+ notifications.MissingPackageAlertNotification,+ notifications.InstallingPackageAlertNotification,+ notifications.ReconnectedNotification,+ notifications.BannerNotification,+ notifications.ReloadNotification,+ notifications.VariableDeclarationNotification,+ notifications.VariableValue,+ notifications.VariablesNotification,+ notifications.VariableValuesNotification,+ notifications.DatasetsNotification,+ notifications.DataColumnPreviewNotification,+ notifications.SQLTablePreviewNotification,+ notifications.SQLTableListPreviewNotification,+ notifications.DataSourceConnectionsNotification,+ notifications.SecretKeysResultNotification,+ notifications.CacheClearedNotification,+ notifications.CacheInfoNotification,+ notifications.QueryParamsSetNotification,+ notifications.QueryParamsAppendNotification,+ notifications.QueryParamsDeleteNotification,+ notifications.QueryParamsClearNotification,+ notifications.UpdateCellCodesNotification,+ notifications.UpdateCellIdsNotification,+ notifications.FocusCellNotification,+ notifications.NotificationMessage,# aiChatMessage,ToolDefinition,@@ -180,6 +175,10 @@ def _generate_server_api_schema() -> dict[str, Any]:packages.PackageOperationResponse,packages.RemovePackageRequest,packages.DependencyTreeResponse,+ lsp.LspHealthResponse,+ lsp.LspRestartRequest,+ lsp.LspRestartResponse,+ lsp.LspServerHealth,home.OpenTutorialRequest,home.RecentFilesResponse,home.RunningNotebooksResponse,@@ -341,6 +340,8 @@ def list_processes() -> None:marimo development ps list"""+ from marimo._cli.print import orange+# pretty print processesresult = get_marimo_processes()for proc in result:@@ -536,6 +537,11 @@ def preview(file_path: Path, port: int, host: str, headless: bool) -> None:from marimo._server.export import run_app_until_completionfrom marimo._server.file_router import AppFileRouterfrom marimo._server.utils import asyncio_run+ from marimo._session.state.serialize import (+ serialize_notebook,+ serialize_session_view,+ )+ from marimo._utils.code import hash_codefrom marimo._utils.marimo_path import MarimoPath# Create file manager for the notebookdiff --git a/marimo/_server/api/endpoints/lsp.py b/marimo/_server/api/endpoints/lsp.pynew file mode 100644index 0000000000..2cb8ebefc1--- /dev/null+++ b/marimo/_server/api/endpoints/lsp.py@@ -0,0 +1,61 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++from typing import TYPE_CHECKING++from starlette.authentication import requires++from marimo._server.api.deps import AppState+from marimo._server.api.utils import parse_request+from marimo._server.models.lsp import (+ LspHealthResponse,+ LspRestartRequest,+ LspRestartResponse,+)+from marimo._server.router import APIRouter++if TYPE_CHECKING:+ from starlette.requests import Request++# Router for LSP endpoints+router = APIRouter()++[email protected]("/health")+@requires("edit")+async def lsp_health(request: Request) -> LspHealthResponse:+ """+ responses:+ 200:+ description: Get health status of all LSP servers+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/LspHealthResponse"+ """+ app_state = AppState(request)+ return await app_state.session_manager.lsp_server.get_health()++[email protected]("/restart")+@requires("edit")+async def lsp_restart(request: Request) -> LspRestartResponse:+ """+ requestBody:+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/LspRestartRequest"+ responses:+ 200:+ description: Restart LSP servers+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/LspRestartResponse"+ """+ app_state = AppState(request)+ body = await parse_request(request, cls=LspRestartRequest)+ return await app_state.session_manager.lsp_server.restart(+ server_ids=body.server_ids+ )diff --git a/marimo/_server/api/router.py b/marimo/_server/api/router.pyindex f30839c278..6abed452e4 100644--- a/marimo/_server/api/router.py+++ b/marimo/_server/api/router.py@@ -23,6 +23,7 @@ from marimo._server.api.endpoints.files import router as files_routerfrom marimo._server.api.endpoints.health import router as health_routerfrom marimo._server.api.endpoints.home import router as home_routerfrom marimo._server.api.endpoints.login import router as login_router+from marimo._server.api.endpoints.lsp import router as lsp_routerfrom marimo._server.api.endpoints.mpl import router as mpl_routerfrom marimo._server.api.endpoints.packages import router as packages_routerfrom marimo._server.api.endpoints.secrets import router as secrets_router@@ -74,6 +75,7 @@ def build_routes(base_url: str = "") -> list[BaseRoute]:app_router.include_router(packages_router, prefix="/api/packages", name="packages")+ app_router.include_router(lsp_router, prefix="/api/lsp", name="lsp")app_router.include_router(health_router, name="health")app_router.include_router(ws_router, name="ws")app_router.include_router(mpl_router, name="mpl")diff --git a/marimo/_server/lsp.py b/marimo/_server/lsp.pyindex 5e1f4d4efb..a7f2ace9a5 100644--- a/marimo/_server/lsp.py+++ b/marimo/_server/lsp.py@@ -2,7 +2,9 @@from __future__ import annotationsimport asyncio+import socketimport subprocess+import timefrom abc import ABC, abstractmethodfrom pathlib import Pathfrom typing import Any, Literal, Optional, Union, cast@@ -13,6 +15,13 @@ from marimo._config.manager import MarimoConfigReaderfrom marimo._config.settings import GLOBAL_SETTINGSfrom marimo._dependencies.dependencies import DependencyManagerfrom marimo._messaging.notification import AlertNotification+from marimo._server.models.lsp import (+ LspHealthResponse,+ LspRestartResponse,+ LspServerHealth,+ LspServerId,+ LspServerStatus,+)from marimo._tracer import server_tracerfrom marimo._utils.net import find_free_portfrom marimo._utils.paths import marimo_package_path@@ -37,6 +46,16 @@ class LspServer(ABC):def is_running(self) -> bool:pass+ @abstractmethod+ async def get_health(self) -> LspHealthResponse:+ pass++ @abstractmethod+ async def restart(+ self, server_ids: Optional[list[LspServerId]] = None+ ) -> LspRestartResponse:+ pass+class BaseLspServer(LspServer):def __init__(self, port: int) -> None:@@ -44,6 +63,7 @@ class BaseLspServer(LspServer):self.process: Optional[subprocess.Popen[str]] = Noneself._health_check_task: Optional[asyncio.Task[None]] = Noneself._startup_failed = False+ self._started_at: Optional[float] = None # Unix timestampself._start_lock = asyncio.Lock()self.log_file = _loggers.get_log_directory() / f"{self.id}.log"@@ -118,6 +138,7 @@ class BaseLspServer(LspServer):)LOGGER.info(f"Started LSP {self.id} at port {self.port}")+ self._started_at = time.time()# Start health monitoring in backgroundif (@@ -153,6 +174,114 @@ class BaseLspServer(LspServer):and self.process.returncode != 0)+ async def ping(+ self, timeout_ms: float = 5000+ ) -> tuple[bool, Optional[float]]:+ """+ Send an active health ping to verify server responsiveness.++ Returns (is_responsive, response_time_ms).+ Uses TCP socket connection check to verify the server port is listening.+ """+ if not self.is_running():+ return False, None++ start = time.monotonic()+ try:+ # Run socket connection in thread to avoid blocking+ loop = asyncio.get_running_loop()+ result = await loop.run_in_executor(+ None, self._tcp_ping, timeout_ms+ )+ elapsed_ms = (time.monotonic() - start) * 1000+ return result, elapsed_ms if result else None+ except Exception:+ return False, None++ def _tcp_ping(self, timeout_ms: float) -> bool:+ """Attempt TCP connection to check if server is listening."""+ try:+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ sock.settimeout(timeout_ms / 1000)+ result = sock.connect_ex(("localhost", self.port))+ sock.close()+ return result == 0+ except Exception:+ return False++ async def restart_server(self) -> Optional[AlertNotification]:+ """Stop and restart this LSP server."""+ self._startup_failed = False+ self._started_at = None+ self.stop()+ await asyncio.sleep(0.5) # Brief delay for cleanup+ return await self.start()++ def _get_status(self) -> LspServerStatus:+ """Determine the current status of the server."""+ if self.has_failed():+ return "crashed"+ if not self.is_running():+ return "stopped"+ # Process is running - will need to check responsiveness externally+ return "running"++ async def get_health(self) -> LspHealthResponse:+ """Get health status of this single LSP server."""+ is_running = self.is_running()++ # Determine server status+ server_status: LspServerStatus+ last_ping_ms: Optional[float] = None++ if self.has_failed():+ server_status = "crashed"+ elif not is_running:+ server_status = "stopped"+ else:+ # Process is running - check responsiveness+ is_responsive, last_ping_ms = await self.ping()+ server_status = "running" if is_responsive else "unresponsive"++ server_health = LspServerHealth(+ server_id=LspServerId(self.id),+ status=server_status,+ port=self.port,+ last_ping_ms=last_ping_ms,+ started_at=self._started_at,+ )++ status: Literal["healthy", "degraded", "unhealthy"]+ if server_status == "running":+ status = "healthy"+ else:+ status = "unhealthy"++ return LspHealthResponse(status=status, servers=[server_health])++ async def restart(+ self, server_ids: Optional[list[LspServerId]] = None+ ) -> LspRestartResponse:+ """Restart this LSP server if requested."""+ sid = LspServerId(self.id)+ # If server_ids specified and this server not in list, skip+ if server_ids is not None and self.id not in server_ids:+ return LspRestartResponse(success=True, restarted=[], errors={})++ try:+ alert = await self.restart_server()+ if alert:+ return LspRestartResponse(+ success=False,+ restarted=[],+ errors={sid: alert.description},+ )+ return LspRestartResponse(success=True, restarted=[sid], errors={})+ except Exception as e:+ return LspRestartResponse(+ success=False, restarted=[], errors={sid: str(e)}+ )+async def _monitor_process_health(self) -> None:"""Monitor the LSP process health and log if it crashes."""if self.process is None:@@ -479,6 +608,9 @@ class TyServer(BaseLspServer):class NoopLspServer(LspServer):+ port: int = 0+ id: str = "noop"+async def start(self) -> None:pass@@ -488,6 +620,15 @@ class NoopLspServer(LspServer):def is_running(self) -> bool:return False+ async def get_health(self) -> LspHealthResponse:+ return LspHealthResponse(status="healthy", servers=[])++ async def restart(+ self, server_ids: Optional[list[LspServerId]] = None+ ) -> LspRestartResponse:+ del server_ids # Unused+ return LspRestartResponse(success=True, restarted=[], errors={})+class CompositeLspServer(LspServer):LANGUAGE_SERVERS = {@@ -556,6 +697,111 @@ class CompositeLspServer(LspServer):def is_running(self) -> bool:return any(server.is_running() for server in self.servers.values())+ async def get_health(self) -> LspHealthResponse:+ """Get aggregated health status of all LSP servers."""+ config = self.config_reader.get_config()+ server_healths: list[LspServerHealth] = []++ for server_id, server in self.servers.items():+ if not self._is_enabled(config, server_id):+ continue++ is_running = server.is_running()++ # Determine server status+ server_status: LspServerStatus+ last_ping_ms: Optional[float] = None+ started_at: Optional[float] = None++ if isinstance(server, BaseLspServer):+ started_at = server._started_at+ if server.has_failed():+ server_status = "crashed"+ elif not is_running:+ server_status = "stopped"+ else:+ # Process is running - check responsiveness+ is_responsive, last_ping_ms = await server.ping()+ server_status = (+ "running" if is_responsive else "unresponsive"+ )+ else:+ server_status = "running" if is_running else "stopped"++ server_healths.append(+ LspServerHealth(+ server_id=LspServerId(server_id),+ status=server_status,+ port=server.port,+ last_ping_ms=last_ping_ms,+ started_at=started_at,+ )+ )++ # Determine aggregate status+ status: Literal["healthy", "degraded", "unhealthy"]+ if not server_healths:+ status = "healthy" # No servers configured+ elif all(s.status == "running" for s in server_healths):+ status = "healthy"+ elif any(s.status == "running" for s in server_healths):+ status = "degraded"+ else:+ status = "unhealthy"++ return LspHealthResponse(status=status, servers=server_healths)++ async def restart(+ self, server_ids: Optional[list[LspServerId]] = None+ ) -> LspRestartResponse:+ """Restart specified or failed LSP servers."""+ config = self.config_reader.get_config()+ restarted: list[LspServerId] = []+ errors: dict[LspServerId, str] = {}++ servers_to_restart: list[LspServerId] = []+ if server_ids is None:+ # Restart all failed/non-responsive servers+ for server_id, server in self.servers.items():+ if not self._is_enabled(config, server_id):+ continue+ if isinstance(server, BaseLspServer):+ is_running = server.is_running()+ if server.has_failed():+ servers_to_restart.append(LspServerId(server_id))+ elif is_running:+ is_responsive, _ = await server.ping()+ if not is_responsive:+ servers_to_restart.append(LspServerId(server_id))+ else:+ servers_to_restart = server_ids++ for server_id in servers_to_restart:+ sid = LspServerId(server_id)+ if server_id not in self.servers:+ errors[sid] = f"Unknown server: {server_id}"+ continue++ server = self.servers[server_id]+ if not isinstance(server, BaseLspServer):+ errors[sid] = "Server does not support restart"+ continue++ try:+ alert = await server.restart_server()+ if alert:+ errors[sid] = alert.description+ else:+ restarted.append(sid)+ except Exception as e:+ errors[sid] = str(e)++ return LspRestartResponse(+ success=len(errors) == 0,+ restarted=restarted,+ errors=errors,+ )+def any_lsp_server_running(config: MarimoConfig) -> bool:# Check if any language servers or copilot are enableddiff --git a/marimo/_server/models/lsp.py b/marimo/_server/models/lsp.pynew file mode 100644index 0000000000..d2135753e0--- /dev/null+++ b/marimo/_server/models/lsp.py@@ -0,0 +1,60 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++from typing import Literal, NewType, Optional++import msgspec++# Type-safe server identifier+LspServerId = NewType("LspServerId", str)++# Status enum for LSP server health+LspServerStatus = Literal[+ "starting", # process launched, initializing+ "running", # healthy and responsive to pings+ "stopped", # not running (never started or cleanly stopped)+ "crashed", # exited with non-zero code+ "unresponsive", # process alive but not responding to pings+]+++class LspServerHealth(msgspec.Struct, rename="camel"):+ """Health status for a single LSP server.++ Status meanings:+ - starting: process launched, initializing+ - running: healthy and responsive to pings+ - stopped: not running (never started or cleanly stopped)+ - crashed: exited with non-zero code+ - unresponsive: process alive but not responding to pings+ """++ server_id: LspServerId+ status: LspServerStatus+ port: int+ last_ping_ms: Optional[float] = None+ error: Optional[str] = None+ started_at: Optional[float] = None # Unix timestamp+++class LspHealthResponse(msgspec.Struct, rename="camel"):+ """Aggregated health response for all LSP servers."""++ status: Literal["healthy", "degraded", "unhealthy"]+ servers: list[LspServerHealth]+++class LspRestartRequest(msgspec.Struct, rename="camel"):+ """Request to restart LSP servers."""++ server_ids: Optional[list[LspServerId]] = (+ None # None = restart failed servers+ )+++class LspRestartResponse(msgspec.Struct, rename="camel"):+ """Response from restart operation."""++ success: bool+ restarted: list[LspServerId] # Server IDs that were restarted+ errors: dict[LspServerId, str] = {} # Server ID -> error messagediff --git a/packages/openapi/api.yaml b/packages/openapi/api.yamlindex 7a1ac27afa..865334b21e 100644--- a/packages/openapi/api.yaml+++ b/packages/openapi/api.yaml@@ -2604,6 +2604,94 @@ components:- keystitle: ListSecretKeysResponsetype: object+ LspHealthResponse:+ description: Aggregated health response for all LSP servers.+ properties:+ servers:+ items:+ $ref: '#/components/schemas/LspServerHealth'+ type: array+ status:+ enum:+ - degraded+ - healthy+ - unhealthy+ required:+ - status+ - servers+ title: LspHealthResponse+ type: object+ LspRestartRequest:+ description: Request to restart LSP servers.+ properties:+ serverIds:+ anyOf:+ - items:+ type: string+ type: array+ - type: 'null'+ default: null+ required: []+ title: LspRestartRequest+ type: object+ LspRestartResponse:+ description: Response from restart operation.+ properties:+ errors:+ additionalProperties:+ type: string+ default: {}+ type: object+ restarted:+ items:+ type: string+ type: array+ success:+ type: boolean+ required:+ - success+ - restarted+ title: LspRestartResponse+ type: object+ LspServerHealth:+ description: "Health status for a single LSP server.\n\n Status meanings:\n\+ \ - starting: process launched, initializing\n - running: healthy and\+ \ responsive to pings\n - stopped: not running (never started or cleanly\+ \ stopped)\n - crashed: exited with non-zero code\n - unresponsive:\+ \ process alive but not responding to pings"+ properties:+ error:+ anyOf:+ - type: string+ - type: 'null'+ default: null+ lastPingMs:+ anyOf:+ - type: number+ - type: 'null'+ default: null+ port:+ type: integer+ serverId:+ type: string+ startedAt:+ anyOf:+ - type: number+ - type: 'null'+ default: null+ status:+ enum:+ - crashed+ - running+ - starting+ - stopped+ - unresponsive+ required:+ - serverId+ - status+ - port+ title: LspServerHealth+ type: objectMCPConfig:description: 'Configuration for MCP servers@@ -4570,7 +4658,7 @@ components:type: objectinfo:title: marimo API- version: 0.19.4+ version: 0.19.6openapi: 3.1.0paths:/@file/{filename_and_length}:@@ -5642,6 +5730,29 @@ paths:type: stringtype: objectdescription: Successfully closed existing sessions+ /api/lsp/health:+ get:+ responses:+ 200:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/LspHealthResponse'+ description: Get health status of all LSP servers+ /api/lsp/restart:+ post:+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/LspRestartRequest'+ responses:+ 200:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/LspRestartResponse'+ description: Restart LSP servers/api/packages/add:post:requestBody:diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.tsindex 1f7dc7661a..16abfbf0ac 100644--- a/packages/openapi/src/api.ts+++ b/packages/openapi/src/api.ts@@ -2432,6 +2432,80 @@ export interface paths {patch?: never;trace?: never;};+ "/api/lsp/health": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ get: {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ requestBody?: never;+ responses: {+ /** @description Get health status of all LSP servers */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["LspHealthResponse"];+ };+ };+ };+ };+ put?: never;+ post?: never;+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };+ "/api/lsp/restart": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ get?: never;+ put?: never;+ post: {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ requestBody?: {+ content: {+ "application/json": components["schemas"]["LspRestartRequest"];+ };+ };+ responses: {+ /** @description Restart LSP servers */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["LspRestartResponse"];+ };+ };+ };+ };+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };"/api/packages/add": {parameters: {query?: never;@@ -4561,6 +4635,58 @@ export interface components {ListSecretKeysResponse: {keys: components["schemas"]["SecretKeysWithProvider"][];};+ /**+ * LspHealthResponse+ * @description Aggregated health response for all LSP servers.+ */+ LspHealthResponse: {+ servers: components["schemas"]["LspServerHealth"][];+ /** @enum {unknown} */+ status: "degraded" | "healthy" | "unhealthy";+ };+ /**+ * LspRestartRequest+ * @description Request to restart LSP servers.+ */+ LspRestartRequest: {+ /** @default null */+ serverIds?: string[] | null;+ };+ /**+ * LspRestartResponse+ * @description Response from restart operation.+ */+ LspRestartResponse: {+ /** @default {} */+ errors?: {+ [key: string]: string;+ };+ restarted: string[];+ success: boolean;+ };+ /**+ * LspServerHealth+ * @description Health status for a single LSP server.+ *+ * Status meanings:+ * - starting: process launched, initializing+ * - running: healthy and responsive to pings+ * - stopped: not running (never started or cleanly stopped)+ * - crashed: exited with non-zero code+ * - unresponsive: process alive but not responding to pings+ */+ LspServerHealth: {+ /** @default null */+ error?: string | null;+ /** @default null */+ lastPingMs?: number | null;+ port: number;+ serverId: string;+ /** @default null */+ startedAt?: number | null;+ /** @enum {unknown} */+ status: "crashed" | "running" | "starting" | "stopped" | "unresponsive";+ };/*** MCPConfig* @description Configuration for MCP serversdiff --git a/tests/_server/api/endpoints/test_lsp_endpoints.py b/tests/_server/api/endpoints/test_lsp_endpoints.pynew file mode 100644index 0000000000..02472a0f57--- /dev/null+++ b/tests/_server/api/endpoints/test_lsp_endpoints.py@@ -0,0 +1,304 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++from typing import TYPE_CHECKING, Any+from unittest.mock import AsyncMock, MagicMock, patch++import pytest+import uvicorn+from starlette.testclient import TestClient++from marimo._server.lsp import (+ BaseLspServer,+ CompositeLspServer,+ NoopLspServer,+)+from marimo._server.main import create_starlette_app+from marimo._server.models.lsp import (+ LspHealthResponse,+ LspRestartResponse,+ LspServerHealth,+)+from tests._server.mocks import (+ get_mock_session_manager,+ get_starlette_server_state_init,+ token_header,+)++if TYPE_CHECKING:+ from starlette.applications import Starlette+++def edit_app() -> Starlette:+ app = create_starlette_app(base_url="")+ session_manager = get_mock_session_manager()+ uvicorn_server = uvicorn.Server(uvicorn.Config(app))+ uvicorn_server.servers = []+ app.state.server = uvicorn_server+ get_starlette_server_state_init(session_manager=session_manager).apply(+ app.state+ )+ return app+++class TestLspEndpoints:+ """Test LSP API endpoints."""++ @pytest.mark.parametrize(+ ("method", "path"),+ [+ ("get", "/api/lsp/health"),+ ("post", "/api/lsp/restart"),+ ],+ )+ def test_unauthorized(+ self, edit_app: Starlette, method: str, path: str+ ) -> None:+ client = TestClient(edit_app)+ kwargs = {"json": {}} if method == "post" else {}+ response = getattr(client, method)(path, **kwargs)+ assert response.status_code == 401++ def test_health(self, edit_app: Starlette) -> None:+ client = TestClient(edit_app)+ response = client.get("/api/lsp/health", headers=token_header())+ assert response.status_code == 200+ content = response.json()+ # NoopLspServer returns healthy with empty servers+ assert content == {"status": "healthy", "servers": []}++ @pytest.mark.parametrize(+ "json_body",+ [+ {},+ {"serverIds": ["pylsp", "copilot"]},+ ],+ )+ def test_restart(+ self, edit_app: Starlette, json_body: dict[str, Any]+ ) -> None:+ client = TestClient(edit_app)+ response = client.post(+ "/api/lsp/restart", json=json_body, headers=token_header()+ )+ assert response.status_code == 200+ content = response.json()+ # NoopLspServer returns success with empty restarted+ assert content == {"success": True, "restarted": [], "errors": {}}+++class TestLspModels:+ """Test LSP model serialization."""++ def test_models(self) -> None:+ # LspServerHealth+ health = LspServerHealth(+ server_id="pylsp",+ status="running",+ port=8080,+ last_ping_ms=5.0,+ )+ assert health.server_id == "pylsp"+ assert health.status == "running"+ assert health.error is None++ # LspHealthResponse+ response = LspHealthResponse(status="healthy", servers=[health])+ assert response.status == "healthy"+ assert len(response.servers) == 1++ # LspRestartResponse+ restart = LspRestartResponse(+ success=True, restarted=["pylsp"], errors={"copilot": "Failed"}+ )+ assert restart.success is True+ assert restart.errors == {"copilot": "Failed"}+++class TestNoopLspServer:+ """Test NoopLspServer returns safe defaults."""++ @pytest.mark.asyncio+ async def test_health_and_restart(self) -> None:+ server = NoopLspServer()++ # Health returns healthy with no servers+ health = await server.get_health()+ assert health.status == "healthy"+ assert health.servers == []++ # Restart always succeeds with no action+ for server_ids in [None, ["pylsp"]]:+ result = await server.restart(server_ids=server_ids)+ assert result.success is True+ assert result.restarted == []+ assert result.errors == {}+++class TestBaseLspServer:+ """Test BaseLspServer ping, health, and restart logic."""++ @pytest.fixture+ def mock_server(self) -> BaseLspServer:+ class MockLspServer(BaseLspServer):+ id = "mock-lsp"++ def validate_requirements(self):+ return True++ def get_command(self):+ return ["echo", "mock"]++ def missing_binary_alert(self):+ return None++ return MockLspServer(port=8080)++ @pytest.mark.asyncio+ async def test_ping_not_running(self, mock_server: BaseLspServer) -> None:+ is_responsive, ping_ms = await mock_server.ping()+ assert is_responsive is False+ assert ping_ms is None++ @pytest.mark.asyncio+ async def test_get_health_not_running(+ self, mock_server: BaseLspServer+ ) -> None:+ health = await mock_server.get_health()+ assert health.status == "unhealthy"+ assert health.servers[0].status == "stopped"++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ ("server_ids", "should_restart"),+ [+ (["other-server"], False),+ (["mock-lsp"], True),+ (None, True),+ ],+ )+ async def test_restart(+ self,+ mock_server: BaseLspServer,+ server_ids: list[str] | None,+ should_restart: bool,+ ) -> None:+ mock_server.restart_server = AsyncMock(return_value=None)+ result = await mock_server.restart(server_ids=server_ids)++ assert result.success is True+ if should_restart:+ assert result.restarted == ["mock-lsp"]+ mock_server.restart_server.assert_called_once()+ else:+ assert result.restarted == []++ @pytest.mark.asyncio+ async def test_restart_with_error(+ self, mock_server: BaseLspServer+ ) -> None:+ mock_server.restart_server = AsyncMock(+ side_effect=Exception("Test error")+ )+ result = await mock_server.restart(server_ids=["mock-lsp"])+ assert result.success is False+ assert "Test error" in result.errors["mock-lsp"]++ @pytest.mark.parametrize(+ ("startup_failed", "returncode", "expected"),+ [+ (True, None, True), # startup failed+ (False, 1, True), # process crashed+ (False, None, False), # no failure+ ],+ )+ def test_has_failed(+ self,+ mock_server: BaseLspServer,+ startup_failed: bool,+ returncode: int | None,+ expected: bool,+ ) -> None:+ mock_server._startup_failed = startup_failed+ if returncode is not None:+ mock_server.process = MagicMock()+ mock_server.process.returncode = returncode+ assert mock_server.has_failed() is expected+++class TestCompositeLspServer:+ """Test CompositeLspServer aggregation logic."""++ @pytest.fixture+ def mock_ports(self):+ """Mock find_free_port to return incrementing ports."""+ port = [8000]++ def side_effect(_: int) -> int:+ port[0] += 1+ return port[0]++ with patch(+ "marimo._server.lsp.find_free_port", side_effect=side_effect+ ):+ yield++ @pytest.fixture+ def config_reader(self) -> MagicMock:+ reader = MagicMock()+ reader.get_config.return_value = {+ "completion": {"copilot": False},+ "language_servers": {"pylsp": {"enabled": True}},+ }+ return reader++ @pytest.mark.asyncio+ async def test_health_no_servers_enabled(+ self, mock_ports: None, config_reader: MagicMock+ ) -> None:+ del mock_ports+ config_reader.get_config.return_value = {+ "completion": {"copilot": False},+ "language_servers": {},+ }+ server = CompositeLspServer(config_reader, min_port=8000)+ health = await server.get_health()+ assert health.status == "healthy"+ assert health.servers == []++ @pytest.mark.asyncio+ async def test_restart_unknown_server(+ self, mock_ports: None, config_reader: MagicMock+ ) -> None:+ del mock_ports+ server = CompositeLspServer(config_reader, min_port=8000)+ result = await server.restart(server_ids=["unknown-server"])+ assert result.success is False+ assert "Unknown server" in result.errors["unknown-server"]++ @pytest.mark.parametrize(+ ("copilot_value", "server_name", "expected"),+ [+ (True, "copilot", True),+ ("github", "copilot", True),+ (False, "copilot", False),+ (False, "pylsp", True), # enabled in fixture+ ],+ )+ def test_is_enabled(+ self,+ mock_ports: None,+ config_reader: MagicMock,+ copilot_value: Any,+ server_name: str,+ expected: bool,+ ) -> None:+ del mock_ports+ config_reader.get_config.return_value = {+ "completion": {"copilot": copilot_value},+ "language_servers": {"pylsp": {"enabled": True}},+ }+ server = CompositeLspServer(config_reader, min_port=8000)+ config = config_reader.get_config()+ assert server._is_enabled(config, server_name) is expected