Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions bundled/scripts/noConfigScripts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,16 @@ debugjava -jar myapp.jar --spring.profiles.active=dev
6. The port is written to a communication file
7. VS Code's file watcher detects the file and automatically starts an attach debug session

The communication file is stored in the extension's workspace-specific VS Code storage directory, not its installation directory. It contains only the local debug host and port, is deleted after a successful attach, and any stale file is removed before the next registration. Its path remains stable across window reloads.

## Troubleshooting

### No-Config Debug Could Not Be Initialized

If the workspace storage directory or its file watcher cannot be initialized, the extension displays a warning and leaves standard Java launch/attach debugging available. No-Config Debug requires an open workspace and writable VS Code workspace storage.

After upgrading from a version that stored the communication file in the extension directory, recreate existing terminals to pick up the new endpoint path.

### Port Already in Use

If you see "Address already in use", another Java debug session is running. Terminate it first.
Expand Down
7 changes: 5 additions & 2 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,12 @@ export async function activate(context: vscode.ExtensionContext): Promise<any> {
// Register No-Config Debug functionality
const noConfigDisposable = await registerNoConfigDebug(
context.environmentVariableCollection,
context.extensionPath
context.extensionPath,
context.storageUri,
);
context.subscriptions.push(noConfigDisposable);
if (noConfigDisposable) {
context.subscriptions.push(noConfigDisposable);
}

// Register Language Model Tools after Java Language Server is ready
registerLanguageModelToolsWhenReady(context);
Expand Down
169 changes: 90 additions & 79 deletions src/noConfigDebugInit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

import * as fs from 'fs';
import * as path from 'path';
import * as crypto from 'crypto';
import * as vscode from 'vscode';

import { sendInfo, sendError } from "vscode-extension-telemetry-wrapper";
Expand All @@ -13,6 +12,17 @@ import { applyAppendIfChanged, applyReplaceIfChanged } from "./envVarSync";

const ENV_VAR_COLLECTION_DESCRIPTION = "Java No-Config Debug";

function clearNoConfigDebugEnvironment(collection: vscode.EnvironmentVariableCollection): void {
for (const variable of ["VSCODE_JDWP_ADAPTER_ENDPOINTS", "VSCODE_JAVA_EXEC", "PATH"]) {
if (collection.get(variable)) {
collection.delete(variable);
}
}
if (collection.description !== undefined) {
collection.description = undefined;
}
}

/**
* Ensures the POSIX no-config debug wrapper can be invoked from a terminal.
*
Expand Down Expand Up @@ -47,6 +57,8 @@ export async function ensureDebugJavaScriptExecutable(
*
* @param envVarCollection - The collection of environment variables to be modified.
* @param extPath - The path to the extension directory.
* @param storageUri - The workspace-specific storage directory provided by VS Code.
* @returns The registration, or undefined when no-config debugging is unavailable.
*
* Environment Variables:
* - `VSCODE_JDWP_ADAPTER_ENDPOINTS`: Path to the file containing the debugger adapter endpoint.
Expand All @@ -56,96 +68,50 @@ export async function ensureDebugJavaScriptExecutable(
export async function registerNoConfigDebug(
envVarCollection: vscode.EnvironmentVariableCollection,
extPath: string,
): Promise<vscode.Disposable> {
storageUri: vscode.Uri | undefined,
): Promise<vscode.Disposable | undefined> {
const collection = envVarCollection;

// create a temp directory for the noConfigDebugAdapterEndpoints
// file path format: extPath/.noConfigDebugAdapterEndpoints/endpoint-stableWorkspaceHash.txt
let workspaceString = vscode.workspace.workspaceFile?.fsPath;
if (!workspaceString) {
workspaceString = vscode.workspace.workspaceFolders?.map((e) => e.uri.fsPath).join(';');
}
if (!workspaceString) {
if (!storageUri) {
clearNoConfigDebugEnvironment(collection);
const error: Error = {
name: "NoConfigDebugError",
message: '[Java Debug] No workspace folder found',
};
sendError(error);
return Promise.resolve(new vscode.Disposable(() => { }));
}

// create a stable hash for the workspace folder, reduce terminal variable churn
const hash = crypto.createHash('sha256');
hash.update(workspaceString.toString());
const stableWorkspaceHash = hash.digest('hex').slice(0, 16);

const tempDirPath = path.join(extPath, '.noConfigDebugAdapterEndpoints');
const tempFilePath = path.join(tempDirPath, `endpoint-${stableWorkspaceHash}.txt`);

// create the temp directory if it doesn't exist
if (!fs.existsSync(tempDirPath)) {
fs.mkdirSync(tempDirPath, { recursive: true });
} else {
// remove endpoint file in the temp directory if it exists (async to avoid blocking)
if (fs.existsSync(tempFilePath)) {
fs.promises.unlink(tempFilePath).catch((err) => {
const error: Error = {
name: "NoConfigDebugError",
message: `[Java Debug] Failed to cleanup old endpoint file: ${err}`,
};
sendError(error);
});
}
return undefined;
}

// Surface a description in VS Code's environment variable UI so users can
// see which extension is contributing these variables.
if (collection.description !== ENV_VAR_COLLECTION_DESCRIPTION) {
collection.description = ENV_VAR_COLLECTION_DESCRIPTION;
}

// Apply our managed variables using diff-aware helpers. On a typical
// window reload the values are unchanged and these calls are no-ops, so
// VS Code does not prompt the user to restart their existing terminals.
// See issue #1647.
//
// Note: We do NOT set JAVA_TOOL_OPTIONS globally to avoid affecting all Java processes
// (javac, maven, gradle, language server, etc.). Instead, JAVA_TOOL_OPTIONS is set
// only in the debugjava wrapper scripts (debugjava.ps1, debugjava.bat, debugjava)
applyReplaceIfChanged(collection, 'VSCODE_JDWP_ADAPTER_ENDPOINTS', tempFilePath);

// Try to get Java executable from Java Language Server
// This ensures we use the same Java version as the project is compiled with.
// If detection fails or returns nothing, we deliberately keep any previously
// set VSCODE_JAVA_EXEC to avoid churn from transient startup failures.
try {
const javaHome = await getJavaHome();
if (javaHome) {
const javaExec = path.join(javaHome, 'bin', 'java');
applyReplaceIfChanged(collection, 'VSCODE_JAVA_EXEC', javaExec);
}
} catch (error) {
// If we can't get Java from Language Server, that's okay
// The wrapper script will fall back to JAVA_HOME or PATH
}
// Workspace storage is stable across reloads and does not require a writable
// extension installation directory (for example, the Nix store).
const tempDirPath = path.join(storageUri.fsPath, '.noConfigDebugAdapterEndpoints');
const tempFilePath = path.join(tempDirPath, 'endpoint.txt');
let fileSystemWatcher: vscode.FileSystemWatcher;

const noConfigScriptsDir = path.join(extPath, 'bundled', 'scripts', 'noConfigScripts');
const debugJavaScriptPath = path.join(noConfigScriptsDir, "debugjava");
try {
await ensureDebugJavaScriptExecutable(debugJavaScriptPath);
} catch (err) {
const error: Error = {
await fs.promises.mkdir(tempDirPath, { recursive: true, mode: 0o700 });
// Finish removing stale data before watching or publishing the endpoint.
await fs.promises.unlink(tempFilePath).catch((error: NodeJS.ErrnoException) => {
if (error.code !== "ENOENT") {
throw error;
}
});
fileSystemWatcher = vscode.workspace.createFileSystemWatcher(
new vscode.RelativePattern(tempDirPath, path.basename(tempFilePath)),
);
Comment thread
wenytang-ms marked this conversation as resolved.
Resolved
} catch (error: unknown) {
clearNoConfigDebugEnvironment(collection);
// Filesystem error messages can contain user paths; report only the error code.
const code = error instanceof Error && "code" in error && typeof error.code === "string" ? error.code : "unknown";
sendError({
name: "NoConfigDebugError",
message: `[Java Debug] Failed to make debugjava executable: ${err}`,
};
sendError(error);
message: `[Java Debug] No-config debug initialization failed (${code}).`,
});
vscode.window.showWarningMessage(
"Java No-Config Debug could not be initialized. Standard Java debugging is still available.",
);
return undefined;
}
applyAppendIfChanged(collection, 'PATH', buildNoConfigPathAppendValue(noConfigScriptsDir));

// create file system watcher for the debuggerAdapterEndpointFolder for when the communication port is written
const fileSystemWatcher = vscode.workspace.createFileSystemWatcher(
new vscode.RelativePattern(tempDirPath, '**/*.txt')
);

