Understanding Plugin Runtimes in VS Code: Context, Lifecycle, and Error Troubleshooting
Learn how VS Code extensions run, how activation events and API object types affect execution, why missing `await` causes common TypeScript errors, and how to trace the path from a file save event to diagnostics and output. Includes a runnable extension example and a practical four-step debugging checklist.
1. What Does “Harness” Mean?
In testing, a harness is a controlled environment built to run the system under test. In plugin development, the term is often used to describe the runtime that an editor extension depends on. This article uses that terminology, while all examples are based on the VS Code Extension API because its documentation is public and its versions are traceable. Always check the official documentation for the VS Code version you are using before relying on specific API details.
VS Code extensions run in a separate extension host process. The host loads extensions, dispatches events, and cleans up resources. Understanding the following three boundaries explains many compilation errors and runtime issues.
2. Three Boundaries of the Extension Runtime
1. Activation timing. An extension is loaded only when one of the activationEvents in package.json is triggered. For example, onLanguage:typescript activates an extension when a TypeScript file is opened. If no activation event is triggered, the code in the extension does not run.
2. Object shape. The object received by an event callback is determined by the API. The callback for workspace.onDidSaveTextDocument receives a TextDocument directly. This object provides the synchronous getText() method, which can be used to read the document text immediately.
3. Declared contributions. Commands, menus, and configuration items registered under the contributes node appear in the editor interface. If a command is registered only in code but not declared under contributes, users will not find it in the Command Palette.
3. A Common Error: Missing await
A frequent mistake looks like this:
const text = vscode.workspace.openTextDocument(uri).getText();
The compiler reports:
Property 'getText' does not exist on type 'Thenable<TextDocument>'
This means that openTextDocument returns an asynchronous value that has not completed yet. The TextDocument object is not available at that point, so its getText method cannot be called. Wait for the result first:
const doc = await vscode.workspace.openTextDocument(uri);const text = doc.getText();
Because await can be used only inside an async function, the activation function or callback must be declared as async when necessary. Also note that the save event callback already provides a TextDocument, so it does not need to call openTextDocument again.
4. Execution Flow: From Saving a File to Displaying Results
A save operation follows this sequence:
- The user saves a file, and the editor emits a save event.
- The host checks which extensions have matching
activationEvents. If a matching extension has not been activated, the host runs itsactivatefunction first. - The
activatefunction registers event listeners and adds the returned disposables tocontext.subscriptions. - When the event occurs, the host invokes the corresponding callback.
- The callback presents its results through a
DiagnosticCollectionor anOutputChannel.
context.subscriptions provides centralized resource cleanup. When an extension is deactivated, the host calls dispose on the objects in the collection, preventing listeners from remaining active after the extension has stopped.
5. Runnable Example: Checking for console.log on Save
The following example marks remaining console.log statements after a TypeScript file is saved. Use an @types/vscode version that matches the engines field.
The relevant fields in package.json are:
{"name": "save-checker","version": "0.0.1","engines": { "vscode": "^1.85.0" },"main": "./out/extension.js","activationEvents": ["onLanguage:typescript"],"contributes": {"commands": [{ "command": "saveChecker.run", "title": "Save Checker: Run" }]}}
The contents of extension.ts are:
import * as vscode from 'vscode';const collection = vscode.languages.createDiagnosticCollection('saveChecker');const output = vscode.window.createOutputChannel('Save Checker');export function activate(context: vscode.ExtensionContext) {const onSave = vscode.workspace.onDidSaveTextDocument((doc) => {if (doc.languageId !== 'typescript') {return;}const lines = doc.getText().split('\n');const diagnostics: vscode.Diagnostic[] = [];lines.forEach((line, index) => {if (line.includes('console.log(')) {const range = new vscode.Range(index, 0, index, line.length);diagnostics.push(new vscode.Diagnostic(range,'Found console.log. Remove it before committing.',vscode.DiagnosticSeverity.Warning));}});collection.set(doc.uri, diagnostics);output.appendLine(`checked ${doc.fileName}: ${diagnostics.length} warnings`);});context.subscriptions.push(onSave, collection, output);}export function deactivate() {}
This example illustrates three important points. First, the callback uses the synchronous getText() method directly and does not miss an await. Second, diagnostic results are written through a DiagnosticCollection, allowing the editor to display warning squiggles on the relevant lines. Third, the listener, diagnostic collection, and output channel are all added to context.subscriptions, so they are released together when the extension is deactivated.
6. Debugging Techniques
- Run a debug instance: Press F5 in the extension project. VS Code starts an Extension Development Host window where the extension runs.
- Inspect output: Content written with
output.appendLineappears in the Output panel. Select Save Checker from the output-channel list. - Set breakpoints: Add a breakpoint inside the callback in
extension.ts, then save a TypeScript file to trigger it. - Check activation status: Run Developer: Show Running Extensions from the Command Palette to see whether the extension is active and how long activation took.
- Control log content: The example records only the file name and warning count, not the file contents. Do not write file contents, tokens, or complete paths containing usernames to logs.
7. Permissions and Security
- Declare only the activation events that are necessary. A narrower event scope reduces loading in unrelated situations.
- Do not log file contents or place tokens in source code. Use
context.secrets(SecretStorage) when sensitive values need to be stored. - Read file contents only when necessary. This example reads only the document that was saved rather than scanning the entire workspace.
8. A Four-Step Troubleshooting Checklist
- Check the type: Start with the type name in the error message and inspect the
@types/vscodedeclarations to determine whether the API returns a synchronous value or aThenable. - Check activation: Verify that an
activationEventwas triggered, then use Show Running Extensions to confirm that the extension is active. - Check the lifecycle: Confirm that every listener has been added to
context.subscriptions. - Check output: Use an output channel and breakpoints to verify that the callback runs and that the received data matches expectations.
