Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,12 @@ initialization-options contract. Fixture metadata is separate from
`initializationOptions`; `__ROOT_URI__`, `__ROOT_FS__`, `__CWD_FS__`, `__PYTHON__`
and `__SEP__` are test-only substitutions, not supported settings variables.
Python and TypeScript tests independently consume `producer.json`, including
host-resolved CWD variables that Python finishes resolving per document.
host-resolved CWD variables that Python finishes resolving per document and an
opt-in enablement payload retaining mixed and nested roots.

`python/tests/test_server_stdio.py` starts a test-only ToolServer over real LSP
stdio and checks initialize/initialized/settings/shutdown/exit. It needs no tool
stdio and checks initialize/initialized/settings/shutdown/exit plus a test-only
formatting handler that consults the participation API. It needs no tool
installation, VS Code host or Node build. Repeated settings application is
covered separately in-process, not by reinitializing a live LSP session.

Expand Down
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,12 @@ For an opt-in typed settings contract without changing runtime behavior, see
the [typed tool definition example](typescript/README.md#typed-tool-definitions).
Existing `ToolConfig` callers do not need to migrate.

For per-folder participation in the existing singleton server, explicitly set
`ToolConfig.workspaceEnablementSetting` and check Python's
`ToolServer.is_document_enabled` in tool-work handlers. Disabled folders retain
their settings entries; there is no automatic execution gate or consumer
adoption. See the [opt-in contract](docs/supported-apis.md#opt-in-per-folder-participation).

Extensions whose servers run tools using the interpreter in each resolved
settings entry can opt in to per-project environments:

Expand Down
67 changes: 67 additions & 0 deletions docs/supported-apis.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ register tool requests or choose how to run the tool. Add those handlers on
|-----------------------|---------|
| `apply_settings(params)`, `get_global_defaults()`, `update_workspace_settings(settings)` | Apply the initialization payload and build/select configured settings |
| `get_settings_by_path(file_path)`, `get_document_key(document)`, `get_settings_by_document(document)` | Route filesystem paths and documents to current workspace settings |
| `is_document_enabled(document)` | Opt-in participation decision using retained workspace state; handlers must check it before tool work |
| `get_cwd(settings, document=None, *, document_path=None)` | Finish per-document CWD substitution, optionally using a notebook's file path |
| `execute_tool(*, argv, mode, settings, ...)` | Dispatch caller-built arguments to `"path"`, `"rpc"` or `"module"` execution and return `RunResult` |
| `log_startup_info(settings=None)`, `log_to_output`, `log_error`, `log_warning`, `log_always` | Shared output and notification behavior |
Expand Down Expand Up @@ -162,6 +163,72 @@ Python's `ToolServerConfig.default_settings` extends global defaults;
the same global keys. Workspace settings are then shallowly overlaid, not deeply
merged.

### Opt-in per-folder participation

The TypeScript lifecycle already uses one language client/server for the window.
Per-folder enablement does not start extra servers or omit disabled folders.
Opt in through the existing `ToolConfig` or `ToolDefinition<TSettings>`:

```typescript
const optedIn = {
...toolConfig, // The extension's existing ToolConfig or ToolDefinition.
workspaceEnablementSetting: 'runTools',
};
activateToolExtension(context, { serverInfo, toolConfig: optedIn });
```

Contribute a resource-scoped boolean `<toolId>.runTools` setting in the extension's
manifest, normally with default `true`. The key is relative to the namespace;
`'enabled'`, `'enable'` and other consumer keys are supported. It need not be added
to `settingsDefaults` or `trackedSettings` just for this contract.
`getWorkspaceSettings`, `getExtensionSettings` and `getGlobalSettings` serialize
the decision as the reserved optional `_toolEnabled` boolean, defaulting to
enabled when absent. Only literal boolean `false` disables participation;
other wire values (including `0`, `"false"` or `null`) remain enabled.
Global resolution uses user/default scope, not a folder's
value. Common subscriptions automatically track the configured key and restart
the singleton with refreshed settings. Manual lifecycle callers must track that
key and refresh their own initialization payload.

All supplied roots, enabled or disabled, retain their identities and settings.
This includes nested workspace folders and, in per-project mode, nested Python
projects. Do not filter the settings list: an omitted disabled root can be
mistaken for an unknown document and inherit enabled fallback settings.

Python consumers opt in by checking the public facade in their handlers:

```python
document = tool.server.workspace.get_text_document(params.text_document.uri)
if not tool.is_document_enabled(document):
return [] # Formatting example; use the handler's appropriate no-work result.
# Existing tool execution and result handling follow.
```

The participation contract is `is_document_enabled`, which uses
`get_settings_by_document`: the most-specific matching
filesystem root supplies its flag; a document outside the known roots uses
global defaults. Opted-in document matching includes filesystem roots and
Windows path casing, without changing legacy routing when no flag is supplied.
Only absolute document paths can match terminal filesystem roots; a relative
path's terminal `.` is not resolved into a CWD workspace match.
An absent/pathless document uses the existing first-workspace
fallback, or CWD/global defaults when there are no roots. For notebook requests,
use the existing synthetic document with the **notebook's actual filesystem
path**, not a raw cell URI as a filesystem path. Virtual roots without local
filesystem paths are not matched by this routing contract.

`get_settings_by_path` is **not enablement-aware**. Its unchanged legacy lookup
can fall back to the first workspace even for an outside resource; do not infer
participation from that result. Use the document-based participation contract.

Without the TypeScript opt-in, no shared flag is added and the helper returns
`True`. Consumer-owned fields such as Pylint's `enabled`, existing hooks and
manual execution remain unchanged. The helper does not gate `execute_tool`,
register handlers, or clear existing diagnostics. Consumers must check it on
every relevant tool-work path and retain their own diagnostic cleanup and policy.
This supplies participation mechanics related to issue #49, not automatic
enablement adoption in any extension.

`ToolServer` owns the writable `global_settings` and `workspace_settings`
dictionaries. Existing aliases and in-place updates remain valid.
[`_settings`](../python/vscode_common_python_lsp/_settings.py) only constructs
Expand Down
47 changes: 47 additions & 0 deletions python/tests/fixtures/settings/producer.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,5 +50,52 @@
"severity": { "E": "Warning" },
"extensionOption": { "enabled": true, "label": "global" }
}
},
"workspaceEnablement": {
"settingKey": "runTools",
"toolDefaults": { "enabled": false },
"configuration": {
"workspaces": [
{ "workspace": "__ROOT_URI__", "values": { "interpreter": ["__PYTHON__"] } },
{ "workspace": "__ROOT_URI__-other", "values": { "interpreter": ["__PYTHON__"], "runTools": false } },
{ "workspace": "__ROOT_URI__/disabled", "values": { "interpreter": ["__PYTHON__"], "runTools": false } },
{ "workspace": "__ROOT_URI__/disabled/enabled", "values": { "interpreter": ["__PYTHON__"], "runTools": true } }
],
"global": { "interpreter": ["__PYTHON__"], "runTools": true }
},
"initializationOptions": {
"settings": [
{
"cwd": "__ROOT_FS__", "workspace": "__ROOT_URI__",
"args": [], "path": [], "interpreter": ["__PYTHON__"],
"importStrategy": "useBundled", "showNotifications": "off",
"enabled": false, "_toolEnabled": true
},
{
"cwd": "__ROOT_FS__-other", "workspace": "__ROOT_URI__-other",
"args": [], "path": [], "interpreter": ["__PYTHON__"],
"importStrategy": "useBundled", "showNotifications": "off",
"enabled": false, "_toolEnabled": false
},
{
"cwd": "__ROOT_FS____SEP__disabled", "workspace": "__ROOT_URI__/disabled",
"args": [], "path": [], "interpreter": ["__PYTHON__"],
"importStrategy": "useBundled", "showNotifications": "off",
"enabled": false, "_toolEnabled": false
},
{
"cwd": "__ROOT_FS____SEP__disabled__SEP__enabled", "workspace": "__ROOT_URI__/disabled/enabled",
"args": [], "path": [], "interpreter": ["__PYTHON__"],
"importStrategy": "useBundled", "showNotifications": "off",
"enabled": false, "_toolEnabled": true
}
],
"globalSettings": {
"cwd": "__CWD_FS__", "workspace": "__CWD_FS__",
"args": [], "path": [], "interpreter": ["__PYTHON__"],
"importStrategy": "fromEnvironment", "showNotifications": "off",
"enabled": false, "_toolEnabled": true
}
}
}
}
15 changes: 15 additions & 0 deletions python/tests/fixtures/settings_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ def main() -> None:
)
)
initialized_received = False
executed_documents: list[str] = []