// Track active debug sessions to prevent duplicates
const activeDebugSessions = new Set<number>();
Expand Down Expand Up @@ -264,7 +230,8 @@ export async function registerNoConfigDebug(
});
};

// Listen for both file creation and modification events
// Listen before publishing the endpoint or awaiting Java/script setup.
// Terminals surviving a reload may already have the stable endpoint path.
const fileCreationEvent = fileSystemWatcher.onDidCreate(handleEndpointFile);
const fileChangeEvent = fileSystemWatcher.onDidChange(handleEndpointFile);

Expand All @@ -277,6 +244,50 @@ export async function registerNoConfigDebug(
}
});

// Surface a description in VS Code's environment variable UI so users can
// see which extension is contributing these variables.
if (collection.description !== ENV_VAR_COLLECTION_DESCRIPTION) {
collection.description = ENV_VAR_COLLECTION_DESCRIPTION;
}

// Apply our managed variables using diff-aware helpers. On a typical
// window reload the values are unchanged and these calls are no-ops, so
// VS Code does not prompt the user to restart their existing terminals.
// See issue #1647.
//
// Note: We do NOT set JAVA_TOOL_OPTIONS globally to avoid affecting all Java processes
// (javac, maven, gradle, language server, etc.). Instead, JAVA_TOOL_OPTIONS is set
// only in the debugjava wrapper scripts (debugjava.ps1, debugjava.bat, debugjava)
applyReplaceIfChanged(collection, 'VSCODE_JDWP_ADAPTER_ENDPOINTS', tempFilePath);

