Skip to content

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.

feat: add `ty` LSP (#5302)

Winston H.84b993779a36
diff --git a/frontend/package.json b/frontend/package.json
index ba39c948bf..903ce6ccb7 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -45,7 +45,7 @@
"@lezer/markdown": "^1.4.3",
"@lezer/python": "^1.1.18",
"@marimo-team/codemirror-ai": "^0.1.11",
- "@marimo-team/codemirror-languageserver": "^1.15.15",
+ "@marimo-team/codemirror-languageserver": "^1.15.19",
"@marimo-team/marimo-api": "file:../openapi",
"@marimo-team/react-slotz": "^0.2.0",
"@mui/material": "^6.4.12",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index b8296a1ed5..53c63e531a 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -112,8 +112,8 @@ importers:
specifier: ^0.1.11
version: 0.1.11(@codemirror/[email protected])(@codemirror/[email protected])
'@marimo-team/codemirror-languageserver':
- specifier: ^1.15.15
- version: 1.15.15(@codemirror/[email protected])(@codemirror/[email protected])
+ specifier: ^1.15.19
+ version: 1.15.19(@codemirror/[email protected])(@codemirror/[email protected])
'@marimo-team/marimo-api':
specifier: file:../openapi
version: file:../openapi
@@ -1601,8 +1601,8 @@ packages:
'@codemirror/state': ^6
'@codemirror/view': ^6
- '@marimo-team/[email protected]':
- resolution: {integrity: sha512-dJCJ0qn6HDNs12Ps4kk67+/ShPKHla9LpbGIsCaIh9SWi7OnWfUTLyCHCMIxS5ROYsDbkzhKknfm4tucKQI9bQ==}
+ '@marimo-team/[email protected]':
+ resolution: {integrity: sha512-LLozJmWYC+rGqQINpDLcDHY4wxY96d4chmgwjB1DQUbUkCmKJHQS1Im0HgScB5FA289WfkAgQyIC59oYF5+wpw==}
peerDependencies:
'@codemirror/state': ^6
'@codemirror/view': ^6
@@ -10237,7 +10237,7 @@ snapshots:
'@codemirror/state': 6.5.2
'@codemirror/view': 6.38.0
- '@marimo-team/[email protected](@codemirror/[email protected])(@codemirror/[email protected])':
+ '@marimo-team/[email protected](@codemirror/[email protected])(@codemirror/[email protected])':
dependencies:
'@codemirror/autocomplete': 6.18.6
'@codemirror/lint': 6.8.5
diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsx
index ccc77436a7..04cc0f8b4f 100644
--- a/frontend/src/components/app-config/user-config-form.tsx
+++ b/frontend/src/components/app-config/user-config-form.tsx
@@ -470,6 +470,48 @@ export const UserConfigForm: React.FC = () => {
</div>
)}
/>
+ <FormField
+ control={form.control}
+ name="language_servers.ty.enabled"
+ render={({ field }) => (
+ <div className="flex flex-col gap-1">
+ <FormItem className={formItemClasses}>
+ <FormLabel>
+ <Badge variant="defaultOutline" className="mr-2">
+ Beta
+ </Badge>
+ ty (
+ <ExternalLink href="https://github.com/astral-sh/ty">
+ ty
+ </ExternalLink>
+ )
+ </FormLabel>
+ <FormControl>
+ <Checkbox
+ data-testid="ty-checkbox"
+ checked={field.value}
+ disabled={field.disabled}
+ onCheckedChange={(checked) => {
+ field.onChange(Boolean(checked));
+ }}
+ />
+ </FormControl>
+ <FormMessage />
+ <IsOverridden
+ userConfig={config}
+ name="language_servers.ty.enabled"
+ />
+ </FormItem>
+ {field.value && !capabilities.ty && (
+ <Banner kind="danger">
+ ty is not available in your current environment. Please
+ install <Kbd className="inline">ty</Kbd> in your
+ environment.
+ </Banner>
+ )}
+ </div>
+ )}
+ />
<FormDescription>
See the{" "}
<ExternalLink href="https://docs.marimo.io/guides/editor_features/language_server/">
diff --git a/frontend/src/core/codemirror/language/languages/python.ts b/frontend/src/core/codemirror/language/languages/python.ts
index c0574637db..40ad68fd7a 100644
--- a/frontend/src/core/codemirror/language/languages/python.ts
+++ b/frontend/src/core/codemirror/language/languages/python.ts
@@ -17,7 +17,6 @@ import {
LanguageServerClient,
languageServerWithClient,
} from "@marimo-team/codemirror-languageserver";
-import { WebSocketTransport } from "@open-rpc/client-js";
import type { CellId } from "@/core/cells/ids";
import { hasCapability } from "@/core/config/capabilities";
import type {
@@ -25,45 +24,28 @@ import type {
DiagnosticsConfig,
LSPConfig,
} from "@/core/config/config-schema";
-import { getFilenameFromDOM } from "@/core/dom/htmlUtils";
import type { HotkeyProvider } from "@/core/hotkeys/hotkeys";
-import { waitForConnectionOpen } from "@/core/network/connection";
import { openFile } from "@/core/network/requests";
-import { getRuntimeManager } from "@/core/runtime/config";
import { Logger } from "@/utils/Logger";
import { once } from "@/utils/once";
-import { Paths } from "@/utils/paths";
import { cellActionsState } from "../../cells/state";
import { pythonCompletionSource } from "../../completion/completer";
import type { PlaceholderType } from "../../config/types";
+import { FederatedLanguageServerClient } from "../../lsp/federated-lsp";
import { NotebookLanguageServerClient } from "../../lsp/notebook-lsp";
-import { CellDocumentUri } from "../../lsp/types";
+import { createTransport } from "../../lsp/transports";
+import { CellDocumentUri, type ILanguageServerClient } from "../../lsp/types";
+import { getLSPDocumentRootUri } from "../../lsp/utils";
import {
clickablePlaceholderExtension,
smartPlaceholderExtension,
} from "../../placeholder/extensions";
import type { LanguageAdapter } from "../types";
-const pylspTransport = once(() => {
- const runtimeManager = getRuntimeManager();
- const transport = new WebSocketTransport(
- runtimeManager.getLSPURL("pylsp").toString(),
- );
-
- // Override connect to ensure runtime is healthy
- const originalConnect = transport.connect.bind(transport);
- transport.connect = async () => {
- await waitForConnectionOpen();
- return originalConnect();
- };
-
- return transport;
-});
-
-const lspClient = once((lspConfig: LSPConfig) => {
+const pylspClient = once((lspConfig: LSPConfig) => {
const lspClientOpts = {
- transport: pylspTransport(),
- rootUri: `file://${Paths.dirname(getFilenameFromDOM() ?? "/")}`,
+ transport: createTransport("pylsp"),
+ rootUri: getLSPDocumentRootUri(),
workspaceFolders: [],
};
const config = lspConfig?.pylsp;
@@ -152,6 +134,25 @@ const lspClient = once((lspConfig: LSPConfig) => {
);
});
+const tyLspClient = once((_: LSPConfig) => {
+ const lspClientOpts = {
+ transport: createTransport("ty"),
+ rootUri: getLSPDocumentRootUri(),
+ workspaceFolders: [],
+ };
+
+ // We wrap the client in a NotebookLanguageServerClient to add some
+ // additional functionality to handle multiple cells
+ return new NotebookLanguageServerClient(
+ new LanguageServerClient({
+ ...lspClientOpts,
+ autoClose: false,
+ getWorkspaceConfiguration: (_) => [{ disableLanguageServices: true }],
+ }),
+ {},
+ );
+});
+
/**
* Language adapter for Python.
*/
@@ -195,12 +196,26 @@ export class PythonLanguageAdapter implements LanguageAdapter<{}> {
// https://discuss.codemirror.net/t/adding-click-event-listener-to-autocomplete-tooltip-info-panel-is-not-working/4741
closeOnBlur: false,
};
+
const hoverOptions = {
hideOnChange: true,
};
+ const clients: ILanguageServerClient[] = [];
+
if (lspConfig?.pylsp?.enabled && hasCapability("pylsp")) {
- const client = lspClient(lspConfig);
+ clients.push(pylspClient(lspConfig));
+ }
+ if (lspConfig?.ty?.enabled && hasCapability("ty")) {
+ clients.push(tyLspClient(lspConfig));
+ }
+
+ if (clients.length > 0) {
+ const client =
+ clients.length === 1
+ ? (clients[0] as NotebookLanguageServerClient)
+ : new FederatedLanguageServerClient(clients);
+
return [
languageServerWithClient({
client: client as unknown as LanguageServerClient,
diff --git a/frontend/src/core/codemirror/lsp/federated-lsp.ts b/frontend/src/core/codemirror/lsp/federated-lsp.ts
new file mode 100644
index 0000000000..382b326af1
--- /dev/null
+++ b/frontend/src/core/codemirror/lsp/federated-lsp.ts
@@ -0,0 +1,235 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import type { LanguageServerPlugin } from "@marimo-team/codemirror-languageserver";
+import type * as LSP from "vscode-languageserver-protocol";
+import { Objects } from "@/utils/objects";
+import type { ILanguageServerClient } from "./types";
+import { getLSPDocument } from "./utils.ts";
+
+function removeFalseyValues<T extends object>(obj: T): T {
+ return Objects.filter(obj, (value) => value !== false && value !== null) as T;
+}
+
+function mergeDictsIgnoreFalsey<T extends object>(dicts: T[]): T {
+ const filteredDicts = dicts.map(removeFalseyValues);
+ return Object.assign({}, ...filteredDicts);
+}
+
+export class FederatedLanguageServerClient implements ILanguageServerClient {
+ private readonly clients: ILanguageServerClient[] = [];
+ public readonly documentUri: string;
+
+ constructor(clients: ILanguageServerClient[]) {
+ this.clients = clients;
+ this.documentUri = getLSPDocument();
+ }
+
+ get clientCapabilities(): LSP.ClientCapabilities | undefined {
+ const capabilities = this.clients
+ .map((client) => {
+ if (client.clientCapabilities) {
+ if (typeof client.clientCapabilities === "function") {
+ return client.clientCapabilities({});
+ }
+ return client.clientCapabilities;
+ }
+ return undefined;
+ })
+ .filter((c) => c != null);
+
+ return mergeDictsIgnoreFalsey<LSP.ClientCapabilities>(capabilities);
+ }
+
+ get ready(): boolean {
+ return this.clients.some((client) => client.ready);
+ }
+
+ set ready(value: boolean) {
+ this.clients.forEach((client) => {
+ client.ready = value;
+ });
+ }
+
+ get capabilities(): LSP.ServerCapabilities | null {
+ const capabilities = this.clients
+ .map((client) => client.capabilities)
+ .filter((c) => c !== null);
+ return mergeDictsIgnoreFalsey<LSP.ServerCapabilities>(capabilities);
+ }
+
+ set capabilities(value: LSP.ServerCapabilities) {
+ this.clients.forEach((client) => {
+ client.capabilities = value;
+ });
+ }
+
+ get initializePromise(): Promise<void> {
+ return this.clients[0].initializePromise;
+ }
+
+ set initializePromise(value: Promise<void>) {
+ this.clients.forEach((client) => {
+ client.initializePromise = value;
+ });
+ }
+
+ private firstWithCapability(
+ capability: keyof LSP.ServerCapabilities,
+ ): ILanguageServerClient | undefined {
+ return this.clients.find((client) => client.capabilities?.[capability]);
+ }
+
+ private clientsWithCapability(
+ capability: keyof LSP.ServerCapabilities,
+ ): ILanguageServerClient[] {
+ return this.clients.filter((client) => client.capabilities?.[capability]);
+ }
+
+ async initialize(): Promise<void> {
+ await Promise.all(this.clients.map((client) => client.initialize()));
+ }
+
+ async close(): Promise<void> {
+ await Promise.all(this.clients.map((client) => client.close()));
+ }
+
+ async textDocumentDidChange(
+ params: LSP.DidChangeTextDocumentParams,
+ ): Promise<LSP.DidChangeTextDocumentParams> {
+ await Promise.all(
+ this.clients.map((client) => client.textDocumentDidChange(params)),
+ );
+
+ return params;
+ }
+
+ async completionItemResolve(
+ item: LSP.CompletionItem,
+ ): Promise<LSP.CompletionItem> {
+ const client = this.firstWithCapability("completionProvider");
+ if (client) {
+ return client.completionItemResolve(item);
+ }
+ return item;
+ }
+
+ async textDocumentCodeAction(
+ params: LSP.CodeActionParams,
+ ): Promise<Array<LSP.Command | LSP.CodeAction> | null> {
+ const client = this.firstWithCapability("codeActionProvider");
+ if (client) {
+ return client.textDocumentCodeAction(params);
+ }
+ return null;
+ }
+
+ async textDocumentRename(
+ params: LSP.RenameParams,
+ ): Promise<LSP.WorkspaceEdit | null> {
+ const client = this.firstWithCapability("renameProvider");
+ if (client) {
+ return client.textDocumentRename(params);
+ }
+ return null;
+ }
+
+ async textDocumentPrepareRename(
+ params: LSP.PrepareRenameParams,
+ ): Promise<LSP.PrepareRenameResult | null> {
+ const client = this.firstWithCapability("renameProvider");
+ if (client) {
+ return client.textDocumentPrepareRename(params);
+ }
+ return null;
+ }
+
+ async textDocumentSignatureHelp(
+ params: LSP.SignatureHelpParams,
+ ): Promise<LSP.SignatureHelp | null> {
+ const client = this.firstWithCapability("signatureHelpProvider");
+ if (client) {
+ return client.textDocumentSignatureHelp(params);
+ }
+ return null;
+ }
+
+ attachPlugin(plugin: LanguageServerPlugin): void {
+ this.clients.forEach((client) => client.attachPlugin(plugin));
+ }
+
+ detachPlugin(plugin: LanguageServerPlugin): void {
+ this.clients.forEach((client) => client.detachPlugin(plugin));
+ }
+
+ // Merge completions from all clients
+ async textDocumentCompletion(
+ params: LSP.CompletionParams,
+ ): Promise<LSP.CompletionList | LSP.CompletionItem[] | null> {
+ const clients = this.clientsWithCapability("completionProvider");
+ const results = await Promise.allSettled(
+ clients.map((client) => client.textDocumentCompletion(params)),
+ );
+
+ return mergeCompletions(results);
+ }
+
+ async textDocumentDefinition(
+ params: LSP.DefinitionParams,
+ ): Promise<LSP.Definition | LSP.LocationLink[] | null> {
+ const client = this.firstWithCapability("definitionProvider");
+ if (client) {
+ return client.textDocumentDefinition(params);
+ }
+ return null;
+ }
+
+ async textDocumentDidOpen(params: LSP.DidOpenTextDocumentParams) {
+ await Promise.all(
+ this.clients.map((client) => client.textDocumentDidOpen(params)),
+ );
+
+ return params;
+ }
+
+ async textDocumentHover(params: LSP.HoverParams): Promise<LSP.Hover> {
+ for (const client of this.clients) {
+ if (!client.capabilities?.hoverProvider) {
+ continue;
+ }
+ const result = await client.textDocumentHover(params);
+ if (result) {
+ return result;
+ }
+ }
+ throw new Error("No hover provider found");
+ }
+}
+
+function mergeCompletions(
+ results: Array<
+ PromiseSettledResult<LSP.CompletionList | LSP.CompletionItem[] | null>
+ >,
+): LSP.CompletionList {
+ const completions: LSP.CompletionItem[] = [];
+ let isIncomplete = false;
+
+ for (const result of results) {
+ if (result.status === "fulfilled") {
+ const res = result.value;
+ if (res == null) {
+ continue;
+ }
+
+ if (Array.isArray(res)) {
+ completions.push(...res);
+ }
+
+ if ("items" in res) {
+ completions.push(...res.items);
+ isIncomplete = isIncomplete || res.isIncomplete;
+ }
+ }
+ }
+
+ return { items: completions, isIncomplete };
+}
diff --git a/frontend/src/core/codemirror/lsp/transports.ts b/frontend/src/core/codemirror/lsp/transports.ts
new file mode 100644
index 0000000000..87998e83f8
--- /dev/null
+++ b/frontend/src/core/codemirror/lsp/transports.ts
@@ -0,0 +1,29 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { WebSocketTransport } from "@open-rpc/client-js";
+import { waitForConnectionOpen } from "../../network/connection";
+import { getRuntimeManager } from "../../runtime/config";
+
+/**
+ * Create a transport for a given LSP server.
+ *
+ * This ensures we are connected to the marimo runtime
+ * before connecting to the LSP server.
+ *
+ * @param serverName - The name of the LSP server.
+ * @returns The transport.
+ */
+export function createTransport(serverName: "pylsp" | "copilot" | "ty") {
+ const runtimeManager = getRuntimeManager();
+ const transport = new WebSocketTransport(
+ runtimeManager.getLSPURL(serverName).toString(),
+ );
+
+ // Override connect to ensure runtime is healthy
+ const originalConnect = transport.connect.bind(transport);
+ transport.connect = async () => {
+ await waitForConnectionOpen();
+ return originalConnect();
+ };
+
+ return transport;
+}
diff --git a/frontend/src/core/codemirror/lsp/utils.ts b/frontend/src/core/codemirror/lsp/utils.ts
index ffd54bd3a2..5e9bc96030 100644
--- a/frontend/src/core/codemirror/lsp/utils.ts
+++ b/frontend/src/core/codemirror/lsp/utils.ts
@@ -1,6 +1,11 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { getFilenameFromDOM } from "@/core/dom/htmlUtils";
+import { Paths } from "@/utils/paths";
export function getLSPDocument() {
return `file://${getFilenameFromDOM() ?? "/__marimo_notebook__.py"}`;
}
+
+export function getLSPDocumentRootUri() {
+ return `file://${Paths.dirname(getFilenameFromDOM() ?? "/")}`;
+}
diff --git a/frontend/src/core/config/capabilities.ts b/frontend/src/core/config/capabilities.ts
index 5d3eb8514a..5d87102f70 100644
--- a/frontend/src/core/config/capabilities.ts
+++ b/frontend/src/core/config/capabilities.ts
@@ -6,6 +6,7 @@ import { store } from "../state/jotai";
export const capabilitiesAtom = atom<Capabilities>({
terminal: false,
pylsp: false,
+ ty: false,
});
export function hasCapability(key: keyof Capabilities): boolean {
diff --git a/frontend/src/core/runtime/runtime.ts b/frontend/src/core/runtime/runtime.ts
index 809b7a0fae..a1ee8adf61 100644
--- a/frontend/src/core/runtime/runtime.ts
+++ b/frontend/src/core/runtime/runtime.ts
@@ -135,7 +135,7 @@ export class RuntimeManager {
/**
* The URL of the copilot server.
*/
- getLSPURL(lsp: "pylsp" | "copilot"): URL {
+ getLSPURL(lsp: "pylsp" | "copilot" | "ty"): URL {
if (lsp === "copilot") {
// For copilot, don't include any query parameters
const url = this.formatWsURL(`/lsp/${lsp}`);
diff --git a/lsp/index.ts b/lsp/index.ts
index eb4ce5782d..a78286eb52 100644
--- a/lsp/index.ts
+++ b/lsp/index.ts
@@ -61,6 +61,7 @@ class WebSocketAdapter implements IWebSocket {
send(content: string): void {
try {
this.webSocket.send(content);
+ this.logger.debug("Sent message:", content);
} catch (error) {
this.logger.error("Failed to send message:", error);
}
@@ -69,8 +70,8 @@ class WebSocketAdapter implements IWebSocket {
onMessage(callback: (data: Data) => void): void {
this.webSocket.onmessage = (event: MessageEvent) => {
try {
- this.logger.debug("Received message:", event.data);
callback(event.data);
+ this.logger.debug("Received message:", event.data);
} catch (error) {
this.logger.error("Error handling message:", error);
}
diff --git a/marimo/_config/config.py b/marimo/_config/config.py
index 30be180f06..352519e19f 100644
--- a/marimo/_config/config.py
+++ b/marimo/_config/config.py
@@ -332,6 +332,18 @@ class PythonLanguageServerConfig(TypedDict, total=False):
enable_pyflakes: bool
+@dataclass
+class TyLanguageServerConfig(TypedDict, total=False):
+ """
+ Configuration options for Ty Language Server.
+
+ ty handles completion, hover, go-to-definition, and diagnostics,
+ but we only use it for diagnostics.
+ """
+
+ enabled: bool
+
+
@dataclass
class LanguageServersConfig(TypedDict, total=False):
"""Configuration options for language servers.
@@ -342,6 +354,7 @@ class LanguageServersConfig(TypedDict, total=False):
"""
pylsp: PythonLanguageServerConfig
+ ty: TyLanguageServerConfig
@dataclass
diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.py
index 486051386e..d3fa090c5c 100644
--- a/marimo/_dependencies/dependencies.py
+++ b/marimo/_dependencies/dependencies.py
@@ -216,7 +216,8 @@ class DependencyManager:
panel = Dependency("panel")
sqlalchemy = Dependency("sqlalchemy")
pylsp = Dependency("pylsp")
- pytest = Dependency("pytest", min_version="8.0.0")
+ ty = Dependency("ty")
+ pytest = Dependency("pytest")
vegafusion = Dependency("vegafusion")
vl_convert_python = Dependency("vl_convert")
dotenv = Dependency("dotenv")
diff --git a/marimo/_messaging/ops.py b/marimo/_messaging/ops.py
index 7b888fe367..c530b69cbf 100644
--- a/marimo/_messaging/ops.py
+++ b/marimo/_messaging/ops.py
@@ -418,11 +418,13 @@ class CompletedRun(Op):
class KernelCapabilities:
terminal: bool = False
pylsp: bool = False
+ ty: bool = False
def __post_init__(self) -> None:
# Only available in mac/linux
self.terminal = not is_windows() and not is_pyodide()
self.pylsp = DependencyManager.pylsp.has()
+ self.ty = DependencyManager.ty.has()
@dataclass
diff --git a/marimo/_server/lsp.py b/marimo/_server/lsp.py
index 9b5fd60442..070d4cc03f 100644
--- a/marimo/_server/lsp.py
+++ b/marimo/_server/lsp.py
@@ -56,7 +56,7 @@ class BaseLspServer(LspServer):
cmd = None
try:
- LOGGER.debug("Starting LSP server at port %s...", self.port)
+ LOGGER.info(f"Starting LSP {self.id} at port {self.port}")
cmd = self.get_command()
# Empty command means the server is not enabled
@@ -102,7 +102,7 @@ class BaseLspServer(LspServer):
variant="danger",
)
- LOGGER.debug("Started LSP server at port %s", self.port)
+ LOGGER.info(f"Started LSP {self.id} at port {self.port}")
except Exception as e:
cmd_str = " ".join(cmd or [])
@@ -226,6 +226,50 @@ class PyLspServer(BaseLspServer):
)
+class TyServer(BaseLspServer):
+ id = "ty"
+
+ def start(self) -> Optional[Alert]:
+ # ty is not required, so we don't want to alert or fail if it is not installed
+ if not DependencyManager.ty.has():
+ LOGGER.debug("ty is not installed. Skipping LSP server.")
+ return None
+ return super().start()
+
+ def validate_requirements(self) -> Union[str, Literal[True]]:
+ if not DependencyManager.ty.has():
+ return "ty is missing. Install it with `pip install ty`."
+
+ if not DependencyManager.which("node"):
+ return "node.js binary is missing. Install node at https://nodejs.org/."
+
+ return True
+
+ def get_command(self) -> list[str]:
+ from ty.__main__ import find_ty_bin # type: ignore
+
+ lsp_bin = marimo_package_path() / "_lsp" / "index.cjs"
+ log_file = _loggers.get_log_directory() / "ty-lsp.log"
+
+ return [
+ "node",
+ str(lsp_bin),
+ "--port",
+ str(self.port),
+ "--lsp",
+ f"{find_ty_bin()} server",
+ "--log-file",
+ str(log_file),
+ ]
+
+ def missing_binary_alert(self) -> Alert:
+ return Alert(
+ title="Ty: Connection Error",
+ description="<span><a class='hyperlink' href='https://github.com/astral-sh/ty'>Install ty</a> for type checking support.</span>",
+ variant="danger",
+ )
+
+
class NoopLspServer(LspServer):
def start(self) -> None:
pass
@@ -240,6 +284,7 @@ class NoopLspServer(LspServer):
class CompositeLspServer(LspServer):
LANGUAGE_SERVERS = {
"pylsp": PyLspServer,
+ "ty": TyServer,
"copilot": CopilotLspServer,
}
diff --git a/openapi/api.yaml b/openapi/api.yaml
index 4874c4c057..db774a35ee 100644
--- a/openapi/api.yaml
+++ b/openapi/api.yaml
@@ -1284,9 +1284,12 @@ components:
type: boolean
terminal:
type: boolean
+ ty:
+ type: boolean
required:
- terminal
- pylsp
+ - ty
type: object
cell_ids:
items:
@@ -1650,6 +1653,11 @@ components:
enabled:
type: boolean
type: object
+ ty:
+ properties:
+ enabled:
+ type: boolean
+ type: object
type: object
package_management:
properties:
diff --git a/openapi/src/api.ts b/openapi/src/api.ts
index cdda237b3b..c36cf6936f 100644
--- a/openapi/src/api.ts
+++ b/openapi/src/api.ts
@@ -3065,6 +3065,7 @@ export interface components {
capabilities: {
pylsp: boolean;
terminal: boolean;
+ ty: boolean;
};
cell_ids: string[];
codes: string[];
@@ -3238,6 +3239,9 @@ export interface components {
enable_ruff?: boolean;
enabled?: boolean;
};
+ ty?: {
+ enabled?: boolean;
+ };
};
package_management: {
/** @enum {string} */
diff --git a/tests/_server/test_lsp.py b/tests/_server/test_lsp.py
index 7552b47d7f..c0da9a2fc8 100644
--- a/tests/_server/test_lsp.py
+++ b/tests/_server/test_lsp.py
@@ -149,15 +149,21 @@ def test_composite_server():
with mock.patch("marimo._server.lsp.DependencyManager") as mock_dm:
mock_dm.pylsp = mock.MagicMock()
mock_dm.pylsp.has.return_value = True
- config = LanguageServersConfig({"pylsp": {"enabled": True}})
+ total_lsp_servers = 3
+ config = LanguageServersConfig(
+ {"pylsp": {"enabled": True}, "ty": {"enabled": True}}
+ )
completion_config = CompletionConfig(
{"copilot": True, "activate_on_typing": True}
)
config_reader = as_reader(completion_config, config)
server = CompositeLspServer(config_reader, min_port=8000)
- assert len(server.servers) == 2 # Both pylsp and copilot enabled
+ assert (
+ len(server.servers) == total_lsp_servers
+ ) # Both pylsp and copilot enabled
assert server._is_enabled("pylsp") is True
assert server._is_enabled("copilot") is True
+ assert server._is_enabled("ty") is True
# Test with only pylsp
config = LanguageServersConfig({"pylsp": {"enabled": True}})
@@ -166,9 +172,24 @@ def test_composite_server():
)
config_reader = as_reader(completion_config, config)
server = CompositeLspServer(config_reader, min_port=8000)
- assert len(server.servers) == 2
+ assert len(server.servers) == total_lsp_servers
assert server._is_enabled("pylsp") is True
assert server._is_enabled("copilot") is False
+ assert server._is_enabled("ty") is False
+
+ # Test with only ty enabled
+ config = LanguageServersConfig(
+ {"ty": {"enabled": True}, "pylsp": {"enabled": False}}
+ )
+ completion_config = CompletionConfig(
+ {"copilot": False, "activate_on_typing": True}
+ )
+ config_reader = as_reader(completion_config, config)
+ server = CompositeLspServer(config_reader, min_port=8000)
+ assert len(server.servers) == total_lsp_servers
+ assert server._is_enabled("pylsp") is False
+ assert server._is_enabled("copilot") is False
+ assert server._is_enabled("ty") is True
# Test with nothing enabled
config = LanguageServersConfig({"pylsp": {"enabled": False}})
@@ -177,9 +198,10 @@ def test_composite_server():
)
config_reader = as_reader(completion_config, config)
server = CompositeLspServer(config_reader, min_port=8000)
- assert len(server.servers) == 2
+ assert len(server.servers) == total_lsp_servers
assert server._is_enabled("pylsp") is False
assert server._is_enabled("copilot") is False
+ assert server._is_enabled("ty") is False
def test_any_lsp_server_running():