@tool.server.feature(lsp.INITIALIZE)
def initialize(params: lsp.InitializeParams) -> None:
Expand All @@ -45,8 +46,22 @@ def inspect_settings(_params: Any) -> dict[str, Any]:
"globalSettings": tool.global_settings,
"initialized": initialized_received,
"serverModule": server_module.__file__,
"executedDocuments": executed_documents,
}

@tool.server.feature(lsp.TEXT_DOCUMENT_FORMATTING)
def format_document(params: lsp.DocumentFormattingParams) -> list[lsp.TextEdit]:
document = tool.server.workspace.get_text_document(params.text_document.uri)
if not tool.is_document_enabled(document):
return []
executed_documents.append(document.uri)
return [
lsp.TextEdit(
range=lsp.Range(lsp.Position(0, 0), lsp.Position(0, 0)),
new_text="participated",
)
]

@tool.server.feature(lsp.SHUTDOWN)
def shutdown(_params: Any) -> None:
tool.handle_shutdown()
Expand Down
175 changes: 175 additions & 0 deletions python/tests/test_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from pygls import uris
from pygls.workspace import TextDocument

from vscode_common_python_lsp.notebook import SyntheticDocument
from vscode_common_python_lsp.server import ToolServer, ToolServerConfig

from .settings_fixtures import load_settings_fixture
Expand Down Expand Up @@ -1442,6 +1443,180 @@ def test_repeated_application_retains_aliases_and_routes_real_uris(self, tmp_pat
assert ts.get_settings_by_document(None) is workspaces[keys[0]]


# ---------------------------------------------------------------------------
# Opt-in participation
# ---------------------------------------------------------------------------


class TestDocumentParticipation:
def test_retained_roots_nested_routing_and_live_updates(self, tmp_path):
root = tmp_path / "workspace café"
fixture = load_settings_fixture("producer", root)["workspaceEnablement"]
ts = _make_server(
ToolServerConfig(
tool_module="testtool",
tool_display="Test Tool",
default_settings=fixture["toolDefaults"],
)
)
options = fixture["initializationOptions"]
ts.apply_settings(
lsp.InitializeParams(
capabilities=lsp.ClientCapabilities(),
process_id=None,
initialization_options=options,
)
)
assert len(ts.workspace_settings) == 4
for setting in options["settings"]:
document = TextDocument(setting["workspace"] + "/src/demo.py")
routed = ts.get_settings_by_document(document)
assert routed["workspace"] == setting["workspace"]
assert routed["enabled"] is False
assert ts.is_document_enabled(document) is setting["_toolEnabled"]

notebook = root / "disabled" / "demo.ipynb"
synthetic = SyntheticDocument(
uri=notebook.as_uri().replace("file:", "vscode-notebook-cell:", 1)
+ "#cell",
path=str(notebook),
source="print('cell')",
)
assert ts.is_document_enabled(synthetic) is False
outside = TextDocument((tmp_path / "outside" / "demo.py").as_uri())
assert ts.is_document_enabled(outside) is True
assert ts.is_document_enabled(None) is True
assert ts.is_document_enabled(_make_document(None)) is True

ts.global_settings["_toolEnabled"] = False
assert ts.is_document_enabled(outside) is False
assert ts.is_document_enabled(None) is True
ts.update_workspace_settings(
[{"workspace": (root / "disabled").as_uri(), "_toolEnabled": True}]
)
assert ts.is_document_enabled(synthetic) is True
ts.workspace_settings.clear()
assert ts.is_document_enabled(None) is False

def test_all_disabled_roots_do_not_fall_back_to_enabled_globals(self, tmp_path):
roots = [tmp_path / "one", tmp_path / "two"]
ts = _make_server()
ts.global_settings["_toolEnabled"] = True
ts.update_workspace_settings(
[{"workspace": root.as_uri(), "_toolEnabled": False} for root in roots]
)
for root in roots:
assert (
ts.is_document_enabled(TextDocument((root / "demo.py").as_uri()))
is False
)
assert ts.is_document_enabled(None) is False
assert (
ts.is_document_enabled(TextDocument((tmp_path / "outside.py").as_uri()))
is True
)

def test_opted_in_filesystem_root_is_not_mistaken_for_global_fallback(
self, tmp_path
):
ts = _make_server()
ts.global_settings["_toolEnabled"] = True
root = pathlib.Path(tmp_path.anchor)
ts.update_workspace_settings(
[{"workspace": root.as_uri(), "_toolEnabled": False}]
)
assert (
ts.is_document_enabled(TextDocument((tmp_path / "demo.py").as_uri()))
is False
)

@pytest.mark.parametrize("opted_in", [False, True], ids=["legacy", "opted-in"])
def test_relative_document_does_not_inherit_cwd_workspace(
self, tmp_path, monkeypatch, opted_in
):
monkeypatch.chdir(tmp_path)
ts = _make_server(
ToolServerConfig(
tool_module="testtool",
tool_display="Test Tool",
resolve_symlinks=True,
)
)
ts.global_settings["args"] = ["--global"]
workspace = {"workspace": tmp_path.as_uri(), "args": ["--cwd"]}
if opted_in:
ts.global_settings["_toolEnabled"] = True
workspace["_toolEnabled"] = False
ts.update_workspace_settings([workspace])
document = _make_document("Untitled-1")

assert ts.get_document_key(document) is None
assert ts.get_settings_by_document(document)["args"] == ["--global"]
assert ts.is_document_enabled(document) is True

@pytest.mark.skipif(os.name != "nt", reason="Windows paths are case-insensitive")
def test_opted_in_windows_casing_matches_but_adjacent_prefix_does_not(
self, tmp_path
):
root = tmp_path / "MixedRoot"
ts = _make_server()
ts.global_settings["_toolEnabled"] = True
ts.update_workspace_settings(
[{"workspace": root.as_uri(), "_toolEnabled": False}]
)
document = _make_document(str(root / "src" / "demo.py").swapcase())
assert ts.get_settings_by_document(document)["workspace"] == root.as_uri()
assert ts.is_document_enabled(document) is False

outside = _make_document(
str(root.with_name(root.name + "-other") / "demo.py").swapcase()
)
assert ts.get_document_key(outside) is None
assert ts.is_document_enabled(outside) is True
assert (
ts.get_settings_by_path(pathlib.Path(outside.path))["_toolEnabled"] is False
)

@pytest.mark.parametrize(
("wire_value", "expected"),
[(False, False), (0, True), (None, True), ("false", True)],
)
def test_only_literal_false_disables_routed_document(
self, tmp_path, wire_value, expected
):
ts = _make_server()
ts.global_settings["_toolEnabled"] = False
ts.update_workspace_settings(
[{"workspace": tmp_path.as_uri(), "_toolEnabled": wire_value}]
)
document = TextDocument((tmp_path / "demo.py").as_uri())
assert ts.is_document_enabled(document) is expected

def test_legacy_enabled_policy_and_execution_remain_consumer_owned(self, tmp_path):
ts = _make_server(
ToolServerConfig(
tool_module="testtool",
tool_display="Test Tool",
default_settings={"enabled": False},
)
)
ts.global_settings["enabled"] = False
ts.update_workspace_settings(
[{"workspace": tmp_path.as_uri(), "enabled": False}]
)
assert (
ts.is_document_enabled(TextDocument((tmp_path / "demo.py").as_uri()))
is True
)
assert ts.is_document_enabled(None) is True
with patch("vscode_common_python_lsp.server.run_path") as run:
run.return_value.stderr = ""
ts.execute_tool(
argv=["tool"], mode="path", settings={"_toolEnabled": False}
)
run.assert_called_once()


# ---------------------------------------------------------------------------
# Constructor
# ---------------------------------------------------------------------------
Expand Down
Loading