// Try to get Java executable from Java Language Server
// This ensures we use the same Java version as the project is compiled with.
// If detection fails or returns nothing, we deliberately keep any previously
// set VSCODE_JAVA_EXEC to avoid churn from transient startup failures.
try {
const javaHome = await getJavaHome();
if (javaHome) {
const javaExec = path.join(javaHome, 'bin', 'java');
applyReplaceIfChanged(collection, 'VSCODE_JAVA_EXEC', javaExec);
}
} catch (error) {
// If we can't get Java from Language Server, that's okay
// The wrapper script will fall back to JAVA_HOME or PATH
}

const noConfigScriptsDir = path.join(extPath, 'bundled', 'scripts', 'noConfigScripts');
const debugJavaScriptPath = path.join(noConfigScriptsDir, "debugjava");
try {
await ensureDebugJavaScriptExecutable(debugJavaScriptPath);
} catch (err) {
const error: Error = {
name: "NoConfigDebugError",
message: `[Java Debug] Failed to make debugjava executable: ${err}`,
};
sendError(error);
}
applyAppendIfChanged(collection, 'PATH', buildNoConfigPathAppendValue(noConfigScriptsDir));

return Promise.resolve(
new vscode.Disposable(() => {
fileSystemWatcher.dispose();
Expand Down
66 changes: 1 addition & 65 deletions test/envVarSync.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,71 +8,7 @@ import {
applyAppendIfChanged,
applyReplaceIfChanged,
} from "../src/envVarSync";

interface FakeMutator {
type: vscode.EnvironmentVariableMutatorType;
value: string;
options: vscode.EnvironmentVariableMutatorOptions;
}

interface FakeCollection extends vscode.EnvironmentVariableCollection {
__calls: { replace: number; append: number; delete: number };
}

function createFakeCollection(): FakeCollection {
const store = new Map<string, FakeMutator>();
const calls = { replace: 0, append: 0, delete: 0 };

const collection = {
persistent: true,
description: undefined as string | vscode.MarkdownString | undefined,
get(name: string): FakeMutator | undefined {
return store.get(name);
},
replace(name: string, value: string, options?: vscode.EnvironmentVariableMutatorOptions): void {
calls.replace += 1;
store.set(name, {
type: vscode.EnvironmentVariableMutatorType.Replace,
value,
options: { applyAtProcessCreation: true, applyAtShellIntegration: false, ...options },
});
},
append(name: string, value: string, options?: vscode.EnvironmentVariableMutatorOptions): void {
calls.append += 1;
store.set(name, {
type: vscode.EnvironmentVariableMutatorType.Append,
value,
options: { applyAtProcessCreation: true, applyAtShellIntegration: false, ...options },
});
},
prepend(name: string, value: string, options?: vscode.EnvironmentVariableMutatorOptions): void {
store.set(name, {
type: vscode.EnvironmentVariableMutatorType.Prepend,
value,
options: { applyAtProcessCreation: true, applyAtShellIntegration: false, ...options },
});
},
delete(name: string): void {
calls.delete += 1;
store.delete(name);
},
clear(): void {
store.clear();
},
forEach(callback: (variable: string, mutator: FakeMutator, collection: any) => void): void {
store.forEach((mutator, variable) => callback(variable, mutator, collection));
},
getScoped(): vscode.EnvironmentVariableCollection {
return collection as unknown as vscode.EnvironmentVariableCollection;
},
*[Symbol.iterator](): IterableIterator<[string, FakeMutator]> {
yield* store.entries();
},
__calls: calls,
};

return collection as unknown as FakeCollection;
}
import { createFakeCollection } from "./helpers/environmentVariableCollection";

suite("envVarSync", () => {
suite("applyReplaceIfChanged", () => {
Expand Down
58 changes: 58 additions & 0 deletions test/helpers/environmentVariableCollection.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.

import * as vscode from "vscode";

export interface FakeCollection extends vscode.EnvironmentVariableCollection {
__calls: { replace: number; append: number; delete: number };
}

export function createFakeCollection(): FakeCollection {
const store = new Map<string, vscode.EnvironmentVariableMutator>();
const calls = { replace: 0, append: 0, delete: 0 };
const collection: FakeCollection = {
persistent: true,
description: undefined,
get(name) {
return store.get(name);
},
replace(name, value, options): void {
calls.replace += 1;
store.set(name, {
type: vscode.EnvironmentVariableMutatorType.Replace,
value,
options: { applyAtProcessCreation: true, applyAtShellIntegration: false, ...options },
});
},
append(name, value, options): void {
calls.append += 1;
store.set(name, {
type: vscode.EnvironmentVariableMutatorType.Append,
value,
options: { applyAtProcessCreation: true, applyAtShellIntegration: false, ...options },
});
},
prepend(name, value, options): void {
store.set(name, {
type: vscode.EnvironmentVariableMutatorType.Prepend,
value,
options: { applyAtProcessCreation: true, applyAtShellIntegration: false, ...options },
});
},
delete(name): void {
calls.delete += 1;
store.delete(name);
},
clear(): void {
store.clear();
},
forEach(callback, thisArg): void {
store.forEach((mutator, variable) => callback.call(thisArg, variable, mutator, collection));
},
Comment thread
wenytang-ms marked this conversation as resolved.
Resolved
*[Symbol.iterator](): IterableIterator<[string, vscode.EnvironmentVariableMutator]> {
yield* store.entries();
},
__calls: calls,
};
return collection;
}
Loading