diff --git a/README.md b/README.md index add4f50..3f8a1d0 100644 --- a/README.md +++ b/README.md @@ -202,6 +202,9 @@ 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. +Optional [launch hooks](typescript/README.md#optional-launch-hooks) support +per-server inherited-environment patches and pre-start notification registration +with client-owned cleanup, without overriding `runServer` or changing settings. 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. diff --git a/typescript/README.md b/typescript/README.md index 075ec6f..e27c7ef 100644 --- a/typescript/README.md +++ b/typescript/README.md @@ -73,6 +73,59 @@ multi-tool-instance isolation. Existing low-level activation APIs remain available unchanged for custom composition; no consumer migration or custom lifecycle hooks are required. +## Optional launch hooks + +Pass `hooks` to `activateToolExtension` or `createToolContext` for runtime-only +customization. `getLaunchEnvironment({ settings, serverId, serverName })` +synchronously returns an environment patch for each actual client-creation +attempt, not each debounced restart request. It must not mutate settings or +`process.env`. An omitted key preserves its inherited value, `''` sets an empty +value, and an explicit `undefined` removes the inherited key. Inherited names +match case-insensitively on Windows and case-sensitively elsewhere. + +The patch is applied to a fresh copy of `process.env` **before** env-file merging, +debugger/built-in assignments, extra paths and finally static `extraEnvVars`. +Thus an env file can reintroduce a removed inherited key; static overrides keep +their existing precedence. A throwing hook fails that launch through the normal +creation-error path. Hooks are not part of `ToolConfig` or the Python settings +payload. Existing callers without hooks retain their environment behavior. + +`configureClient({ client, settings, serverId, serverName, registerDisposable })` +registers tool-specific handlers on the new client **before** `client.start()`. +For example, add this property alongside `serverInfo` and `toolConfig` in the +activation options: + +```typescript +hooks: { + configureClient: ({ client, registerDisposable }) => { + registerDisposable(client.onNotification('example/score', (score: number) => { + // Update extension-owned UI here. + })); + }, +}, +``` + +Register each returned disposable immediately, so earlier registrations can be +released if later setup throws. The callback must finish synchronously and +return no value; its `undefined` return type deliberately rejects async callbacks. +Do not start, stop or replace the client from this hook. The runtime owns client +lifetime; tool-specific UI stays owned by the extension. + +Each actual client generation has an idempotent setup scope, separate from +post-start state listeners. It is closed on setup/start/trace failure, retirement +after an old stop settles or replacement takes ownership, missing-interpreter +retirement, and shutdown. Registrations added to an already closed scope are +disposed immediately. Cleanup errors are contained. Shutdown closes scopes even +while creation/start is pending; it still does not promise to interrupt or drain +every in-flight lifecycle operation. A late successful start is stopped. + +Lower-level `restartServer` callers can pass the same hooks and an optional +shutdown `signal`. Its returned `disposables` include the setup scope. The optional +`clientSetup` result property identifies that same scope for custom composition +that needs to retire it separately from state listeners; it is not an additional +resource to dispose twice. `createServer` alone accepts only the environment hook +and remains an unstarted-client factory. + ## 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 7181510..33cd49c 100644 --- a/typescript/src/activation.ts +++ b/typescript/src/activation.ts @@ -19,7 +19,7 @@ import { createConfigFileWatchers } from './configWatcher'; import { traceError, traceLog, traceVerbose } from './logging'; import { NullFormatter } from './nullFormatter'; import { PythonEnvironmentsProvider } from './python'; -import { restartServer, RestartServerOptions } from './server'; +import { restartServer, RestartServerOptions, ToolLifecycleHooks } from './server'; import { checkIfConfigurationChanged, getExtensionSettings, getWorkspaceSettings } from './settings'; import { registerLanguageStatusItem, updateStatus } from './status'; import { IBaseSettings, IServerInfo, ToolConfig } from './types'; @@ -139,6 +139,7 @@ export interface CreateToolContextOptions { outputChannel: vscode.LogOutputChannel; toolConfig: ToolConfig; pythonProvider: PythonEnvironmentsProvider; + hooks?: ToolLifecycleHooks; } /** @@ -163,6 +164,13 @@ export function createToolContext(options: CreateToolContextOptions): ToolExtens let pythonInitialized = false; let extensionSubscriptions: vscode.Disposable[] | undefined; let serverDisposables: vscode.Disposable[] = []; + let clientSetup: vscode.Disposable | undefined; + const hookShutdown = options.hooks ? new AbortController() : undefined; + + function disposeClientSetup(): void { + clientSetup?.dispose(); + clientSetup = undefined; + } const nullFormatter = toolConfig.isFormatter ? new NullFormatter() : undefined; nullFormatter?.register(); @@ -238,6 +246,7 @@ export function createToolContext(options: CreateToolContextOptions): ToolExtens } ctx.lsClient = undefined; } + disposeClientSetup(); for (const d of serverDisposables) { try { d.dispose(); @@ -288,7 +297,10 @@ export function createToolContext(options: CreateToolContextOptions): ToolExtens toolConfig, pythonProvider, extensionSettings, + hooks: options.hooks, + signal: hookShutdown?.signal, onOldClientStopped: () => { + disposeClientSetup(); if (!disposed) { nullFormatter?.register(); } @@ -316,8 +328,10 @@ export function createToolContext(options: CreateToolContextOptions): ToolExtens return; } + disposeClientSetup(); ctx.lsClient = result.client; - serverDisposables = result.disposables; + clientSetup = result.clientSetup; + serverDisposables = result.disposables.filter((disposable) => disposable !== clientSetup); if (nullFormatter && result.client) { if (result.client.state === State.Running) { @@ -404,6 +418,8 @@ export function createToolContext(options: CreateToolContextOptions): ToolExtens dispose(): void { disposed = true; + hookShutdown?.abort(); + disposeClientSetup(); if (restartTimer) { clearTimeout(restartTimer); restartTimer = undefined; diff --git a/typescript/src/index.ts b/typescript/src/index.ts index e40b46e..5baccd1 100644 --- a/typescript/src/index.ts +++ b/typescript/src/index.ts @@ -71,10 +71,13 @@ export { createConfigFileWatchers } from './configWatcher'; export { createServer, CreateServerOptions, + ClientSetupContext, getServerCwd, restartServer, RestartServerOptions, RestartServerResult, + ServerLaunchContext, + ToolLifecycleHooks, } from './server'; // Null formatter helper diff --git a/typescript/src/server.ts b/typescript/src/server.ts index 472f27d..30f91ce 100644 --- a/typescript/src/server.ts +++ b/typescript/src/server.ts @@ -97,6 +97,33 @@ export function getServerCwd(settings: IBaseSettings): string { // Server creation // --------------------------------------------------------------------------- +/** Resolved bootstrap settings and identity for one actual client launch. */ +export interface ServerLaunchContext { + readonly settings: Readonly; + readonly serverId: string; + readonly serverName: string; +} + +/** Register handlers on the new client before start; the runtime owns its lifetime. */ +export interface ClientSetupContext extends ServerLaunchContext { + readonly client: LanguageClient; + /** Register each resource immediately, including before later setup can throw. */ + registerDisposable(disposable: Disposable): void; +} + +/** Optional runtime customization, never serialized into Python settings. */ +export interface ToolLifecycleHooks { + /** + * Synchronously patch a fresh copy of the inherited environment before + * env-file merging and built-in/static assignments. An explicit undefined + * removes an inherited key from the launched environment; omitted keys are + * unchanged. Inherited key matching is case-insensitive on Windows. + */ + getLaunchEnvironment?(context: ServerLaunchContext): Readonly>; + /** Synchronous registration only: do not start/stop the client or return an async task. */ + configureClient?(context: ClientSetupContext): undefined; +} + /** Options for {@link createServer}. */ export interface CreateServerOptions { settings: IBaseSettings; @@ -106,6 +133,7 @@ export interface CreateServerOptions { initializationOptions: IInitOptions; toolConfig: ToolConfig; debuggerPath?: string; + hooks?: Pick; } /** @@ -129,6 +157,17 @@ export async function createServer(options: CreateServerOptions): Promise = { ...process.env }; + const launchEnvironment = options.hooks?.getLaunchEnvironment?.({ settings, serverId, serverName }); + if (launchEnvironment) { + for (const [key, value] of Object.entries(launchEnvironment)) { + const matchingKeys = process.platform === 'win32' + ? Object.keys(newEnv).filter((existingKey) => existingKey.toLowerCase() === key.toLowerCase()) + : []; + for (const matchingKey of matchingKeys.length ? matchingKeys : [key]) { + newEnv[matchingKey] = value; + } + } + } // Load environment variables from python.envFile (.env) const workspaceUri = parseWorkspaceUri(settings.workspace); @@ -185,6 +224,21 @@ export async function createServer(options: CreateServerOptions): Promise candidate.toLowerCase() === key.toLowerCase() && newEnv[candidate] !== undefined, + ); + if (overrideKey) { + newEnv[key] = newEnv[overrideKey]; + } + } + } + } + // Choose server script (debug vs normal) const isDebugScript = toolConfig.debugServerScript ? await fsapi.pathExists(toolConfig.debugServerScript) : false; const scriptPath = @@ -231,6 +285,9 @@ export interface RestartServerOptions { outputChannel: LogOutputChannel; toolConfig: ToolConfig; pythonProvider: PythonEnvironmentsProvider; + hooks?: ToolLifecycleHooks; + /** Close hook resources immediately on shutdown; in-flight start/stop is not interrupted. */ + signal?: AbortSignal; /** * Synchronous notification after the old client's stop settles with state Stopped, * before replacement creation. Also applies when stop rejects but leaves @@ -243,6 +300,64 @@ export interface RestartServerOptions { export interface RestartServerResult { client: LanguageClient | undefined; disposables: Disposable[]; + /** Also included in disposables; kept separately from pre-stop state listeners by activation. */ + clientSetup?: Disposable; +} + +function createClientSetup(signal?: AbortSignal): Pick & Disposable { + let closed = false; + const resources: Disposable[] = []; + + function disposeResource(resource: Disposable): void { + try { + void Promise.resolve(resource.dispose()).catch((error) => + traceError(`Server: Client setup disposal failed: ${error}`), + ); + } catch (error) { + traceError(`Server: Client setup disposal failed: ${error}`); + } + } + + const scope = { + registerDisposable(resource: Disposable): void { + if (closed) { + disposeResource(resource); + } else { + resources.push(resource); + } + }, + dispose(): void { + if (closed) { + return; + } + closed = true; + signal?.removeEventListener('abort', scope.dispose); + for (const resource of resources.splice(0).reverse()) { + disposeResource(resource); + } + }, + }; + if (signal?.aborted) { + scope.dispose(); + } else { + signal?.addEventListener('abort', scope.dispose, { once: true }); + } + return scope; +} + +async function disposeClient(client: LanguageClient, stop = false): Promise { + if (stop) { + try { + await client.stop(); + } catch (error) { + traceVerbose(`Server: Stop after cancelled startup: ${error}`); + } + } + try { + await client.dispose(); + } catch (error) { + traceVerbose(`Server: Dispose after failed or cancelled startup: ${error}`); + } } /** @@ -258,6 +373,9 @@ export async function restartServer( ): Promise { const { settings, extensionSettings, serverId, serverName, outputChannel, toolConfig, pythonProvider } = options; + if (options.signal?.aborted) { + return { client: undefined, disposables: [] }; + } if (oldLsClient) { traceInfo('Server: Stop requested'); try { @@ -272,6 +390,9 @@ export async function restartServer( } } + if (options.signal?.aborted) { + return { client: undefined, disposables: [] }; + } updateStatus(undefined, LanguageStatusSeverity.Information, true); const resolveInterpreter = pythonProvider.getInterpreterDetails.bind(pythonProvider); @@ -279,6 +400,13 @@ export async function restartServer( let newLSClient: LanguageClient; try { + const initializationOptions = { + settings: extensionSettings ?? (await getExtensionSettings(serverId, toolConfig, resolveInterpreter)), + globalSettings: await getGlobalSettings(serverId, toolConfig), + }; + if (options.signal?.aborted) { + return { client: undefined, disposables: [] }; + } newLSClient = await createServer({ settings, serverId, @@ -286,30 +414,56 @@ export async function restartServer( outputChannel, toolConfig, debuggerPath, - initializationOptions: { - settings: extensionSettings ?? (await getExtensionSettings(serverId, toolConfig, resolveInterpreter)), - globalSettings: await getGlobalSettings(serverId, toolConfig), - }, + hooks: options.hooks, + initializationOptions, }); } catch (ex) { - updateStatus(l10n.t('Server failed to start.'), LanguageStatusSeverity.Error); - traceError(`Server: Creation failed: ${ex}`); + if (!options.signal?.aborted) { + updateStatus(l10n.t('Server failed to start.'), LanguageStatusSeverity.Error); + traceError(`Server: Creation failed: ${ex}`); + } return { client: undefined, disposables: [] }; } - traceInfo('Server: Start requested.'); + if (options.signal?.aborted) { + await disposeClient(newLSClient); + return { client: undefined, disposables: [] }; + } + const clientSetup = options.hooks?.configureClient ? createClientSetup(options.signal) : undefined; const serverCwd = getServerCwd(settings); try { + if (clientSetup) { + options.hooks?.configureClient?.({ + settings, + serverId, + serverName, + client: newLSClient, + registerDisposable: clientSetup.registerDisposable, + }); + } + if (options.signal?.aborted) { + clientSetup?.dispose(); + await disposeClient(newLSClient); + return { client: undefined, disposables: [] }; + } + traceInfo('Server: Start requested.'); await newLSClient.start(); + if (options.signal?.aborted) { + await disposeClient(newLSClient, true); + return { client: undefined, disposables: [] }; + } await newLSClient.setTrace(getLSClientTraceLevel(outputChannel.logLevel, env.logLevel)); + if (options.signal?.aborted) { + await disposeClient(newLSClient, true); + return { client: undefined, disposables: [] }; + } } catch (ex) { - updateStatus(l10n.t('Server failed to start.'), LanguageStatusSeverity.Error); - traceError(`Server: Start failed (CWD: ${serverCwd}): ${ex}`); - try { - newLSClient.dispose(); - } catch (ex) { - traceVerbose(`Server: Dispose after start failure: ${ex}`); + clientSetup?.dispose(); + if (!options.signal?.aborted) { + updateStatus(l10n.t('Server failed to start.'), LanguageStatusSeverity.Error); + traceError(`Server: Start failed (CWD: ${serverCwd}): ${ex}`); } + await disposeClient(newLSClient); return { client: undefined, disposables: [] }; } @@ -319,7 +473,7 @@ export async function restartServer( updateStatus(undefined, LanguageStatusSeverity.Information, false); // Register state listener only after successful start - const disposables: Disposable[] = []; + const disposables: Disposable[] = clientSetup ? [clientSetup] : []; disposables.push( newLSClient.onDidChangeState((e) => { switch (e.newState) { @@ -337,5 +491,5 @@ export async function restartServer( }), ); - return { client: newLSClient, disposables }; + return { client: newLSClient, disposables, ...(clientSetup ? { clientSetup } : {}) }; } diff --git a/typescript/src/toolExtension.ts b/typescript/src/toolExtension.ts index 034716d..86f8ce1 100644 --- a/typescript/src/toolExtension.ts +++ b/typescript/src/toolExtension.ts @@ -5,6 +5,7 @@ import * as vscode from 'vscode'; import { createToolContext, deactivateServer, registerCommonSubscriptions, ToolExtensionContext } from './activation'; import { registerLogger } from './logging'; import { PythonEnvironmentsProvider } from './python'; +import { ToolLifecycleHooks } from './server'; import { IServerInfo, ToolConfig } from './types'; import { createOutputChannel } from './vscodeapi'; @@ -13,6 +14,7 @@ export interface ActivateToolExtensionOptions { serverInfo: IServerInfo; /** Accepts legacy ToolConfig and structurally compatible ToolDefinition values. */ toolConfig: ToolConfig; + hooks?: ToolLifecycleHooks; } /** The facade's lifetime handle, not a client-ready notification. */ @@ -129,6 +131,7 @@ export function activateToolExtension( outputChannel, toolConfig, pythonProvider, + hooks: options.hooks, }); registerCommonSubscriptions( { subscriptions }, diff --git a/typescript/tests/_languageclient_mock.ts b/typescript/tests/_languageclient_mock.ts index caa968e..bdbd85a 100644 --- a/typescript/tests/_languageclient_mock.ts +++ b/typescript/tests/_languageclient_mock.ts @@ -23,6 +23,7 @@ export class LanguageClient { private _name: string; private _stateListeners: Array<(e: { oldState: State; newState: State }) => void> = []; private _state: State = State.Stopped; + private _notificationHandlers = new Map void>>(); /** Exposed for test assertions on the constructed server options. */ public readonly serverOptions: unknown; @@ -56,6 +57,20 @@ export class LanguageClient { this._stateListeners.forEach((l) => l({ oldState, newState })); } + onNotification(method: string, handler: (params: unknown) => void) { + let handlers = this._notificationHandlers.get(method); + if (!handlers) { + handlers = new Set(); + this._notificationHandlers.set(method, handlers); + } + handlers.add(handler); + return { dispose: () => handlers.delete(handler) }; + } + + simulateNotification(method: string, params: unknown): void { + this._notificationHandlers.get(method)?.forEach((handler) => handler(params)); + } + async start(): Promise { this._state = State.Running; } diff --git a/typescript/tests/activation.test.ts b/typescript/tests/activation.test.ts index b82c3c8..23e1d73 100644 --- a/typescript/tests/activation.test.ts +++ b/typescript/tests/activation.test.ts @@ -258,9 +258,12 @@ suite('createToolContext', () => { test('runServer stops stale client when interpreter is cleared', async () => { const stopStub = sandbox.stub().resolves(); const mockClient = { stop: stopStub } as unknown as import('vscode-languageclient/node').LanguageClient; + const clientSetup = { dispose: sandbox.stub() }; // First run succeeds — sets up a client - (serverModule.restartServer as sinon.SinonStub).resolves({ client: mockClient, disposables: [] }); + (serverModule.restartServer as sinon.SinonStub).resolves({ + client: mockClient, disposables: [clientSetup], clientSetup, + }); const ctx = createToolContext(makeOptions()); await ctx.runServer(); assert.strictEqual(ctx.lsClient, mockClient); @@ -279,6 +282,9 @@ suite('createToolContext', () => { await ctx.runServer(); assert.isTrue(stopStub.calledOnce, 'should stop the stale client'); assert.isUndefined(ctx.lsClient, 'client should be cleared'); + sinon.assert.calledOnce(clientSetup.dispose); + ctx.dispose(); + sinon.assert.calledOnce(clientSetup.dispose); }); test('dispose during in-flight restart cleans up late results and cancels queued retry', async () => { diff --git a/typescript/tests/server.test.ts b/typescript/tests/server.test.ts index 3369d70..865f4ca 100644 --- a/typescript/tests/server.test.ts +++ b/typescript/tests/server.test.ts @@ -2,11 +2,22 @@ // Licensed under the MIT License. import { assert } from 'chai'; +import { execFileSync } from 'child_process'; import * as sinon from 'sinon'; +import * as path from 'path'; import { LanguageStatusSeverity, LogOutputChannel, Uri, LogLevel, WorkspaceFolder } from 'vscode'; import { State } from 'vscode-languageclient'; import { LanguageClient } from 'vscode-languageclient/node'; -import { getServerCwd, createServer, restartServer, CreateServerOptions, RestartServerOptions, RestartServerResult } from '../src/server'; +import { + getServerCwd, + createServer, + restartServer, + CreateServerOptions, + RestartServerOptions, + RestartServerResult, + ServerLaunchContext, + ClientSetupContext, +} from '../src/server'; import * as envFileModule from '../src/envFile'; import * as status from '../src/status'; import * as utilities from '../src/utilities'; @@ -186,6 +197,18 @@ suite('createServer', () => { }; } + function serverEnvironment(client: LanguageClient): NodeJS.ProcessEnv { + return (client as unknown as { + serverOptions: { options: { env: NodeJS.ProcessEnv } }; + }).serverOptions.options.env; + } + + function launchedEnvironment(client: LanguageClient): NodeJS.ProcessEnv { + return JSON.parse(execFileSync(process.execPath, [ + '-e', 'process.stdout.write(JSON.stringify(process.env))', + ], { env: serverEnvironment(client), encoding: 'utf8' })) as NodeJS.ProcessEnv; + } + test('returns a LanguageClient instance', async () => { const client = await createServer(makeCreateOptions()); assert.instanceOf(client, LanguageClient); @@ -257,6 +280,153 @@ suite('createServer', () => { assert.include(env.PYTHONPATH, '/envfile/path'); }); + /* eslint-disable @typescript-eslint/naming-convention -- Environment keys retain their actual spelling. */ + test('patches inherited environment per launch without mutating the host or settings', async () => { + const host = { ...process.env, S7_REMOVE: 'inherited', S7_EMPTY: 'inherited', S7_KEEP: 'inherited' }; + sandbox.stub(process, 'env').value(host); + const settings = makeSettings({ custom: false }); + const originalSettings = structuredClone(settings); + let value = 'first'; + const getLaunchEnvironment = sandbox.spy((context: ServerLaunchContext) => { + assert.strictEqual(context.settings, settings); + return { S7_VALUE: value, S7_REMOVE: undefined, S7_EMPTY: '' }; + }); + const options = makeCreateOptions({ settings, hooks: { getLaunchEnvironment } }); + const first = await createServer(options); + value = 'second'; + const second = await createServer(options); + const environment = (client: LanguageClient) => + (client as unknown as { serverOptions: { options: { env: NodeJS.ProcessEnv } } }).serverOptions.options.env; + + assert.strictEqual(environment(first).S7_VALUE, 'first'); + assert.strictEqual(environment(second).S7_VALUE, 'second'); + assert.notProperty(launchedEnvironment(first), 'S7_REMOVE'); + assert.strictEqual(environment(first).S7_EMPTY, ''); + assert.strictEqual(environment(first).S7_KEEP, 'inherited'); + assert.strictEqual(process.env, host); + assert.strictEqual(host.S7_REMOVE, 'inherited'); + assert.strictEqual(host.S7_EMPTY, 'inherited'); + assert.notProperty(host, 'S7_VALUE'); + assert.deepEqual(settings, originalSettings); + sinon.assert.calledTwice(getLaunchEnvironment); + sinon.assert.calledWithExactly(getLaunchEnvironment, { settings, serverId: 'flake8', serverName: 'Flake8' }); + }); + + test('replaces every inherited Windows casing without adding a competing alias', async () => { + sandbox.stub(process, 'platform').value('win32'); + const host = { ...process.env, Path: 'first', PATH: 'second', S7_MiXeD: 'inherited' }; + sandbox.stub(process, 'env').value(host); + const client = await createServer(makeCreateOptions({ + hooks: { getLaunchEnvironment: () => ({ path: 'replacement', S7_MIXED: '' }) }, + })); + const environment = serverEnvironment(client); + + assert.strictEqual(environment.Path, 'replacement'); + assert.strictEqual(environment.PATH, 'replacement'); + assert.notProperty(environment, 'path'); + assert.strictEqual(environment.S7_MiXeD, ''); + assert.notProperty(environment, 'S7_MIXED'); + const launched = launchedEnvironment(client); + const paths = Object.entries(launched).filter(([key]) => key.toLowerCase() === 'path'); + assert.isNotEmpty(paths); + paths.forEach(([, value]) => assert.strictEqual(value, 'replacement')); + assert.strictEqual(host.Path, 'first'); + assert.strictEqual(host.PATH, 'second'); + assert.strictEqual(host.S7_MiXeD, 'inherited'); + }); + + test('removes every inherited Windows casing from the executable child', async () => { + sandbox.stub(process, 'platform').value('win32'); + const host = { ...process.env, Path: 'first', PATH: 'second', S7_MiXeD: 'inherited' }; + sandbox.stub(process, 'env').value(host); + const client = await createServer(makeCreateOptions({ + hooks: { getLaunchEnvironment: () => ({ path: undefined, S7_MIXED: undefined }) }, + })); + + const environment = serverEnvironment(client); + assert.property(environment, 'Path'); + assert.isUndefined(environment.Path); + assert.property(environment, 'PATH'); + assert.isUndefined(environment.PATH); + assert.property(environment, 'S7_MiXeD'); + assert.isUndefined(environment.S7_MiXeD); + const launchedKeys = Object.keys(launchedEnvironment(client)); + assert.notInclude(launchedKeys.map((key) => key.toLowerCase()), 's7_mixed'); + assert.strictEqual(host.Path, 'first'); + assert.strictEqual(host.PATH, 'second'); + assert.strictEqual(host.S7_MiXeD, 'inherited'); + }); + + test('lets later layers reintroduce removed Windows aliases', async () => { + sandbox.stub(process, 'platform').value('win32'); + sandbox.stub(process, 'env').value({ ...process.env, S7_MiXeD: 'inherited', S7_Static: 'inherited' }); + (envFileModule.getEnvFileVars as sinon.SinonStub).resolves({ s7_mixed: 'env-file' }); + const client = await createServer(makeCreateOptions({ + toolConfig: makeToolConfig({ extraEnvVars: { s7_static: 'static' } }), + hooks: { getLaunchEnvironment: () => ({ S7_MIXED: undefined, S7_STATIC: undefined }) }, + })); + const environment = serverEnvironment(client); + + assert.strictEqual(environment.S7_MiXeD, 'env-file'); + assert.strictEqual(environment.s7_mixed, 'env-file'); + assert.strictEqual(environment.S7_Static, 'static'); + const launchedEnvironmentVariables = Object.entries(launchedEnvironment(client)); + const launched = launchedEnvironmentVariables + .filter(([key]) => key.toLowerCase() === 's7_mixed'); + assert.lengthOf(launched, 1); + assert.strictEqual(launched[0][1], 'env-file'); + const launchedStatic = launchedEnvironmentVariables.filter(([key]) => key.toLowerCase() === 's7_static'); + assert.lengthOf(launchedStatic, 1); + assert.strictEqual(launchedStatic[0][1], 'static'); + }); + + test('keeps hook environment keys case-sensitive outside Windows', async () => { + sandbox.stub(process, 'platform').value('linux'); + sandbox.stub(process, 'env').value({ S7_MiXeD: 'inherited', S7_KEEP: 'inherited' }); + const client = await createServer(makeCreateOptions({ + hooks: { getLaunchEnvironment: () => ({ S7_MIXED: 'replacement', s7_keep: undefined }) }, + })); + const environment = serverEnvironment(client); + + assert.strictEqual(environment.S7_MiXeD, 'inherited'); + assert.strictEqual(environment.S7_MIXED, 'replacement'); + assert.strictEqual(environment.S7_KEEP, 'inherited'); + assert.isUndefined(environment.s7_keep); + }); + + test('keeps env-file, built-in and static precedence over the launch patch', async () => { + sandbox.stub(process, 'env').value({ S7_REMOVED_THEN_LOADED: 'inherited' }); + (envFileModule.getEnvFileVars as sinon.SinonStub).resolves({ + S7_REMOVED_THEN_LOADED: 'env-file', + S7_STATIC: 'env-file', + PYTHONPATH: 'env-file-path', + }); + const client = await createServer(makeCreateOptions({ + settings: makeSettings({ extraPaths: ['extra-path'] }), + toolConfig: makeToolConfig({ extraEnvVars: { S7_STATIC: 'static', PYTHONUTF8: 'static' } }), + hooks: { + getLaunchEnvironment: () => ({ + S7_REMOVED_THEN_LOADED: undefined, + S7_STATIC: 'hook', + LS_IMPORT_STRATEGY: 'hook', + LS_SHOW_NOTIFICATION: 'hook', + PYTHONUTF8: 'hook', + PYTHONPATH: 'hook-path', + }), + }, + })); + const environment = (client as unknown as { + serverOptions: { options: { env: NodeJS.ProcessEnv } }; + }).serverOptions.options.env; + assert.strictEqual(environment.S7_REMOVED_THEN_LOADED, 'env-file'); + assert.strictEqual(environment.S7_STATIC, 'static'); + assert.strictEqual(environment.LS_IMPORT_STRATEGY, 'useBundled'); + assert.strictEqual(environment.LS_SHOW_NOTIFICATION, 'off'); + assert.strictEqual(environment.PYTHONUTF8, 'static'); + assert.strictEqual(environment.PYTHONPATH, ['hook-path', 'env-file-path', 'extra-path'].join(path.delimiter)); + }); + /* eslint-enable @typescript-eslint/naming-convention */ + test('throws when interpreter array is empty', async () => { const options = makeCreateOptions({ settings: makeSettings({ interpreter: [] }), @@ -460,6 +630,142 @@ suite('restartServer', () => { } }); + test('contains environment hook failure without starting a client', async () => { + const start = sandbox.spy(LanguageClient.prototype, 'start'); + const result = await restartServer(makeRestartOptions({ + hooks: { getLaunchEnvironment: () => { throw new Error('environment hook failed'); } }, + })); + assert.isUndefined(result.client); + assert.isEmpty(result.disposables); + assert.strictEqual(updateStatusStub.lastCall.args[1], LanguageStatusSeverity.Error); + sinon.assert.notCalled(start); + }); + + test('registers handlers on the new client before start and returns their owned scope', async () => { + const received = sandbox.spy(); + const originalStart = LanguageClient.prototype.start; + const start = sandbox.stub(LanguageClient.prototype, 'start').callsFake(async function (this: LanguageClient) { + (this as unknown as import('./_languageclient_mock').LanguageClient) + .simulateNotification('example/score', 42); + await originalStart.call(this); + }); + const configureClient = sandbox.spy((context: ClientSetupContext): undefined => { + assert.strictEqual(context.client.state, State.Stopped); + context.registerDisposable(context.client.onNotification('example/score', received)); + }); + const result = await restartServer(makeRestartOptions({ hooks: { configureClient } })); + + try { + sinon.assert.calledOnce(configureClient); + assert.strictEqual(configureClient.firstCall.args[0].client, result.client); + sinon.assert.callOrder(configureClient, start, received); + sinon.assert.calledOnceWithExactly(received, 42); + assert.include(result.disposables, result.clientSetup); + result.disposables.forEach((disposable) => disposable.dispose()); + (result.client as unknown as import('./_languageclient_mock').LanguageClient) + .simulateNotification('example/score', 100); + sinon.assert.calledOnce(received); + } finally { + disposeResult(result); + } + }); + + for (const phase of ['setup', 'start', 'setTrace'] as const) { + test(`releases partially registered resources on ${phase} failure despite cleanup errors`, async () => { + const first = { dispose: sandbox.stub().throws(new Error('cleanup failed')) }; + const second = { dispose: sandbox.stub().rejects(new Error('async cleanup failed')) }; + const start = phase === 'start' + ? sandbox.stub(LanguageClient.prototype, 'start').rejects(new Error('start failed')) + : sandbox.spy(LanguageClient.prototype, 'start'); + if (phase === 'setTrace') { + sandbox.stub(LanguageClient.prototype, 'setTrace').rejects(new Error('trace failed')); + } + const dispose = sandbox.spy(LanguageClient.prototype, 'dispose'); + const result = await restartServer(makeRestartOptions({ + hooks: { + configureClient: ({ registerDisposable }) => { + registerDisposable(first); + registerDisposable(second); + if (phase === 'setup') { + throw new Error('setup failed'); + } + }, + }, + })); + + assert.isUndefined(result.client); + assert.isEmpty(result.disposables); + sinon.assert.calledOnce(first.dispose); + sinon.assert.calledOnce(second.dispose); + sinon.assert.calledOnce(dispose); + if (phase === 'setup') { + sinon.assert.notCalled(start); + } + }); + } + + test('does not configure or start a client when shutdown occurs during environment loading', async () => { + const loading = deferred(); + const loaded = deferred>(); + (envFileModule.getEnvFileVars as sinon.SinonStub).callsFake(() => { + loading.resolve(); + return loaded.promise; + }); + const controller = new AbortController(); + const configureClient = sandbox.spy(() => undefined); + const start = sandbox.spy(LanguageClient.prototype, 'start'); + const dispose = sandbox.spy(LanguageClient.prototype, 'dispose'); + const restarting = restartServer(makeRestartOptions({ + signal: controller.signal, + hooks: { configureClient }, + })); + await loading.promise; + controller.abort(); + loaded.resolve({}); + const result = await restarting; + assert.isUndefined(result.client); + sinon.assert.notCalled(configureClient); + sinon.assert.notCalled(start); + sinon.assert.calledOnce(dispose); + }); + + test('closes in-flight setup immediately and stops a late-started client after shutdown', async () => { + const entered = deferred(); + const started = deferred(); + sandbox.stub(LanguageClient.prototype, 'start').callsFake(async () => { + entered.resolve(); + await started.promise; + }); + const controller = new AbortController(); + const resource = { dispose: sandbox.stub() }; + const lateResource = { dispose: sandbox.stub() }; + let register!: ClientSetupContext['registerDisposable']; + const stop = sandbox.spy(LanguageClient.prototype, 'stop'); + const dispose = sandbox.spy(LanguageClient.prototype, 'dispose'); + const trace = sandbox.spy(LanguageClient.prototype, 'setTrace'); + const restarting = restartServer(makeRestartOptions({ + signal: controller.signal, + hooks: { + configureClient: ({ registerDisposable }) => { + register = registerDisposable; + registerDisposable(resource); + }, + }, + })); + await entered.promise; + controller.abort(); + sinon.assert.calledOnce(resource.dispose); + register(lateResource); + sinon.assert.calledOnce(lateResource.dispose); + started.resolve(); + const result = await restarting; + assert.isUndefined(result.client); + sinon.assert.calledOnce(stop); + sinon.assert.calledOnce(dispose); + sinon.assert.notCalled(trace); + sinon.assert.calledOnce(resource.dispose); + }); + for (const phase of ['start', 'setTrace'] as const) { test(`reports ${phase} rejection and disposes the client without installing a listener`, async () => { const entered = deferred(); diff --git a/typescript/tests/toolExtension.test.ts b/typescript/tests/toolExtension.test.ts index 5ff0e6b..8694dac 100644 --- a/typescript/tests/toolExtension.test.ts +++ b/typescript/tests/toolExtension.test.ts @@ -10,7 +10,7 @@ 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 { activateToolExtension, ToolExtensionRuntime, ToolLifecycleHooks } from '../src'; import { IServerInfo, ToolConfig } from '../src/types'; import * as vscodeapi from '../src/vscodeapi'; @@ -71,10 +71,11 @@ suite('activateToolExtension', () => { return { context: { subscriptions } as vscode.ExtensionContext, unrelated }; } - function activate(context: vscode.ExtensionContext, overrides?: Partial) { + function activate(context: vscode.ExtensionContext, overrides?: Partial, hooks?: ToolLifecycleHooks) { const runtime = activateToolExtension(context, { serverInfo, toolConfig: { ...toolConfig, ...overrides }, + hooks, }); runtimes.push(runtime); return runtime; @@ -386,6 +387,163 @@ suite('activateToolExtension', () => { ); }); + test('keeps old handlers through stop and retires them before replacement setup', async () => { + const clients: import('./_languageclient_mock').LanguageClient[] = []; + const handlers: ReturnType[] = []; + const received = sandbox.spy(); + const environment = sandbox.spy(() => ({ toolFlag: 'enabled' })); + start.restore(); + const originalStart = LanguageClient.prototype.start; + sandbox.stub(LanguageClient.prototype, 'start').callsFake(async function (this: LanguageClient) { + (this as unknown as import('./_languageclient_mock').LanguageClient) + .simulateNotification('example/score', 'during-start'); + await originalStart.call(this); + }); + const { context } = makeContext(); + const runtime = activate(context, undefined, { + getLaunchEnvironment: environment, + configureClient: ({ client, registerDisposable }) => { + clients.push(client as unknown as import('./_languageclient_mock').LanguageClient); + const owned = resource('client.handlers'); + handlers.push(owned); + registerDisposable(owned); + registerDisposable(client.onNotification('example/score', received)); + }, + }); + await nextImmediate(); + assert.lengthOf(clients, 1); + sinon.assert.calledOnceWithExactly(received, 'during-start'); + + stop.restore(); + const originalStop = LanguageClient.prototype.stop; + const stopping = deferred(); + const stopped = deferred(); + sandbox.stub(LanguageClient.prototype, 'stop').callsFake(async function (this: LanguageClient) { + stopping.resolve(); + await stopped.promise; + await originalStop.call(this); + }); + const restarting = commands.get('example.restart')!(); + await stopping.promise; + sinon.assert.notCalled(handlers[0].dispose); + clients[0].simulateNotification('example/score', 'before-stop'); + sinon.assert.calledWithExactly(received, 'before-stop'); + stopped.resolve(); + await restarting; + assert.lengthOf(clients, 2); + sinon.assert.calledOnce(handlers[0].dispose); + sinon.assert.notCalled(handlers[1].dispose); + sinon.assert.calledTwice(environment); + const count = received.callCount; + clients[0].simulateNotification('example/score', 'stale'); + assert.strictEqual(received.callCount, count); + clients[1].simulateNotification('example/score', 'current'); + assert.strictEqual(received.callCount, count + 1); + await runtime.deactivate(); + sinon.assert.calledOnce(handlers[1].dispose); + clients[1].simulateNotification('example/score', 'after-shutdown'); + assert.strictEqual(received.callCount, count + 1); + }); + + test('does not run hooks for coalesced requests and cleans each actual generation once', async () => { + const { context } = makeContext(); + const hooks = { + getLaunchEnvironment: sandbox.spy(() => ({})), + configureClient: sandbox.spy(({ registerDisposable }: Parameters< + NonNullable + >[0]): undefined => { + registerDisposable(resource('client.handlers')); + }), + }; + const runtime = activate(context, { restartDelay: 50 }, hooks); + await nextImmediate(); + const clock = sandbox.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + start.restore(); + const originalStart = LanguageClient.prototype.start; + const entered = deferred(); + const started = deferred(); + sandbox.stub(LanguageClient.prototype, 'start').callsFake(async function (this: LanguageClient) { + entered.resolve(); + await started.promise; + await originalStart.call(this); + }); + const restart = commands.get('example.restart')!; + const restarting = restart(); + await entered.promise; + await restart(); + await restart(); + sinon.assert.calledTwice(hooks.getLaunchEnvironment); + sinon.assert.calledTwice(hooks.configureClient); + await clock.tickAsync(50); + sinon.assert.calledTwice(hooks.configureClient); + started.resolve(); + await restarting; + await clock.tickAsync(50); + sinon.assert.calledThrice(hooks.configureClient); + sinon.assert.calledThrice(hooks.getLaunchEnvironment); + await runtime.deactivate(); + const owned = resources.filter((item) => item.name === 'client.handlers'); + assert.lengthOf(owned, 3); + owned.forEach((item) => sinon.assert.calledOnce(item.dispose)); + }); + + for (const stopped of [false, true]) { + test(`retires old setup after a failed stop leaving the client ${stopped ? 'Stopped' : 'Running'}`, async () => { + const owned: ReturnType[] = []; + const { context } = makeContext(); + const runtime = activate(context, undefined, { + configureClient: ({ registerDisposable }) => { + const handlers = resource('client.handlers'); + owned.push(handlers); + registerDisposable(handlers); + }, + }); + await nextImmediate(); + const oldClient = start.firstCall.thisValue as LanguageClient; + stop.restore(); + const originalStop = LanguageClient.prototype.stop; + sandbox.stub(LanguageClient.prototype, 'stop').callsFake(async function (this: LanguageClient) { + if (this === oldClient) { + if (stopped) { + await originalStop.call(this); + } + throw new Error('stop failed'); + } + await originalStop.call(this); + }); + await commands.get('example.restart')!(); + assert.lengthOf(owned, 2); + sinon.assert.calledOnce(owned[0].dispose); + sinon.assert.notCalled(owned[1].dispose); + await runtime.deactivate(); + owned.forEach((item) => sinon.assert.calledOnce(item.dispose)); + }); + } + + test('shutdown closes hook resources before an in-flight start settles', async () => { + const { context } = makeContext(); + const entered = deferred(); + const started = deferred(); + start.restore(); + sandbox.stub(LanguageClient.prototype, 'start').callsFake(async () => { + entered.resolve(); + await started.promise; + }); + const owned = resource('client.handlers'); + const runtime = activate(context, undefined, { + configureClient: ({ registerDisposable }) => { + registerDisposable(owned); + }, + }); + await entered.promise; + const shutdown = runtime.deactivate(); + sinon.assert.calledOnce(owned.dispose); + started.resolve(); + await shutdown; + sinon.assert.calledOnce(stop); + sinon.assert.calledOnce(owned.dispose); + }); + test('contains unexpected initializer rejections and still cleans up', async () => { const toolContext = { lsClient: undefined, diff --git a/typescript/tests/toolExtension.typecheck.ts b/typescript/tests/toolExtension.typecheck.ts index 54d1dc8..315d07d 100644 --- a/typescript/tests/toolExtension.typecheck.ts +++ b/typescript/tests/toolExtension.typecheck.ts @@ -9,6 +9,7 @@ import { ToolConfig, ToolDefinition, ToolExtensionRuntime, + ToolLifecycleHooks, } from '../src'; // Compile-only adoption checks; no lifecycle/client generics or casts are needed. @@ -36,9 +37,34 @@ export async function checkActivationFacade( const typedOptions: ActivateToolExtensionOptions = { serverInfo, toolConfig: definition, + hooks: { + getLaunchEnvironment: ({ settings, serverId, serverName }) => { + const interpreter: string[] = settings.interpreter; + const custom: unknown = settings.enabled; + return { + /* eslint-disable @typescript-eslint/naming-convention -- Environment keys retain their actual spelling. */ + EXAMPLE_INTERPRETER: interpreter[0], + EXAMPLE_ID: serverId, + EXAMPLE_NAME: serverName, + EXAMPLE_CUSTOM: custom === true ? '1' : undefined, + /* eslint-enable @typescript-eslint/naming-convention */ + }; + }, + configureClient: ({ client, registerDisposable, settings }) => { + const interpreter: string[] = settings.interpreter; + registerDisposable(client.onNotification('example/score', (_score: number) => { + void interpreter; + })); + }, + } satisfies ToolLifecycleHooks, }; 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(); } + +export const invalidAsyncSetup: ToolLifecycleHooks = { + // @ts-expect-error Setup is synchronous; client readiness cannot depend on an async callback. + configureClient: async () => {}, +};