Skip to content

[S6] Add an opt-in activation facade with explicit lifetime ownership #149

Closed

Description

Goal and roadmap position

Implement S6: an additive activation facade so a conventional Python-tool extension can adopt the shared client runtime without manually composing its activation boilerplate.

Typed tool definitions and source-only consumption have landed. The next sequence is:

S6 activation facade -> S7 demonstrated lifecycle hooks -> individual consumer migrations

The source-build/provenance work remains deferred and independent.

Inspection baseline: a1bff322958e63357a1b98d0d6eedcde2ff7de5e. Implement from current main.

Current composition and relevant files

Extensions currently compose these public pieces themselves:

  1. createOutputChannel(serverInfo.name) and registerLogger(outputChannel).
  2. new PythonEnvironmentsProvider(toolConfig).
  3. createToolContext({ serverInfo, outputChannel, toolConfig, pythonProvider }).
  4. registerCommonSubscriptions(context, { ...same dependencies, toolContext }).
  5. Deferred toolContext.initialize(subscriptions), traditionally scheduled with setImmediate.
  6. deactivateServer(toolContext) during extension deactivation, plus subscription disposal.

Canonical implementation:

  • typescript/src/activation.ts: ToolExtensionContext, CreateToolContextOptions, createToolContext, registerCommonSubscriptions, deactivateServer.
  • typescript/src/python.ts: provider constructor, initializePython, API subscriptions, dispose.
  • typescript/src/logging.ts: registerLogger returns a disposable; logging is currently module-global.
  • typescript/src/vscodeapi.ts: createOutputChannel(name) creates a log output channel.
  • typescript/src/types.ts: ToolConfig, ToolDefinition<TSettings>, ToolSettings<TSettings>, IServerInfo.
  • typescript/src/index.ts: public exports.
  • typescript/tests/activation.test.ts: existing lifecycle/formatter/deactivation characterizations.
  • typescript/tests/toolDefinition.typecheck.ts: compile-only public API cases.

There is already substantial restart, formatter and interpreter behavior in these helpers. The facade must compose that code, not replace it.

Proposed adoption shape

Add a small opt-in public entry point and a narrow shutdown handle. Suggested names are activateToolExtension, ActivateToolExtensionOptions and ToolExtensionRuntime; equivalent naming is acceptable if the ownership and timing contracts stay explicit.

For example, in a consuming extension's src/extension.ts:

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<void> {
    await runtime?.deactivate();
    runtime = undefined;
}

The facade accepts explicit serverInfo and toolConfig. Existing ToolConfig values and opt-in ToolDefinition<TSettings> values must both work without casts or generifying the entire lifecycle.

Do not silently infer a tool's policies from extension IDs or filesystem layout. The example deliberately leaves manifest loading and tool-definition construction explicit.

Required behavior

Compose once, preserve activation order

  • Create/register the shared output/logger, Python provider and tool context once per activation.
  • Wire common subscriptions before deferred initialization: Python initialization can emit the initial interpreter event.
  • Preserve the existing deferred-start pattern. Returning the runtime handle must not imply that Python is resolved or the language client is Running.
  • Keep all existing public low-level APIs available and behaviorally unchanged. A small dedicated facade module is preferable to reorganizing the legacy lifecycle.

Make ownership and shutdown explicit

  • Register facade-owned lifetime cleanup with the supplied extension context.
  • Provide an awaitable deactivation operation that delegates client shutdown to the existing deactivateServer behavior.
  • Cancel/guard the facade's deferred initializer if shutdown happens before it runs.
  • Make repeated explicit shutdown and extension-context disposal safe; do not start a client or restore a formatter because the facade's scheduled callback ran after shutdown.
  • Dispose only resources created/registered for this facade. Do not clear the caller's subscriptions or dispose unrelated caller-owned resources.
  • Clean up partial construction if a synchronous setup step fails.
  • Account for subscriptions arriving after an asynchronous initialization step settles during teardown: closed facade-owned collection/lifetime handling must not leak those new disposables.
  • Define how asynchronous initialization and cleanup failures are observed/logged; do not introduce unhandled promise rejections.

This is not a restart-queue or in-flight-start synchronization redesign. Legacy runServer() can schedule a delayed retry and resolve before that retry completes. Existing dispose() does not await every in-flight restart. Do not promise stronger client-readiness/quiescence semantics merely by adding the facade; document inherited limits and report a separately scoped bug if needed.

Preserve extension behavior

Do not change:

  • Interpreter selection, explicit-interpreter initialization shortcuts, per-project double opt-in, or package-refresh opt-in.
  • Command IDs, config watchers, log/trace behavior, formatter placeholder registration/fallback, debounce/restart timing or launch environment precedence.
  • Settings defaults, unknown fields, { settings, globalSettings } payload shape or explicit trackedSettings.
  • Tool-specific policies or Python bootstrap/import layout.

The logger/status remain module-global today. Do not claim that this facade adds safe multi-tool-instance isolation, and do not bundle a global-state refactor into S6.

Tests and acceptance

  • The public entry point/options/runtime handle compile through the built source-relative public entry.
  • Existing ToolConfig and ToolDefinition<TSettings> adoption both type-check.
  • A representative facade composition matches the equivalent legacy manual composition. Exercise real shared context/subscription helpers with mocked external APIs in at least one test; testing only helper-call arguments is insufficient.
  • Cover configured-interpreter and Python-managed initial startup, with common listeners installed before an initial interpreter event and no duplicate startup/subscriptions.
  • Cover a common trigger such as the restart command/config change through the facade without changing the existing restart contract.
  • Cover shutdown before deferred startup, repeated shutdown/context disposal, partial-setup failure and a late asynchronous subscription after teardown.
  • Formatter behavior remains protected by existing characterizations and a focused facade lifetime case where relevant.
  • Unrelated extension subscriptions/resources survive facade shutdown.
  • Existing TypeScript tests/build/lint pass on the pinned Node version. Current main has 161 TS runtime tests; existing pretest also compiles type assertions.
  • New/touched code follows repository formatting; do not broadly reformat pre-existing production files.
  • Root/TypeScript documentation has a minimal source-based example and states startup timing, shutdown ownership and inherited lifecycle limitations.
  • No changes to Python, settings fixtures, dependency versions, package identities, directory layout or consumer repositories.

Useful commands, from typescript/: npm run build, npm test -- --reporter dot, npm run lint, plus targeted formatting, public-declaration/example checks and git diff --check.

Use .nvmrc (currently Node 24.17.0). The full production Prettier check has pre-existing failures; do not turn this increment into unrelated formatting work. Native extension/VS Code UI integration is a separate validation level: describe mocked/shared tests accurately rather than calling them a five-consumer compatibility pass.

Explicit non-goals

No Pylint/isort custom hooks, consumer migrations, monkey-patch replacement, generic plugin framework, broad test-only dependency-injection API, restart scheduler rewrite, new wire version, Python decomposition, singleton elimination, directory moves, source-provenance framework or publishing/version automation.

S7 will add the few demonstrated hooks; later reviewed consumer PRs will adopt the facade one extension at a time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions