From 3a78739af7a137768239dbab38fc1fee0ab7d84f Mon Sep 17 00:00:00 2001 From: Eduardo Villalpando Mello Date: Mon, 16 Nov 2026 13:12:34 -0800 Subject: [PATCH] Add opt-in activation facade with explicit lifetime ownership Compose the existing shared lifecycle behind a small activation handle. Preserve deferred startup, own cleanup and late subscriptions, and document inherited lifecycle limits with focused runtime and public API checks. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 85ef72cc-9e26-4bc4-b1c3-55256d9bef91 --- README.md | 9 + typescript/README.md | 63 +++ typescript/src/activation.ts | 6 +- typescript/src/configWatcher.ts | 76 ++-- typescript/src/index.ts | 3 + typescript/src/status.ts | 19 +- typescript/src/toolExtension.ts | 155 ++++++++ typescript/tests/toolExtension.test.ts | 405 ++++++++++++++++++++ typescript/tests/toolExtension.typecheck.ts | 44 +++ 9 files changed, 744 insertions(+), 36 deletions(-) create mode 100644 typescript/src/toolExtension.ts create mode 100644 typescript/tests/toolExtension.test.ts create mode 100644 typescript/tests/toolExtension.typecheck.ts diff --git a/README.md b/README.md index 506bd10..add4f50 100644 --- a/README.md +++ b/README.md @@ -197,6 +197,15 @@ notes, but they do not trigger or gate the submodule updates. ### Optional configuration +For an additive activation entry point with explicit resource ownership, see +the [activation facade example](typescript/README.md#opt-in-activation-facade). +`activateToolExtension(context, { serverInfo, toolConfig })` returns a small +runtime handle; initialization remains deferred, not client-ready. Await +`runtime.deactivate()` for facade cleanup and existing client-stop behavior. +It preserves caller-owned subscriptions, but does not drain every legacy +in-flight restart or isolate the module-global logger/status. Existing manual +composition remains supported. + 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. diff --git a/typescript/README.md b/typescript/README.md index e8b1e0b..075ec6f 100644 --- a/typescript/README.md +++ b/typescript/README.md @@ -10,6 +10,69 @@ published package or a supported bare-module import. See the [main README](../README.md#consuming-in-extensions) for build order, consumer type-checking and bundling instructions. +## Opt-in activation facade + +For conventional tools, `activateToolExtension` composes the existing shared +helpers. It accepts explicit `IServerInfo` and either a legacy `ToolConfig` or +a `ToolDefinition`; it does not load a manifest or infer tool policy. +For example, in the consuming extension's `src/extension.ts`: + +```typescript +import { ExtensionContext } from 'vscode'; +import { + activateToolExtension, + loadServerDefaults, + ToolExtensionRuntime, +} from '../external/vscode-common-python-lsp/typescript/dist'; +import { toolDefinition } from './toolDefinition'; + +let runtime: ToolExtensionRuntime | undefined; + +export function activate(context: ExtensionContext): void { + runtime = activateToolExtension(context, { + serverInfo: loadServerDefaults(context.extensionPath), + toolConfig: toolDefinition, + }); +} + +export async function deactivate(): Promise { + await runtime?.deactivate(); + runtime = undefined; +} +``` + +`toolDefinition` supplies the extension's existing policies and server script +path (see the typed example below). Build the pinned shared checkout before +type-checking and bundle its public entry and dependencies as described in the +main README. + +The facade installs common listeners and, for formatters, the placeholder +synchronously, then initializes with `setImmediate`. **The returned handle is +not a client-ready promise**: Python resolution and client startup remain +deferred. Common listeners are present before Python can emit its initial +interpreter event. + +The facade owns its output channel, logger registration, Python provider, +tool context, commands, watchers and listeners. It adds one cleanup disposable +to `context.subscriptions`; it does not remove or dispose unrelated caller +subscriptions. Context disposal initiates shutdown; `await runtime.deactivate()` +observes it. Both paths are idempotent. Shutdown cancels pending initialization, +disposes the tool context, and delegates client stopping to `deactivateServer`. +If initialization already started, shutdown waits for that `initialize()` call +to settle and disposes any late subscriptions immediately; unresolved Python +API acquisition can therefore delay shutdown. Logging stays available during +this cleanup. Synchronous activation failures roll back owned resources and +are rethrown; asynchronous initialization/cleanup failures are caught and logged. + +This is composition, not a new restart scheduler. As with the low-level APIs, +`runServer()` may resolve after scheduling a delayed retry, and shutdown does +**not** drain every in-flight restart/start (including startup triggered by a +Python event). No stronger client-readiness or full-quiescence guarantee is +implied. Logger and status are still module-global: this is not independent +multi-tool-instance isolation. Existing low-level activation APIs remain +available unchanged for custom composition; no consumer migration or custom +lifecycle hooks are required. + ## Typed tool definitions Adoption is optional. Annotate a definition with `ToolDefinition` to diff --git a/typescript/src/activation.ts b/typescript/src/activation.ts index a0a5894..7181510 100644 --- a/typescript/src/activation.ts +++ b/typescript/src/activation.ts @@ -496,7 +496,7 @@ export interface RegisterSubscriptionsOptions { * this call. */ export function registerCommonSubscriptions( - context: vscode.ExtensionContext, + context: Pick, options: RegisterSubscriptionsOptions, ): void { const { serverInfo, outputChannel, toolConfig, toolContext, pythonProvider } = options; @@ -517,6 +517,8 @@ export function registerCommonSubscriptions( outputChannel.onDidChangeLogLevel(async (e) => { await changeLogLevel(e, vscode.env.logLevel); }), + ); + context.subscriptions.push( vscode.env.onDidChangeLogLevel(async (e) => { await changeLogLevel(outputChannel.logLevel, e); }), @@ -534,6 +536,8 @@ export function registerCommonSubscriptions( registerCommand(`${serverId}.showLogs`, async () => { outputChannel.show(); }), + ); + context.subscriptions.push( registerCommand(`${serverId}.restart`, async () => { await safeRunServer(toolContext, 'restart command'); }), diff --git a/typescript/src/configWatcher.ts b/typescript/src/configWatcher.ts index 8c2cb85..1203339 100644 --- a/typescript/src/configWatcher.ts +++ b/typescript/src/configWatcher.ts @@ -28,41 +28,53 @@ export function createConfigFileWatchers( toolName: string, onConfigChanged: () => Promise, ): Disposable[] { - return configFiles.map((pattern) => { - const watcher = workspace.createFileSystemWatcher(`**/${pattern}`); - let disposed = false; - let pending: Promise | undefined; + const watchers: Disposable[] = []; + try { + for (const pattern of configFiles) { + const watcher = workspace.createFileSystemWatcher(`**/${pattern}`); + const registrations: Disposable[] = [watcher]; + let disposed = false; + let pending: Promise | undefined; - const handleEvent = (event: string) => { - if (disposed) { - return; - } - traceLog(`${toolName} config file ${event}: ${pattern}`); - const run = () => - onConfigChanged().catch((e) => traceError(`Config file ${event} handler failed`, e)); - - const nextPending = (pending ? pending.then(run, run) : run()).finally(() => { - if (pending === nextPending) { - pending = undefined; + const handleEvent = (event: string) => { + if (disposed) { + return; } - }); + traceLog(`${toolName} config file ${event}: ${pattern}`); + const run = () => onConfigChanged().catch((e) => traceError(`Config file ${event} handler failed`, e)); - pending = nextPending; - }; + const nextPending = (pending ? pending.then(run, run) : run()).finally(() => { + if (pending === nextPending) { + pending = undefined; + } + }); - const changeDisposable = watcher.onDidChange(() => handleEvent('changed')); - const createDisposable = watcher.onDidCreate(() => handleEvent('created')); - const deleteDisposable = watcher.onDidDelete(() => handleEvent('deleted')); + pending = nextPending; + }; - return { - dispose(): void { - disposed = true; - pending = undefined; - changeDisposable.dispose(); - createDisposable.dispose(); - deleteDisposable.dispose(); - watcher.dispose(); - }, - }; - }); + watchers.push({ + dispose(): void { + disposed = true; + pending = undefined; + for (const disposable of registrations.splice(0).reverse()) { + try { + disposable.dispose(); + } catch (error) { + traceError('Config watcher cleanup failed', error); + } + } + }, + }); + registrations.push(watcher.onDidChange(() => handleEvent('changed'))); + registrations.push(watcher.onDidCreate(() => handleEvent('created'))); + registrations.push(watcher.onDidDelete(() => handleEvent('deleted'))); + } + return watchers; + } catch (error) { + // A caller cannot own watchers that this factory never returned. + for (const watcher of watchers.reverse()) { + watcher.dispose(); + } + throw error; + } } diff --git a/typescript/src/index.ts b/typescript/src/index.ts index 8a11c0c..e40b46e 100644 --- a/typescript/src/index.ts +++ b/typescript/src/index.ts @@ -89,3 +89,6 @@ export { RegisterSubscriptionsOptions, ToolExtensionContext, } from './activation'; + +// Opt-in activation facade +export { activateToolExtension, ActivateToolExtensionOptions, ToolExtensionRuntime } from './toolExtension'; diff --git a/typescript/src/status.ts b/typescript/src/status.ts index 94ed765..e16d002 100644 --- a/typescript/src/status.ts +++ b/typescript/src/status.ts @@ -5,6 +5,7 @@ import { LanguageStatusItem, Disposable, l10n, LanguageStatusSeverity } from 'vs import { Command } from 'vscode-languageclient'; import { createLanguageStatusItem } from './vscodeapi'; import { getDocumentSelector } from './utilities'; +import { traceError } from './logging'; let _status: LanguageStatusItem | undefined; export function registerLanguageStatusItem(id: string, name: string, command: string): Disposable { @@ -12,9 +13,21 @@ export function registerLanguageStatusItem(id: string, name: string, command: st const status = createLanguageStatusItem(id, getDocumentSelector()); _status = status; - status.name = name; - status.text = name; - status.command = Command.create(l10n.t('Open logs'), command); + try { + status.name = name; + status.text = name; + status.command = Command.create(l10n.t('Open logs'), command); + } catch (error) { + if (_status === status) { + _status = undefined; + } + try { + status.dispose(); + } catch (cleanupError) { + traceError('Language status cleanup failed', cleanupError); + } + throw error; + } return { dispose: () => { diff --git a/typescript/src/toolExtension.ts b/typescript/src/toolExtension.ts new file mode 100644 index 0000000..034716d --- /dev/null +++ b/typescript/src/toolExtension.ts @@ -0,0 +1,155 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +import * as vscode from 'vscode'; +import { createToolContext, deactivateServer, registerCommonSubscriptions, ToolExtensionContext } from './activation'; +import { registerLogger } from './logging'; +import { PythonEnvironmentsProvider } from './python'; +import { IServerInfo, ToolConfig } from './types'; +import { createOutputChannel } from './vscodeapi'; + +/** Explicit tool metadata and policy for {@link activateToolExtension}. */ +export interface ActivateToolExtensionOptions { + serverInfo: IServerInfo; + /** Accepts legacy ToolConfig and structurally compatible ToolDefinition values. */ + toolConfig: ToolConfig; +} + +/** The facade's lifetime handle, not a client-ready notification. */ +export interface ToolExtensionRuntime { + /** + * Idempotently cancel deferred initialization and dispose facade-owned resources. + * + * Stops the client via deactivateServer and waits for an already-started + * initialize() to settle, disposing late subscriptions too. This does not + * drain every in-flight restart or delayed retry in the legacy lifecycle. + * Cleanup failures are logged rather than rejected. + */ + deactivate(): Promise; +} + +/** + * Compose the shared runtime without changing the existing tool lifecycle. + * + * Common listeners and a formatter placeholder (when enabled) are installed + * synchronously. Initialization is deferred with setImmediate: returning this + * handle does not mean Python is resolved or the language client is Running. + * + * Owns its output channel, logger, Python provider, tool context and subscriptions; + * the caller's other subscriptions are untouched. Context disposal initiates the + * same cleanup as deactivate(); explicitly await deactivate() to observe completion. + * The existing module-global logger/status still preclude independent tool instances. + */ +export function activateToolExtension( + context: vscode.ExtensionContext, + options: ActivateToolExtensionOptions, +): ToolExtensionRuntime { + let outputChannel: vscode.LogOutputChannel | undefined; + let logger: vscode.Disposable | undefined; + let toolContext: ToolExtensionContext | undefined; + let scheduled: NodeJS.Immediate | undefined; + let initialization: Promise = Promise.resolve(); + let closed = false; + let finishShutdown!: () => void; + const shutdown = new Promise((resolve) => { + finishShutdown = resolve; + }); + const subscriptions: vscode.Disposable[] = []; + const pendingDisposals: Promise[] = []; + + function report(message: string, error: unknown): void { + try { + outputChannel?.error(`${message}: ${error}`); + } catch { + // A broken output channel must not turn cleanup into an unhandled rejection. + } + } + + async function dispose(disposable: vscode.Disposable | undefined): Promise { + try { + await disposable?.dispose(); + } catch (error) { + report('Tool extension cleanup failed', error); + } + } + + // Legacy initialization appends to this array after awaits. Once closed, + // dispose additions immediately instead of retaining unowned subscriptions. + subscriptions.push = (...items) => { + if (closed) { + for (const item of items) { + pendingDisposals.push(dispose(item)); + } + } else { + Array.prototype.push.apply(subscriptions, items); + } + return subscriptions.length; + }; + + async function teardown(): Promise { + // Dispose the context first so events/late initialization cannot revive it. + const stopping = deactivateServer(toolContext).catch((error) => + report('Tool extension shutdown failed', error), + ); + for (const disposable of subscriptions.splice(0).reverse()) { + pendingDisposals.push(dispose(disposable)); + } + await Promise.all([stopping, initialization]); + while (pendingDisposals.length > 0) { + await Promise.all(pendingDisposals.splice(0)); + } + // Keep logging available until initialization and late cleanup have settled. + await dispose(logger); + await dispose(outputChannel); + } + + function deactivate(): Promise { + if (!closed) { + closed = true; + if (scheduled) { + clearImmediate(scheduled); + scheduled = undefined; + } + void teardown().then(finishShutdown, (error) => { + report('Tool extension shutdown failed', error); + finishShutdown(); + }); + } + return shutdown; + } + + try { + const { serverInfo, toolConfig } = options; + outputChannel = createOutputChannel(serverInfo.name); + logger = registerLogger(outputChannel); + const pythonProvider = new PythonEnvironmentsProvider(toolConfig); + subscriptions.push(pythonProvider); + toolContext = createToolContext({ + serverInfo, + outputChannel, + toolConfig, + pythonProvider, + }); + registerCommonSubscriptions( + { subscriptions }, + { serverInfo, outputChannel, toolConfig, toolContext, pythonProvider }, + ); + context.subscriptions.push({ dispose: () => void deactivate() }); + scheduled = setImmediate(() => { + scheduled = undefined; + initialization = Promise.resolve() + .then(() => { + if (!closed) { + return toolContext?.initialize(subscriptions); + } + return undefined; + }) + .catch((error) => report('Tool extension initialization failed', error)); + }); + return { deactivate }; + } catch (error) { + report('Tool extension activation failed', error); + void deactivate(); + throw error; + } +} diff --git a/typescript/tests/toolExtension.test.ts b/typescript/tests/toolExtension.test.ts new file mode 100644 index 0000000..5ff0e6b --- /dev/null +++ b/typescript/tests/toolExtension.test.ts @@ -0,0 +1,405 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +import { assert } from 'chai'; +import * as path from 'path'; +import * as sinon from 'sinon'; +import * as vscode from 'vscode'; +import { PythonEnvironmentApi, PythonEnvironments } from '@vscode/python-environments'; +import { LanguageClient } from 'vscode-languageclient/node'; +import * as activation from '../src/activation'; +import { registerLogger } from '../src/logging'; +import { PythonEnvironmentsProvider } from '../src/python'; +import { activateToolExtension, ToolExtensionRuntime } from '../src'; +import { IServerInfo, ToolConfig } from '../src/types'; +import * as vscodeapi from '../src/vscodeapi'; + +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise((res) => { + resolve = res; + }); + return { promise, resolve }; +} + +function nextImmediate(): Promise { + return new Promise((resolve) => setImmediate(resolve)); +} + +const serverInfo: IServerInfo = { name: 'Example', module: 'example' }; +const toolConfig: ToolConfig = { + toolId: 'example', + toolDisplayName: 'Example', + toolModule: 'example', + minimumPythonVersion: { major: 3, minor: 10 }, + configFiles: ['tool.toml', 'setup.cfg'], + settingsDefaults: { enabled: false, ignorePatterns: [] }, + trackedSettings: ['args', 'path', 'enabled', 'envFile'], + serverScript: path.join(process.cwd(), 'bundled', 'tool', 'lsp_server.py'), +}; + +suite('activateToolExtension', () => { + let sandbox: sinon.SinonSandbox; + let runtimes: ToolExtensionRuntime[]; + let resources: Array<{ name: string; dispose: sinon.SinonStub }>; + let commands: Map Promise>; + let channels: vscode.LogOutputChannel[]; + let configuredInterpreter: string[] | undefined; + let api: { + getEnvironment: sinon.SinonStub; + onDidChangeEnvironment: sinon.SinonStub; + onDidChangePythonProjects: sinon.SinonStub; + onDidChangePackages: sinon.SinonStub; + }; + let start: sinon.SinonSpy; + let stop: sinon.SinonSpy; + let initializePython: sinon.SinonSpy; + let providerDispose: sinon.SinonSpy; + + function resource(name: string, onDispose?: () => void) { + const disposable = { + name, + dispose: sandbox.stub().callsFake(onDispose ?? (() => undefined)), + }; + resources.push(disposable); + return disposable; + } + + function makeContext() { + const unrelated = resource('unrelated'); + const subscriptions: vscode.Disposable[] = [unrelated]; + return { context: { subscriptions } as vscode.ExtensionContext, unrelated }; + } + + function activate(context: vscode.ExtensionContext, overrides?: Partial) { + const runtime = activateToolExtension(context, { + serverInfo, + toolConfig: { ...toolConfig, ...overrides }, + }); + runtimes.push(runtime); + return runtime; + } + + function makeWatcher() { + return { + ...resource('watcher'), + ignoreCreateEvents: false, + ignoreChangeEvents: false, + ignoreDeleteEvents: false, + onDidChange: sandbox.stub().callsFake(() => resource('watcher.change')), + onDidCreate: sandbox.stub().callsFake(() => resource('watcher.create')), + onDidDelete: sandbox.stub().callsFake(() => resource('watcher.delete')), + }; + } + + setup(() => { + sandbox = sinon.createSandbox(); + runtimes = []; + resources = []; + channels = []; + commands = new Map(); + configuredInterpreter = [path.join(process.cwd(), 'configured-python')]; + sandbox + .stub(vscode.workspace, 'workspaceFolders') + .value([{ uri: vscode.Uri.file(process.cwd()), name: 'workspace', index: 0 }]); + sandbox.stub(vscode.workspace, 'getConfiguration').callsFake( + () => + ({ + get: (key: string, fallback?: unknown) => + key === 'interpreter' ? configuredInterpreter : fallback, + inspect: (key: string) => ({ + globalValue: key === 'interpreter' ? configuredInterpreter : undefined, + }), + }) as vscode.WorkspaceConfiguration, + ); + sandbox.stub(vscode.window, 'createOutputChannel').callsFake((name) => { + const channel = { + ...resource('output'), + name, + logLevel: vscode.LogLevel.Info, + appendLine: sandbox.stub(), + error: sandbox.stub(), + warn: sandbox.stub(), + info: sandbox.stub(), + debug: sandbox.stub(), + show: sandbox.stub(), + onDidChangeLogLevel: sandbox.stub().callsFake(() => resource('channel.logLevel')), + } as unknown as vscode.LogOutputChannel; + channels.push(channel); + return channel; + }); + sandbox.stub(vscode.env, 'onDidChangeLogLevel').callsFake(() => resource('global.logLevel')); + sandbox.stub(vscodeapi, 'onDidChangeConfiguration').callsFake(() => resource('configuration')); + sandbox.stub(vscode.commands, 'registerCommand').callsFake((name, callback) => { + commands.set(name, callback); + return resource(name, () => commands.delete(name)); + }); + sandbox + .stub(vscode.languages, 'createLanguageStatusItem') + .callsFake(() => resource('status') as unknown as vscode.LanguageStatusItem); + sandbox.stub(vscode.languages, 'registerDocumentFormattingEditProvider').callsFake(() => resource('formatter')); + sandbox.stub(vscode.workspace, 'createFileSystemWatcher').callsFake(makeWatcher); + api = { + getEnvironment: sandbox.stub().resolves({ + version: '3.12.0', + execInfo: { + run: { executable: path.join(process.cwd(), 'managed-python') }, + }, + }), + onDidChangeEnvironment: sandbox.stub().callsFake(() => resource('python.environment')), + onDidChangePythonProjects: sandbox.stub().callsFake(() => resource('python.projects')), + onDidChangePackages: sandbox.stub().callsFake(() => resource('python.packages')), + }; + sandbox.stub(PythonEnvironments, 'api').resolves(api as unknown as PythonEnvironmentApi); + start = sandbox.spy(LanguageClient.prototype, 'start'); + stop = sandbox.spy(LanguageClient.prototype, 'stop'); + initializePython = sandbox.spy(PythonEnvironmentsProvider.prototype, 'initializePython'); + providerDispose = sandbox.spy(PythonEnvironmentsProvider.prototype, 'dispose'); + }); + + teardown(async () => { + await Promise.all(runtimes.map((runtime) => runtime.deactivate())); + sandbox.restore(); + }); + + for (const interpreter of ['configured', 'Python-managed']) { + test(`matches manual composition for ${interpreter} startup and restart`, async () => { + if (interpreter === 'Python-managed') { + configuredInterpreter = undefined; + } + + function snapshot() { + const client = start.lastCall.thisValue as LanguageClient; + return { + initializationOptions: client.clientOptions.initializationOptions, + commands: Array.from(commands.keys()), + registrations: resources.map((item) => item.name), + }; + } + + // Real shared helpers, settings resolution and server composition; + // only VS Code, Python extension and LanguageClient APIs are mocked. + const subscriptions: vscode.Disposable[] = []; + const outputChannel = vscodeapi.createOutputChannel(serverInfo.name); + const logger = registerLogger(outputChannel); + const pythonProvider = new PythonEnvironmentsProvider(toolConfig); + const ctx = activation.createToolContext({ + serverInfo, + outputChannel, + toolConfig, + pythonProvider, + }); + activation.registerCommonSubscriptions( + { subscriptions }, + { + serverInfo, + outputChannel, + toolConfig, + pythonProvider, + toolContext: ctx, + }, + ); + const scheduled = setImmediate(() => void ctx.initialize(subscriptions)); + const manual = { + deactivate: async () => { + clearImmediate(scheduled); + await activation.deactivateServer(ctx); + subscriptions + .splice(0) + .reverse() + .forEach((item) => item.dispose()); + pythonProvider.dispose(); + logger.dispose(); + outputChannel.dispose(); + }, + }; + runtimes.push(manual); + await nextImmediate(); + assert.equal(start.callCount, 1); + const expectedStartup = snapshot(); + await commands.get('example.restart')!(); + assert.equal(start.callCount, 2); + const expectedRestart = snapshot(); + await manual.deactivate(); + runtimes.pop(); + + resources = []; + const { context, unrelated } = makeContext(); + // The unrelated caller resource is not part of the manual inventory. + resources = []; + const runtime = activate(context); + assert.equal(start.callCount, 2, 'startup stays deferred'); + assert.lengthOf(context.subscriptions, 2, 'only a lifetime handle belongs to the caller'); + await nextImmediate(); + + assert.equal(start.callCount, 3, 'the initial interpreter event starts exactly one client'); + assert.equal(initializePython.callCount, interpreter === 'configured' ? 0 : 2); + assert.deepEqual(snapshot(), expectedStartup); + const restartCommand = commands.get('example.restart')!; + await restartCommand(); + assert.equal(start.callCount, 4, 'one command triggers one restart'); + assert.deepEqual(snapshot(), expectedRestart); + await runtime.deactivate(); + assert.equal(commands.size, 0); + assert.isTrue(unrelated.dispose.notCalled); + await restartCommand(); + assert.equal(start.callCount, 4, 'shutdown prevents a stale callback from restarting the client'); + }); + } + + test('cancels deferred startup and the formatter placeholder with idempotent shutdown', async () => { + const { context, unrelated } = makeContext(); + const runtime = activate(context, { isFormatter: true }); + const formatter = resources.find((item) => item.name === 'formatter')!; + assert.isDefined(formatter, 'formatter is available synchronously before startup'); + const lifetime = context.subscriptions[1]; + const shutdown = runtime.deactivate(); + assert.isTrue(formatter.dispose.calledOnce); + lifetime.dispose(); + lifetime.dispose(); + assert.strictEqual(runtime.deactivate(), shutdown); + await shutdown; + await nextImmediate(); + assert.isTrue(start.notCalled); + assert.isTrue(initializePython.notCalled); + assert.isTrue(providerDispose.calledOnce); + assert.isTrue(unrelated.dispose.notCalled); + assert.lengthOf(context.subscriptions, 2); + assert.lengthOf( + resources.filter((item) => item.name === 'formatter'), + 1, + ); + for (const item of resources.filter((item) => item !== unrelated)) { + assert.isTrue(item.dispose.calledOnce, item.name); + } + }); + + test('context disposal initiates the same awaitable shutdown', async () => { + const { context } = makeContext(); + const runtime = activate(context); + await nextImmediate(); + const stopping = deferred(); + stop.restore(); + const stopStub = sandbox.stub(LanguageClient.prototype, 'stop').returns(stopping.promise); + context.subscriptions[1].dispose(); + assert.isTrue(stopStub.calledOnce); + assert.isTrue((channels[0].dispose as sinon.SinonStub).notCalled); + const shutdown = runtime.deactivate(); + context.subscriptions[1].dispose(); + stopping.resolve(); + await shutdown; + assert.isTrue(stopStub.calledOnce); + assert.isTrue((channels[0].dispose as sinon.SinonStub).calledOnce); + }); + + test('rolls back partial activation without touching caller resources', async () => { + const { context, unrelated } = makeContext(); + const partial = makeWatcher(); + partial.onDidCreate.throws(new Error('watcher setup failed')); + (vscode.workspace.createFileSystemWatcher as sinon.SinonStub).onSecondCall().returns(partial); + assert.throws(() => activate(context, { isFormatter: true }), 'watcher setup failed'); + await nextImmediate(); + assert.lengthOf(context.subscriptions, 1); + assert.isTrue(unrelated.dispose.notCalled); + for (const item of resources.filter((item) => item !== unrelated)) { + assert.isTrue(item.dispose.calledOnce, item.name); + } + assert.isTrue(providerDispose.calledOnce); + assert.isTrue(start.notCalled); + assert.equal(commands.size, 0); + assert.isTrue((channels[0].error as sinon.SinonStub).calledWithMatch('watcher setup failed')); + }); + + test('awaits late initialization subscriptions and contains cleanup failures', async () => { + const late = resource('python.environment'); + const disposing = deferred(); + late.dispose.callsFake(async () => { + await disposing.promise; + throw new Error('late disposal rejected'); + }); + api.onDidChangeEnvironment.returns(late); + const acquisition = deferred(); + (PythonEnvironments.api as sinon.SinonStub).returns(acquisition.promise); + configuredInterpreter = undefined; + const { context, unrelated } = makeContext(); + const runtime = activate(context, { + isFormatter: true, + refreshExtensionOnPackagesChange: true, + }); + await nextImmediate(); + assert.isTrue(initializePython.calledOnce); + resources.find((item) => item.name === 'global.logLevel')!.dispose.throws(new Error('disposal threw')); + + const shutdown = runtime.deactivate(); + let settled = false; + void shutdown.then(() => { + settled = true; + }); + await nextImmediate(); + assert.isFalse(settled); + assert.isTrue((channels[0].dispose as sinon.SinonStub).notCalled); + acquisition.resolve(api); + await nextImmediate(); + assert.isTrue(late.dispose.calledOnce); + assert.isFalse(settled); + assert.isTrue((channels[0].dispose as sinon.SinonStub).notCalled); + disposing.resolve(); + await shutdown; + + for (const name of ['python.environment', 'python.projects', 'python.packages']) { + const items = resources.filter((item) => item.name === name); + assert.lengthOf(items, 1, name); + assert.isTrue(items[0].dispose.calledOnce, name); + } + assert.isTrue(start.notCalled, 'the late initial event cannot start a server'); + assert.lengthOf( + resources.filter((item) => item.name === 'formatter'), + 1, + ); + assert.isTrue(resources.find((item) => item.name === 'formatter')!.dispose.calledOnce); + const error = channels[0].error as sinon.SinonStub; + assert.isTrue(error.calledWithMatch('late disposal rejected')); + assert.isTrue(error.calledWithMatch('disposal threw')); + assert.isTrue((channels[0].dispose as sinon.SinonStub).calledOnce); + assert.isTrue(unrelated.dispose.notCalled); + }); + + test('cleans up an in-flight configured startup without restoring a disposed formatter', async () => { + const starting = deferred(); + start.restore(); + const startStub = sandbox.stub(LanguageClient.prototype, 'start').returns(starting.promise); + const clientDispose = sandbox.spy(LanguageClient.prototype, 'dispose'); + const { context } = makeContext(); + const runtime = activate(context, { isFormatter: true }); + await nextImmediate(); + assert.isTrue(startStub.calledOnce); + const shutdown = runtime.deactivate(); + const formatter = resources.find((item) => item.name === 'formatter')!; + assert.isTrue(formatter.dispose.calledOnce); + starting.resolve(); + await shutdown; + assert.isTrue(stop.calledOnce); + assert.isTrue(clientDispose.calledOnce); + assert.lengthOf( + resources.filter((item) => item.name === 'formatter'), + 1, + ); + }); + + test('contains unexpected initializer rejections and still cleans up', async () => { + const toolContext = { + lsClient: undefined, + initialize: sandbox.stub().rejects(new Error('unexpected initializer rejection')), + runServer: sandbox.stub().resolves(), + dispose: sandbox.stub(), + }; + sandbox.stub(activation, 'createToolContext').returns(toolContext); + const { context } = makeContext(); + const runtime = activate(context); + await nextImmediate(); + assert.isTrue((channels[0].error as sinon.SinonStub).calledWithMatch('unexpected initializer rejection')); + await runtime.deactivate(); + assert.isTrue(toolContext.dispose.calledOnce); + assert.isTrue((channels[0].dispose as sinon.SinonStub).calledOnce); + }); +}); diff --git a/typescript/tests/toolExtension.typecheck.ts b/typescript/tests/toolExtension.typecheck.ts new file mode 100644 index 0000000..54d1dc8 --- /dev/null +++ b/typescript/tests/toolExtension.typecheck.ts @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +import { ExtensionContext } from 'vscode'; +import { + activateToolExtension, + ActivateToolExtensionOptions, + IServerInfo, + ToolConfig, + ToolDefinition, + ToolExtensionRuntime, +} from '../src'; + +// Compile-only adoption checks; no lifecycle/client generics or casts are needed. +export async function checkActivationFacade( + context: ExtensionContext, + serverInfo: IServerInfo, + legacy: ToolConfig, +): Promise { + const legacyOptions: ActivateToolExtensionOptions = { + serverInfo, + toolConfig: legacy, + }; + const legacyRuntime: ToolExtensionRuntime = activateToolExtension(context, legacyOptions); + const shutdown: Promise = legacyRuntime.deactivate(); + await shutdown; + + interface Settings { + enabled: boolean; + ignorePatterns: string[]; + } + const definition: ToolDefinition = { + ...legacy, + settingsDefaults: { enabled: false, ignorePatterns: [] }, + }; + const typedOptions: ActivateToolExtensionOptions = { + serverInfo, + toolConfig: definition, + }; + const runtime: ToolExtensionRuntime = activateToolExtension(context, typedOptions); + // @ts-expect-error The facade handle does not expose a mutable language client. + runtime.lsClient = undefined; + await runtime.deactivate(); +}