diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 58c0c0d..d013861 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -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. diff --git a/README.md b/README.md index c594c8e..286d4f1 100644 --- a/README.md +++ b/README.md @@ -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: diff --git a/docs/supported-apis.md b/docs/supported-apis.md index 3a3f297..b9db68d 100644 --- a/docs/supported-apis.md +++ b/docs/supported-apis.md @@ -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 | @@ -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`: + +```typescript +const optedIn = { + ...toolConfig, // The extension's existing ToolConfig or ToolDefinition. + workspaceEnablementSetting: 'runTools', +}; +activateToolExtension(context, { serverInfo, toolConfig: optedIn }); +``` + +Contribute a resource-scoped boolean `.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 diff --git a/python/tests/fixtures/settings/producer.json b/python/tests/fixtures/settings/producer.json index 108e27c..4e1577c 100644 --- a/python/tests/fixtures/settings/producer.json +++ b/python/tests/fixtures/settings/producer.json @@ -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 + } + } } } diff --git a/python/tests/fixtures/settings_server.py b/python/tests/fixtures/settings_server.py index be7fded..1f0a94e 100644 --- a/python/tests/fixtures/settings_server.py +++ b/python/tests/fixtures/settings_server.py @@ -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: @@ -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() diff --git a/python/tests/test_server.py b/python/tests/test_server.py index af63a4d..cbbccc3 100644 --- a/python/tests/test_server.py +++ b/python/tests/test_server.py @@ -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 @@ -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 # --------------------------------------------------------------------------- diff --git a/python/tests/test_server_stdio.py b/python/tests/test_server_stdio.py index 397547b..d02635a 100644 --- a/python/tests/test_server_stdio.py +++ b/python/tests/test_server_stdio.py @@ -15,6 +15,7 @@ import time from typing import Any +import pytest from pygls import uris import vscode_common_python_lsp.server as server_module @@ -194,3 +195,86 @@ def test_real_stdio_settings_and_lifecycle(tmp_path): ) assert "fixture shutdown complete" in client.stderr assert "fixture exit complete" in client.stderr + + +@pytest.mark.parametrize("opted_in", [True, False]) +def test_real_stdio_participation_contract(tmp_path, opted_in): + root = tmp_path / "workspace café" + root.mkdir() + options = load_settings_fixture("producer", root)["workspaceEnablement"][ + "initializationOptions" + ] + if not opted_in: + for setting in [*options["settings"], options["globalSettings"]]: + del setting["_toolEnabled"] + client = _LspProcess(tmp_path) + try: + client.send( + { + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "processId": None, + "rootUri": root.as_uri(), + "capabilities": {}, + "initializationOptions": options, + }, + } + ) + assert client.response(1)["capabilities"]["documentFormattingProvider"] + client.send({"jsonrpc": "2.0", "method": "initialized", "params": {}}) + expected_executed = [] + resources = [ + (setting["workspace"] + "/demo.py", setting.get("_toolEnabled", True)) + for setting in options["settings"] + ] + resources.append(((tmp_path / "outside" / "demo.py").as_uri(), True)) + resources.append(((root / "disabled" / "demo.ipynb").as_uri(), not opted_in)) + for request_id, (uri, enabled) in enumerate(resources, 2): + client.send( + { + "jsonrpc": "2.0", + "method": "textDocument/didOpen", + "params": { + "textDocument": { + "uri": uri, + "languageId": "python", + "version": 1, + "text": "print('hello')", + } + }, + } + ) + client.send( + { + "jsonrpc": "2.0", + "id": request_id, + "method": "textDocument/formatting", + "params": { + "textDocument": {"uri": uri}, + "options": {"tabSize": 4, "insertSpaces": True}, + }, + } + ) + edits = client.response(request_id) + if enabled: + assert edits[0]["newText"] == "participated" + expected_executed.append(uri) + else: + assert edits == [] + + client.send( + {"jsonrpc": "2.0", "id": 20, "method": "test/settings", "params": {}} + ) + inspection = client.response(20) + assert len(inspection["settings"]) == 4 + assert inspection["executedDocuments"] == expected_executed + client.send({"jsonrpc": "2.0", "id": 21, "method": "shutdown", "params": None}) + assert client.response(21) is None + client.send({"jsonrpc": "2.0", "method": "exit", "params": None}) + assert client.process.wait(timeout=TIMEOUT) == 0 + finally: + client.close() + print(client.stderr, file=sys.stderr) + client.assert_protocol_complete() diff --git a/python/vscode_common_python_lsp/_routing.py b/python/vscode_common_python_lsp/_routing.py index 2a4665a..2490997 100644 --- a/python/vscode_common_python_lsp/_routing.py +++ b/python/vscode_common_python_lsp/_routing.py @@ -90,14 +90,32 @@ def get_document_key( if facade.workspace_settings: document_workspace = pathlib.Path(document.path) workspaces = {s["workspaceFS"] for s in facade.workspace_settings.values()} - - while document_workspace != document_workspace.parent: + opted_in = any("_toolEnabled" in s for s in facade.workspace_settings.values()) + workspace_keys = None + if opted_in: + workspace_keys = { + pathlib.Path(s["workspaceFS"]): s["workspaceFS"] + for s in facade.workspace_settings.values() + } + # A relative path's terminal "." must not resolve to a CWD workspace. + include_filesystem_root = opted_in and document_workspace.is_absolute() + + while ( + include_filesystem_root or document_workspace != document_workspace.parent + ): norm_path = normalize_path( str(document_workspace), resolve_symlinks=facade.config.resolve_symlinks, ) - if norm_path in workspaces: - return norm_path + key = ( + workspace_keys.get(pathlib.Path(norm_path)) + if workspace_keys is not None + else norm_path + ) + if key in workspaces: + return key + if document_workspace == document_workspace.parent: + break document_workspace = document_workspace.parent return None diff --git a/python/vscode_common_python_lsp/_settings.py b/python/vscode_common_python_lsp/_settings.py index 6438f70..e95254d 100644 --- a/python/vscode_common_python_lsp/_settings.py +++ b/python/vscode_common_python_lsp/_settings.py @@ -24,6 +24,8 @@ def get_global_defaults( "showNotifications", config.default_notification_level ), } + if "_toolEnabled" in global_settings: + base["_toolEnabled"] = global_settings["_toolEnabled"] for key, default in config.default_settings.items(): base[key] = global_settings.get(key, default) # Hardcoded settings ignore whatever the client sent in GLOBAL_SETTINGS. diff --git a/python/vscode_common_python_lsp/server.py b/python/vscode_common_python_lsp/server.py index b4685f3..e59d998 100644 --- a/python/vscode_common_python_lsp/server.py +++ b/python/vscode_common_python_lsp/server.py @@ -142,6 +142,26 @@ def get_settings_by_document(self, document: TextDocument | None) -> dict[str, A self, document, normalize_path=normalize_path, uris=uris ) + def is_document_enabled(self, document: TextDocument | None) -> bool: + """Return the routed document's opt-in participation decision. + + TypeScript's ``workspaceEnablementSetting`` supplies ``_toolEnabled`` + without omitting disabled roots or replacing consumer-owned ``enabled``. + Only literal ``False`` disables; missing or other values mean enabled. + Outside-workspace documents use global defaults; absent/pathless + documents retain the first-workspace fallback. + For notebooks, pass the synthetic document with the notebook's file path. + + Handlers must call this before tool work. Execution helpers and existing + consumer policies are not automatically gated. + Participation uses ``get_settings_by_document``, not the legacy + ``get_settings_by_path`` lookup and its first-workspace fallback. + """ + return ( + self.get_settings_by_document(document).get("_toolEnabled", True) + is not False + ) + # ----------------------------------------------------------------- # CWD resolution # ----------------------------------------------------------------- diff --git a/typescript/src/activation.ts b/typescript/src/activation.ts index 33cd49c..894f7ab 100644 --- a/typescript/src/activation.ts +++ b/typescript/src/activation.ts @@ -562,9 +562,13 @@ export function registerCommonSubscriptions( // Configuration change context.subscriptions.push( onDidChangeConfiguration(async (e: vscode.ConfigurationChangeEvent) => { - const trackedSettings = toolConfig.supportsPerProjectEnvironments - ? [...toolConfig.trackedSettings, USE_PER_PROJECT_ENVIRONMENTS] - : toolConfig.trackedSettings; + const trackedSettings = [...toolConfig.trackedSettings]; + if (toolConfig.supportsPerProjectEnvironments) { + trackedSettings.push(USE_PER_PROJECT_ENVIRONMENTS); + } + if (toolConfig.workspaceEnablementSetting) { + trackedSettings.push(toolConfig.workspaceEnablementSetting); + } if (checkIfConfigurationChanged(e, serverId, trackedSettings)) { await safeRunServer(toolContext, 'config change'); } diff --git a/typescript/src/settings.ts b/typescript/src/settings.ts index 0b0bec5..7cc202e 100644 --- a/typescript/src/settings.ts +++ b/typescript/src/settings.ts @@ -233,6 +233,10 @@ export async function getWorkspaceSettings( settings.cwd = expandTilde(settings.cwd); } + if (toolConfig.workspaceEnablementSetting) { + settings._toolEnabled = config.get(toolConfig.workspaceEnablementSetting, true) !== false; + } + return settings; } @@ -281,12 +285,19 @@ export async function getGlobalSettings( settings[key] = getGlobalValue(config, key, defaultValue); } + if (toolConfig.workspaceEnablementSetting) { + settings._toolEnabled = getGlobalValue(config, toolConfig.workspaceEnablementSetting, true) !== false; + } + return settings; } /** * Resolve settings for the supplied roots, or all workspace folders by - * default. Consumers may supply Python project roots to enable per-project + * default. Disabled roots remain represented so document routing cannot + * mistake them for resources outside the workspace. + * + * Consumers may supply Python project roots to enable per-project * interpreter resolution while retaining a singleton language server. */ export function getExtensionSettings( diff --git a/typescript/src/types.ts b/typescript/src/types.ts index d0a7516..b41d0e2 100644 --- a/typescript/src/types.ts +++ b/typescript/src/types.ts @@ -20,6 +20,8 @@ interface ICommonSettings { importStrategy: string; showNotifications: string; extraPaths?: string[]; + /** Reserved shared wire state; absent unless workspace enablement is opted in. */ + _toolEnabled?: boolean; } /** Base settings resolved per workspace by the settings module. */ @@ -54,6 +56,18 @@ export interface ToolConfig { settingsDefaults: Record; trackedSettings: string[]; + /** + * Opt in to per-folder participation using this boolean configuration key + * (e.g. 'enabled', 'enable' or 'runTools'), relative to toolId. + * Resolvers retain every root and send its value as `_toolEnabled`, defaulting + * to true. Common subscriptions track the key automatically. + * + * Python handlers must call ToolServer.is_document_enabled before tool work; + * this does not gate execution or replace consumer-owned settings/hooks. + * Unset preserves the existing settings payload and execution behavior. + */ + workspaceEnablementSetting?: string; + // Environment extraEnvVars?: Record; diff --git a/typescript/tests/activation.test.ts b/typescript/tests/activation.test.ts index 23e1d73..3aea816 100644 --- a/typescript/tests/activation.test.ts +++ b/typescript/tests/activation.test.ts @@ -21,7 +21,7 @@ import * as loggingModule from '../src/logging'; import * as settingsModule from '../src/settings'; import * as serverModule from '../src/server'; import * as statusModule from '../src/status'; -import { IServerInfo, ToolConfig } from '../src/types'; +import { IInitOptions, IServerInfo, ToolConfig } from '../src/types'; import { PythonEnvironmentsProvider } from '../src/python'; import * as utilities from '../src/utilities'; import * as vscodeapi from '../src/vscodeapi'; @@ -745,6 +745,83 @@ suite('registerCommonSubscriptions', () => { assert.isTrue((options.toolContext.runServer as sinon.SinonStub).calledOnce); }); + + for (const perProject of [false, true]) { + test(`custom enablement changes restart the singleton with every root (per-project: ${perProject})`, async () => { + const root = { uri: vscode.Uri.file(process.cwd()), name: 'root', index: 0 }; + const disabled = { + uri: vscode.Uri.file(path.join(process.cwd(), 'disabled')), + name: 'disabled', index: 1, + }; + const project = { + uri: vscode.Uri.file(path.dirname(__filename)), name: 'project', index: 0, + }; + let enabled = false; + sandbox.stub(utilities, 'getProjectRoot').resolves(root); + sandbox.stub(vscodeapi, 'getWorkspaceFolders').returns([root, disabled]); + sandbox.stub(vscodeapi, 'getWorkspaceFolder').returns(root); + sandbox.stub(envFileModule, 'getEnvFileVars').resolves({}); + sandbox.stub(vscodeapi, 'getConfiguration').callsFake((_namespace, scope) => ({ + get: (key: string, fallback?: unknown) => { + if (key === 'usePerProjectEnvironments') { + return perProject; + } + if (key === 'runTools') { + return (scope as vscode.WorkspaceFolder)?.uri === disabled.uri ? enabled : true; + } + return fallback; + }, + inspect: () => undefined, + }) as unknown as vscode.WorkspaceConfiguration); + let configurationHandler!: (event: vscode.ConfigurationChangeEvent) => Promise; + (vscodeapi.onDidChangeConfiguration as sinon.SinonStub).callsFake((handler) => { + configurationHandler = handler; + return { dispose: sinon.stub() }; + }); + const provider = makeMockProvider(sandbox); + (provider.getPythonProjects as sinon.SinonStub).resolves([project]); + const toolConfig = makeToolConfig({ + trackedSettings: ['args'], + workspaceEnablementSetting: 'runTools', + supportsPerProjectEnvironments: perProject, + }); + const toolContext = createToolContext({ + serverInfo: makeServerInfo(), outputChannel: makeMockOutputChannel(), + toolConfig, pythonProvider: provider, + }); + registerCommonSubscriptions(context, makeRegisterOptions({ toolConfig, toolContext })); + const snapshots = () => { + const client = toolContext.lsClient as unknown as import('./_languageclient_mock').LanguageClient; + return (client.clientOptions as { initializationOptions: IInitOptions }).initializationOptions; + }; + try { + await toolContext.runServer(); + assert.isDefined(toolContext.lsClient); + const before = snapshots(); + const firstClient = toolContext.lsClient!; + const expectedRoots = [root, disabled, ...(perProject ? [project] : [])] + .map((folder) => folder.uri.toString()); + assert.deepEqual(before.settings.map((settings) => settings.workspace), expectedRoots); + assert.isFalse(before.settings[1]._toolEnabled); + assert.isTrue(before.globalSettings._toolEnabled); + + enabled = true; + await configurationHandler({ + affectsConfiguration: (key: string) => key === 'flake8.runTools', + }); + const after = snapshots(); + assert.deepEqual(after.settings.map((settings) => settings.workspace), expectedRoots); + assert.isTrue(after.settings[1]._toolEnabled); + assert.notStrictEqual(toolContext.lsClient, firstClient); + assert.equal(firstClient.state, State.Stopped); + assert.equal(toolContext.lsClient!.state, State.Running); + assert.deepEqual(toolConfig.trackedSettings, ['args']); + } finally { + await deactivateServer(toolContext); + subscriptions.forEach((subscription) => subscription.dispose()); + } + }); + } }); // --------------------------------------------------------------------------- diff --git a/typescript/tests/settingsWorkspace.test.ts b/typescript/tests/settingsWorkspace.test.ts index be45cea..caedf3f 100644 --- a/typescript/tests/settingsWorkspace.test.ts +++ b/typescript/tests/settingsWorkspace.test.ts @@ -5,14 +5,14 @@ import { assert } from 'chai'; import { readFileSync } from 'fs'; import * as path from 'path'; import * as sinon from 'sinon'; -import { pathToFileURL } from 'url'; +import { fileURLToPath, pathToFileURL } from 'url'; import { Uri, WorkspaceFolder } from 'vscode'; import { ToolDefinition } from '../src'; import { checkIfConfigurationChanged, expandTilde, - getExtraPaths, getExtensionSettings, + getExtraPaths, getGlobalSettings, getWorkspaceSettings, logLegacySettings, @@ -100,6 +100,15 @@ suite('settings — workspace & global resolution', () => { toolDefaults: ToolDefinition['settingsDefaults']; configuration: { workspace: Record; global: Record }; initializationOptions: IInitOptions; + workspaceEnablement: { + settingKey: string; + toolDefaults: ToolConfig['settingsDefaults']; + configuration: { + workspaces: { workspace: string; values: Record }[]; + global: Record; + }; + initializationOptions: IInitOptions; + }; }; getConfigurationStub.returns({ get: (key: string, fallback?: unknown) => @@ -125,6 +134,47 @@ suite('settings — workspace & global resolution', () => { }; assert.deepEqual(typed, actual); assert.deepEqual(await getWorkspaceSettings('flake8', root, typedToolConfig), actual.settings[0]); + + const enablement = fixture.workspaceEnablement; + const roots = enablement.configuration.workspaces.map((entry, index) => { + const folder = makeWorkspace(`root-${index}`, fileURLToPath(entry.workspace), index); + sinon.stub(folder.uri, 'toString').returns(entry.workspace); + return folder; + }); + (vscodeapi.getWorkspaceFolder as sinon.SinonStub).callsFake((uri: Uri) => + roots.find((folder) => folder.uri.toString() === uri.toString()), + ); + getConfigurationStub.callsFake((_namespace: string, scope?: WorkspaceFolder) => { + const values = enablement.configuration.workspaces.find( + (entry) => entry.workspace === scope?.uri?.toString(), + )?.values; + return { + get: (key: string, fallback?: unknown) => values?.[key] ?? fallback, + inspect: (key: string) => ({ globalValue: enablement.configuration.global[key] }), + }; + }); + const optedIn: ToolDefinition<{ enabled: boolean }> = { + ...toolConfig, + settingsDefaults: { enabled: false }, + workspaceEnablementSetting: enablement.settingKey, + }; + const optedInPayload: IInitOptions = { + settings: await getExtensionSettings('flake8', optedIn, undefined, roots), + globalSettings: await getGlobalSettings('flake8', optedIn), + }; + assert.deepEqual(optedInPayload, enablement.initializationOptions); + + const legacy = { ...optedIn, workspaceEnablementSetting: undefined }; + const legacyPayload: IInitOptions = { + settings: await getExtensionSettings('flake8', legacy, undefined, roots), + globalSettings: await getGlobalSettings('flake8', legacy), + }; + assert.deepEqual( + legacyPayload, + JSON.parse(JSON.stringify(optedInPayload), (key: string, value: unknown) => + key === '_toolEnabled' ? undefined : value, + ), + ); }); test('typed definitions preserve defaults and project only declared custom keys', async () => { @@ -507,4 +557,69 @@ suite('settings — workspace & global resolution', () => { ); }); }); + + suite('opt-in per-folder participation', () => { + const wsA = makeWorkspace('folder-a', '/home/user/projects/a', 0); + const wsB = makeWorkspace('folder-b', '/home/user/projects/b', 1); + + test('legacy enabled:false retains every root without adding shared policy', async () => { + getWorkspaceFoldersStub.returns([wsA, wsB]); + getConfigurationStub.returns({ + get: (key: string, fallback?: unknown) => key === 'enabled' ? false : fallback, + }); + const resolveInterpreter = sinon.stub().resolves({ path: ['/tool/python'] }); + const result = await getExtensionSettings('flake8', makeToolConfig(), resolveInterpreter); + assert.lengthOf(result, 2); + assert.equal(resolveInterpreter.callCount, 2); + for (const settings of result) { + assert.isFalse(settings.enabled); + assert.notProperty(settings, '_toolEnabled'); + } + }); + + for (const settingKey of ['enabled', 'enable', 'runTools']) { + test(`retains all disabled folders with the configured ${settingKey} key`, async () => { + getWorkspaceFoldersStub.returns([wsA, wsB]); + getConfigurationStub.returns({ + get: (key: string, def?: unknown) => key === settingKey ? false : def, + }); + const result = await getExtensionSettings('flake8', makeToolConfig({ + workspaceEnablementSetting: settingKey, + })); + assert.deepEqual(result.map((settings) => settings.workspace), [ + wsA.uri.toString(), wsB.uri.toString(), + ]); + assert.isTrue(result.every((settings) => settings._toolEnabled === false)); + }); + } + + test('absent opt-in setting is enabled without replacing consumer defaults', async () => { + getConfigurationStub.returns({ + get: (_key: string, def?: unknown) => def, + inspect: () => ({ workspaceValue: false }), + }); + const toolConfig = makeToolConfig({ + settingsDefaults: { enabled: false }, + workspaceEnablementSetting: 'runTools', + }); + const workspace = await getWorkspaceSettings('flake8', wsA, toolConfig); + const global = await getGlobalSettings('flake8', toolConfig); + for (const settings of [workspace, global]) { + assert.isTrue(settings._toolEnabled); + assert.isFalse(settings.enabled); + } + }); + + test('global opt-out uses user scope, not an enabled workspace value', async () => { + getConfigurationStub.returns({ + get: (_key: string, def?: unknown) => def, + inspect: (key: string) => key === 'runTools' + ? { globalValue: false, workspaceValue: true } : undefined, + }); + const result = await getGlobalSettings('flake8', makeToolConfig({ + workspaceEnablementSetting: 'runTools', + })); + assert.isFalse(result._toolEnabled); + }); + }); });