From 0902ebbe4e7acff6227ed11400f600c1a1df2a03 Mon Sep 17 00:00:00 2001 From: misha-db Date: Thu, 27 Aug 2026 12:38:26 +0400 Subject: [PATCH 01/31] HTTP proxy support --- packages/databricks-vscode/package.json | 5 + .../src/configuration/auth/AuthProvider.ts | 12 ++ .../src/utils/network/proxyAgent.test.ts | 122 +++++++++++++++ .../src/utils/network/proxyAgent.ts | 142 ++++++++++++++++++ .../src/vscode-objs/WorkspaceConfigs.ts | 30 ++++ yarn.lock | 64 +++++++- 6 files changed, 373 insertions(+), 2 deletions(-) create mode 100644 packages/databricks-vscode/src/utils/network/proxyAgent.test.ts create mode 100644 packages/databricks-vscode/src/utils/network/proxyAgent.ts diff --git a/packages/databricks-vscode/package.json b/packages/databricks-vscode/package.json index 2bf3276f2..ec8980b45 100644 --- a/packages/databricks-vscode/package.json +++ b/packages/databricks-vscode/package.json @@ -1831,6 +1831,10 @@ "type": "number", "default": 5, "description": "The interval in minutes at which the remote state of the bundle is refreshed." + }, + "databricks.proxy.strictSSL": { + "type": "boolean", + "markdownDescription": "Controls whether TLS certificates are verified for the extension's Databricks SDK calls. When unset, the built-in `#http.proxyStrictSSL#` value is used. Set to `false` only when a corporate CA certificate cannot be resolved from the system trust store." } } } @@ -1892,6 +1896,7 @@ "@types/shell-quote": "^1.7.5", "@vscode/debugadapter": "^1.64.0", "@vscode/extension-telemetry": "^1.5.2", + "@vscode/proxy-agent": "^0.44.0", "@vscode/webview-ui-toolkit": "^1.4.0", "add": "^2.0.6", "ansi-to-html": "^0.7.2", diff --git a/packages/databricks-vscode/src/configuration/auth/AuthProvider.ts b/packages/databricks-vscode/src/configuration/auth/AuthProvider.ts index 268d4b2af..45cf8081d 100644 --- a/packages/databricks-vscode/src/configuration/auth/AuthProvider.ts +++ b/packages/databricks-vscode/src/configuration/auth/AuthProvider.ts @@ -17,6 +17,10 @@ import {AzureCliCheck} from "./AzureCliCheck"; import {DatabricksCliCheck} from "./DatabricksCliCheck"; import {Loggers} from "../../logger"; import {CliWrapper} from "../../cli/CliWrapper"; +import { + applyProxyStrictSSLEnv, + getDatabricksHttpAgent, +} from "../../utils/network/proxyAgent"; // TODO: Resolve this with SDK's AuthType. export type AuthType = @@ -53,9 +57,17 @@ export abstract class AuthProvider { async getWorkspaceClient(): Promise { const config = await this.getSdkConfig(); + // The SDK pins its own agent per request, bypassing VS Code's global + // proxy/CA patching. Inject a proxy- and system-CA-aware agent so + // in-process SDK calls work behind corporate proxies and internal-CA + // TLS interception, matching the bundled CLI's behaviour. + applyProxyStrictSSLEnv(); + const agent = await getDatabricksHttpAgent(this.host); + return new WorkspaceClient(config, { product: "databricks-vscode", productVersion: extensionVersion, + agent, }); } diff --git a/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts b/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts new file mode 100644 index 000000000..f353710dc --- /dev/null +++ b/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts @@ -0,0 +1,122 @@ +import * as assert from "assert"; +import * as https from "node:https"; +import * as http from "node:http"; +import {reset, spy, when} from "ts-mockito"; +import {HttpsProxyAgent} from "https-proxy-agent"; +import {HttpProxyAgent} from "http-proxy-agent"; +import {workspaceConfigs} from "../../vscode-objs/WorkspaceConfigs"; +import { + applyProxyStrictSSLEnv, + getDatabricksHttpAgent, + resetProxyAgentCaches, + strictSSL, +} from "./proxyAgent"; + +describe(__filename, () => { + let configsSpy: typeof workspaceConfigs; + let existingEnv: NodeJS.ProcessEnv; + + beforeEach(() => { + existingEnv = Object.assign({}, process.env); + resetProxyAgentCaches(); + configsSpy = spy(workspaceConfigs); + // Defaults: strict SSL on, no proxy configured. + when(configsSpy.proxyStrictSSL).thenReturn(true); + when(configsSpy.httpProxy).thenReturn(undefined); + when(configsSpy.httpNoProxy).thenReturn([]); + }); + + afterEach(() => { + reset(configsSpy); + process.env = existingEnv; + }); + + describe("strictSSL / applyProxyStrictSSLEnv", () => { + it("reflects the effective setting", () => { + when(configsSpy.proxyStrictSSL).thenReturn(true); + assert.strictEqual(strictSSL(), true); + + when(configsSpy.proxyStrictSSL).thenReturn(false); + assert.strictEqual(strictSSL(), false); + }); + + it("sets DATABRICKS_SDK_PROXY_STRICT_SSL only when disabled", () => { + when(configsSpy.proxyStrictSSL).thenReturn(false); + applyProxyStrictSSLEnv(); + assert.strictEqual( + process.env.DATABRICKS_SDK_PROXY_STRICT_SSL, + "false" + ); + + when(configsSpy.proxyStrictSSL).thenReturn(true); + applyProxyStrictSSLEnv(); + assert.strictEqual( + process.env.DATABRICKS_SDK_PROXY_STRICT_SSL, + undefined + ); + }); + }); + + describe("getDatabricksHttpAgent", () => { + it("returns a plain https agent when no proxy is configured", async () => { + const agent = await getDatabricksHttpAgent( + new URL("https://example.com") + ); + assert.ok(agent instanceof https.Agent); + assert.ok(!(agent instanceof HttpsProxyAgent)); + }); + + it("returns an https proxy agent when http.proxy is set", async () => { + when(configsSpy.httpProxy).thenReturn("http://127.0.0.1:8080"); + const agent = await getDatabricksHttpAgent( + new URL("https://example.com") + ); + assert.ok(agent instanceof HttpsProxyAgent); + }); + + it("honours the http.proxy setting for http hosts", async () => { + when(configsSpy.httpProxy).thenReturn("http://127.0.0.1:8080"); + const agent = await getDatabricksHttpAgent( + new URL("http://example.com") + ); + assert.ok(agent instanceof HttpProxyAgent); + }); + + it("returns a plain agent when the host matches noProxy", async () => { + when(configsSpy.httpProxy).thenReturn("http://127.0.0.1:8080"); + when(configsSpy.httpNoProxy).thenReturn(["example.com"]); + const agent = await getDatabricksHttpAgent( + new URL("https://example.com") + ); + assert.ok(agent instanceof https.Agent); + assert.ok(!(agent instanceof HttpsProxyAgent)); + }); + + it("falls back to a plain http agent for http hosts without a proxy", async () => { + const agent = await getDatabricksHttpAgent( + new URL("http://example.com") + ); + assert.ok(agent instanceof http.Agent); + assert.ok(!(agent instanceof HttpProxyAgent)); + }); + + it("loads the system certificate trust store onto https agents", async () => { + const agent = (await getDatabricksHttpAgent( + new URL("https://example.com") + )) as https.Agent; + const ca = (agent.options as https.AgentOptions).ca; + assert.ok(Array.isArray(ca) && ca.length > 0); + }); + + it("disables certificate verification when strict SSL is off", async () => { + when(configsSpy.proxyStrictSSL).thenReturn(false); + const agent = (await getDatabricksHttpAgent( + new URL("https://example.com") + )) as https.Agent; + assert.strictEqual( + (agent.options as https.AgentOptions).rejectUnauthorized, + false + ); + }); + }); +}); diff --git a/packages/databricks-vscode/src/utils/network/proxyAgent.ts b/packages/databricks-vscode/src/utils/network/proxyAgent.ts new file mode 100644 index 000000000..66af2b726 --- /dev/null +++ b/packages/databricks-vscode/src/utils/network/proxyAgent.ts @@ -0,0 +1,142 @@ +import * as http from "node:http"; +import * as https from "node:https"; +import { + createProxyResolver, + loadSystemCertificates, + LogLevel, + type Log, + type ProxyAgentParams, +} from "@vscode/proxy-agent"; +import {HttpProxyAgent} from "http-proxy-agent"; +import {HttpsProxyAgent} from "https-proxy-agent"; +import {logging} from "@databricks/sdk-experimental"; +import {Loggers} from "../../logger"; +import {workspaceConfigs} from "../../vscode-objs/WorkspaceConfigs"; + +// Mirror the SDK's own default agent tuning (see @databricks/sdk-experimental +// api-client.js ApiClient.getAgent), so behaviour is unchanged apart from the +// proxy + CA wiring we add on top. +const KEEP_ALIVE_MSECS = 15000; + +function getLog(): Log { + const logger = logging.NamedLogger.getOrCreate(Loggers.Extension); + return { + trace: (message, ...args) => logger.debug(message, args), + debug: (message, ...args) => logger.debug(message, args), + info: (message, ...args) => logger.info(message, args), + warn: (message, ...args) => logger.warn(message, args), + error: (message, ...args) => + logger.error( + message instanceof Error ? message.message : message, + args + ), + }; +} + +/** + * Build the params @vscode/proxy-agent needs to resolve a proxy the same way + * VS Code core does: `http.proxy` setting first, then the `http(s)_proxy` env + * vars, honouring `http.noProxy` and `NO_PROXY`. System/PAC auto-detection is + * intentionally disabled (`isUseHostProxyEnabled: false`) — it needs Electron's + * proxy resolver, which the extension host doesn't expose. + */ +function getProxyAgentParams(): ProxyAgentParams { + const log = getLog(); + return { + resolveProxy: async () => undefined, + getProxyURL: () => workspaceConfigs.httpProxy, + getProxySupport: () => "on", + getNoProxyConfig: () => workspaceConfigs.httpNoProxy, + isAdditionalFetchSupportEnabled: () => false, + isWebSocketPatchEnabled: () => false, + addCertificatesV1: () => false, + addCertificatesV2: () => true, + loadSystemCertificatesFromNode: () => true, + loadAdditionalCertificates: async () => [], + log, + getLogLevel: () => LogLevel.Error, + proxyResolveTelemetry: () => {}, + isUseHostProxyEnabled: () => false, + env: process.env, + }; +} + +let systemCertificatesPromise: Promise | undefined; + +/** + * Load and cache the OS certificate trust store (Windows/macOS/Linux) plus + * Node's bundled CAs. Cached for the session; call {@link resetProxyAgentCaches} + * in tests. + */ +async function getSystemCertificates(params: ProxyAgentParams) { + if (!systemCertificatesPromise) { + systemCertificatesPromise = loadSystemCertificates({ + loadSystemCertificatesFromNode: + params.loadSystemCertificatesFromNode, + log: params.log, + }); + } + return systemCertificatesPromise; +} + +/** Reset the cached system certificates. Test-only. */ +export function resetProxyAgentCaches() { + systemCertificatesPromise = undefined; +} + +/** + * Whether the SDK must verify TLS certificates. `false` only when the user + * opted out via `databricks.proxy.strictSSL` or `http.proxyStrictSSL`. + */ +export function strictSSL(): boolean { + return workspaceConfigs.proxyStrictSSL; +} + +/** + * Keep the SDK's own fetch path (fetch.js reads DATABRICKS_SDK_PROXY_STRICT_SSL) + * and the bundled CLI subprocess consistent with the injected agent's + * `rejectUnauthorized`. + */ +export function applyProxyStrictSSLEnv() { + if (strictSSL()) { + delete process.env.DATABRICKS_SDK_PROXY_STRICT_SSL; + } else { + process.env.DATABRICKS_SDK_PROXY_STRICT_SSL = "false"; + } +} + +/** + * Build the HTTP(S) agent the Databricks SDK should use, wiring in the proxy + * (VS Code `http.proxy` setting + `http(s)_proxy` env vars, honouring + * `NO_PROXY`) and the OS certificate trust store. This is what lets the + * in-process SDK calls work behind corporate proxies and internal-CA TLS + * interception, matching the bundled CLI's behaviour. + */ +export async function getDatabricksHttpAgent( + host: URL +): Promise { + const params = getProxyAgentParams(); + const isHttps = host.protocol === "https:"; + + const ca = await getSystemCertificates(params); + const rejectUnauthorized = strictSSL(); + + const resolver = createProxyResolver(params); + const proxyUrl = await resolver.resolveProxyURL(host.toString()); + + const agentOptions: https.AgentOptions = { + keepAlive: true, + keepAliveMsecs: KEEP_ALIVE_MSECS, + ...(isHttps ? {ca, rejectUnauthorized} : {}), + }; + + if (proxyUrl) { + return isHttps + ? new HttpsProxyAgent(proxyUrl, agentOptions) + : new HttpProxyAgent(proxyUrl, agentOptions); + } + + return isHttps + ? new https.Agent(agentOptions) + : new http.Agent(agentOptions); +} diff --git a/packages/databricks-vscode/src/vscode-objs/WorkspaceConfigs.ts b/packages/databricks-vscode/src/vscode-objs/WorkspaceConfigs.ts index a6b18bc47..bc4bde816 100644 --- a/packages/databricks-vscode/src/vscode-objs/WorkspaceConfigs.ts +++ b/packages/databricks-vscode/src/vscode-objs/WorkspaceConfigs.ts @@ -139,6 +139,36 @@ export const workspaceConfigs = { return new Time(config, TimeUnits.minutes).toMillSeconds().value; }, + + /** + * Whether TLS certificates must be verified for the extension's SDK HTTP + * calls. `databricks.proxy.strictSSL`, when explicitly set, overrides the + * built-in `http.proxyStrictSSL`; both default to `true`. + */ + get proxyStrictSSL(): boolean { + const override = workspace + .getConfiguration("databricks") + .get("proxy.strictSSL"); + if (override !== undefined && override !== null) { + return override; + } + return ( + workspace.getConfiguration("http").get("proxyStrictSSL") ?? + true + ); + }, + + /** The `http.proxy` VS Code setting, mirrored for the SDK proxy resolver. */ + get httpProxy(): string | undefined { + return ( + workspace.getConfiguration("http").get("proxy") || undefined + ); + }, + + /** The `http.noProxy` VS Code setting, mirrored for the SDK proxy resolver. */ + get httpNoProxy(): string[] { + return workspace.getConfiguration("http").get("noProxy", []); + }, }; export type WorkspaceConfigs = typeof workspaceConfigs; diff --git a/yarn.lock b/yarn.lock index c45b0579b..0c2973c75 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1528,6 +1528,13 @@ __metadata: languageName: node linkType: hard +"@tootallnate/once@npm:^3.0.0": + version: 3.0.1 + resolution: "@tootallnate/once@npm:3.0.1" + checksum: 1ec82a3ff0dd2270eb09631789bd63a34445f62dd3031f0d620f4b1c81c5916d5cdb312ae651c4e390ecf62115279165421024efa75b2bb708d0699dc80c4a42 + languageName: node + linkType: hard + "@tootallnate/quickjs-emscripten@npm:^0.23.0": version: 0.23.0 resolution: "@tootallnate/quickjs-emscripten@npm:0.23.0" @@ -2066,6 +2073,25 @@ __metadata: languageName: node linkType: hard +"@vscode/proxy-agent@npm:^0.44.0": + version: 0.44.0 + resolution: "@vscode/proxy-agent@npm:0.44.0" + dependencies: + "@tootallnate/once": ^3.0.0 + "@vscode/windows-ca-certs": ^0.3.1 + agent-base: ^7.0.1 + debug: ^4.3.4 + http-proxy-agent: ^7.0.0 + https-proxy-agent: ^7.0.2 + socks-proxy-agent: ^8.0.1 + undici: ^7.2.0 + dependenciesMeta: + "@vscode/windows-ca-certs": + optional: true + checksum: 4ebf8fd3c1764c1bb94665e4c70ff7c43eedfebac3a0af29e2912349076a530b3956908ab91b860745f49f64707717187b1d21c14445d8966c07195c2ffb5b7d + languageName: node + linkType: hard + "@vscode/test-electron@npm:^2.4.1": version: 2.5.2 resolution: "@vscode/test-electron@npm:2.5.2" @@ -2106,6 +2132,16 @@ __metadata: languageName: node linkType: hard +"@vscode/windows-ca-certs@npm:^0.3.1": + version: 0.3.4 + resolution: "@vscode/windows-ca-certs@npm:0.3.4" + dependencies: + node-addon-api: ^8.2.0 + node-gyp: latest + conditions: os=win32 + languageName: node + linkType: hard + "@wdio/allure-reporter@npm:^9.1.3": version: 9.29.0 resolution: "@wdio/allure-reporter@npm:9.29.0" @@ -2530,6 +2566,13 @@ __metadata: languageName: node linkType: hard +"agent-base@npm:^7.0.1": + version: 7.1.4 + resolution: "agent-base@npm:7.1.4" + checksum: 86a7f542af277cfbd77dd61e7df8422f90bac512953709003a1c530171a9d019d072e2400eab2b59f84b49ab9dd237be44315ca663ac73e82b3922d10ea5eafa + languageName: node + linkType: hard + "agent-base@npm:^7.1.0": version: 7.1.0 resolution: "agent-base@npm:7.1.0" @@ -4023,6 +4066,7 @@ __metadata: "@typescript-eslint/utils": ^8.62.0 "@vscode/debugadapter": ^1.64.0 "@vscode/extension-telemetry": ^1.5.2 + "@vscode/proxy-agent": ^0.44.0 "@vscode/test-electron": ^3.1.0 "@vscode/webview-ui-toolkit": ^1.4.0 "@wdio/cli": ^9.29.0 @@ -6200,7 +6244,7 @@ __metadata: languageName: node linkType: hard -"https-proxy-agent@npm:^7.0.1, https-proxy-agent@npm:^7.0.5, https-proxy-agent@npm:^7.0.6": +"https-proxy-agent@npm:^7.0.1, https-proxy-agent@npm:^7.0.2, https-proxy-agent@npm:^7.0.5, https-proxy-agent@npm:^7.0.6": version: 7.0.6 resolution: "https-proxy-agent@npm:7.0.6" dependencies: @@ -7855,6 +7899,15 @@ __metadata: languageName: node linkType: hard +"node-addon-api@npm:^8.2.0": + version: 8.9.2 + resolution: "node-addon-api@npm:8.9.2" + dependencies: + node-gyp: latest + checksum: 820b3099b7d27c555fd9d98c986feab52d7eaf2e4dac1bce927857368baa0f2a3f31db5bd5112acd45222fd33a453b3baf8bf78771a0643a4b712e09a33f0fdf + languageName: node + linkType: hard + "node-domexception@npm:^1.0.0": version: 1.0.0 resolution: "node-domexception@npm:1.0.0" @@ -9402,7 +9455,7 @@ __metadata: languageName: node linkType: hard -"socks-proxy-agent@npm:^8.0.5": +"socks-proxy-agent@npm:^8.0.1, socks-proxy-agent@npm:^8.0.5": version: 8.0.5 resolution: "socks-proxy-agent@npm:8.0.5" dependencies: @@ -10345,6 +10398,13 @@ __metadata: languageName: node linkType: hard +"undici@npm:^7.2.0": + version: 7.29.0 + resolution: "undici@npm:7.29.0" + checksum: b3327e05259e66c61d3e05242bf63899c68d277302208f4fc1c7c0b880a9ba82651b8b3215584ffd424d8c8410f0114b6c3a89e6af604c703dc33009daa99ed3 + languageName: node + linkType: hard + "unicode-properties@npm:^1.4.1": version: 1.4.1 resolution: "unicode-properties@npm:1.4.1" From 3a86ca0dc8f923f16eba9f325a17bca867c6bacc Mon Sep 17 00:00:00 2001 From: misha-db Date: Thu, 27 Aug 2026 15:49:28 +0400 Subject: [PATCH 02/31] Apply proxy agent to Databricks/Azure CLI login checks --- .../src/configuration/auth/AzureCliCheck.ts | 11 +++++++++++ .../src/configuration/auth/DatabricksCliCheck.ts | 11 +++++++++++ 2 files changed, 22 insertions(+) diff --git a/packages/databricks-vscode/src/configuration/auth/AzureCliCheck.ts b/packages/databricks-vscode/src/configuration/auth/AzureCliCheck.ts index 3029b7905..48848aec2 100644 --- a/packages/databricks-vscode/src/configuration/auth/AzureCliCheck.ts +++ b/packages/databricks-vscode/src/configuration/auth/AzureCliCheck.ts @@ -14,6 +14,10 @@ import { FileNotFoundException, isFileNotFound, } from "@databricks/sdk-experimental/dist/config/execUtils"; +import { + applyProxyStrictSSLEnv, + getDatabricksHttpAgent, +} from "../../utils/network/proxyAgent"; // eslint-disable-next-line @typescript-eslint/naming-convention const {NamedLogger} = logging; @@ -212,6 +216,12 @@ export class AzureCliCheck implements Disposable { expired: boolean; error?: Error; }> { + // Match AuthProvider.getWorkspaceClient(): inject a proxy- and + // system-CA-aware agent so this login probe works behind corporate + // proxies and internal-CA TLS interception. + applyProxyStrictSSLEnv(); + const agent = await getDatabricksHttpAgent(host); + const workspaceClient = new WorkspaceClient( { host: host.toString(), @@ -221,6 +231,7 @@ export class AzureCliCheck implements Disposable { { product: "databricks-vscode", productVersion: extensionVersion, + agent, } ); try { diff --git a/packages/databricks-vscode/src/configuration/auth/DatabricksCliCheck.ts b/packages/databricks-vscode/src/configuration/auth/DatabricksCliCheck.ts index 1d06988f7..c8fe0b9d7 100644 --- a/packages/databricks-vscode/src/configuration/auth/DatabricksCliCheck.ts +++ b/packages/databricks-vscode/src/configuration/auth/DatabricksCliCheck.ts @@ -14,6 +14,10 @@ import {DatabricksCliAuthProvider} from "./AuthProvider"; import {orchestrate, OrchestrationLoopError, Step} from "./orchestrate"; import {Loggers} from "../../logger"; import {execFile} from "../../cli/CliWrapper"; +import { + applyProxyStrictSSLEnv, + getDatabricksHttpAgent, +} from "../../utils/network/proxyAgent"; // eslint-disable-next-line @typescript-eslint/no-require-imports const extensionVersion = require("../../../package.json") @@ -111,6 +115,12 @@ export class DatabricksCliCheck implements Disposable { private async tryLogin( cancellationToken?: CancellationToken ): Promise { + // Match AuthProvider.getWorkspaceClient(): inject a proxy- and + // system-CA-aware agent so this login probe works behind corporate + // proxies and internal-CA TLS interception. + applyProxyStrictSSLEnv(); + const agent = await getDatabricksHttpAgent(this.authProvider.host); + const workspaceClient = new WorkspaceClient( { host: this.authProvider.host.toString(), @@ -124,6 +134,7 @@ export class DatabricksCliCheck implements Disposable { { product: "databricks-vscode", productVersion: extensionVersion, + agent, } ); From 8e6c83a6743485be0345081a1941d3d23ea7e767 Mon Sep 17 00:00:00 2001 From: misha-db Date: Thu, 27 Aug 2026 16:22:20 +0400 Subject: [PATCH 03/31] Cleanup --- .../src/configuration/auth/AuthProvider.ts | 30 ++------------- .../src/configuration/auth/AzureCliCheck.ts | 30 ++------------- .../configuration/auth/DatabricksCliCheck.ts | 25 ++---------- .../src/utils/network/proxyAgent.test.ts | 15 ++++++++ .../src/utils/network/proxyAgent.ts | 38 ++++++++++++++++++- 5 files changed, 62 insertions(+), 76 deletions(-) diff --git a/packages/databricks-vscode/src/configuration/auth/AuthProvider.ts b/packages/databricks-vscode/src/configuration/auth/AuthProvider.ts index 45cf8081d..4598a5860 100644 --- a/packages/databricks-vscode/src/configuration/auth/AuthProvider.ts +++ b/packages/databricks-vscode/src/configuration/auth/AuthProvider.ts @@ -1,26 +1,14 @@ /* eslint-disable @typescript-eslint/naming-convention */ -import { - Config, - ProductVersion, - WorkspaceClient, - logging, -} from "@databricks/sdk-experimental"; +import {Config, WorkspaceClient, logging} from "@databricks/sdk-experimental"; import {CancellationToken, ProgressLocation, window} from "vscode"; import {normalizeHost} from "../../utils/urlUtils"; import {workspaceConfigs} from "../../vscode-objs/WorkspaceConfigs"; -// eslint-disable-next-line @typescript-eslint/no-require-imports -const extensionVersion = require("../../../package.json") - .version as ProductVersion; - import {AzureCliCheck} from "./AzureCliCheck"; import {DatabricksCliCheck} from "./DatabricksCliCheck"; import {Loggers} from "../../logger"; import {CliWrapper} from "../../cli/CliWrapper"; -import { - applyProxyStrictSSLEnv, - getDatabricksHttpAgent, -} from "../../utils/network/proxyAgent"; +import {createWorkspaceClient} from "../../utils/network/proxyAgent"; // TODO: Resolve this with SDK's AuthType. export type AuthType = @@ -56,19 +44,7 @@ export abstract class AuthProvider { async getWorkspaceClient(): Promise { const config = await this.getSdkConfig(); - - // The SDK pins its own agent per request, bypassing VS Code's global - // proxy/CA patching. Inject a proxy- and system-CA-aware agent so - // in-process SDK calls work behind corporate proxies and internal-CA - // TLS interception, matching the bundled CLI's behaviour. - applyProxyStrictSSLEnv(); - const agent = await getDatabricksHttpAgent(this.host); - - return new WorkspaceClient(config, { - product: "databricks-vscode", - productVersion: extensionVersion, - agent, - }); + return createWorkspaceClient(config, this.host); } /** diff --git a/packages/databricks-vscode/src/configuration/auth/AzureCliCheck.ts b/packages/databricks-vscode/src/configuration/auth/AzureCliCheck.ts index 48848aec2..c0f6837b7 100644 --- a/packages/databricks-vscode/src/configuration/auth/AzureCliCheck.ts +++ b/packages/databricks-vscode/src/configuration/auth/AzureCliCheck.ts @@ -1,9 +1,4 @@ -import { - Context, - ProductVersion, - WorkspaceClient, - logging, -} from "@databricks/sdk-experimental"; +import {Context, logging} from "@databricks/sdk-experimental"; import {CancellationToken, commands, Disposable, Uri, window} from "vscode"; import {Loggers} from "../../logger"; import {AzureCliAuthProvider} from "./AuthProvider"; @@ -14,18 +9,11 @@ import { FileNotFoundException, isFileNotFound, } from "@databricks/sdk-experimental/dist/config/execUtils"; -import { - applyProxyStrictSSLEnv, - getDatabricksHttpAgent, -} from "../../utils/network/proxyAgent"; +import {createWorkspaceClient} from "../../utils/network/proxyAgent"; // eslint-disable-next-line @typescript-eslint/naming-convention const {NamedLogger} = logging; -// eslint-disable-next-line @typescript-eslint/no-require-imports -const extensionVersion = require("../../../package.json") - .version as ProductVersion; - type AzureCloud = "AzureCloud" | "AzureChinaCloud" | "AzureUSGovernment"; type AzureStepName = @@ -216,23 +204,13 @@ export class AzureCliCheck implements Disposable { expired: boolean; error?: Error; }> { - // Match AuthProvider.getWorkspaceClient(): inject a proxy- and - // system-CA-aware agent so this login probe works behind corporate - // proxies and internal-CA TLS interception. - applyProxyStrictSSLEnv(); - const agent = await getDatabricksHttpAgent(host); - - const workspaceClient = new WorkspaceClient( + const workspaceClient = await createWorkspaceClient( { host: host.toString(), authType: "azure-cli", azureLoginAppId: this.azureLoginAppId, }, - { - product: "databricks-vscode", - productVersion: extensionVersion, - agent, - } + host ); try { await workspaceClient.currentUser.me( diff --git a/packages/databricks-vscode/src/configuration/auth/DatabricksCliCheck.ts b/packages/databricks-vscode/src/configuration/auth/DatabricksCliCheck.ts index c8fe0b9d7..eaea1bc67 100644 --- a/packages/databricks-vscode/src/configuration/auth/DatabricksCliCheck.ts +++ b/packages/databricks-vscode/src/configuration/auth/DatabricksCliCheck.ts @@ -1,8 +1,6 @@ import { CancellationToken, Context, - ProductVersion, - WorkspaceClient, logging, } from "@databricks/sdk-experimental"; import { @@ -14,14 +12,7 @@ import {DatabricksCliAuthProvider} from "./AuthProvider"; import {orchestrate, OrchestrationLoopError, Step} from "./orchestrate"; import {Loggers} from "../../logger"; import {execFile} from "../../cli/CliWrapper"; -import { - applyProxyStrictSSLEnv, - getDatabricksHttpAgent, -} from "../../utils/network/proxyAgent"; - -// eslint-disable-next-line @typescript-eslint/no-require-imports -const extensionVersion = require("../../../package.json") - .version as ProductVersion; +import {createWorkspaceClient} from "../../utils/network/proxyAgent"; type StepName = "tryLogin" | "login"; @@ -115,13 +106,7 @@ export class DatabricksCliCheck implements Disposable { private async tryLogin( cancellationToken?: CancellationToken ): Promise { - // Match AuthProvider.getWorkspaceClient(): inject a proxy- and - // system-CA-aware agent so this login probe works behind corporate - // proxies and internal-CA TLS interception. - applyProxyStrictSSLEnv(); - const agent = await getDatabricksHttpAgent(this.authProvider.host); - - const workspaceClient = new WorkspaceClient( + const workspaceClient = await createWorkspaceClient( { host: this.authProvider.host.toString(), authType: "databricks-cli", @@ -131,11 +116,7 @@ export class DatabricksCliCheck implements Disposable { ? {workspaceId: this.authProvider.workspaceId} : {}), }, - { - product: "databricks-vscode", - productVersion: extensionVersion, - agent, - } + this.authProvider.host ); try { diff --git a/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts b/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts index f353710dc..ba9c0a149 100644 --- a/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts +++ b/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts @@ -5,8 +5,10 @@ import {reset, spy, when} from "ts-mockito"; import {HttpsProxyAgent} from "https-proxy-agent"; import {HttpProxyAgent} from "http-proxy-agent"; import {workspaceConfigs} from "../../vscode-objs/WorkspaceConfigs"; +import {WorkspaceClient} from "@databricks/sdk-experimental"; import { applyProxyStrictSSLEnv, + createWorkspaceClient, getDatabricksHttpAgent, resetProxyAgentCaches, strictSSL, @@ -119,4 +121,17 @@ describe(__filename, () => { ); }); }); + + describe("createWorkspaceClient", () => { + it("builds a client tagged with the extension product and a proxy-aware agent", async () => { + const client = await createWorkspaceClient( + {host: "https://example.com", authType: "pat", token: "t"}, + new URL("https://example.com") + ); + assert.ok(client instanceof WorkspaceClient); + assert.strictEqual(client.apiClient.product, "databricks-vscode"); + const agent = await client.apiClient.getAgent(); + assert.ok(agent instanceof https.Agent); + }); + }); }); diff --git a/packages/databricks-vscode/src/utils/network/proxyAgent.ts b/packages/databricks-vscode/src/utils/network/proxyAgent.ts index 66af2b726..e861c6989 100644 --- a/packages/databricks-vscode/src/utils/network/proxyAgent.ts +++ b/packages/databricks-vscode/src/utils/network/proxyAgent.ts @@ -9,10 +9,18 @@ import { } from "@vscode/proxy-agent"; import {HttpProxyAgent} from "http-proxy-agent"; import {HttpsProxyAgent} from "https-proxy-agent"; -import {logging} from "@databricks/sdk-experimental"; +import { + logging, + ProductVersion, + WorkspaceClient, +} from "@databricks/sdk-experimental"; import {Loggers} from "../../logger"; import {workspaceConfigs} from "../../vscode-objs/WorkspaceConfigs"; +// eslint-disable-next-line @typescript-eslint/no-require-imports +const extensionVersion = require("../../../package.json") + .version as ProductVersion; + // Mirror the SDK's own default agent tuning (see @databricks/sdk-experimental // api-client.js ApiClient.getAgent), so behaviour is unchanged apart from the // proxy + CA wiring we add on top. @@ -140,3 +148,31 @@ export async function getDatabricksHttpAgent( ? new https.Agent(agentOptions) : new http.Agent(agentOptions); } + +// The config shape the WorkspaceClient constructor accepts (ConfigOptions | Config), +// derived from the constructor so we don't depend on ConfigOptions — the SDK index +// doesn't re-export it. +type WorkspaceClientConfig = ConstructorParameters[0]; + +/** + * Construct a WorkspaceClient wired for the extension's network environment. + * + * The SDK pins its own agent per request, bypassing VS Code's global proxy/CA + * patching. This injects a proxy- and system-CA-aware agent (and keeps the SDK + * fetch path and bundled-CLI subprocess consistent via the strict-SSL env) so + * in-process SDK calls work behind corporate proxies and internal-CA TLS + * interception, matching the bundled CLI's behaviour. This is the only place + * the extension should build a WorkspaceClient. + */ +export async function createWorkspaceClient( + config: WorkspaceClientConfig, + host: URL +): Promise { + applyProxyStrictSSLEnv(); + const agent = await getDatabricksHttpAgent(host); + return new WorkspaceClient(config, { + product: "databricks-vscode", + productVersion: extensionVersion, + agent, + }); +} From 699309c80c10d448851ba27ddef73dfd78351697 Mon Sep 17 00:00:00 2001 From: misha-db Date: Thu, 27 Aug 2026 18:57:09 +0400 Subject: [PATCH 04/31] Fix packaging build and harden system-CA loading --- packages/databricks-vscode/package.json | 2 +- .../src/utils/network/proxyAgent.test.ts | 26 +++++++++++++++++ .../src/utils/network/proxyAgent.ts | 29 +++++++++++++++++-- 3 files changed, 53 insertions(+), 4 deletions(-) diff --git a/packages/databricks-vscode/package.json b/packages/databricks-vscode/package.json index ec8980b45..0fbec6f21 100644 --- a/packages/databricks-vscode/package.json +++ b/packages/databricks-vscode/package.json @@ -1872,7 +1872,7 @@ "package:copy-webview-toolkit": "cp ./node_modules/@vscode/webview-ui-toolkit/dist/toolkit.js ./out/toolkit.js", "package:copy-markdown-it": "cp ./node_modules/markdown-it/dist/browser/markdown-it.umd.min.js ./out/markdown-it.min.js", "package:copy-highlight": "esbuild ./node_modules/highlight.js/lib/common.js --bundle --format=iife --global-name=hljs --outfile=out/highlight.min.js --minify", - "esbuild:base": "esbuild ./src/extension.ts --bundle --outfile=out/extension.js --external:vscode --format=cjs --platform=node --sourcemap --target=es2019", + "esbuild:base": "esbuild ./src/extension.ts --bundle --outfile=out/extension.js --external:vscode --external:@vscode/windows-ca-certs --format=cjs --platform=node --sourcemap --target=es2019", "build": "yarn run package:wrappers:write && yarn run package:jupyter-init-script:write && tsc --build --force", "watch": "yarn run package:wrappers:write && yarn run package:jupyter-init-script:write && yarn run package:copy-webview-toolkit && yarn run package:copy-markdown-it && yarn run package:copy-highlight && tsc --build --watch --verbose", "fix": "eslint src --fix && prettier . --write", diff --git a/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts b/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts index ba9c0a149..0503056f4 100644 --- a/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts +++ b/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts @@ -120,6 +120,32 @@ describe(__filename, () => { false ); }); + + it("falls back to Node's bundled CAs when the system store can't be read", async () => { + // @vscode/proxy-agent reads the store via tls.getCACertificates, + // which is absent/throws on older runtimes. Simulate that failure + // on the shared (required) tls module proxy-agent also sees. + // eslint-disable-next-line @typescript-eslint/no-require-imports + const tls = require("node:tls"); + const original = tls.getCACertificates; + tls.getCACertificates = () => { + throw new Error("getCACertificates unavailable"); + }; + try { + const agent = (await getDatabricksHttpAgent( + new URL("https://example.com") + )) as https.Agent; + // `ca` must be omitted (not [] / undefined) so Node keeps its + // bundled roots instead of trusting nothing. + assert.ok(!("ca" in (agent.options as https.AgentOptions))); + assert.strictEqual( + (agent.options as https.AgentOptions).rejectUnauthorized, + true + ); + } finally { + tls.getCACertificates = original; + } + }); }); describe("createWorkspaceClient", () => { diff --git a/packages/databricks-vscode/src/utils/network/proxyAgent.ts b/packages/databricks-vscode/src/utils/network/proxyAgent.ts index e861c6989..b241eb781 100644 --- a/packages/databricks-vscode/src/utils/network/proxyAgent.ts +++ b/packages/databricks-vscode/src/utils/network/proxyAgent.ts @@ -69,19 +69,39 @@ function getProxyAgentParams(): ProxyAgentParams { }; } -let systemCertificatesPromise: Promise | undefined; +let systemCertificatesPromise: Promise | undefined; /** * Load and cache the OS certificate trust store (Windows/macOS/Linux) plus * Node's bundled CAs. Cached for the session; call {@link resetProxyAgentCaches} * in tests. + * + * Returns `undefined` (never a rejected/empty promise) when the store can't be + * read. @vscode/proxy-agent reads it via Node's `tls.getCACertificates`, which + * only exists on Node >= 22.15; on the older runtimes some supported VS Code + * builds still ship, that call throws. Swallowing it here lets the caller fall + * back to Node's bundled roots instead of failing the whole SDK request — a + * missing custom CA is recoverable (users can set `databricks.proxy.strictSSL`), + * a broken agent is not. */ -async function getSystemCertificates(params: ProxyAgentParams) { +async function getSystemCertificates( + params: ProxyAgentParams +): Promise { if (!systemCertificatesPromise) { systemCertificatesPromise = loadSystemCertificates({ loadSystemCertificatesFromNode: params.loadSystemCertificatesFromNode, log: params.log, + }).catch((e) => { + params.log.error( + "Failed to load system certificates; falling back to Node's " + + "bundled CAs. Custom/corporate CAs may not be trusted.", + e + ); + // Don't cache the rejection — leave the promise unset so a later + // call can retry. + systemCertificatesPromise = undefined; + return undefined; }); } return systemCertificatesPromise; @@ -132,10 +152,13 @@ export async function getDatabricksHttpAgent( const resolver = createProxyResolver(params); const proxyUrl = await resolver.resolveProxyURL(host.toString()); + // Only override `ca` when we actually loaded a trust store. Passing `ca: + // undefined` (or `[]`) would replace Node's bundled roots with nothing and + // break every TLS handshake, so omit it entirely on the fallback path. const agentOptions: https.AgentOptions = { keepAlive: true, keepAliveMsecs: KEEP_ALIVE_MSECS, - ...(isHttps ? {ca, rejectUnauthorized} : {}), + ...(isHttps ? {rejectUnauthorized, ...(ca ? {ca} : {})} : {}), }; if (proxyUrl) { From 2382b3e1aaa89aa00b670bed3482c3f420a4e982 Mon Sep 17 00:00:00 2001 From: misha-db Date: Mon, 7 Sep 2026 12:24:09 +0400 Subject: [PATCH 05/31] Support vscode http proxy settings in databricks cli calls --- .../src/utils/envVarGenerators.test.ts | 55 ++++++++++++++++++- .../src/utils/envVarGenerators.ts | 40 +++++++++++++- 2 files changed, 91 insertions(+), 4 deletions(-) diff --git a/packages/databricks-vscode/src/utils/envVarGenerators.test.ts b/packages/databricks-vscode/src/utils/envVarGenerators.test.ts index 22ab6e72c..19ab0b4e3 100644 --- a/packages/databricks-vscode/src/utils/envVarGenerators.test.ts +++ b/packages/databricks-vscode/src/utils/envVarGenerators.test.ts @@ -1,5 +1,5 @@ /* eslint-disable @typescript-eslint/naming-convention */ -import {anything, instance, mock, when} from "ts-mockito"; +import {anything, instance, mock, reset, spy, when} from "ts-mockito"; import {ConnectionManager} from "../configuration/ConnectionManager"; import {DatabricksWorkspace} from "../configuration/DatabricksWorkspace"; import {ApiClient, Config} from "@databricks/sdk-experimental"; @@ -13,6 +13,7 @@ import { import {Uri} from "vscode"; import assert from "assert"; import {AuthProvider} from "../configuration/auth/AuthProvider"; +import {workspaceConfigs} from "../vscode-objs/WorkspaceConfigs"; describe(__filename, () => { let mockConnectionManager: ConnectionManager; @@ -22,8 +23,14 @@ describe(__filename, () => { const mockHost = "http://example.com"; let mockApiClient: ApiClient; let existingEnv: any; + let configsSpy: typeof workspaceConfigs; beforeEach(() => { + configsSpy = spy(workspaceConfigs); + // Default: no proxy configured via VS Code settings, so getProxyEnvVars + // falls back to the process env vars the tests set explicitly. + when(configsSpy.httpProxy).thenReturn(undefined); + when(configsSpy.httpNoProxy).thenReturn([]); mockConnectionManager = mock(ConnectionManager); mockDatabricksWorkspace = mock(DatabricksWorkspace); mockCluster = mock(Cluster); @@ -45,6 +52,7 @@ describe(__filename, () => { }); afterEach(() => { + reset(configsSpy); process.env = existingEnv; }); @@ -86,6 +94,51 @@ describe(__filename, () => { }); }); + it("should use the http.proxy setting for both schemes when set", () => { + delete process.env.HTTP_PROXY; + delete process.env.HTTPS_PROXY; + delete process.env.http_proxy; + delete process.env.https_proxy; + when(configsSpy.httpProxy).thenReturn("http://proxy.local:8080"); + + const actual = getProxyEnvVars(); + assert.deepEqual(actual, { + HTTP_PROXY: "http://proxy.local:8080", + HTTPS_PROXY: "http://proxy.local:8080", + NO_PROXY: undefined, + }); + }); + + it("should let the http.proxy setting win over env vars", () => { + process.env.HTTP_PROXY = "http://env-proxy.local:1"; + process.env.HTTPS_PROXY = "http://env-proxy.local:1"; + when(configsSpy.httpProxy).thenReturn("http://setting-proxy.local:2"); + + const actual = getProxyEnvVars(); + assert.deepEqual(actual, { + HTTP_PROXY: "http://setting-proxy.local:2", + HTTPS_PROXY: "http://setting-proxy.local:2", + NO_PROXY: undefined, + }); + }); + + it("should merge http.noProxy setting with the NO_PROXY env var", () => { + delete process.env.no_proxy; + process.env.NO_PROXY = "shared.example.com,env.example.com"; + when(configsSpy.httpNoProxy).thenReturn([ + "setting.example.com", + "shared.example.com", + ]); + + const actual = getProxyEnvVars(); + assert.deepEqual(actual, { + HTTP_PROXY: undefined, + HTTPS_PROXY: undefined, + // Deduped: "shared.example.com" appears in both sources but once here. + NO_PROXY: "setting.example.com,shared.example.com,env.example.com", + }); + }); + it("should generate env vars with expected cluster id", () => { const actual = getCommonDatabricksEnvVars( instance(mockConnectionManager), diff --git a/packages/databricks-vscode/src/utils/envVarGenerators.ts b/packages/databricks-vscode/src/utils/envVarGenerators.ts index cf34e0139..e824319f7 100644 --- a/packages/databricks-vscode/src/utils/envVarGenerators.ts +++ b/packages/databricks-vscode/src/utils/envVarGenerators.ts @@ -4,6 +4,7 @@ import {ExtensionContext, Uri} from "vscode"; import {logging, Headers} from "@databricks/sdk-experimental"; import {ConnectionManager} from "../configuration/ConnectionManager"; import {TerraformMetadata} from "./terraformUtils"; +import {workspaceConfigs} from "../vscode-objs/WorkspaceConfigs"; // eslint-disable-next-line @typescript-eslint/no-require-imports const packageJson = require("../../package.json"); @@ -140,12 +141,45 @@ export async function getDbConnectEnvVars( /* eslint-enable @typescript-eslint/naming-convention */ } +/** + * Proxy env vars forwarded to the bundled Databricks CLI (and any other + * subprocess). The Go CLI does no proxy handling of its own — it relies on Go's + * `http.ProxyFromEnvironment`, which reads only these env vars — so this is the + * only way to route CLI traffic through a proxy. + * + * Precedence mirrors the in-process SDK path (`proxyAgent.ts` + * `getProxyAgentParams`): the VS Code `http.proxy` / `http.noProxy` settings win + * over the OS `http(s)_proxy` / `no_proxy` env vars. That keeps the CLI and the + * SDK resolving the same proxy from the same inputs, so a user who configures the + * proxy purely through the VS Code setting gets it applied to both. + * + * Absent values stay `undefined` so `removeUndefinedKeys(...)` at the call sites + * strips them, leaving the CLI's own env untouched when nothing is configured. + */ export function getProxyEnvVars() { + // The `http.proxy` setting is a single URL used for both schemes. + const settingProxy = workspaceConfigs.httpProxy; + const httpProxy = + settingProxy || process.env.HTTP_PROXY || process.env.http_proxy; + const httpsProxy = + settingProxy || process.env.HTTPS_PROXY || process.env.https_proxy; + + // Merge the `http.noProxy` setting (an array) with the comma-separated + // NO_PROXY env var, deduping at host granularity. + const envNoProxy = process.env.NO_PROXY || process.env.no_proxy || ""; + const noProxyParts = [ + ...workspaceConfigs.httpNoProxy, + ...envNoProxy.split(","), + ] + .map((v) => v.trim()) + .filter((v) => v.length > 0); + const noProxy = [...new Set(noProxyParts)].join(",") || undefined; + return { /* eslint-disable @typescript-eslint/naming-convention */ - HTTP_PROXY: process.env.HTTP_PROXY || process.env.http_proxy, - HTTPS_PROXY: process.env.HTTPS_PROXY || process.env.https_proxy, - NO_PROXY: process.env.NO_PROXY || process.env.no_proxy, + HTTP_PROXY: httpProxy, + HTTPS_PROXY: httpsProxy, + NO_PROXY: noProxy, /* eslint-enable @typescript-eslint/naming-convention */ }; } From 90a3350381fe70eafa370caeb3a4732118f8b09e Mon Sep 17 00:00:00 2001 From: misha-db Date: Mon, 7 Sep 2026 13:21:43 +0400 Subject: [PATCH 06/31] Unify DATABRICKS_SDK_PROXY_STRICT_SSL resolution on activation --- packages/databricks-vscode/src/extension.ts | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/packages/databricks-vscode/src/extension.ts b/packages/databricks-vscode/src/extension.ts index dbfcda270..23a193360 100644 --- a/packages/databricks-vscode/src/extension.ts +++ b/packages/databricks-vscode/src/extension.ts @@ -97,6 +97,7 @@ import {BundleVariableModel} from "./bundle/models/BundleVariableModel"; import {BundleVariableTreeDataProvider} from "./ui/bundle-variables/BundleVariableTreeDataProvider"; import {ConfigurationTreeViewManager} from "./ui/configuration-view/ConfigurationTreeViewManager"; import {getCLIDependenciesEnvVars} from "./utils/envVarGenerators"; +import {applyProxyStrictSSLEnv} from "./utils/network/proxyAgent"; import {EnvironmentCommands} from "./language/EnvironmentCommands"; import {PackageManagerTelemetry} from "./language/PackageManagerTelemetry"; import {WorkspaceFolderManager} from "./vscode-objs/WorkspaceFolderManager"; @@ -663,20 +664,16 @@ export async function activate( customWhenContext.updateShowClusterView(); } - function updateStrictSSLEnv() { - const httpConfig = workspace.getConfiguration("http"); - const proxyStrictSSL = httpConfig.get("proxyStrictSSL"); - process.env["DATABRICKS_SDK_PROXY_STRICT_SSL"] = proxyStrictSSL - ? "true" - : "false"; - } - updateFeatureContexts(); - updateStrictSSLEnv(); + // Resolve TLS strict-SSL through the same layered setting the SDK client + // path uses (databricks.proxy.strictSSL -> http.proxyStrictSSL -> true), so + // both writers of DATABRICKS_SDK_PROXY_STRICT_SSL agree and verification + // stays on by default when nothing is configured. + applyProxyStrictSSLEnv(); context.subscriptions.push( workspace.onDidChangeConfiguration(() => { updateFeatureContexts(); - updateStrictSSLEnv(); + applyProxyStrictSSLEnv(); }) ); From f2e837d30720d5820573014d23a976a45151d13e Mon Sep 17 00:00:00 2001 From: misha-db Date: Mon, 7 Sep 2026 14:40:43 +0400 Subject: [PATCH 07/31] Trust OS-installed corporate CAs in the SDK path on all Node versions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit workspace TLS cert chains to an OS-trusted internal CA. Two causes: - proxyAgent hardcoded loadSystemCertificatesFromNode: true, so @vscode/proxy-agent called tls.getCACertificates (Node >= 22.15 only). On older Node (shipped by many supported VS Code builds) it threw, the OS store was lost, and the agent fell back to Node's bundled roots — which don't include the corp CA. - On the success path the agent set `ca` to only the OS store, which *replaces* Node's bundled public roots (getCACertificates('system') returns far fewer certs than tls.rootCertificates), a latent bug that could break public-root TLS. Fixes: - Make loadSystemCertificatesFromNode version-aware so older runtimes use proxy-agent's native readers (@vscode/windows-ca-certs on Windows, security on macOS, PEM files on Linux). - Always merge tls.rootCertificates + OS store + configured PEM; omit `ca` entirely only when nothing extra is loaded. - Add databricks.proxy.caCert setting as a cross-platform escape hatch. - Ship @vscode/windows-ca-certs in the win32 VSIXs (win32-only optional dep, copied into out/node_modules via package-vsix.sh gating). A missing/failed native module degrades to bundled roots + caCert, never a hard failure. TLS verification stays on by default throughout. --- packages/databricks-vscode/package.json | 10 +- .../scripts/copy-windows-ca-certs.sh | 50 +++++++++ .../databricks-vscode/scripts/package-vsix.sh | 8 ++ .../src/utils/network/proxyAgent.test.ts | 101 +++++++++++++++++- .../src/utils/network/proxyAgent.ts | 98 +++++++++++++++-- .../src/vscode-objs/WorkspaceConfigs.ts | 15 +++ 6 files changed, 267 insertions(+), 15 deletions(-) create mode 100755 packages/databricks-vscode/scripts/copy-windows-ca-certs.sh diff --git a/packages/databricks-vscode/package.json b/packages/databricks-vscode/package.json index 0fbec6f21..54737f7e8 100644 --- a/packages/databricks-vscode/package.json +++ b/packages/databricks-vscode/package.json @@ -1835,6 +1835,10 @@ "databricks.proxy.strictSSL": { "type": "boolean", "markdownDescription": "Controls whether TLS certificates are verified for the extension's Databricks SDK calls. When unset, the built-in `#http.proxyStrictSSL#` value is used. Set to `false` only when a corporate CA certificate cannot be resolved from the system trust store." + }, + "databricks.proxy.caCert": { + "type": "string", + "markdownDescription": "Absolute path to a PEM bundle of additional CA certificates to trust for the extension's Databricks SDK calls, merged with the OS trust store and Node's built-in roots. Use when a corporate CA cannot be read from the system store." } } } @@ -1854,7 +1858,7 @@ "version": "1.14.0" }, "scripts": { - "vscode:prepublish": "rm -rf out && yarn run package:compile && yarn run package:wrappers:write && yarn run package:jupyter-init-script:write && yarn run package:copy-webview-toolkit && yarn run package:copy-markdown-it && yarn run package:copy-highlight && yarn run generate-telemetry", + "vscode:prepublish": "rm -rf out && yarn run package:compile && yarn run package:wrappers:write && yarn run package:jupyter-init-script:write && yarn run package:copy-webview-toolkit && yarn run package:copy-markdown-it && yarn run package:copy-highlight && yarn run package:copy-windows-ca-certs && yarn run generate-telemetry", "package": "vsce package --baseContentUrl https://github.com/databricks/databricks-vscode/blob/${TAG:-main}/packages/databricks-vscode --baseImagesUrl https://github.com/_gh/raw/databricks/databricks-vscode/${TAG:-main}/packages/databricks-vscode", "package:linux:x64": "./scripts/package-vsix.sh linux-x64", "package:linux:arm64": "./scripts/package-vsix.sh linux-arm64", @@ -1872,6 +1876,7 @@ "package:copy-webview-toolkit": "cp ./node_modules/@vscode/webview-ui-toolkit/dist/toolkit.js ./out/toolkit.js", "package:copy-markdown-it": "cp ./node_modules/markdown-it/dist/browser/markdown-it.umd.min.js ./out/markdown-it.min.js", "package:copy-highlight": "esbuild ./node_modules/highlight.js/lib/common.js --bundle --format=iife --global-name=hljs --outfile=out/highlight.min.js --minify", + "package:copy-windows-ca-certs": "bash ./scripts/copy-windows-ca-certs.sh", "esbuild:base": "esbuild ./src/extension.ts --bundle --outfile=out/extension.js --external:vscode --external:@vscode/windows-ca-certs --format=cjs --platform=node --sourcemap --target=es2019", "build": "yarn run package:wrappers:write && yarn run package:jupyter-init-script:write && tsc --build --force", "watch": "yarn run package:wrappers:write && yarn run package:jupyter-init-script:write && yarn run package:copy-webview-toolkit && yarn run package:copy-markdown-it && yarn run package:copy-highlight && tsc --build --watch --verbose", @@ -1911,6 +1916,9 @@ "winston": "^3.11.0", "yaml": "^2.8.3" }, + "optionalDependencies": { + "@vscode/windows-ca-certs": "^0.3.1" + }, "devDependencies": { "@istanbuljs/nyc-config-typescript": "^1.0.2", "@sinonjs/fake-timers": "^15.4.0", diff --git a/packages/databricks-vscode/scripts/copy-windows-ca-certs.sh b/packages/databricks-vscode/scripts/copy-windows-ca-certs.sh new file mode 100755 index 000000000..6f74f84a9 --- /dev/null +++ b/packages/databricks-vscode/scripts/copy-windows-ca-certs.sh @@ -0,0 +1,50 @@ +#!/bin/bash +# +# Copy the native @vscode/windows-ca-certs module into out/node_modules so the +# esbuild bundle's runtime `require("@vscode/windows-ca-certs")` resolves in the +# packaged extension. The bundle marks the module external (a native .node can't +# be bundled) and the VSIX excludes the top-level node_modules/**, so the module +# has to live under out/ to ship — same approach as the other package:copy-* +# steps. It runs from vscode:prepublish (before vsce zips out/), which is the +# only point at which we can add files to the packaged output. +# +# The module is a win32-only optional dependency, so this is a no-op unless we're +# packaging a win32 VSIX. package-vsix.sh signals that by exporting +# INCLUDE_WINDOWS_CA_CERTS=1 for the win32-* targets; for any other invocation +# (dev builds, mac/linux VSIXs) we skip. +# +# Even for win32 targets the module may be absent when the VSIX is cross-built on +# a non-Windows host (yarn honours the os=win32 install condition and skips it +# there). We warn rather than fail: at runtime a missing module degrades to +# Node's bundled roots plus databricks.proxy.caCert, so the build should still +# succeed. To actually ship the native reader, build the win32 VSIX on a Windows +# host (or install a prebuilt @vscode/windows-ca-certs) so the module is present. + +set -euo pipefail + +# get path of the repo (parent of scripts/) +cd "$(dirname "$(realpath "$0")")/.." + +if [ "${INCLUDE_WINDOWS_CA_CERTS:-}" != "1" ]; then + # Not a win32 packaging target — nothing to do. + exit 0 +fi + +SRC="./node_modules/@vscode/windows-ca-certs" +DEST="./out/node_modules/@vscode/windows-ca-certs" + +if [ ! -d "$SRC" ]; then + echo "WARNING: $SRC not found — packaging a win32 VSIX without the native" >&2 + echo "Windows CA reader. On older Node the SDK will fall back to Node's" >&2 + echo "bundled roots (+ databricks.proxy.caCert). Build on a Windows host to" >&2 + echo "include it." >&2 + exit 0 +fi + +rm -rf "$DEST" +mkdir -p "$(dirname "$DEST")" +# Copy the whole module directory (index.js, package.json, build/Release/*.node, +# etc.) so its own require() calls and the native addon all resolve at runtime. +cp -R "$SRC" "$DEST" + +echo "Copied @vscode/windows-ca-certs -> $DEST" diff --git a/packages/databricks-vscode/scripts/package-vsix.sh b/packages/databricks-vscode/scripts/package-vsix.sh index 5795f9dc8..088e35ea8 100755 --- a/packages/databricks-vscode/scripts/package-vsix.sh +++ b/packages/databricks-vscode/scripts/package-vsix.sh @@ -58,6 +58,14 @@ if [ $ARCH != "win32-arm64" ]; then fi yarn run prettier package.json --write + +# Ship the native Windows CA reader (@vscode/windows-ca-certs) only in the win32 +# VSIXs. vscode:prepublish reads this to decide whether to copy the module into +# out/ (see scripts/copy-windows-ca-certs.sh). +case $ARCH in + win32-*) export INCLUDE_WINDOWS_CA_CERTS=1 ;; +esac + TAG="release-v$(cat package.json | jq -r .version)" yarn run package -t $VSXI_ARCH git checkout -- package.json diff --git a/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts b/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts index 0503056f4..357931e75 100644 --- a/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts +++ b/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts @@ -1,6 +1,10 @@ import * as assert from "assert"; import * as https from "node:https"; import * as http from "node:http"; +import * as tls from "node:tls"; +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; import {reset, spy, when} from "ts-mockito"; import {HttpsProxyAgent} from "https-proxy-agent"; import {HttpProxyAgent} from "http-proxy-agent"; @@ -10,10 +14,16 @@ import { applyProxyStrictSSLEnv, createWorkspaceClient, getDatabricksHttpAgent, + loadSystemCertificatesFromNode, resetProxyAgentCaches, strictSSL, } from "./proxyAgent"; +// A syntactically-valid but throwaway PEM used to assert it lands in the agent's +// `ca` list. It never has to verify anything — the tests only check membership. +const FAKE_CA_PEM = + "-----BEGIN CERTIFICATE-----\nMIIBFake\n-----END CERTIFICATE-----\n"; + describe(__filename, () => { let configsSpy: typeof workspaceConfigs; let existingEnv: NodeJS.ProcessEnv; @@ -22,10 +32,11 @@ describe(__filename, () => { existingEnv = Object.assign({}, process.env); resetProxyAgentCaches(); configsSpy = spy(workspaceConfigs); - // Defaults: strict SSL on, no proxy configured. + // Defaults: strict SSL on, no proxy or custom CA configured. when(configsSpy.proxyStrictSSL).thenReturn(true); when(configsSpy.httpProxy).thenReturn(undefined); when(configsSpy.httpNoProxy).thenReturn([]); + when(configsSpy.proxyCaCert).thenReturn(undefined); }); afterEach(() => { @@ -102,12 +113,23 @@ describe(__filename, () => { assert.ok(!(agent instanceof HttpProxyAgent)); }); - it("loads the system certificate trust store onto https agents", async () => { + it("merges the system trust store with Node's bundled roots (never replaces them)", async () => { const agent = (await getDatabricksHttpAgent( new URL("https://example.com") )) as https.Agent; const ca = (agent.options as https.AgentOptions).ca; - assert.ok(Array.isArray(ca) && ca.length > 0); + assert.ok(Array.isArray(ca)); + // tls.getCACertificates('system') returns only the OS store; setting + // `ca` to that alone would drop Node's bundled public roots. The + // agent must carry at least all of the bundled roots. + assert.ok( + (ca as unknown[]).length >= tls.rootCertificates.length, + `expected >= ${tls.rootCertificates.length} CAs, got ${ + (ca as unknown[]).length + }` + ); + // A known bundled root is still present. + assert.ok((ca as string[]).includes(tls.rootCertificates[0])); }); it("disables certificate verification when strict SSL is off", async () => { @@ -146,6 +168,79 @@ describe(__filename, () => { tls.getCACertificates = original; } }); + + it("merges databricks.proxy.caCert onto the trust store", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "dbx-ca-")); + const pemPath = path.join(dir, "corp-ca.pem"); + fs.writeFileSync(pemPath, FAKE_CA_PEM); + when(configsSpy.proxyCaCert).thenReturn(pemPath); + try { + const agent = (await getDatabricksHttpAgent( + new URL("https://example.com") + )) as https.Agent; + const ca = (agent.options as https.AgentOptions).ca as string[]; + assert.ok(Array.isArray(ca)); + assert.ok(ca.includes(FAKE_CA_PEM)); + // Still anchored on the bundled roots. + assert.ok(ca.includes(tls.rootCertificates[0])); + } finally { + fs.rmSync(dir, {recursive: true, force: true}); + } + }); + + it("applies databricks.proxy.caCert even when the system store can't be read", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "dbx-ca-")); + const pemPath = path.join(dir, "corp-ca.pem"); + fs.writeFileSync(pemPath, FAKE_CA_PEM); + when(configsSpy.proxyCaCert).thenReturn(pemPath); + // eslint-disable-next-line @typescript-eslint/no-require-imports + const tlsMod = require("node:tls"); + const original = tlsMod.getCACertificates; + tlsMod.getCACertificates = () => { + throw new Error("getCACertificates unavailable"); + }; + try { + const agent = (await getDatabricksHttpAgent( + new URL("https://example.com") + )) as https.Agent; + const ca = (agent.options as https.AgentOptions).ca as string[]; + assert.ok(Array.isArray(ca)); + assert.ok(ca.includes(FAKE_CA_PEM)); + assert.ok(ca.includes(tls.rootCertificates[0])); + } finally { + tlsMod.getCACertificates = original; + fs.rmSync(dir, {recursive: true, force: true}); + } + }); + + it("ignores an unreadable databricks.proxy.caCert path", async () => { + when(configsSpy.proxyCaCert).thenReturn( + path.join(os.tmpdir(), "does-not-exist-xyz.pem") + ); + // Must not throw; falls back to the rest of the trust store. + const agent = (await getDatabricksHttpAgent( + new URL("https://example.com") + )) as https.Agent; + const ca = (agent.options as https.AgentOptions).ca as string[]; + assert.ok(!ca || !ca.includes(FAKE_CA_PEM)); + }); + }); + + describe("loadSystemCertificatesFromNode", () => { + it("is true when tls.getCACertificates exists, false when it doesn't", () => { + // eslint-disable-next-line @typescript-eslint/no-require-imports + const tlsMod = require("node:tls"); + const original = tlsMod.getCACertificates; + try { + tlsMod.getCACertificates = () => []; + assert.strictEqual(loadSystemCertificatesFromNode(), true); + + tlsMod.getCACertificates = undefined; + assert.strictEqual(loadSystemCertificatesFromNode(), false); + } finally { + tlsMod.getCACertificates = original; + } + }); }); describe("createWorkspaceClient", () => { diff --git a/packages/databricks-vscode/src/utils/network/proxyAgent.ts b/packages/databricks-vscode/src/utils/network/proxyAgent.ts index b241eb781..698e31ec7 100644 --- a/packages/databricks-vscode/src/utils/network/proxyAgent.ts +++ b/packages/databricks-vscode/src/utils/network/proxyAgent.ts @@ -1,5 +1,7 @@ import * as http from "node:http"; import * as https from "node:https"; +import * as tls from "node:tls"; +import {readFile} from "node:fs/promises"; import { createProxyResolver, loadSystemCertificates, @@ -26,6 +28,26 @@ const extensionVersion = require("../../../package.json") // proxy + CA wiring we add on top. const KEEP_ALIVE_MSECS = 15000; +/** + * Whether to let @vscode/proxy-agent read the OS trust store via Node's + * `tls.getCACertificates`. + * + * That API was added in Node 22.15. proxy-agent's "from Node" path calls it + * unconditionally, so on older runtimes (shipped by many supported VS Code + * builds) it throws and we lose the OS trust store. When it's missing we return + * `false` so proxy-agent instead uses its native readers (the + * `@vscode/windows-ca-certs` module on Windows, `security` on macOS, PEM bundle + * files on Linux), which work on every Node version. + * + * Evaluated per call (not cached) so tests can simulate an older runtime. + */ +export function loadSystemCertificatesFromNode(): boolean { + return ( + typeof (tls as {getCACertificates?: unknown}).getCACertificates === + "function" + ); +} + function getLog(): Log { const logger = logging.NamedLogger.getOrCreate(Loggers.Extension); return { @@ -59,7 +81,7 @@ function getProxyAgentParams(): ProxyAgentParams { isWebSocketPatchEnabled: () => false, addCertificatesV1: () => false, addCertificatesV2: () => true, - loadSystemCertificatesFromNode: () => true, + loadSystemCertificatesFromNode, loadAdditionalCertificates: async () => [], log, getLogLevel: () => LogLevel.Error, @@ -77,12 +99,15 @@ let systemCertificatesPromise: Promise | undefined; * in tests. * * Returns `undefined` (never a rejected/empty promise) when the store can't be - * read. @vscode/proxy-agent reads it via Node's `tls.getCACertificates`, which - * only exists on Node >= 22.15; on the older runtimes some supported VS Code - * builds still ship, that call throws. Swallowing it here lets the caller fall - * back to Node's bundled roots instead of failing the whole SDK request — a - * missing custom CA is recoverable (users can set `databricks.proxy.strictSSL`), - * a broken agent is not. + * read. @vscode/proxy-agent reads it either via Node's `tls.getCACertificates` + * (Node >= 22.15) or, on older runtimes, its native readers (the + * `@vscode/windows-ca-certs` module on Windows, `security` on macOS, PEM files + * on Linux) — see {@link loadSystemCertificatesFromNode}. If that native module is + * absent (e.g. not shipped for this platform) the read can still fail; swallowing + * it here lets the caller fall back to Node's bundled roots instead of failing + * the whole SDK request. A missing custom CA is recoverable (users can point + * `databricks.proxy.caCert` at their PEM, or opt out via + * `databricks.proxy.strictSSL`), a broken agent is not. */ async function getSystemCertificates( params: ProxyAgentParams @@ -133,6 +158,54 @@ export function applyProxyStrictSSLEnv() { } } +/** + * Read the user-configured `databricks.proxy.caCert` PEM bundle, if set. Returns + * `undefined` when the setting is empty or the file can't be read — a bad path + * shouldn't break every TLS handshake, so we log and fall back to the rest of + * the trust store. + */ +async function loadConfiguredCaCert(): Promise { + const caCertPath = workspaceConfigs.proxyCaCert; + if (!caCertPath) { + return undefined; + } + try { + return await readFile(caCertPath, "utf8"); + } catch (e) { + getLog().error( + `Failed to read databricks.proxy.caCert from "${caCertPath}"; ` + + "ignoring it. The certificate it points at will not be trusted.", + e + ); + return undefined; + } +} + +/** + * Assemble the CA trust list for the SDK's HTTPS agent, or `undefined` to leave + * Node's default store in place. + * + * Any list we build is anchored on `tls.rootCertificates` (Node's bundled public + * roots) and then extended with the OS trust store and the configured PEM. + * Setting `ca` *replaces* Node's defaults, so if we set it to only the extra + * certs, public-root TLS would break — hence the merge. When we have nothing to + * add (system store unreadable and no `caCert`), return `undefined` so the + * caller omits `ca` and Node keeps its defaults. + */ +function buildCaBundle( + systemCerts: string[] | undefined, + configuredCaCert: string | undefined +): (string | Buffer)[] | undefined { + if (!systemCerts && !configuredCaCert) { + return undefined; + } + return [ + ...tls.rootCertificates, + ...(systemCerts ?? []), + ...(configuredCaCert ? [configuredCaCert] : []), + ]; +} + /** * Build the HTTP(S) agent the Databricks SDK should use, wiring in the proxy * (VS Code `http.proxy` setting + `http(s)_proxy` env vars, honouring @@ -146,15 +219,18 @@ export async function getDatabricksHttpAgent( const params = getProxyAgentParams(); const isHttps = host.protocol === "https:"; - const ca = await getSystemCertificates(params); + const systemCerts = await getSystemCertificates(params); + const configuredCaCert = await loadConfiguredCaCert(); + const ca = buildCaBundle(systemCerts, configuredCaCert); const rejectUnauthorized = strictSSL(); const resolver = createProxyResolver(params); const proxyUrl = await resolver.resolveProxyURL(host.toString()); - // Only override `ca` when we actually loaded a trust store. Passing `ca: - // undefined` (or `[]`) would replace Node's bundled roots with nothing and - // break every TLS handshake, so omit it entirely on the fallback path. + // Only set `ca` when we have certs to add on top of Node's bundled roots + // (which `buildCaBundle` already folds in). On the fallback path `ca` is + // `undefined`, so we omit it entirely and Node keeps its default store — + // passing `undefined`/`[]` would instead trust nothing. const agentOptions: https.AgentOptions = { keepAlive: true, keepAliveMsecs: KEEP_ALIVE_MSECS, diff --git a/packages/databricks-vscode/src/vscode-objs/WorkspaceConfigs.ts b/packages/databricks-vscode/src/vscode-objs/WorkspaceConfigs.ts index bc4bde816..662c07dcf 100644 --- a/packages/databricks-vscode/src/vscode-objs/WorkspaceConfigs.ts +++ b/packages/databricks-vscode/src/vscode-objs/WorkspaceConfigs.ts @@ -169,6 +169,21 @@ export const workspaceConfigs = { get httpNoProxy(): string[] { return workspace.getConfiguration("http").get("noProxy", []); }, + + /** + * Absolute path to a PEM bundle of additional CA certificates to trust for + * the extension's SDK calls, merged with the OS trust store and Node's + * built-in roots. An escape hatch for corporate CAs that can't be read from + * the system store (e.g. older runtimes where the native reader is + * unavailable). + */ + get proxyCaCert(): string | undefined { + return ( + workspace + .getConfiguration("databricks") + .get("proxy.caCert") || undefined + ); + }, }; export type WorkspaceConfigs = typeof workspaceConfigs; From 25219fd668d5d8783bfa210dd8b057e7ef94f0eb Mon Sep 17 00:00:00 2001 From: misha-db Date: Mon, 7 Sep 2026 15:04:29 +0400 Subject: [PATCH 08/31] Dedupe CA bundle, tighten types, clarify docs - buildCaBundle: dedupe with a Set (the OS store commonly re-lists the public roots already in tls.rootCertificates) and tighten the return type to string[] (it never produced Buffers). - getProxyEnvVars: document that http.proxy overrides the env var while no_proxy is unioned with it, not overridden. - Add a test asserting the CA bundle contains no duplicates. --- .../databricks-vscode/src/utils/envVarGenerators.ts | 10 ++++++---- .../src/utils/network/proxyAgent.test.ts | 6 ++++++ .../src/utils/network/proxyAgent.ts | 13 +++++++++---- 3 files changed, 21 insertions(+), 8 deletions(-) diff --git a/packages/databricks-vscode/src/utils/envVarGenerators.ts b/packages/databricks-vscode/src/utils/envVarGenerators.ts index e824319f7..f564fa711 100644 --- a/packages/databricks-vscode/src/utils/envVarGenerators.ts +++ b/packages/databricks-vscode/src/utils/envVarGenerators.ts @@ -148,10 +148,12 @@ export async function getDbConnectEnvVars( * only way to route CLI traffic through a proxy. * * Precedence mirrors the in-process SDK path (`proxyAgent.ts` - * `getProxyAgentParams`): the VS Code `http.proxy` / `http.noProxy` settings win - * over the OS `http(s)_proxy` / `no_proxy` env vars. That keeps the CLI and the - * SDK resolving the same proxy from the same inputs, so a user who configures the - * proxy purely through the VS Code setting gets it applied to both. + * `getProxyAgentParams`): the VS Code `http.proxy` setting wins over the OS + * `http(s)_proxy` env vars. That keeps the CLI and the SDK resolving the same + * proxy from the same inputs, so a user who configures the proxy purely through + * the VS Code setting gets it applied to both. `no_proxy` is the exception — the + * `http.noProxy` setting and the env var are *unioned* (not overridden), since a + * bypass list is only ever safer when it's broader. * * Absent values stay `undefined` so `removeUndefinedKeys(...)` at the call sites * strips them, leaving the CLI's own env untouched when nothing is configured. diff --git a/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts b/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts index 357931e75..100f72a5d 100644 --- a/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts +++ b/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts @@ -130,6 +130,12 @@ describe(__filename, () => { ); // A known bundled root is still present. assert.ok((ca as string[]).includes(tls.rootCertificates[0])); + // Deduped: the OS store often re-lists the bundled roots, but each + // cert appears at most once in the handed-off list. + assert.strictEqual( + new Set(ca as string[]).size, + (ca as string[]).length + ); }); it("disables certificate verification when strict SSL is off", async () => { diff --git a/packages/databricks-vscode/src/utils/network/proxyAgent.ts b/packages/databricks-vscode/src/utils/network/proxyAgent.ts index 698e31ec7..0a0ac174d 100644 --- a/packages/databricks-vscode/src/utils/network/proxyAgent.ts +++ b/packages/databricks-vscode/src/utils/network/proxyAgent.ts @@ -191,18 +191,23 @@ async function loadConfiguredCaCert(): Promise { * certs, public-root TLS would break — hence the merge. When we have nothing to * add (system store unreadable and no `caCert`), return `undefined` so the * caller omits `ca` and Node keeps its defaults. + * + * Deduped because the OS store commonly re-lists the public roots already in + * `tls.rootCertificates`; a `Set` keeps the handed-off list minimal. */ function buildCaBundle( systemCerts: string[] | undefined, configuredCaCert: string | undefined -): (string | Buffer)[] | undefined { +): string[] | undefined { if (!systemCerts && !configuredCaCert) { return undefined; } return [ - ...tls.rootCertificates, - ...(systemCerts ?? []), - ...(configuredCaCert ? [configuredCaCert] : []), + ...new Set([ + ...tls.rootCertificates, + ...(systemCerts ?? []), + ...(configuredCaCert ? [configuredCaCert] : []), + ]), ]; } From a6630e1100510a17735d40e17339aaf3a5d9d625 Mon Sep 17 00:00:00 2001 From: misha-db Date: Mon, 7 Sep 2026 16:12:36 +0400 Subject: [PATCH 09/31] Honor SDK timeout and merged no-proxy config Preserve the Databricks SDK request timeout when injecting the extension's proxy-aware HTTP agent, including the SDK's default 5s timeout. Also merge VS Code http.noProxy with NO_PROXY/no_proxy for SDK proxy resolution so SDK calls and CLI subprocesses honor the same bypass list. --- .../src/utils/network/proxyAgent.test.ts | 66 +++++++++++++++++++ .../src/utils/network/proxyAgent.ts | 24 ++++++- 2 files changed, 87 insertions(+), 3 deletions(-) diff --git a/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts b/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts index 100f72a5d..cbb806667 100644 --- a/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts +++ b/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts @@ -105,6 +105,19 @@ describe(__filename, () => { assert.ok(!(agent instanceof HttpsProxyAgent)); }); + it("returns a plain agent when the host matches NO_PROXY and http.noProxy is also set", async () => { + process.env.NO_PROXY = "example.com"; + when(configsSpy.httpProxy).thenReturn("http://127.0.0.1:8080"); + when(configsSpy.httpNoProxy).thenReturn(["setting.example.com"]); + + const agent = await getDatabricksHttpAgent( + new URL("https://example.com") + ); + + assert.ok(agent instanceof https.Agent); + assert.ok(!(agent instanceof HttpsProxyAgent)); + }); + it("falls back to a plain http agent for http hosts without a proxy", async () => { const agent = await getDatabricksHttpAgent( new URL("http://example.com") @@ -113,6 +126,40 @@ describe(__filename, () => { assert.ok(!(agent instanceof HttpProxyAgent)); }); + it("sets the SDK default request timeout on plain agents", async () => { + const agent = (await getDatabricksHttpAgent( + new URL("https://example.com") + )) as https.Agent; + + assert.strictEqual( + (agent.options as https.AgentOptions).timeout, + 5000 + ); + }); + + it("preserves the configured SDK request timeout on plain agents", async () => { + const agent = (await getDatabricksHttpAgent( + new URL("https://example.com"), + 60 + )) as https.Agent; + + assert.strictEqual( + (agent.options as https.AgentOptions).timeout, + 60000 + ); + }); + + it("preserves the configured SDK request timeout on proxy agents", async () => { + when(configsSpy.httpProxy).thenReturn("http://127.0.0.1:8080"); + + const agent = (await getDatabricksHttpAgent( + new URL("https://example.com"), + 60 + )) as HttpsProxyAgent; + + assert.strictEqual(agent.connectOpts.timeout, 60000); + }); + it("merges the system trust store with Node's bundled roots (never replaces them)", async () => { const agent = (await getDatabricksHttpAgent( new URL("https://example.com") @@ -260,5 +307,24 @@ describe(__filename, () => { const agent = await client.apiClient.getAgent(); assert.ok(agent instanceof https.Agent); }); + + it("preserves the configured SDK request timeout on the injected agent", async () => { + const client = await createWorkspaceClient( + { + host: "https://example.com", + authType: "pat", + token: "t", + httpTimeoutSeconds: 60, + }, + new URL("https://example.com") + ); + + const agent = (await client.apiClient.getAgent()) as https.Agent; + + assert.strictEqual( + (agent.options as https.AgentOptions).timeout, + 60000 + ); + }); }); }); diff --git a/packages/databricks-vscode/src/utils/network/proxyAgent.ts b/packages/databricks-vscode/src/utils/network/proxyAgent.ts index 0a0ac174d..85c91668f 100644 --- a/packages/databricks-vscode/src/utils/network/proxyAgent.ts +++ b/packages/databricks-vscode/src/utils/network/proxyAgent.ts @@ -27,6 +27,7 @@ const extensionVersion = require("../../../package.json") // api-client.js ApiClient.getAgent), so behaviour is unchanged apart from the // proxy + CA wiring we add on top. const KEEP_ALIVE_MSECS = 15000; +const DEFAULT_HTTP_TIMEOUT_SECONDS = 5; /** * Whether to let @vscode/proxy-agent read the OS trust store via Node's @@ -76,7 +77,7 @@ function getProxyAgentParams(): ProxyAgentParams { resolveProxy: async () => undefined, getProxyURL: () => workspaceConfigs.httpProxy, getProxySupport: () => "on", - getNoProxyConfig: () => workspaceConfigs.httpNoProxy, + getNoProxyConfig: () => getNoProxyConfig(), isAdditionalFetchSupportEnabled: () => false, isWebSocketPatchEnabled: () => false, addCertificatesV1: () => false, @@ -91,6 +92,18 @@ function getProxyAgentParams(): ProxyAgentParams { }; } +function getNoProxyConfig(): string[] { + const envNoProxy = process.env.NO_PROXY || process.env.no_proxy || ""; + const noProxyParts = [ + ...workspaceConfigs.httpNoProxy, + ...envNoProxy.split(","), + ] + .map((v) => v.trim()) + .filter((v) => v.length > 0); + + return [...new Set(noProxyParts)]; +} + let systemCertificatesPromise: Promise | undefined; /** @@ -219,7 +232,8 @@ function buildCaBundle( * interception, matching the bundled CLI's behaviour. */ export async function getDatabricksHttpAgent( - host: URL + host: URL, + httpTimeoutSeconds?: number ): Promise { const params = getProxyAgentParams(); const isHttps = host.protocol === "https:"; @@ -239,6 +253,7 @@ export async function getDatabricksHttpAgent( const agentOptions: https.AgentOptions = { keepAlive: true, keepAliveMsecs: KEEP_ALIVE_MSECS, + timeout: (httpTimeoutSeconds || DEFAULT_HTTP_TIMEOUT_SECONDS) * 1000, ...(isHttps ? {rejectUnauthorized, ...(ca ? {ca} : {})} : {}), }; @@ -273,7 +288,10 @@ export async function createWorkspaceClient( host: URL ): Promise { applyProxyStrictSSLEnv(); - const agent = await getDatabricksHttpAgent(host); + const agent = await getDatabricksHttpAgent( + host, + config.httpTimeoutSeconds + ); return new WorkspaceClient(config, { product: "databricks-vscode", productVersion: extensionVersion, From 0727387b61ecb646cdb743d473d5501260856330 Mon Sep 17 00:00:00 2001 From: misha-db Date: Wed, 9 Sep 2026 13:15:33 +0400 Subject: [PATCH 10/31] Update yarn.lock --- yarn.lock | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/yarn.lock b/yarn.lock index 0c2973c75..1eaad58ac 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4069,6 +4069,7 @@ __metadata: "@vscode/proxy-agent": ^0.44.0 "@vscode/test-electron": ^3.1.0 "@vscode/webview-ui-toolkit": ^1.4.0 + "@vscode/windows-ca-certs": ^0.3.1 "@wdio/cli": ^9.29.0 "@wdio/local-runner": ^9.29.0 "@wdio/mocha-framework": ^9.29.0 @@ -4106,6 +4107,9 @@ __metadata: winston: ^3.11.0 yaml: ^2.8.3 yargs: ^17.7.2 + dependenciesMeta: + "@vscode/windows-ca-certs": + optional: true languageName: unknown linkType: soft From 705b4f01879d7e7971f80ec69297e8f1f79c02af Mon Sep 17 00:00:00 2001 From: misha-db Date: Wed, 9 Sep 2026 13:32:33 +0400 Subject: [PATCH 11/31] Update proxyAgent.ts --- packages/databricks-vscode/src/utils/network/proxyAgent.ts | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/packages/databricks-vscode/src/utils/network/proxyAgent.ts b/packages/databricks-vscode/src/utils/network/proxyAgent.ts index 85c91668f..da9c43d29 100644 --- a/packages/databricks-vscode/src/utils/network/proxyAgent.ts +++ b/packages/databricks-vscode/src/utils/network/proxyAgent.ts @@ -288,10 +288,7 @@ export async function createWorkspaceClient( host: URL ): Promise { applyProxyStrictSSLEnv(); - const agent = await getDatabricksHttpAgent( - host, - config.httpTimeoutSeconds - ); + const agent = await getDatabricksHttpAgent(host, config.httpTimeoutSeconds); return new WorkspaceClient(config, { product: "databricks-vscode", productVersion: extensionVersion, From 24df84449663f695d0f87cf2c87d4b5ee4c05eb7 Mon Sep 17 00:00:00 2001 From: Grigory Panov Date: Wed, 9 Sep 2026 18:02:57 +0200 Subject: [PATCH 12/31] fix(python-setup): actionable error for E_MERGE on a [project]-less pyproject (#2180) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Problem Automated `setup-local` fails with **E_MERGE** / `pyproject.toml has no [project] table to hold requires-python` on a valid [PEP 735](https://peps.python.org/pep-0735/) dependency-groups-only manifest — a `pyproject.toml` that deliberately has no `[project]` table (e.g. a Databricks Apps repo whose app runtime pip-installs `requirements.txt`). Reported in #2177. The `"no [project] table…"` text comes from the CLI's merge phase (`libs/localenv`, `MergeManaged` → `errNoProjectTable`), which refuses to write the runtime's `requires-python` when there is no `[project]` table to hold it. That is intentional CLI behaviour, but the extension surfaced it badly: - `errorMessages.ts` gave the generic, non-actionable *"Failed to merge the runtime constraints…"* copy. - `reportSetupIssue.ts` routed **all** `E_MERGE` to `databricks/databricks-vscode` as a reportable defect — so our own report flow auto-generated issue #2177 for a valid, user-fixable manifest shape. ## Fix - Add `isMissingProjectTableFailure(result)` — detects this `E_MERGE` variant by the CLI message (mirroring the existing `isIndexUnreachableFailure`), scoped to `E_MERGE`. - `getPythonSetupErrorMessage` returns actionable copy for it: add a minimal `[project]` table (name, version, `requires-python`), or set `databricks.python.environmentSetup` to `manual`. Generic `E_MERGE` keeps the neutral copy. - `formatSetupFailureDetail` spells out both fixes in the output channel so the guidance survives the notification being dismissed. No new button — the primary fix is a manual edit. - `reportRepoForResult` excludes this variant, so it no longer prompts a bug report. A generic `E_MERGE` stays report-worthy. No new settings, state, telemetry, or commands. Purely presentational + report-routing; generic `E_MERGE` behaviour is unchanged. ## Testing - New unit tests for the detector, the message mapping, the detail block, and the report-routing exclusion. - Full unit suite, `tsc`, `eslint`, and `prettier` clean on the changed files. Fixes #2177 This pull request and its description were written by Isaac. Co-authored-by: Isaac --- .../python-setup/utils/errorMessages.test.ts | 125 ++++++++++++++++++ .../src/python-setup/utils/errorMessages.ts | 70 +++++++++- .../utils/reportSetupIssue.test.ts | 21 +++ .../python-setup/utils/reportSetupIssue.ts | 12 +- 4 files changed, 222 insertions(+), 6 deletions(-) diff --git a/packages/databricks-vscode/src/python-setup/utils/errorMessages.test.ts b/packages/databricks-vscode/src/python-setup/utils/errorMessages.test.ts index e0ab5e5b6..de1116533 100644 --- a/packages/databricks-vscode/src/python-setup/utils/errorMessages.test.ts +++ b/packages/databricks-vscode/src/python-setup/utils/errorMessages.test.ts @@ -6,6 +6,7 @@ import { getPythonSetupErrorMessage, INSTALL_UV_COMMAND_ID, isIndexUnreachableFailure, + isMissingProjectTableFailure, USE_MANUAL_SETUP_COMMAND_ID, } from "./errorMessages"; import { @@ -27,6 +28,15 @@ const INDEX_UNREACHABLE_CLI_MSG = "error: Failed to fetch: `https://pypi.org/simple/ipykernel/`\n" + " Caused by: tcp connect error: Connection refused (os error 61)"; +/** + * The real CLI text for `errNoProjectTable` (libs/localenv): the merge phase + * refuses to write requires-python because the pyproject.toml has no [project] + * table. Wrapped by the "merge managed regions failed:" prefix exactly as it + * reaches the user (see databricks/databricks-vscode#2177). + */ +const NO_PROJECT_TABLE_CLI_MSG = + "merge managed regions failed: pyproject.toml has no [project] table to hold requires-python"; + /** Build a minimal failed result carrying a specific error. */ function failure( code: PythonSetupErrorCode, @@ -153,6 +163,31 @@ describe("getPythonSetupErrorMessage", () => { ); }); + it("maps a [project]-less E_MERGE to actionable copy, not the generic merge text", () => { + // The errNoProjectTable variant: a valid dependency-groups-only manifest, + // so the copy names the concrete fix instead of the generic merge failure. + const msg = getPythonSetupErrorMessage( + failure("E_MERGE", { + message: NO_PROJECT_TABLE_CLI_MSG, + failurePhase: "merge", + }) + ); + expect(msg).to.match(/\[project\] table/i); + expect(msg).to.match(/requires-python/i); + expect(msg).to.contain("databricks.python.environmentSetup"); + expect(msg).to.not.match(/failed to merge the runtime constraints/i); + }); + + it("keeps the generic merge copy for an E_MERGE that is not the [project]-table case", () => { + const msg = getPythonSetupErrorMessage( + failure("E_MERGE", { + message: "cannot merge: unsupported TOML multi-line string", + failurePhase: "merge", + }) + ); + expect(msg).to.match(/failed to merge the runtime constraints/i); + }); + it("reassures nothing changed when diskMutated is false", () => { const msg = getPythonSetupErrorMessage( failure("E_FETCH", {diskMutated: false, failurePhase: "fetch"}) @@ -388,6 +423,20 @@ describe("getPythonSetupErrorAction", () => { }); }); + it("offers no remediation button for a [project]-less E_MERGE (the fix is a manual edit)", () => { + // Option A: the primary fix (add a [project] table) is a manual edit with + // no one-click command, so this variant carries no button — its guidance + // lives in the message and the output-channel detail instead. + expect( + getPythonSetupErrorAction( + failure("E_MERGE", { + message: NO_PROJECT_TABLE_CLI_MSG, + failurePhase: "merge", + }) + ) + ).to.equal(undefined); + }); + it("offers no action for codes with no clear remediation doc", () => { for (const code of [ "E_USAGE", @@ -541,6 +590,33 @@ describe("formatSetupFailureDetail", () => { expect(detail).to.not.contain("databricks.python.environmentSetup"); }); + it("spells out the [project]-table + manual-mode fixes for a [project]-less E_MERGE", () => { + const detail = formatSetupFailureDetail( + failure("E_MERGE", { + message: NO_PROJECT_TABLE_CLI_MSG, + failurePhase: "merge", + }) + ); + // Still carries the raw CLI error … + expect(detail).to.contain("requires-python"); + // … plus both remediation paths (a concrete [project] table + manual mode). + expect(detail).to.contain("[project]"); + expect(detail).to.contain("databricks.python.environmentSetup"); + expect(detail).to.match(/manual/i); + // This variant has no button (Option A), so no "label: undefined" line. + expect(detail).to.not.contain("undefined"); + }); + + it("adds no [project]-table block for a generic E_MERGE", () => { + const detail = formatSetupFailureDetail( + failure("E_MERGE", { + message: "cannot merge: unsupported TOML multi-line string", + }) + ); + expect(detail).to.not.match(/add a minimal \[project\] table/i); + expect(detail).to.not.contain("databricks.python.environmentSetup"); + }); + it("adds no remediation block for a non-connectivity E_PROVISION", () => { const detail = formatSetupFailureDetail( failure("E_PROVISION", { @@ -784,3 +860,52 @@ describe("isIndexUnreachableFailure", () => { expect(isIndexUnreachableFailure(ok)).to.equal(false); }); }); + +describe("isMissingProjectTableFailure", () => { + it("is true for E_MERGE whose message names a missing [project] table", () => { + expect( + isMissingProjectTableFailure( + failure("E_MERGE", {message: NO_PROJECT_TABLE_CLI_MSG}) + ) + ).to.equal(true); + }); + + it("is false for a generic E_MERGE (e.g. a multiline-string rejection)", () => { + expect( + isMissingProjectTableFailure( + failure("E_MERGE", { + message: "cannot merge: unsupported TOML multi-line string", + }) + ) + ).to.equal(false); + }); + + it("is false for an E_MERGE that references a [project] table without saying there is none", () => { + // Guards the match against a hypothetical future merge defect whose + // message merely mentions the [project] table (e.g. an invalid value in + // it): that is a real bug and must keep its generic copy and bug-report + // prompt, not be relabeled as the user-fixable missing-table case. + expect( + isMissingProjectTableFailure( + failure("E_MERGE", { + message: "failed to rewrite [project] table: invalid TOML", + }) + ) + ).to.equal(false); + }); + + it("is false for a non-E_MERGE code even with a matching message", () => { + // Scoped to E_MERGE: only the merge phase produces errNoProjectTable. + expect( + isMissingProjectTableFailure( + failure("E_WRITE", {message: NO_PROJECT_TABLE_CLI_MSG}) + ) + ).to.equal(false); + }); + + it("is false when there is no error object", () => { + const ok = failure("E_MERGE"); + ok.error = null; + expect(isMissingProjectTableFailure(ok)).to.equal(false); + }); +}); diff --git a/packages/databricks-vscode/src/python-setup/utils/errorMessages.ts b/packages/databricks-vscode/src/python-setup/utils/errorMessages.ts index df3d2663f..4f66c998f 100644 --- a/packages/databricks-vscode/src/python-setup/utils/errorMessages.ts +++ b/packages/databricks-vscode/src/python-setup/utils/errorMessages.ts @@ -128,6 +128,27 @@ export function isIndexUnreachableFailure(result: PythonSetupResult): boolean { return INDEX_CONNECTIVITY_SYMPTOMS.some((s) => msg.includes(s)); } +/** + * True when an E_MERGE failure is the CLI refusing to write requires-python + * because the pyproject.toml has no `[project]` table (libs/localenv's + * `errNoProjectTable`) — a valid, user-fixable manifest shape (a PEP 735 + * dependency-groups-only file), not a merge defect. It gets actionable copy and + * is excluded from the report-a-bug routing, while a generic E_MERGE is + * untouched. The CLI emits no distinct code, so we read its message (mirroring + * {@link isIndexUnreachableFailure}); matching `no [project] table` — not the + * bare phrase — keeps a future merge bug that merely mentions the table from + * being misclassified as this user-fixable case. + */ +export function isMissingProjectTableFailure( + result: PythonSetupResult +): boolean { + const err = result.error; + if (!err || err.code !== "E_MERGE") { + return false; + } + return (err.message?.toLowerCase() ?? "").includes("no [project] table"); +} + /** * Command that flips `databricks.python.environmentSetup` to `manual` for the * current project. Surfaced as the E_FETCH remediation button so a user whose @@ -217,16 +238,36 @@ const INDEX_UNREACHABLE_MESSAGE = "environment variable, or add an index-url to your pip config), then try " + "again. See the logs for details."; +/** + * Popup copy for the `[project]`-less variant of E_MERGE, replacing the generic + * "failed to merge" text. The primary fix is a manual edit (add a `[project]` + * table), so there is no remediation button; {@link formatSetupFailureDetail} + * spells out both fixes for the log. + */ +const MISSING_PROJECT_TABLE_MESSAGE = + "Your pyproject.toml has no [project] table, so setup can't record the " + + "runtime's required Python version (requires-python) there. Add a minimal " + + "[project] table (a name and version) and setup will fill it in — or set " + + '"databricks.python.environmentSetup" to "manual" to skip automated setup ' + + "and use your existing environment as-is."; + export function getPythonSetupErrorMessage(result: PythonSetupResult): string { const err = result.error; if (!err) { return GENERIC; } - // Checked before the per-code map: a blocked index arrives as E_PROVISION, - // whose generic "dependency conflict" copy points at the wrong cause. - const base = isIndexUnreachableFailure(result) - ? INDEX_UNREACHABLE_MESSAGE - : BASE_MESSAGE[err.code]?.(result) ?? GENERIC; + // Checked before the per-code map: both a blocked index (arriving as + // E_PROVISION) and a [project]-less pyproject (arriving as E_MERGE) are told + // apart by the CLI's message, not a distinct code, and their per-code copy + // would misdirect. + let base: string; + if (isIndexUnreachableFailure(result)) { + base = INDEX_UNREACHABLE_MESSAGE; + } else if (isMissingProjectTableFailure(result)) { + base = MISSING_PROJECT_TABLE_MESSAGE; + } else { + base = BASE_MESSAGE[err.code]?.(result) ?? GENERIC; + } return base + diskStateSuffix(result, err); } @@ -403,6 +444,25 @@ export function formatSetupFailureDetail( 'setting to "manual". The extension then uses your existing interpreter/.venv (with its databricks-connect) as-is.' ); } + // The [project]-less variant of E_MERGE: spell out both fixes here so they + // survive the notification being dismissed. The popup only summarises them. + if (isMissingProjectTableFailure(result)) { + lines.push( + "", + "Automated setup writes the runtime's required Python version into " + + "your pyproject.toml's [project] table, but this file has none (a " + + "valid dependency-groups-only manifest). You have two options:", + "", + " 1. Add a minimal [project] table so the pin has a home, for example:", + " [project]", + ' name = "my-project"', + ' version = "0.0.0"', + " Setup fills in requires-python for you — you don't need to set it.", + "", + ' 2. Or skip automated setup and manage the environment yourself: set the "databricks.python.environmentSetup" ' + + 'setting to "manual". The extension then uses your existing interpreter/.venv as-is.' + ); + } // A genuine E_PROVISION conflict gets no report button (it is usually the // user's own dependencies). But if the *published constraints* are what // conflict, that is a defect worth reporting — so offer a soft, conditional diff --git a/packages/databricks-vscode/src/python-setup/utils/reportSetupIssue.test.ts b/packages/databricks-vscode/src/python-setup/utils/reportSetupIssue.test.ts index 069ee7be0..64e9ef9d8 100644 --- a/packages/databricks-vscode/src/python-setup/utils/reportSetupIssue.test.ts +++ b/packages/databricks-vscode/src/python-setup/utils/reportSetupIssue.test.ts @@ -24,6 +24,14 @@ const INDEX_UNREACHABLE_CLI_MSG = "error: Failed to fetch: `https://pypi.org/simple/ipykernel/`\n" + " Caused by: tcp connect error: Connection refused (os error 61)"; +/** + * The CLI text for the errNoProjectTable variant of E_MERGE — a valid + * dependency-groups-only pyproject with no [project] table. Used to prove this + * user-fixable manifest shape is NOT report-worthy, unlike a generic E_MERGE. + */ +const NO_PROJECT_TABLE_CLI_MSG = + "merge managed regions failed: pyproject.toml has no [project] table to hold requires-python"; + /** Build a minimal failed result carrying a specific error. */ function failure( code: PythonSetupErrorCode, @@ -99,6 +107,19 @@ describe("reportRepoForResult / isReportWorthy", () => { expect(isReportWorthy(r)).to.equal(false); }); + it("does NOT treat a [project]-less E_MERGE as report-worthy", () => { + // A valid PEP 735 dependency-groups-only manifest is user-fixable, not a + // merge bug (errorMessages gives actionable copy), so it must not prompt a + // bug report — that mis-prompt is what auto-filed issue #2177. Generic + // E_MERGE (above) stays report-worthy. + const r = failure("E_MERGE", { + message: NO_PROJECT_TABLE_CLI_MSG, + failurePhase: "merge", + }); + expect(reportRepoForResult(r)).to.equal(undefined); + expect(isReportWorthy(r)).to.equal(false); + }); + it("does NOT offer a report for preflight/local/network codes", () => { for (const code of [ "E_USAGE", diff --git a/packages/databricks-vscode/src/python-setup/utils/reportSetupIssue.ts b/packages/databricks-vscode/src/python-setup/utils/reportSetupIssue.ts index 6d4963d79..6a1f3f7b5 100644 --- a/packages/databricks-vscode/src/python-setup/utils/reportSetupIssue.ts +++ b/packages/databricks-vscode/src/python-setup/utils/reportSetupIssue.ts @@ -3,6 +3,7 @@ import type { PythonSetupErrorCode, } from "../models/PythonSetupResult"; import type {PrimaryManager} from "../../language/packageManagerDetection"; +import {isMissingProjectTableFailure} from "./errorMessages"; import type {PythonSetupErrorAction} from "./errorMessages"; /** @@ -27,7 +28,9 @@ export type ReportRepo = * constraints have no entry for the runtime (`E_ENV_UNSUPPORTED`) or don't * validate after provisioning (`E_VALIDATE`). * - Extension/CLI behaviour defects → `databricks/databricks-vscode`: merging - * into or writing the user's pyproject.toml broke. + * into or writing the user's pyproject.toml broke. Exception: the + * `[project]`-less variant of `E_MERGE` is a valid, user-fixable manifest + * shape, not a defect — `reportRepoForResult` filters it out (see there). * * `E_PROVISION` is deliberately absent: a uv resolution conflict is usually the * user's own declared dependencies (possibly private packages), not a constraint @@ -77,6 +80,13 @@ export function reportRepoForResult( if (!err) { return undefined; } + // The [project]-less variant of E_MERGE is a valid, user-fixable manifest + // shape (errorMessages gives it actionable copy), not a merge defect — so it + // is not report-worthy, even though a generic E_MERGE is. Prompting a bug + // report for it is what auto-filed databricks/databricks-vscode#2177. + if (isMissingProjectTableFailure(result)) { + return undefined; + } return REPORT_ROUTING[err.code]; } From 1f935b0de31cdb31aaf3ba7375f8acef24755f06 Mon Sep 17 00:00:00 2001 From: eng-dev-ecosystem-bot <110475461+eng-dev-ecosystem-bot@users.noreply.github.com> Date: Wed, 9 Sep 2026 18:20:04 +0200 Subject: [PATCH 13/31] Update Databricks CLI to v1.16.0 (#2183) Update Databricks CLI to v1.16.0 --- packages/databricks-vscode/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/databricks-vscode/package.json b/packages/databricks-vscode/package.json index 5ad792786..0efc339b2 100644 --- a/packages/databricks-vscode/package.json +++ b/packages/databricks-vscode/package.json @@ -1880,7 +1880,7 @@ "useYarn": false }, "cli": { - "version": "1.15.0" + "version": "1.16.0" }, "scripts": { "vscode:prepublish": "rm -rf out && yarn run package:compile && yarn run package:wrappers:write && yarn run package:jupyter-init-script:write && yarn run package:copy-webview-toolkit && yarn run package:copy-markdown-it && yarn run package:copy-highlight && yarn run package:copy-windows-ca-certs && yarn run generate-telemetry", From 84aa6f6a3f87ac7b77a0775341ad9f53802fe87c Mon Sep 17 00:00:00 2001 From: Grigory Panov Date: Wed, 9 Sep 2026 18:21:47 +0200 Subject: [PATCH 14/31] feat(python-setup): add the Python-setup preset picker (Full / DB Connect / Python) (#2179) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Why The uv-native "set up Python environment" flow always ran the **Full** preset — it hardcoded a flag-free `setup-local` invocation. Users had no way to pick a lighter tier, even though the CLI already exposes the orthogonal `--no-constraints` / `--no-dbconnect` flags. Separately, the two-value telemetry `mode` dimension (`default` | `constraints-only`, derived from `skipDbconnect`) cannot represent a `--no-constraints`-only run: a DB Connect run would report `mode: default` despite skipping the pins. A picker that sets the two axes orthogonally makes that gap actionable. ## What - **New pure util `pythonSetupPresetPicker.ts`:** - `SetupPreset = full | dbconnect | python` and `presetToFlags` (full → no flags; dbconnect → `--no-constraints`; python → `--no-constraints --no-dbconnect`). - `buildPresetPickItems` — the three rows (Full starred and first), copy verbatim from the spec. - `computeTargetLabel` — `serverless v5` / `Runtime 17.3` / a generic fallback when the runtime is unknown. - `pickSetupPreset` — single-select, explicit `createQuickPick` lifecycle (`onDidAccept` resolves the row, `onDidHide` = dismissed); `createQuickPick` injected as a seam for tests. - **Controller:** a `pickSetupPreset` dep is invoked after compute resolves (so the title names the target). Dismissing it bails out silently with **no attempt recorded**, mirroring a dismissed serverless-version prompt. The invocation's skip flags come from the chosen preset. - **Wiring:** the dep composes `computeTargetLabel` + the injected `createQuickPick`; `extension.ts` resolves the cluster's DBR (reusing the attached cluster, else fetching by id) so the title always carries the runtime. - **Telemetry:** a new categorical `setupPreset` dimension on `python_env.setup.attempt`, disambiguating the two orthogonal skip axes. The legacy `mode` field is retained, derived as before, for dashboard continuity. ## Testing - `test:unit`: 1098 passing. New coverage: preset→flags mapping, verbatim row copy, compute-label formatting, picker accept/dismiss, controller flag-threading + dismissal + `setupPreset`/`mode` telemetry, wiring composition (title from serverless/cluster DBR), and the telemetry emitter allowlist. - `tsc` + `eslint` clean on changed files. This pull request and its description were written by Isaac. --------- Co-authored-by: Isaac --- packages/databricks-vscode/src/extension.ts | 27 +++ .../PythonSetupEnvironmentSetup.test.ts | 103 +++++++++ .../PythonSetupEnvironmentSetup.ts | 33 ++- .../controllers/pythonSetupDeps.test.ts | 118 +++++++++- .../controllers/pythonSetupDeps.ts | 32 +++ .../utils/pythonSetupPresetPicker.test.ts | 215 ++++++++++++++++++ .../utils/pythonSetupPresetPicker.ts | 143 ++++++++++++ .../src/telemetry/constants.ts | 14 ++ .../telemetry/pythonSetupExtensions.test.ts | 19 ++ .../src/telemetry/pythonSetupExtensions.ts | 9 + .../src/test/e2e/setup_local.ucws.e2e.ts | 23 +- 11 files changed, 729 insertions(+), 7 deletions(-) create mode 100644 packages/databricks-vscode/src/python-setup/utils/pythonSetupPresetPicker.test.ts create mode 100644 packages/databricks-vscode/src/python-setup/utils/pythonSetupPresetPicker.ts diff --git a/packages/databricks-vscode/src/extension.ts b/packages/databricks-vscode/src/extension.ts index 6752f2676..58f090d02 100644 --- a/packages/databricks-vscode/src/extension.ts +++ b/packages/databricks-vscode/src/extension.ts @@ -15,6 +15,7 @@ import {ConnectionManager} from "./configuration/ConnectionManager"; import {ClusterListDataProvider} from "./cluster/ClusterListDataProvider"; import {ClusterModel} from "./cluster/ClusterModel"; import {ClusterCommands} from "./cluster/ClusterCommands"; +import {Cluster} from "./sdk-extensions/Cluster"; import {ConfigurationDataProvider} from "./ui/configuration-view/ConfigurationDataProvider"; import {composePythonSetupEntry} from "./ui/configuration-view/pythonSetupEntry"; import {routeEnvironmentSetup} from "./language/pythonSetupRouting"; @@ -1021,6 +1022,32 @@ export async function activate( "databricks.connection.attachClusterQuickPick" ) ), + createQuickPick: (...args) => window.createQuickPick(...args), + // The preset picker's title names the resolved runtime. Reuse the + // attached cluster's already-loaded DBR when its id matches; + // otherwise (e.g. a cluster just picked inline, whose attach has not + // propagated yet) fetch it by id so the title always carries the + // runtime. Any failure degrades to a generic title, so it must not + // reject into the setup flow. + clusterDbrVersion: async (clusterId) => { + try { + const attached = connectionManager.cluster; + if (attached?.id === clusterId) { + return attached.dbrVersion; + } + const apiClient = connectionManager.apiClient; + if (apiClient === undefined) { + return undefined; + } + const cluster = await Cluster.fromClusterId( + apiClient, + clusterId + ); + return cluster.dbrVersion; + } catch { + return undefined; + } + }, setActiveInterpreter: async (interpreterPath, root) => { await pythonExtensionWrapper.api.environments.updateActiveEnvironmentPath( interpreterPath, diff --git a/packages/databricks-vscode/src/python-setup/controllers/PythonSetupEnvironmentSetup.test.ts b/packages/databricks-vscode/src/python-setup/controllers/PythonSetupEnvironmentSetup.test.ts index 31703e2e2..b2c9088b8 100644 --- a/packages/databricks-vscode/src/python-setup/controllers/PythonSetupEnvironmentSetup.test.ts +++ b/packages/databricks-vscode/src/python-setup/controllers/PythonSetupEnvironmentSetup.test.ts @@ -17,6 +17,7 @@ import { } from "../models/fixtures/setupLocalResults"; import {PythonSetupErrorAction} from "../utils/errorMessages"; import {SetupLocalInvocation} from "../utils/setupLocalArgs"; +import {SetupPreset} from "../utils/pythonSetupPresetPicker"; import { PythonSetupAttempt, PythonSetupOutcomeReport, @@ -136,6 +137,10 @@ function makeDeps( // Mirror the production wrapper: hand the task a log sink and a // (never-cancelled) progress token. withProgress: async (_title, task) => task(() => {}, makeToken()), + // Default: the user picks the recommended Full preset, so a run happens + // with no skip flags (matching the pre-picker behaviour these tests were + // written against). Tests that exercise other presets override this. + pickSetupPreset: async () => "full", // Telemetry defaults to a no-op sink; tests that assert on events pass // a recorder instead. recordSetupAttempt: () => () => {}, @@ -1067,6 +1072,7 @@ describe("PythonSetupEnvironmentSetup telemetry", () => { targetType: "serverless", serverlessVersion: "5", mode: "default", + setupPreset: "full", // hasPyprojectToml defaults to true, so this is not greenfield. isGreenfield: false, // First run for the project: not yet ready. @@ -1592,3 +1598,100 @@ describe("PythonSetupEnvironmentSetup telemetry", () => { ]); }); }); + +describe("PythonSetupEnvironmentSetup.setup preset selection", () => { + /** Assert on the invocation the CLI was actually handed. */ + function invocationFor(preset: SetupPreset) { + const cli = makeCli(); + const setup = new PythonSetupEnvironmentSetup( + makeDeps({cli, pickSetupPreset: async () => preset}) + ); + return setup.setup().then(() => cli.calls[0]); + } + + it("runs the full preset with no skip flags", async () => { + const invocation = await invocationFor("full"); + expect(invocation.skipConstraints).to.equal(undefined); + expect(invocation.skipDbconnect).to.equal(undefined); + }); + + it("runs the dbconnect preset with --no-constraints only", async () => { + const invocation = await invocationFor("dbconnect"); + expect(invocation.skipConstraints).to.equal(true); + expect(invocation.skipDbconnect).to.equal(undefined); + }); + + it("runs the python preset with both --no-constraints and --no-dbconnect", async () => { + const invocation = await invocationFor("python"); + expect(invocation.skipConstraints).to.equal(true); + expect(invocation.skipDbconnect).to.equal(true); + }); + + it("passes the resolved compute to the preset picker", async () => { + const seen: Array = []; + const setup = new PythonSetupEnvironmentSetup( + makeDeps({ + resolveCompute: async () => ({ + status: "ok", + compute: {kind: "cluster", clusterId: "0710-abc"}, + }), + pickSetupPreset: async (compute) => { + seen.push(compute); + return "full"; + }, + }) + ); + + await setup.setup(); + + expect(seen).to.deep.equal([{kind: "cluster", clusterId: "0710-abc"}]); + }); + + it("does not run the CLI or record an attempt when the picker is dismissed", async () => { + const cli = makeCli(); + const telemetry = makeTelemetryRecorder(); + const setup = new PythonSetupEnvironmentSetup( + makeDeps({ + cli, + ...telemetry, + pickSetupPreset: async () => undefined, + }) + ); + + await setup.setup(); + + // Dismissing the picker is a deliberate bail-out before any run starts, + // so nothing is spawned and no attempt is recorded (mirroring a + // dismissed serverless-version prompt). + expect(cli.calls).to.have.length(0); + expect(telemetry.attempts).to.have.length(0); + expect(telemetry.results).to.have.length(0); + expect(setup.ready).to.equal(false); + }); + + it("records the chosen preset on the attempt (dbconnect keeps mode default)", async () => { + const telemetry = makeTelemetryRecorder(); + const setup = new PythonSetupEnvironmentSetup( + makeDeps({...telemetry, pickSetupPreset: async () => "dbconnect"}) + ); + + await setup.setup(); + + expect(telemetry.attempts[0].setupPreset).to.equal("dbconnect"); + // dbconnect skips only the pins (databricks-connect stays), so the + // legacy mode dimension is still "default". + expect(telemetry.attempts[0].mode).to.equal("default"); + }); + + it("maps the python preset to the constraints-only telemetry mode", async () => { + const telemetry = makeTelemetryRecorder(); + const setup = new PythonSetupEnvironmentSetup( + makeDeps({...telemetry, pickSetupPreset: async () => "python"}) + ); + + await setup.setup(); + + expect(telemetry.attempts[0].setupPreset).to.equal("python"); + expect(telemetry.attempts[0].mode).to.equal("constraints-only"); + }); +}); diff --git a/packages/databricks-vscode/src/python-setup/controllers/PythonSetupEnvironmentSetup.ts b/packages/databricks-vscode/src/python-setup/controllers/PythonSetupEnvironmentSetup.ts index 99391faaa..2ff4f21b9 100644 --- a/packages/databricks-vscode/src/python-setup/controllers/PythonSetupEnvironmentSetup.ts +++ b/packages/databricks-vscode/src/python-setup/controllers/PythonSetupEnvironmentSetup.ts @@ -29,6 +29,7 @@ import { } from "../utils/reportSetupIssue"; import {isReauthRequiredError} from "../utils/authErrors"; import {SetupLocalInvocation} from "../utils/setupLocalArgs"; +import {presetToFlags, SetupPreset} from "../utils/pythonSetupPresetPicker"; import { PythonSetupAttempt, PythonSetupResultReporter, @@ -123,6 +124,18 @@ export interface PythonSetupSetupDeps { */ resolveCompute: () => Promise; + /** + * Ask the user which preset to provision for the resolved compute (Full / + * DB Connect / Python). Returns the chosen preset, or `undefined` when the + * picker is dismissed — a deliberate bail-out before any run starts, so the + * flow stops silently and records no attempt, mirroring a dismissed + * serverless-version prompt. Called after compute resolves so the picker's + * title can name the resolved target. + */ + pickSetupPreset: ( + compute: SetupCompute + ) => Promise; + /** * Point the MS Python extension at the provisioned venv interpreter for * `projectRoot`. The root is passed in (not re-read) so adoption always @@ -368,8 +381,17 @@ export class PythonSetupEnvironmentSetup implements Disposable { } const compute = resolved.compute; + // A dismissed picker is a deliberate bail-out before any run starts, so + // return silently and record no attempt — like the dismissed + // serverless-version prompt above. + const preset = await this.deps.pickSetupPreset(compute); + if (preset === undefined) { + return; + } + const invocation: SetupLocalInvocation = { compute, + ...presetToFlags(preset), }; // From here a run really happens, so the attempt is recorded and every @@ -378,7 +400,8 @@ export class PythonSetupEnvironmentSetup implements Disposable { // spawn and interpreter adoption. const {reportResult, packageManager} = await this.recordAttempt( invocation, - cwd + cwd, + preset ); // Per-run report context: the static build info plus this run's manager. const reportEnv: ReportEnvironment = { @@ -593,7 +616,8 @@ export class PythonSetupEnvironmentSetup implements Disposable { */ private async recordAttempt( invocation: SetupLocalInvocation, - projectRoot: string + projectRoot: string, + setupPreset: SetupPreset ): Promise<{ reportResult: PythonSetupResultReporter; packageManager: PrimaryManager; @@ -635,8 +659,11 @@ export class PythonSetupEnvironmentSetup implements Disposable { serverlessVersion: compute.kind === "serverless" ? compute.version : undefined, // --no-dbconnect is the orthogonal spelling of the legacy - // --constraints-only, so it maps to that telemetry mode. + // --constraints-only, so it maps to that telemetry mode. The + // richer, unambiguous axis is `setupPreset`; `mode` is kept for + // dashboard continuity. mode: invocation.skipDbconnect ? "constraints-only" : "default", + setupPreset, isGreenfield, // A run against a project already marked ready this session is a // re-run (the ready row's Re-run button / row click); anything diff --git a/packages/databricks-vscode/src/python-setup/controllers/pythonSetupDeps.test.ts b/packages/databricks-vscode/src/python-setup/controllers/pythonSetupDeps.test.ts index 530ae33f0..2be23a135 100644 --- a/packages/databricks-vscode/src/python-setup/controllers/pythonSetupDeps.test.ts +++ b/packages/databricks-vscode/src/python-setup/controllers/pythonSetupDeps.test.ts @@ -1,11 +1,12 @@ import {expect} from "chai"; -import {commands, env, Uri, window} from "vscode"; +import {commands, env, QuickPick, QuickPickItem, Uri, window} from "vscode"; import { makePythonSetupDeps, makePythonSetupVisibility, PythonSetupWiringDeps, resolveComputeFrom, } from "./pythonSetupDeps"; +import {PresetPickItem} from "../utils/pythonSetupPresetPicker"; import {PythonSetupState} from "../../vscode-objs/StateStorage"; import {SetupCompute} from "./PythonSetupEnvironmentSetup"; import {Telemetry} from "../../telemetry"; @@ -165,6 +166,64 @@ describe("resolveComputeFrom", () => { }); }); +/** + * A minimal scriptable QuickPick stand-in (see `AiToolsCommands.test.ts`). + * `onShow` decides which item is selected, or dismisses. + */ +class FakeQuickPick { + title?: string; + placeholder?: string; + items: readonly QuickPickItem[] = []; + selectedItems: readonly QuickPickItem[] = []; + private acceptCbs: Array<() => void> = []; + private hideCbs: Array<() => void> = []; + constructor( + private readonly onShow: ( + pick: FakeQuickPick + ) => {selected: readonly QuickPickItem[]} | "dismiss" + ) {} + onDidAccept(cb: () => void) { + this.acceptCbs.push(cb); + return {dispose() {}}; + } + onDidHide(cb: () => void) { + this.hideCbs.push(cb); + return {dispose() {}}; + } + show() { + const r = this.onShow(this); + if (r === "dismiss") { + this.hideCbs.forEach((cb) => cb()); + return; + } + this.selectedItems = r.selected; + this.acceptCbs.forEach((cb) => cb()); + } + hide() { + this.hideCbs.forEach((cb) => cb()); + } + dispose() {} +} + +/** + * A `createQuickPick` factory (typed as the real `window.createQuickPick` + * seam) that scripts the widget's outcome and records the created instances so + * a test can read the title the wiring set. + */ +function fakeCreateQuickPick( + onShow: ( + pick: FakeQuickPick + ) => {selected: readonly QuickPickItem[]} | "dismiss" +) { + const created: FakeQuickPick[] = []; + const create = (() => { + const pick = new FakeQuickPick(onShow); + created.push(pick); + return pick as unknown as QuickPick; + }) as () => QuickPick; + return {create, created}; +} + function makeWiring( overrides: Partial = {} ): PythonSetupWiringDeps { @@ -185,6 +244,8 @@ function makeWiring( promptServerlessVersion: async () => "4", persistServerlessVersion: async () => {}, promptSelectCompute: async () => undefined, + createQuickPick: fakeCreateQuickPick(() => "dismiss").create, + clusterDbrVersion: async () => undefined, setActiveInterpreter: async () => {}, persistSetupState: () => {}, log: {append: () => {}, show: () => {}}, @@ -1041,3 +1102,58 @@ describe("makePythonSetupDeps showReauthPrompt", () => { expect(executed).to.have.length(0); }); }); + +describe("makePythonSetupDeps pickSetupPreset", () => { + it("titles the picker with the serverless target and returns the picked preset", async () => { + const {create, created} = fakeCreateQuickPick((pick) => ({ + // Pick the DB Connect row (the second one). + selected: [pick.items[1]], + })); + const deps = makePythonSetupDeps(makeWiring({createQuickPick: create})); + + const preset = await deps.pickSetupPreset({ + kind: "serverless", + version: "5", + }); + + expect(preset).to.equal("dbconnect"); + expect(created[0].title).to.equal( + "Set up Python environment for serverless v5" + ); + }); + + it("titles the picker with the cluster's runtime, resolved from its DBR", async () => { + const requested: string[] = []; + const {create, created} = fakeCreateQuickPick(() => "dismiss"); + const deps = makePythonSetupDeps( + makeWiring({ + createQuickPick: create, + clusterDbrVersion: async (id) => { + requested.push(id); + return [17, 3, "x"]; + }, + }) + ); + + await deps.pickSetupPreset({kind: "cluster", clusterId: "0710-abc"}); + + // The DBR is looked up for the resolved cluster id, and its major.minor + // becomes the runtime shown in the title. + expect(requested).to.deep.equal(["0710-abc"]); + expect(created[0].title).to.equal( + "Set up Python environment for Runtime 17.3" + ); + }); + + it("returns undefined when the picker is dismissed", async () => { + const deps = makePythonSetupDeps( + makeWiring({ + createQuickPick: fakeCreateQuickPick(() => "dismiss").create, + }) + ); + + expect( + await deps.pickSetupPreset({kind: "serverless", version: "5"}) + ).to.equal(undefined); + }); +}); diff --git a/packages/databricks-vscode/src/python-setup/controllers/pythonSetupDeps.ts b/packages/databricks-vscode/src/python-setup/controllers/pythonSetupDeps.ts index e9300fd09..adbf317f8 100644 --- a/packages/databricks-vscode/src/python-setup/controllers/pythonSetupDeps.ts +++ b/packages/databricks-vscode/src/python-setup/controllers/pythonSetupDeps.ts @@ -11,6 +11,10 @@ import {PythonSetupErrorAction} from "../utils/errorMessages"; import {ReportEnvironment} from "../utils/reportSetupIssue"; import {isUvSetupSuitable} from "../utils/pythonSetupGate"; import {withElapsedProgress} from "../utils/setupProgress"; +import { + computeTargetLabel, + pickSetupPreset, +} from "../utils/pythonSetupPresetPicker"; import {formatSetupLog, formatSetupNotification} from "../utils/setupSummary"; import {venvInterpreterPath} from "../utils/venvInterpreterPath"; import {readVenvProjectName} from "../utils/venvProjectName"; @@ -159,6 +163,22 @@ export interface PythonSetupWiringDeps { * propagates asynchronously, so an immediate re-read would race it. */ promptSelectCompute: () => Promise; + /** + * The explicit-lifecycle QuickPick factory (`window.createQuickPick`), + * injected so the preset picker can be driven in tests without a VS Code + * host. + */ + createQuickPick: (typeof window)["createQuickPick"]; + /** + * The DBR version of the attached cluster, as `[major, minor, patch]` (see + * `Cluster.dbrVersion`), for the preset picker's title. `undefined` when it + * cannot be resolved (unknown cluster, custom image), in which case the + * title falls back to a generic cluster label. Only consulted for a cluster + * target. + */ + clusterDbrVersion: ( + clusterId: string + ) => Promise | undefined>; /** Point the MS Python extension at an interpreter path (project-scoped). */ setActiveInterpreter: (interpreterPath: string, root: Uri) => Promise; /** Persist the post-setup state (workspace-scoped) for drift detection. */ @@ -238,6 +258,18 @@ export function makePythonSetupDeps( } return {status: "ok", compute: {kind: "serverless", version}}; }, + pickSetupPreset: async (compute) => { + // A cluster's runtime label needs its DBR version; serverless + // carries its version directly, so no lookup is needed there. + const dbrVersion = + compute.kind === "cluster" + ? await wiring.clusterDbrVersion(compute.clusterId) + : undefined; + return pickSetupPreset( + computeTargetLabel(compute, dbrVersion), + wiring.createQuickPick + ); + }, adoptInterpreter: async (venvPath: string, projectRoot: string) => { await wiring.setActiveInterpreter( venvInterpreterPath(venvPath), diff --git a/packages/databricks-vscode/src/python-setup/utils/pythonSetupPresetPicker.test.ts b/packages/databricks-vscode/src/python-setup/utils/pythonSetupPresetPicker.test.ts new file mode 100644 index 000000000..7bc609dec --- /dev/null +++ b/packages/databricks-vscode/src/python-setup/utils/pythonSetupPresetPicker.test.ts @@ -0,0 +1,215 @@ +import {expect} from "chai"; +import {QuickPick, QuickPickItem} from "vscode"; +import { + buildPresetPickItems, + computeTargetLabel, + pickSetupPreset, + presetToFlags, + PresetPickItem, +} from "./pythonSetupPresetPicker"; + +/** + * A minimal, scriptable stand-in for a VS Code QuickPick, mirroring the fake + * used in `AiToolsCommands.test.ts`. `onAccept` decides which item is selected + * (from the items assigned to the pick) and whether the pick is accepted or + * dismissed, then drives the accept/hide callbacks the way the real widget + * would. + */ +class FakeQuickPick { + title?: string; + placeholder?: string; + items: readonly QuickPickItem[] = []; + selectedItems: readonly QuickPickItem[] = []; + private acceptCbs: Array<() => void> = []; + private hideCbs: Array<() => void> = []; + public disposed = false; + + constructor( + private readonly onAccept: ( + pick: FakeQuickPick + ) => {selected: readonly QuickPickItem[]} | "dismiss" + ) {} + + onDidAccept(cb: () => void) { + this.acceptCbs.push(cb); + return {dispose() {}}; + } + onDidHide(cb: () => void) { + this.hideCbs.push(cb); + return {dispose() {}}; + } + show() { + const result = this.onAccept(this); + if (result === "dismiss") { + this.hideCbs.forEach((cb) => cb()); + return; + } + this.selectedItems = result.selected; + this.acceptCbs.forEach((cb) => cb()); + } + hide() { + this.hideCbs.forEach((cb) => cb()); + } + dispose() { + this.disposed = true; + } +} + +/** + * A factory that hands `pickSetupPreset` a `FakeQuickPick`, typed as the real + * `window.createQuickPick` seam. `onAccept` scripts the widget's outcome, and + * `created` exposes the instance so a test can read the title/placeholder/items + * the picker set on it. + */ +function fakeCreateQuickPick( + onAccept: ( + pick: FakeQuickPick + ) => {selected: readonly QuickPickItem[]} | "dismiss" +) { + const created: FakeQuickPick[] = []; + const create = (() => { + const pick = new FakeQuickPick(onAccept); + created.push(pick); + return pick as unknown as QuickPick; + }) as () => QuickPick; + return {create, created}; +} + +describe("presetToFlags", () => { + it("maps the full preset to no skip flags", () => { + expect(presetToFlags("full")).to.deep.equal({}); + }); + + it("maps the dbconnect preset to --no-constraints only", () => { + expect(presetToFlags("dbconnect")).to.deep.equal({ + skipConstraints: true, + }); + }); + + it("maps the python preset to both --no-constraints and --no-dbconnect", () => { + expect(presetToFlags("python")).to.deep.equal({ + skipConstraints: true, + skipDbconnect: true, + }); + }); +}); + +describe("buildPresetPickItems", () => { + it("lists the three presets in the Full, DB Connect, Python order", () => { + const items = buildPresetPickItems(); + expect(items.map((i) => i.preset)).to.deep.equal([ + "full", + "dbconnect", + "python", + ]); + }); + + it("presents the Full row with its verbatim copy, starred and first", () => { + const [full] = buildPresetPickItems(); + expect(full.label).to.equal("$(star-full) Full environment setup"); + expect(full.description).to.equal( + "Recommended so code runs as it would on Databricks" + ); + expect(full.detail).to.equal( + "Installs matching Python + Databricks Connect versions and pins cluster dependencies." + ); + }); + + it("presents the DB Connect row with its verbatim copy", () => { + const dbconnect = buildPresetPickItems()[1]; + expect(dbconnect.label).to.equal("$(tools) DB Connect setup"); + expect(dbconnect.description).to.equal( + "Recommended to run Spark code remotely." + ); + expect(dbconnect.detail).to.equal( + "Installs matching Python + Databricks Connect versions only." + ); + }); + + it("presents the Python row with its verbatim copy and no description", () => { + const python = buildPresetPickItems()[2]; + expect(python.label).to.equal("$(code) Python setup"); + expect(python.description).to.equal(undefined); + expect(python.detail).to.equal( + "Installs matching Python version only." + ); + }); +}); + +describe("computeTargetLabel", () => { + it("labels a serverless target with its vN version", () => { + expect(computeTargetLabel({kind: "serverless", version: "5"})).to.equal( + "serverless v5" + ); + }); + + it("labels a cluster target with its major.minor runtime", () => { + expect( + computeTargetLabel({kind: "cluster", clusterId: "0710-abc"}, [ + 17, + 3, + "x", + ]) + ).to.equal("Runtime 17.3"); + }); + + it("falls back to a generic cluster label when the runtime is unparsable", () => { + expect( + computeTargetLabel({kind: "cluster", clusterId: "0710-abc"}, [ + "x", + "x", + "x", + ]) + ).to.equal("the attached cluster"); + }); + + it("falls back to a generic cluster label when no runtime is known", () => { + expect( + computeTargetLabel({kind: "cluster", clusterId: "0710-abc"}) + ).to.equal("the attached cluster"); + }); +}); + +describe("pickSetupPreset", () => { + it("titles the picker with the resolved compute and documents the side effects", async () => { + const {create, created} = fakeCreateQuickPick(() => "dismiss"); + + await pickSetupPreset("serverless v5", create); + + expect(created[0].title).to.equal( + "Set up Python environment for serverless v5" + ); + expect(created[0].placeholder).to.equal( + "Create a uv managed .venv and pyproject.toml (if one exists, it's saved to pyproject.toml.bak)" + ); + // The picker offers exactly the three preset rows. + expect(created[0].items).to.have.length(3); + }); + + it("resolves the chosen preset when the user accepts a row", async () => { + const {create} = fakeCreateQuickPick((pick) => ({ + // Accept the DB Connect row (the second one). + selected: [pick.items[1]], + })); + + expect(await pickSetupPreset("Runtime 17.3", create)).to.equal( + "dbconnect" + ); + }); + + it("resolves undefined when the user dismisses the picker", async () => { + const {create} = fakeCreateQuickPick(() => "dismiss"); + + expect(await pickSetupPreset("Runtime 17.3", create)).to.equal( + undefined + ); + }); + + it("disposes the picker once it hides", async () => { + const {create, created} = fakeCreateQuickPick(() => "dismiss"); + + await pickSetupPreset("serverless v5", create); + + expect(created[0].disposed).to.equal(true); + }); +}); diff --git a/packages/databricks-vscode/src/python-setup/utils/pythonSetupPresetPicker.ts b/packages/databricks-vscode/src/python-setup/utils/pythonSetupPresetPicker.ts new file mode 100644 index 000000000..dad6b40b9 --- /dev/null +++ b/packages/databricks-vscode/src/python-setup/utils/pythonSetupPresetPicker.ts @@ -0,0 +1,143 @@ +import {QuickPick, QuickPickItem} from "vscode"; +import {SetupLocalInvocation} from "./setupLocalArgs"; + +/** The resolved compute target a setup run provisions for. */ +export type SetupComputeTarget = SetupLocalInvocation["compute"]; + +/** + * The Python-setup preset the user picks. Each tier nests inside the previous + * one, so they map onto the two orthogonal `setup-local` skip flags (see + * {@link presetToFlags}): + * + * - `full` — matching Python + Databricks Connect, and the runtime/dependency + * pins. No flags. + * - `dbconnect` — matching Python + Databricks Connect, but no pins + * (`--no-constraints`). + * - `python` — matching Python only (`--no-constraints --no-dbconnect`). + * + * The fourth flag combination (pins without databricks-connect, today's + * `--constraints-only`) is intentionally not a tier: keeping the tiers strictly + * nested is what lets a single-select picker present them as one axis. + */ +export type SetupPreset = "full" | "dbconnect" | "python"; + +/** The `setup-local` skip flags a preset resolves to. */ +export interface SetupPresetFlags { + skipConstraints?: boolean; + skipDbconnect?: boolean; +} + +/** + * Map a preset to the orthogonal skip flags the CLI invocation carries. Only + * the `true` flags are set, so a `full` run adds nothing and the argv stays + * flag-free (matching `buildSetupLocalArgs`, which pushes a flag only when its + * field is truthy). + */ +export function presetToFlags(preset: SetupPreset): SetupPresetFlags { + switch (preset) { + case "full": + return {}; + case "dbconnect": + return {skipConstraints: true}; + case "python": + return {skipConstraints: true, skipDbconnect: true}; + } +} + +/** + * The human label for the resolved compute target, used in the picker title + * (e.g. "Set up Python environment for Runtime 17.3"). Serverless carries its + * version directly; a cluster is described by its DBR major.minor when the + * `dbrVersion` is known and parseable, and otherwise by a generic label — the + * cluster id is never a resolved runtime and a cluster *name* is user-chosen + * (routinely a person's name), so neither is shown. + */ +export function computeTargetLabel( + compute: SetupComputeTarget, + dbrVersion?: Array +): string { + if (compute.kind === "serverless") { + return `serverless v${compute.version}`; + } + const [major, minor] = dbrVersion ?? []; + if (typeof major === "number" && typeof minor === "number") { + return `Runtime ${major}.${minor}`; + } + return "the attached cluster"; +} + +/** A preset QuickPick row; `preset` is the choice the row resolves to. */ +export interface PresetPickItem extends QuickPickItem { + preset: SetupPreset; +} + +/** Documents the shared side effects every tier has (all provision a venv). */ +const PLACEHOLDER = + "Create a uv managed .venv and pyproject.toml (if one exists, it's saved to pyproject.toml.bak)"; + +/** + * Build the three preset rows in nesting order (Full → DB Connect → Python). + * Pure, so the copy is unit-testable without a VS Code host. Full is listed + * first and starred as the recommendation; the codicons (`$(...)`) render as + * inline icons in the QuickPick. + */ +export function buildPresetPickItems(): PresetPickItem[] { + return [ + { + label: "$(star-full) Full environment setup", + description: "Recommended so code runs as it would on Databricks", + detail: "Installs matching Python + Databricks Connect versions and pins cluster dependencies.", + preset: "full", + }, + { + label: "$(tools) DB Connect setup", + description: "Recommended to run Spark code remotely.", + detail: "Installs matching Python + Databricks Connect versions only.", + preset: "dbconnect", + }, + { + label: "$(code) Python setup", + detail: "Installs matching Python version only.", + preset: "python", + }, + ]; +} + +/** + * Show the single-select preset picker for a resolved compute target and return + * the chosen preset, or `undefined` if the user dismissed it. + * + * Uses the explicit-lifecycle `createQuickPick` API (not the one-shot + * `showQuickPick`) so `onDidAccept` resolves the chosen row and `onDidHide` + * reports a dismissal, matching the ticket's UX contract. `createQuickPick` is + * injected (the wiring passes `window.createQuickPick`) so the flow is + * unit-testable without a VS Code host. The title carries `computeLabel` (the + * resolved compute, e.g. "Runtime 17.3" or "serverless v5") and the placeholder + * documents the shared side effects. + */ +export function pickSetupPreset( + computeLabel: string, + createQuickPick: () => QuickPick +): Promise { + const quickPick = createQuickPick(); + quickPick.title = `Set up Python environment for ${computeLabel}`; + quickPick.placeholder = PLACEHOLDER; + quickPick.items = buildPresetPickItems(); + + return new Promise((resolve) => { + let picked: SetupPreset | undefined; + quickPick.onDidAccept(() => { + const selected = quickPick.selectedItems[0]; + if (selected === undefined) { + return; + } + picked = selected.preset; + quickPick.hide(); + }); + quickPick.onDidHide(() => { + resolve(picked); + quickPick.dispose(); + }); + quickPick.show(); + }); +} diff --git a/packages/databricks-vscode/src/telemetry/constants.ts b/packages/databricks-vscode/src/telemetry/constants.ts index 1e9b2a322..8e0c91736 100644 --- a/packages/databricks-vscode/src/telemetry/constants.ts +++ b/packages/databricks-vscode/src/telemetry/constants.ts @@ -154,6 +154,11 @@ import type { PythonSetupErrorCode, } from "../python-setup/models/PythonSetupResult"; export type {PythonSetupMode, PythonSetupErrorCode}; +// The setup preset is an extension-side concept (the picker's tiers), not part +// of the CLI wire contract, so it is owned by the picker util. Type-only, for +// the attempt event's schema. +import type {SetupPreset} from "../python-setup/utils/pythonSetupPresetPicker"; +export type {SetupPreset}; /** * How a setup run ended. @@ -541,6 +546,7 @@ export class EventTypes { targetType: ComputeType; serverlessVersion?: string; mode: PythonSetupMode; + setupPreset: SetupPreset; isGreenfield?: boolean; trigger: PythonSetupRunTrigger; }> = { @@ -570,6 +576,14 @@ export class EventTypes { comment: "Whether databricks-connect is included (default) or only the runtime constraints (constraints-only)", }, + setupPreset: { + comment: + "The preset tier the user picked: full (matching Python + Databricks Connect + " + + "pinned cluster dependencies), dbconnect (matching Python + Databricks Connect, " + + "no pins), or python (matching Python only). Disambiguates the two orthogonal " + + "skip axes that the two-value mode field cannot: a dbconnect run skips the pins " + + "yet reports mode=default", + }, isGreenfield: { comment: "Whether the project has no pyproject.toml yet. Omitted unless the project is " + diff --git a/packages/databricks-vscode/src/telemetry/pythonSetupExtensions.test.ts b/packages/databricks-vscode/src/telemetry/pythonSetupExtensions.test.ts index 24696dfda..641e934f0 100644 --- a/packages/databricks-vscode/src/telemetry/pythonSetupExtensions.test.ts +++ b/packages/databricks-vscode/src/telemetry/pythonSetupExtensions.test.ts @@ -40,6 +40,7 @@ describe(__filename, () => { targetType: "serverless", serverlessVersion: "5", mode: "default", + setupPreset: "full", isGreenfield: true, trigger: "initial", }); @@ -58,6 +59,7 @@ describe(__filename, () => { "event.targetType": "serverless", "event.serverlessVersion": "5", "event.mode": "default", + "event.setupPreset": "full", "event.isGreenfield": "true", "event.trigger": "initial", }); @@ -75,6 +77,7 @@ describe(__filename, () => { packageManager: "uv", targetType: "cluster", mode: "default", + setupPreset: "full", trigger: "initial", }); reportResult({outcome: "ok"}); @@ -96,6 +99,7 @@ describe(__filename, () => { packageManager: "pip", targetType: "cluster", mode: "constraints-only", + setupPreset: "python", serverlessVersion: undefined, isGreenfield: undefined, trigger: "initial", @@ -114,6 +118,7 @@ describe(__filename, () => { "event.packageManager": "pip", "event.targetType": "cluster", "event.mode": "constraints-only", + "event.setupPreset": "python", "event.trigger": "initial", }); expect(events[1].props).to.deep.equal({ @@ -134,6 +139,7 @@ describe(__filename, () => { packageManager: "uv", targetType: "cluster", mode: "default", + setupPreset: "full", isGreenfield: false, trigger: "initial", }); @@ -162,6 +168,7 @@ describe(__filename, () => { packageManager: "uv", targetType: "cluster", mode: "default", + setupPreset: "full", trigger: "initial", }); reportResult({ @@ -181,6 +188,7 @@ describe(__filename, () => { packageManager: "uv", targetType: "cluster", mode: "default", + setupPreset: "full", trigger: "initial", }); reportResult({outcome: "failed", failurePhase: "provision"}); @@ -195,6 +203,7 @@ describe(__filename, () => { packageManager: "uv", targetType: "cluster", mode: "default", + setupPreset: "full", trigger: "initial", }); reportResult({outcome: "ok"}); @@ -221,6 +230,7 @@ describe(__filename, () => { packageManager: "uv", targetType: "cluster", mode: "default", + setupPreset: "full", trigger: "initial", })({outcome: "ok", pythonSetupFlow}); @@ -244,6 +254,7 @@ describe(__filename, () => { packageManager: "uv", targetType: "cluster", mode: "default", + setupPreset: "full", trigger: "initial", })({outcome: "ok", envKey}); expect(events[1].props["event.envKey"]).to.equal(envKey); @@ -272,6 +283,7 @@ describe(__filename, () => { packageManager: "uv", targetType: "cluster", mode: "default", + setupPreset: "full", trigger: "initial", })({outcome: "ok", envKey}); expect(events[1].props["event.envKey"]).to.equal("other"); @@ -286,6 +298,7 @@ describe(__filename, () => { targetType: "serverless", serverlessVersion: "5", mode: "default", + setupPreset: "full", trigger: "initial", })({ outcome: "ok", @@ -327,6 +340,7 @@ describe(__filename, () => { targetType: "serverless", serverlessVersion: "5", mode: "default", + setupPreset: "full", trigger: "initial", })({outcome: "ok", envKey: "serverless/serverless-v5", warnings: []}); @@ -344,6 +358,7 @@ describe(__filename, () => { packageManager: "uv", targetType: "cluster", mode: "default", + setupPreset: "full", trigger: "initial", })({ outcome: "ok", @@ -380,6 +395,7 @@ describe(__filename, () => { packageManager: "uv", targetType: "cluster", mode: "default", + setupPreset: "full", trigger: "initial", })({outcome: "cancelled"}); @@ -399,6 +415,7 @@ describe(__filename, () => { packageManager: "uv", targetType: "cluster", mode: "default", + setupPreset: "full", trigger: "initial", clusterId: "0710-142042-secretcluster", projectPath: "/Users/jane/projects/acme", @@ -417,6 +434,7 @@ describe(__filename, () => { expect(Object.keys(events[0].props).sort()).to.deep.equal([ "event.mode", "event.packageManager", + "event.setupPreset", "event.targetType", "event.trigger", "version", @@ -454,6 +472,7 @@ describe(__filename, () => { packageManager: "uv", targetType: "cluster", mode: "default", + setupPreset: "full", trigger: "initial", }); diff --git a/packages/databricks-vscode/src/telemetry/pythonSetupExtensions.ts b/packages/databricks-vscode/src/telemetry/pythonSetupExtensions.ts index 68c03066f..a7e9a89dd 100644 --- a/packages/databricks-vscode/src/telemetry/pythonSetupExtensions.ts +++ b/packages/databricks-vscode/src/telemetry/pythonSetupExtensions.ts @@ -11,6 +11,7 @@ import type { PythonSetupOptOutSource, PythonSetupOutcome, PythonSetupRunTrigger, + SetupPreset, TargetCompute, } from "./constants"; import {PythonSetupWarning} from "../python-setup/models/PythonSetupResult"; @@ -26,6 +27,13 @@ export interface PythonSetupAttempt { /** The chosen serverless environment version; absent for clusters. */ serverlessVersion?: string; mode: PythonSetupMode; + /** + * The preset tier the user picked (full | dbconnect | python). Kept + * alongside {@link mode} because the two-value mode field cannot represent + * the orthogonal skip axes the picker enables: a `dbconnect` run skips the + * pins yet still reports `mode: "default"`. + */ + setupPreset: SetupPreset; /** * Whether the project has no `pyproject.toml` yet, or `undefined` when the * signal would be misleading — for a pip/conda project the absence of a @@ -276,6 +284,7 @@ Telemetry.prototype.recordPythonSetupAttempt = function ( packageManager: attempt.packageManager, targetType: attempt.targetType, mode: attempt.mode, + setupPreset: attempt.setupPreset, trigger: attempt.trigger, ...(attempt.serverlessVersion !== undefined ? {serverlessVersion: attempt.serverlessVersion} diff --git a/packages/databricks-vscode/src/test/e2e/setup_local.ucws.e2e.ts b/packages/databricks-vscode/src/test/e2e/setup_local.ucws.e2e.ts index e059e73b4..c1edda213 100644 --- a/packages/databricks-vscode/src/test/e2e/setup_local.ucws.e2e.ts +++ b/packages/databricks-vscode/src/test/e2e/setup_local.ucws.e2e.ts @@ -206,11 +206,18 @@ describe("Set up local Python environment (uv) on serverless", async function () it("should set up the environment with uv (setup-local)", async () => { // The router command; a clean (uv-suitable) project routes it to the uv // flow, which shells out to `databricks environments setup-local`. - // Compute + version are already resolved, so no prompt. + // Compute + version are already resolved, so the preset picker below is + // the only prompt. await executeCommandWhenAvailable( "Databricks: Setup python environment" ); + // Once compute is resolved the flow asks which preset to provision; take + // the recommended Full tier (starred, first) so the full environment is + // set up (matching Python + Databricks Connect + pinned dependencies). + const presetInput = await waitForQuickInput(); + await presetInput.selectQuickPick(0); + await waitForVenvInterpreter(projectDir); // The completion toast is informational and can expire before a poll @@ -262,12 +269,22 @@ describe("Set up local Python environment (uv) on serverless", async function () // executeCommand resolves when the (re-entrancy-guarded) run settles; a // re-run over an already-provisioned env is a warm uv sync, so it returns // quickly rather than paying another cold provision. - await browser.executeWorkbench(async (vscode) => { - await vscode.commands.executeCommand( + // rerunPythonEnv is palette-hidden (when:false), so fire it by id — but + // do NOT await it inside executeWorkbench: the command now blocks on the + // preset picker (driven just below), so awaiting here would deadlock — + // the callback can't return while the picker is open, so the picker + // could never be answered. + await browser.executeWorkbench((vscode) => { + void vscode.commands.executeCommand( "databricks.environment.rerunPythonEnv" ); }); + // Take the recommended Full tier again so the re-run provisions the same + // environment. + const rerunPresetInput = await waitForQuickInput(); + await rerunPresetInput.selectQuickPick(0); + // A fresh "Python environment ready" toast is the re-run-SPECIFIC success // signal. A failed run never clears readiness (readyRoots/state persist) // and never removes the .venv, so the interpreter and the ready row alone From 7da67f14fc284937fe34b959a388d1b79b66d205 Mon Sep 17 00:00:00 2001 From: Grigory Panov Date: Thu, 10 Sep 2026 10:14:54 +0200 Subject: [PATCH 15/31] feat(python-setup): recover from a constraint conflict with a Retry-as-DB-Connect fallback (#2186) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Why The uv-native "set up Python environment" **Full** preset pins the cluster's dependencies, so `uv sync` can fail when those pins conflict with the user's own dependencies. The CLI now emits a distinct **`E_PROVISION_CONFLICT`** for that case (shipped in **CLI v1.16.0**, already bundled on `main`). Rather than the generic `E_PROVISION` toast ("uv could not resolve the project's dependencies… adjust your dependencies"), offer a one-click recovery: re-run as **DB Connect** (`--no-constraints`), which drops the conflicting cluster-dependency pins while keeping matched Python + databricks-connect. ## What - **`E_PROVISION_CONFLICT`** — a distinct result-model error code for a genuine pin-vs-local conflict (a generic sync failure stays `E_PROVISION`), with its own copy: *"The cluster dependencies conflict with your local dependencies, so uv sync couldn't resolve the environment."* - **Recovery UX** (Full-preset conflict only) — the generic toast is replaced with **Retry DB Connect setup** and **Open pyproject.toml**. "Show Logs" is dropped from this self-service toast (the channel is still revealed). - **Restore-then-retry** — the conflict fails *after* the runtime pins were merged into `pyproject.toml` (`diskMutated: true`, pre-merge file saved to the CLI's `backupPath`). So **Retry** first restores that backup, then re-runs with the `dbconnect` preset — `--no-constraints` alone would only stop the retry from re-adding pins, not remove those already on disk. The restore is atomic (temp sibling + rename) and refuses a `backupPath` resolving outside the project. When `backupPath` is absent/empty (e.g. a no-op-merge re-run), Retry isn't offered and the run falls back to the ordinary doc-link handling. - **Guards** — `runGuarded`/`runResolved` let the retry re-enter with the `dbconnect` preset directly (no re-prompt), coalesced so a click can't race an in-flight run; `dbconnect` skips constraints so the retry can't loop; a stale toast's Retry no-ops once the project is ready. - **Telemetry** — a `conflict_retry` value on the existing `python_env.setup.attempt` `trigger` dimension marks recovery runs, paired with the `python_env.setup.result` outcome for the recovery success rate. No new event. A conflict is never report-worthy (it's the user's own dependencies). ## Live against the shipped CLI Unlike when this was first written, **CLI v1.16.0 (on `main`) emits `E_PROVISION_CONFLICT`**, so the recovery path is now exercised end-to-end, not dormant. Note: the CLI only populates `backupPath` on the *first* merge; a re-run over an already-merged `pyproject.toml` is a no-op merge and returns an empty `backupPath`, in which case the run correctly falls through to the generic path (the truthy-`backupPath` guard). ## Testing - `test:unit`: new coverage for the conflict copy + fallback doc link, the `run`-action dispatch, `openProjectFile`, the controller conflict→retry flow (restore-before-retry ordering, `--no-constraints` + adopt on success, `conflict_retry` telemetry paired with its outcome, open pyproject at the run's cwd, `reportOffered: false`, missing/empty-`backupPath` and non-Full fallbacks, restore-failure aborts without a retry attempt), and the atomic/in-project restore wiring. - `tsc` + `eslint` + `prettier` clean on changed files. Supersedes #2181, which merged into the (now-defunct) preset-picker branch rather than `main`. This pull request and its description were written by Isaac. Co-authored-by: Isaac --- .../src/python-setup/README.md | 3 + .../PythonSetupEnvironmentSetup.test.ts | 540 ++++++++++++++++++ .../PythonSetupEnvironmentSetup.ts | 195 ++++++- .../controllers/pythonSetupDeps.test.ts | 212 +++++++ .../controllers/pythonSetupDeps.ts | 63 +- .../python-setup/models/PythonSetupResult.ts | 9 + .../python-setup/utils/errorMessages.test.ts | 38 ++ .../src/python-setup/utils/errorMessages.ts | 54 +- .../src/telemetry/constants.ts | 12 +- .../src/telemetry/pythonSetupExtensions.ts | 8 +- 10 files changed, 1083 insertions(+), 51 deletions(-) diff --git a/packages/databricks-vscode/src/python-setup/README.md b/packages/databricks-vscode/src/python-setup/README.md index c24b48e72..3f349c10b 100644 --- a/packages/databricks-vscode/src/python-setup/README.md +++ b/packages/databricks-vscode/src/python-setup/README.md @@ -19,6 +19,9 @@ the mapped message alone (see `reportSetupIssue.ts` for the closed routing list) such a conflict is usually the user's own declared dependencies. When the published constraints are what conflict, that genuine case is served by a soft, conditional pointer in the output log instead (see `formatSetupFailureDetail`). +`E_PROVISION_CONFLICT` (the CLI's distinct pins-vs-local code) follows the same +policy; the Full-preset flow additionally offers a restore-and-retry recovery +(see `buildConflictRecoveryActions`). **Privacy posture.** The issue body carries build metadata (error code, phase, env key, package manager, extension/CLI versions, OS) plus the CLI's stderr. The diff --git a/packages/databricks-vscode/src/python-setup/controllers/PythonSetupEnvironmentSetup.test.ts b/packages/databricks-vscode/src/python-setup/controllers/PythonSetupEnvironmentSetup.test.ts index b2c9088b8..f7913796a 100644 --- a/packages/databricks-vscode/src/python-setup/controllers/PythonSetupEnvironmentSetup.test.ts +++ b/packages/databricks-vscode/src/python-setup/controllers/PythonSetupEnvironmentSetup.test.ts @@ -124,6 +124,8 @@ function makeDeps( compute: {kind: "serverless", version: "5"}, }), adoptInterpreter: async () => {}, + openProjectFile: async () => {}, + restoreProjectFile: async () => {}, saveState: () => {}, notify: async () => {}, showReauthPrompt: async () => {}, @@ -1695,3 +1697,541 @@ describe("PythonSetupEnvironmentSetup.setup preset selection", () => { expect(telemetry.attempts[0].mode).to.equal("constraints-only"); }); }); + +describe("PythonSetupEnvironmentSetup constraint-conflict recovery", () => { + /** + * A Full-preset run whose pinned cluster dependencies conflict with the + * user's local ones: the CLI's distinct E_PROVISION_CONFLICT. Constraints are + * merged before the provision fails, so disk is mutated and a backup exists. + */ + function conflictResult(): PythonSetupResult { + return { + schemaVersion: 1, + command: "environments setup-local", + ok: false, + mode: "default", + dryRun: false, + greenfield: false, + backupPath: "/proj/pyproject.toml.bak", + phases: [ + {phase: "preflight", status: "ok"}, + {phase: "resolve", status: "ok"}, + {phase: "fetch", status: "ok"}, + {phase: "merge", status: "ok"}, + {phase: "provision", status: "error"}, + {phase: "validate", status: "pending"}, + ], + warnings: [], + durationMs: 0, + error: { + code: "E_PROVISION_CONFLICT", + failurePhase: "provision", + message: + "error: No solution found when resolving dependencies: the " + + "runtime requires pyarrow<19 but your project requires " + + "pyarrow==21.0.0", + diskMutated: true, + }, + }; + } + + /** A CLI that returns a scripted result per call, in order. */ + function makeScriptedCli(results: PythonSetupResult[]) { + const calls: SetupLocalInvocation[] = []; + let i = 0; + return { + calls, + run: async (invocation: SetupLocalInvocation) => { + calls.push(invocation); + return results[Math.min(i++, results.length - 1)]; + }, + }; + } + + it("shows the conflict copy with Retry and Open pyproject actions on a Full-preset conflict", async () => { + const shown: {message: string; actions?: PythonSetupErrorAction[]}[] = + []; + const setup = new PythonSetupEnvironmentSetup( + makeDeps({ + cli: makeCli({resolve: conflictResult()}), + pickSetupPreset: async () => "full", + showError: async (message, _detail, actions) => { + shown.push({message, actions}); + }, + }) + ); + + await setup.setup(); + + expect(shown).to.have.length(1); + expect(shown[0].message).to.match(/cluster dependencies conflict/i); + // The two recovery buttons, in order; both are in-process run-actions. + expect(shown[0].actions?.map((a) => a.label)).to.deep.equal([ + "Retry DB Connect setup", + "Open pyproject.toml", + ]); + for (const action of shown[0].actions ?? []) { + expect(action).to.have.property("run"); + } + }); + + it("hides the Show Logs button on the conflict toast (self-service)", async () => { + const seen: Array<{includeShowLogs?: boolean} | undefined> = []; + const setup = new PythonSetupEnvironmentSetup( + makeDeps({ + cli: makeCli({resolve: conflictResult()}), + pickSetupPreset: async () => "full", + showError: async (_message, _detail, _actions, options) => { + seen.push(options); + }, + }) + ); + + await setup.setup(); + + expect(seen).to.have.length(1); + expect(seen[0]).to.deep.equal({includeShowLogs: false}); + }); + + it("keeps the Show Logs button for an ordinary (non-conflict) failure", async () => { + const seen: Array<{includeShowLogs?: boolean} | undefined> = []; + const setup = new PythonSetupEnvironmentSetup( + makeDeps({ + cli: makeCli({resolve: ERROR_NO_TARGET}), + showError: async (_message, _detail, _actions, options) => { + seen.push(options); + }, + }) + ); + + await setup.setup(); + + // No opt-out: showError keeps its default trailing Show Logs button. + expect(seen[0]).to.equal(undefined); + }); + + it("re-runs with --no-constraints (and adopts) when Retry DB Connect setup is picked", async () => { + const cli = makeScriptedCli([conflictResult(), SUCCESS_REAL_RUN]); + const adopted: string[] = []; + let retryAction: PythonSetupErrorAction | undefined; + const setup = new PythonSetupEnvironmentSetup( + makeDeps({ + cli, + pickSetupPreset: async () => "full", + adoptInterpreter: async (venvPath) => { + adopted.push(venvPath); + }, + showError: async (_message, _detail, actions) => { + retryAction = actions?.find( + (a) => a.label === "Retry DB Connect setup" + ); + }, + }) + ); + + await setup.setup(); + // The initial Full run failed; the user clicks Retry (a deferred click, + // after the original run settled). + expect(setup.ready).to.equal(false); + expect(retryAction).to.not.equal(undefined); + await (retryAction as {run: () => Promise}).run(); + + // Two runs: the Full attempt, then the DB Connect retry (restore + --no-constraints). + expect(cli.calls).to.have.length(2); + expect(cli.calls[0].skipConstraints).to.equal(undefined); + expect(cli.calls[1].skipConstraints).to.equal(true); + expect(cli.calls[1].skipDbconnect).to.equal(undefined); + // The retry succeeded, so the interpreter is adopted and the project is ready. + expect(adopted).to.deep.equal([SUCCESS_REAL_RUN.venvPath]); + expect(setup.ready).to.equal(true); + }); + + it("records the retry as a dbconnect run with the conflict_retry trigger", async () => { + const cli = makeScriptedCli([conflictResult(), SUCCESS_REAL_RUN]); + const telemetry = makeTelemetryRecorder(); + let retryAction: PythonSetupErrorAction | undefined; + const setup = new PythonSetupEnvironmentSetup( + makeDeps({ + cli, + ...telemetry, + pickSetupPreset: async () => "full", + showError: async (_message, _detail, actions) => { + retryAction = actions?.find( + (a) => a.label === "Retry DB Connect setup" + ); + }, + }) + ); + + await setup.setup(); + await (retryAction as {run: () => Promise}).run(); + + // The initial Full attempt is a first-time setup; the retry is labeled + // distinctly so a conflict recovery can be counted separately from a + // first-time DB Connect pick (both would otherwise be initial/dbconnect). + expect( + telemetry.attempts.map((a) => ({ + preset: a.setupPreset, + trigger: a.trigger, + })) + ).to.deep.equal([ + {preset: "full", trigger: "initial"}, + {preset: "dbconnect", trigger: "conflict_retry"}, + ]); + // The paired result carries the retry's outcome — success here — so + // (b)/(a) is derivable from the same attempt→result pairing. + expect(telemetry.results).to.have.length(2); + expect(telemetry.results[0].outcome).to.equal("failed"); + expect(telemetry.results[1].outcome).to.equal("ok"); + }); + + it("opens pyproject.toml (at the run's cwd) when Open pyproject.toml is picked", async () => { + const openedRoots: string[] = []; + let openAction: PythonSetupErrorAction | undefined; + const setup = new PythonSetupEnvironmentSetup( + makeDeps({ + cli: makeCli({resolve: conflictResult()}), + projectRoot: () => "/proj", + pickSetupPreset: async () => "full", + openProjectFile: async (root) => { + openedRoots.push(root); + }, + showError: async (_message, _detail, actions) => { + openAction = actions?.find( + (a) => a.label === "Open pyproject.toml" + ); + }, + }) + ); + + await setup.setup(); + await (openAction as {run: () => Promise}).run(); + + expect(openedRoots).to.deep.equal(["/proj"]); + }); + + it("records the conflict failure without offering a report", async () => { + const telemetry = makeTelemetryRecorder(); + const setup = new PythonSetupEnvironmentSetup( + makeDeps({ + ...telemetry, + cli: makeCli({resolve: conflictResult()}), + pickSetupPreset: async () => "full", + }) + ); + + await setup.setup(); + + expect(telemetry.results[0]).to.include({ + outcome: "failed", + errorCode: "E_PROVISION_CONFLICT", + failurePhase: "provision", + // A conflict is the user's own deps → never report-worthy. + reportOffered: false, + }); + }); + + it("falls back to the generic action when a conflict arrives on a run that already dropped the pins", async () => { + // Defensive: only Full pins cluster deps, so a conflict on a dbconnect + // run should never happen — but if it does, "Retry DB Connect setup" would + // be nonsensical (and loop), so use the ordinary doc-link handling. + const shown: {actions?: PythonSetupErrorAction[]}[] = []; + const setup = new PythonSetupEnvironmentSetup( + makeDeps({ + cli: makeCli({resolve: conflictResult()}), + pickSetupPreset: async () => "dbconnect", + showError: async (_message, _detail, actions) => { + shown.push({actions}); + }, + }) + ); + + await setup.setup(); + + expect(shown[0].actions).to.deep.equal([ + { + label: "Resolve dependency conflicts", + url: "https://docs.astral.sh/uv/concepts/resolution/", + }, + ]); + }); + + it("does not loop: a DB Connect retry that also fails gets the generic action, not another Retry", async () => { + // The retry runs with --no-constraints, so even if it somehow returns + // E_PROVISION_CONFLICT again the !skipConstraints gate makes it + // non-recoverable — the generic doc-link handling, never a second + // "Retry DB Connect setup" (which would loop). + const cli = makeScriptedCli([conflictResult(), conflictResult()]); + const shown: {actions?: PythonSetupErrorAction[]}[] = []; + let retryAction: PythonSetupErrorAction | undefined; + const setup = new PythonSetupEnvironmentSetup( + makeDeps({ + cli, + pickSetupPreset: async () => "full", + showError: async (_message, _detail, actions) => { + shown.push({actions}); + retryAction = actions?.find( + (a) => a.label === "Retry DB Connect setup" + ); + }, + }) + ); + + await setup.setup(); + expect(retryAction).to.not.equal(undefined); + await (retryAction as {run: () => Promise}).run(); + + expect(cli.calls).to.have.length(2); + expect(cli.calls[1].skipConstraints).to.equal(true); + // The retry's failure toast carries only the generic doc link — no + // recovery button, so there is no way to loop. + expect(shown).to.have.length(2); + expect(shown[1].actions).to.deep.equal([ + { + label: "Resolve dependency conflicts", + url: "https://docs.astral.sh/uv/concepts/resolution/", + }, + ]); + }); + + it("coalesces a Retry click onto an in-flight run instead of starting a concurrent one", async () => { + // The retry goes through the same re-entrancy guard as a fresh setup: + // if another run is already in flight when the (still-open) conflict + // toast's Retry is clicked, it must coalesce onto that run rather than + // spawn a second, concurrent project-mutating CLI process — and, since a + // queued dbconnect retry could otherwise clobber a run that is about to + // succeed, coalescing (not queuing) is the intended, safe behavior. + let releaseSecond: (r: PythonSetupResult) => void = () => {}; + const secondGate = new Promise((res) => { + releaseSecond = res; + }); + const calls: SetupLocalInvocation[] = []; + let call = 0; + const cli = { + calls, + run: (invocation: SetupLocalInvocation) => { + calls.push(invocation); + return call++ === 0 + ? Promise.resolve(conflictResult()) + : secondGate; + }, + }; + let retryAction: PythonSetupErrorAction | undefined; + const setup = new PythonSetupEnvironmentSetup( + makeDeps({ + cli, + pickSetupPreset: async () => "full", + showError: async (_message, _detail, actions) => { + retryAction = actions?.find( + (a) => a.label === "Retry DB Connect setup" + ); + }, + }) + ); + + // First Full run fails with a conflict; the guard is now released. + await setup.setup(); + expect(calls).to.have.length(1); + expect(retryAction).to.not.equal(undefined); + + // A second setup starts and is left in flight (its guard is held). + const second = setup.setup(); + // Clicking the stale Retry now must coalesce onto the in-flight run. + const retryPromise = (retryAction as {run: () => Promise}).run(); + + releaseSecond(SUCCESS_REAL_RUN); + await Promise.all([second, retryPromise]); + + // Two runs total (the Full conflict and the second run) — the Retry did + // not spawn a third, concurrent CLI process. + expect(calls).to.have.length(2); + }); + + it("does not re-provision when the project became ready before a stale Retry is clicked", async () => { + // The conflict toast lingers in the Notifications Center, so its Retry + // can be clicked long after a separate run has since set the project up. + // Re-provisioning as DB Connect then would silently downgrade the + // working environment, so a stale Retry must no-op once ready. + const cli = makeScriptedCli([conflictResult(), SUCCESS_REAL_RUN]); + let retryAction: PythonSetupErrorAction | undefined; + const setup = new PythonSetupEnvironmentSetup( + makeDeps({ + cli, + pickSetupPreset: async () => "full", + showError: async (_message, _detail, actions) => { + retryAction = actions?.find( + (a) => a.label === "Retry DB Connect setup" + ); + }, + }) + ); + + // Full run conflicts (retry captured, project not ready)… + await setup.setup(); + expect(setup.ready).to.equal(false); + // …then a later run succeeds and marks the project ready. + await setup.setup(); + expect(setup.ready).to.equal(true); + expect(cli.calls).to.have.length(2); + + // Clicking the now-stale Retry must not re-run the CLI. + await (retryAction as {run: () => Promise}).run(); + expect(cli.calls).to.have.length(2); + expect(setup.ready).to.equal(true); + }); + + it("restores the CLI's backup before the DB Connect retry re-runs", async () => { + // The conflict fails after the pins were merged into pyproject.toml, so + // the retry must roll the file back to the CLI's backup *before* + // re-running with --no-constraints (which alone would leave the + // already-written conflicting pins in place). + const scripted = makeScriptedCli([conflictResult(), SUCCESS_REAL_RUN]); + const events: string[] = []; + const restored: Array<{root: string; backupPath: string}> = []; + // A CliRunner wrapper that records the run order (assigned to a variable + // so the extra fields aren't excess-property-checked as a literal would). + const cli = { + run: async (invocation: SetupLocalInvocation) => { + events.push("cli"); + return scripted.run(invocation); + }, + }; + let retryAction: PythonSetupErrorAction | undefined; + const setup = new PythonSetupEnvironmentSetup( + makeDeps({ + cli, + pickSetupPreset: async () => "full", + restoreProjectFile: async (root, backupPath) => { + events.push("restore"); + restored.push({root, backupPath}); + }, + showError: async (_message, _detail, actions) => { + retryAction = actions?.find( + (a) => a.label === "Retry DB Connect setup" + ); + }, + }) + ); + + await setup.setup(); + await (retryAction as {run: () => Promise}).run(); + + // The restore targets the run's cwd with the CLI-reported backup path… + expect(restored).to.deep.equal([ + {root: "/proj", backupPath: "/proj/pyproject.toml.bak"}, + ]); + // …and it happens between the failed Full run and the DB Connect retry. + expect(events).to.deep.equal(["cli", "restore", "cli"]); + }); + + it("does not run the CLI or record a retry attempt when the restore fails", async () => { + // A failed restore leaves the conflicting pins on disk, so re-running + // would just conflict again: abort before spawning the CLI or recording + // a second attempt, and let showError's action-error handling log it. + const cli = makeScriptedCli([conflictResult(), SUCCESS_REAL_RUN]); + const telemetry = makeTelemetryRecorder(); + let retryAction: PythonSetupErrorAction | undefined; + const setup = new PythonSetupEnvironmentSetup( + makeDeps({ + cli, + ...telemetry, + pickSetupPreset: async () => "full", + restoreProjectFile: async () => { + throw new Error("copy failed"); + }, + showError: async (_message, _detail, actions) => { + retryAction = actions?.find( + (a) => a.label === "Retry DB Connect setup" + ); + }, + }) + ); + + await setup.setup(); + expect(retryAction).to.not.equal(undefined); + + // The run-action rejects so showError (its only production caller) can + // log the failure; here we assert only that nothing was launched. + let threw = false; + try { + await (retryAction as {run: () => Promise}).run(); + } catch { + threw = true; + } + expect(threw).to.equal(true); + + // Only the initial Full attempt happened: no DB Connect retry ran, and + // no second attempt/result was recorded. + expect(cli.calls).to.have.length(1); + expect(telemetry.attempts).to.have.length(1); + expect(telemetry.results).to.have.length(1); + expect(setup.ready).to.equal(false); + }); + + it("does not offer Retry when the conflict result has no backup to restore", async () => { + // Without a backupPath there is nothing to roll the merged pins back to, + // so the restore-then-retry recovery cannot run — fall through to the + // ordinary doc-link handling instead of offering a Retry that would + // re-run against the still-conflicting file. + const noBackup: PythonSetupResult = { + ...conflictResult(), + backupPath: undefined, + }; + const shown: {actions?: PythonSetupErrorAction[]}[] = []; + const seenOptions: Array<{includeShowLogs?: boolean} | undefined> = []; + const setup = new PythonSetupEnvironmentSetup( + makeDeps({ + cli: makeCli({resolve: noBackup}), + pickSetupPreset: async () => "full", + showError: async (_message, _detail, actions, options) => { + shown.push({actions}); + seenOptions.push(options); + }, + }) + ); + + await setup.setup(); + + expect(shown[0].actions).to.deep.equal([ + { + label: "Resolve dependency conflicts", + url: "https://docs.astral.sh/uv/concepts/resolution/", + }, + ]); + // Not a self-service toast without the Retry button, so Show Logs stays. + expect(seenOptions[0]).to.equal(undefined); + }); + + it("does not offer Retry when backupPath is an empty string", async () => { + // The CLI marks backupPath omitempty, so "" shouldn't occur — but if it + // did, offering Retry would hand the user a button that can only throw + // (restore rejects an empty path) while hiding Show Logs. Treat empty as + // "no backup": fall through to the ordinary doc-link handling. + const emptyBackup: PythonSetupResult = { + ...conflictResult(), + backupPath: "", + }; + const shown: {actions?: PythonSetupErrorAction[]}[] = []; + const seenOptions: Array<{includeShowLogs?: boolean} | undefined> = []; + const setup = new PythonSetupEnvironmentSetup( + makeDeps({ + cli: makeCli({resolve: emptyBackup}), + pickSetupPreset: async () => "full", + showError: async (_message, _detail, actions, options) => { + shown.push({actions}); + seenOptions.push(options); + }, + }) + ); + + await setup.setup(); + + expect(shown[0].actions).to.deep.equal([ + { + label: "Resolve dependency conflicts", + url: "https://docs.astral.sh/uv/concepts/resolution/", + }, + ]); + expect(seenOptions[0]).to.equal(undefined); + }); +}); diff --git a/packages/databricks-vscode/src/python-setup/controllers/PythonSetupEnvironmentSetup.ts b/packages/databricks-vscode/src/python-setup/controllers/PythonSetupEnvironmentSetup.ts index 2ff4f21b9..cfe2f6063 100644 --- a/packages/databricks-vscode/src/python-setup/controllers/PythonSetupEnvironmentSetup.ts +++ b/packages/databricks-vscode/src/python-setup/controllers/PythonSetupEnvironmentSetup.ts @@ -34,6 +34,7 @@ import { PythonSetupAttempt, PythonSetupResultReporter, } from "../../telemetry/pythonSetupExtensions"; +import type {PythonSetupRunTrigger} from "../../telemetry/constants"; import {PrimaryManager} from "../../language/packageManagerDetection"; import { isUvSetupSuitable, @@ -144,6 +145,26 @@ export interface PythonSetupSetupDeps { */ adoptInterpreter: (venvPath: string, projectRoot: string) => Promise; + /** + * Open the project's pyproject.toml in an editor — the "Open pyproject.toml" + * button on a constraint-conflict failure, so the user can inspect and + * adjust the dependencies that clashed. Takes the run's captured root so it + * targets the project the failing run mutated, even after a mid-run switch. + */ + openProjectFile: (projectRoot: string) => Promise; + + /** + * Restore `/pyproject.toml` from the CLI's pre-merge + * `backupPath` (see {@link PythonSetupResult.backupPath}) by copying it over + * the file. First step of the "Retry DB Connect setup" recovery, whose + * rationale lives on {@link buildConflictRecoveryActions}; a rejection there + * aborts the retry before any CLI run. + */ + restoreProjectFile: ( + projectRoot: string, + backupPath: string + ) => Promise; + saveState: (state: PythonSetupPersistedState) => void; /** @@ -171,11 +192,17 @@ export interface PythonSetupSetupDeps { * each opens an external URL or runs a VS Code command. Most failures carry * one; `E_UV_MISSING` carries two ("Install uv" + "Installation guide", see * `getPythonSetupErrorActions`). + * + * `options.includeShowLogs` defaults to true; pass `false` to omit the + * trailing "Show Logs" button — for a self-service toast whose own buttons + * are the remedy (the recoverable constraint conflict), so the row stays + * short. The channel is still written and revealed, so the log is reachable. */ showError: ( message: string, detail?: string, - actions?: PythonSetupErrorAction[] + actions?: PythonSetupErrorAction[], + options?: {includeShowLogs?: boolean} ) => Promise; showSuccess: (result: PythonSetupResult) => Promise; @@ -305,19 +332,27 @@ export class PythonSetupEnvironmentSetup implements Disposable { } setup(): Promise { - // Re-entrancy guard: coalesce concurrent callers onto the running run - // rather than spawning a second project-mutating CLI process. The guard - // releases when the run's *work* settles; the terminal notification is - // presented via {@link present} (fire-and-forget), so a toast left open - // never wedges the entry -- see that method. + return this.runGuarded(() => this.runSetup()); + } + + /** + * Re-entrancy guard: coalesce concurrent callers onto the running run rather + * than spawning a second project-mutating CLI process. The guard releases + * when the run's *work* settles; the terminal notification is presented via + * {@link present} (fire-and-forget), so a toast left open never wedges the + * entry -- see that method. Used both for a fresh {@link setup} and for the + * constraint-conflict retry, so a retry click cannot race a run already in + * flight. + */ + private runGuarded(run: () => Promise): Promise { if (this.inFlight) { return this.inFlight; } - const run = this.runSetup().finally(() => { + const guarded = run().finally(() => { this.inFlight = undefined; }); - this.inFlight = run; - return run; + this.inFlight = guarded; + return guarded; } /** @@ -344,8 +379,7 @@ export class PythonSetupEnvironmentSetup implements Disposable { } private async runSetup(): Promise { - const {cli, projectRoot, isVisible, resolveCompute, withProgress} = - this.deps; + const {projectRoot, isVisible, resolveCompute} = this.deps; const cwd = projectRoot(); if (cwd === undefined) { @@ -389,6 +423,29 @@ export class PythonSetupEnvironmentSetup implements Disposable { return; } + await this.runResolved(compute, cwd, preset); + } + + /** + * Run a resolved invocation (compute + preset) to completion: record the + * attempt, spawn the CLI under a progress indicator, then adopt the + * interpreter and persist state on success — or surface a mapped error on + * failure. Split out from {@link runSetup} so the constraint-conflict + * "Retry DB Connect setup" recovery can re-enter it with the `dbconnect` preset + * directly, without re-prompting the compute or the preset picker. + * + * `trigger` overrides how the attempt is labeled: the retry passes + * `conflict_retry`; the normal path leaves it undefined so + * {@link recordAttempt} derives `initial` / `rerun` from readiness. + */ + private async runResolved( + compute: SetupCompute, + cwd: string, + preset: SetupPreset, + trigger?: PythonSetupRunTrigger + ): Promise { + const {cli, withProgress} = this.deps; + const invocation: SetupLocalInvocation = { compute, ...presetToFlags(preset), @@ -401,7 +458,8 @@ export class PythonSetupEnvironmentSetup implements Disposable { const {reportResult, packageManager} = await this.recordAttempt( invocation, cwd, - preset + preset, + trigger ); // Per-run report context: the static build info plus this run's manager. const reportEnv: ReportEnvironment = { @@ -469,14 +527,36 @@ export class PythonSetupEnvironmentSetup implements Disposable { result.pythonResolution === "installed_fallback" ? "manual_selection_requested" : result.pythonResolution; - const actions = remediationActions.some( - (candidate) => - candidate.command === SELECT_PYTHON_INTERPRETER_COMMAND_ID - ) - ? remediationActions - : reportAction - ? [reportAction] - : remediationActions; + // A constraint conflict is recoverable only when this run carried the + // pins (Full preset) AND the CLI saved a pre-merge backup to roll them + // back to. Without either, fall through to the ordinary doc-link + // handling rather than offer a "retry as DB Connect" that can't work + // (nothing to restore) or would loop (a run that already skipped pins). + const conflictBackupPath = + result.error?.code === "E_PROVISION_CONFLICT" && + !invocation.skipConstraints && + // Truthiness, not just `!== undefined`: a (contract-forbidden) + // empty backupPath has nothing to restore, so it must fall + // through rather than offer a Retry that could only throw. + result.backupPath + ? result.backupPath + : undefined; + const recoverableConflict = conflictBackupPath !== undefined; + const actions = recoverableConflict + ? this.buildConflictRecoveryActions( + compute, + cwd, + conflictBackupPath + ) + : remediationActions.some( + (candidate) => + candidate.command === + SELECT_PYTHON_INTERPRETER_COMMAND_ID + ) + ? remediationActions + : reportAction + ? [reportAction] + : remediationActions; reportResult({ outcome: "failed", ...(pythonSetupFlow !== undefined ? {pythonSetupFlow} : {}), @@ -495,7 +575,12 @@ export class PythonSetupEnvironmentSetup implements Disposable { result, reportRepo ? reportLogLink(reportRepo) : undefined ), - actions + actions, + // The recoverable conflict is self-service via its Retry / + // Open buttons, so drop the trailing "Show Logs" to keep the + // notification's button row short (the channel is revealed + // regardless). + recoverableConflict ? {includeShowLogs: false} : undefined ) ); return; @@ -601,6 +686,56 @@ export class PythonSetupEnvironmentSetup implements Disposable { this.present(this.deps.showSuccess(result)); } + /** + * The two recovery buttons for a Full-preset constraint conflict, both + * run-actions (their behavior needs the run's live compute/cwd): + * + * - "Retry DB Connect setup" restores pyproject.toml from the CLI's pre-merge + * `backupPath`, then re-runs as DB Connect (`--no-constraints`). The restore + * is load-bearing: the conflict fails *after* the pins were merged to disk, + * so `--no-constraints` alone would leave the conflicting pins in place and + * only skip re-adding them. It runs through {@link runGuarded} — so a click + * can't race an in-flight run, and the restore only fires when the retry + * actually runs — and no-ops once the project is ready, so a stale toast's + * Retry can't downgrade an environment a later run provisioned. A failed + * restore throws before the CLI spawns, leaving showError to log it. + * - "Open pyproject.toml" opens the merged file so the user can adjust the + * dependencies that clashed. + */ + private buildConflictRecoveryActions( + compute: SetupCompute, + cwd: string, + backupPath: string + ): PythonSetupErrorAction[] { + return [ + { + label: "Retry DB Connect setup", + run: () => { + // A stale Retry (project provisioned by a later run since the + // conflict) must not re-provision and downgrade it. + if (this.readyRoots.has(cwd)) { + return; + } + return this.runGuarded(async () => { + // Restore before re-running; a failure throws here, before + // any attempt is recorded or the CLI spawns. + await this.deps.restoreProjectFile(cwd, backupPath); + await this.runResolved( + compute, + cwd, + "dbconnect", + "conflict_retry" + ); + }); + }, + }, + { + label: "Open pyproject.toml", + run: () => this.deps.openProjectFile(cwd), + }, + ]; + } + /** * Emit the attempt event for a run that is about to start and return its * outcome reporter. @@ -617,7 +752,8 @@ export class PythonSetupEnvironmentSetup implements Disposable { private async recordAttempt( invocation: SetupLocalInvocation, projectRoot: string, - setupPreset: SetupPreset + setupPreset: SetupPreset, + trigger?: PythonSetupRunTrigger ): Promise<{ reportResult: PythonSetupResultReporter; packageManager: PrimaryManager; @@ -665,11 +801,16 @@ export class PythonSetupEnvironmentSetup implements Disposable { mode: invocation.skipDbconnect ? "constraints-only" : "default", setupPreset, isGreenfield, - // A run against a project already marked ready this session is a - // re-run (the ready row's Re-run button / row click); anything - // else is the first setup. Derived from state, not the command, - // so every entry point labels the same event correctly. - trigger: this.readyRoots.has(projectRoot) ? "rerun" : "initial", + // An explicit trigger wins (the constraint-conflict retry passes + // `conflict_retry`, so its recovery clicks are countable and not + // conflated with a first-time DB Connect pick). Otherwise it is + // derived from state: a run against a project already marked ready + // this session is a re-run (the ready row's Re-run button / row + // click), anything else the first setup. Derived from state, not + // the command, so every entry point labels the same event. + trigger: + trigger ?? + (this.readyRoots.has(projectRoot) ? "rerun" : "initial"), }); return { packageManager, diff --git a/packages/databricks-vscode/src/python-setup/controllers/pythonSetupDeps.test.ts b/packages/databricks-vscode/src/python-setup/controllers/pythonSetupDeps.test.ts index 2be23a135..79e316e5c 100644 --- a/packages/databricks-vscode/src/python-setup/controllers/pythonSetupDeps.test.ts +++ b/packages/databricks-vscode/src/python-setup/controllers/pythonSetupDeps.test.ts @@ -1,4 +1,7 @@ import {expect} from "chai"; +import {mkdtemp, readdir, readFile, rm, writeFile} from "fs/promises"; +import {tmpdir} from "os"; +import path from "path"; import {commands, env, QuickPick, QuickPickItem, Uri, window} from "vscode"; import { makePythonSetupDeps, @@ -919,6 +922,215 @@ describe("makePythonSetupDeps showError", () => { originalOpen; } }); + + it("runs a run-action's callback when its button is picked", async () => { + // A run-action carries an in-process closure (the constraint-conflict + // "Retry DB Connect setup" / "Open pyproject.toml" buttons need runtime + // state, so they can't be a static url/command). + const deps = makePythonSetupDeps( + makeWiring({log: {append: () => {}, show: () => {}}}) + ); + let ran = 0; + reply = "Retry DB Connect setup"; + + await deps.showError("conflict copy", "detail", [ + {label: "Retry DB Connect setup", run: async () => void ran++}, + ]); + + expect(ran).to.equal(1); + }); + + it("omits the Show Logs button when includeShowLogs is false", async () => { + // A self-service toast (the recoverable constraint conflict) drops the + // trailing Show Logs so its own action buttons fit; the channel is still + // revealed, so the log stays reachable. + const deps = makePythonSetupDeps( + makeWiring({log: {append: () => {}, show: () => {}}}) + ); + reply = undefined; + + await deps.showError( + "conflict copy", + "detail", + [ + {label: "Retry DB Connect setup", run: async () => {}}, + {label: "Open pyproject.toml", run: async () => {}}, + ], + {includeShowLogs: false} + ); + + expect(shownWith[0].actions).to.deep.equal([ + "Retry DB Connect setup", + "Open pyproject.toml", + ]); + expect(shownWith[0].actions).to.not.contain("Show Logs"); + }); + + it("does not run a run-action's callback when its button is not picked", async () => { + const deps = makePythonSetupDeps( + makeWiring({log: {append: () => {}, show: () => {}}}) + ); + let ran = 0; + reply = "Show Logs"; + + await deps.showError("conflict copy", "detail", [ + {label: "Retry DB Connect setup", run: async () => void ran++}, + ]); + + expect(ran).to.equal(0); + }); + + it("does not reject when a run-action's callback throws", async () => { + // showError is the failure-reporting path and its one caller does not + // wrap it, so a throwing callback must be contained (logged), not escape. + const appended: string[] = []; + const deps = makePythonSetupDeps( + makeWiring({ + log: {append: (c) => appended.push(c), show: () => {}}, + }) + ); + reply = "Retry DB Connect setup"; + + await deps.showError("conflict copy", "detail", [ + { + label: "Retry DB Connect setup", + run: async () => { + throw new Error("retry blew up"); + }, + }, + ]); + + expect(appended.join("")).to.contain("retry blew up"); + }); +}); + +describe("makePythonSetupDeps openProjectFile", () => { + let originalShow: typeof window.showTextDocument; + let opened: string[]; + + beforeEach(() => { + originalShow = window.showTextDocument; + opened = []; + (window as unknown as {showTextDocument: unknown}).showTextDocument = + async (uri: Uri) => { + opened.push(uri.fsPath); + return {} as any; + }; + }); + + afterEach(() => { + (window as unknown as {showTextDocument: unknown}).showTextDocument = + originalShow; + }); + + it("opens the project's pyproject.toml in an editor", async () => { + const deps = makePythonSetupDeps(makeWiring()); + + await deps.openProjectFile("/proj"); + + expect(opened).to.have.length(1); + expect(opened[0]).to.match(/[/\\]proj[/\\]pyproject\.toml$/); + }); +}); + +describe("makePythonSetupDeps restoreProjectFile", () => { + it("copies the CLI's backup over the project's pyproject.toml", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "vpex-restore-")); + try { + const pyproject = path.join(dir, "pyproject.toml"); + const backup = path.join(dir, "pyproject.toml.bak"); + // The failed run's conflicting file, and the pre-merge backup. + await writeFile(pyproject, "conflicting = true\n"); + await writeFile(backup, "original = true\n"); + + const deps = makePythonSetupDeps(makeWiring()); + await deps.restoreProjectFile(dir, backup); + + // pyproject.toml now holds the backup's (original) contents again. + expect(await readFile(pyproject, "utf8")).to.equal( + "original = true\n" + ); + } finally { + await rm(dir, {recursive: true, force: true}); + } + }); + + it("leaves no temp artifact behind after a successful restore", async () => { + // The restore writes atomically (copy to a temp sibling, then rename), + // so no stray *.tmp file may survive a successful run. + const dir = await mkdtemp(path.join(tmpdir(), "vpex-restore-")); + try { + const backup = path.join(dir, "pyproject.toml.bak"); + await writeFile(path.join(dir, "pyproject.toml"), "conflicting\n"); + await writeFile(backup, "original\n"); + + const deps = makePythonSetupDeps(makeWiring()); + await deps.restoreProjectFile(dir, backup); + + const entries = await readdir(dir); + expect(entries.sort()).to.deep.equal([ + "pyproject.toml", + "pyproject.toml.bak", + ]); + } finally { + await rm(dir, {recursive: true, force: true}); + } + }); + + it("refuses to restore from a backup outside the project (and leaves the file untouched)", async () => { + // backupPath comes from the CLI result; a path outside the project must + // never be copied over pyproject.toml. + const project = await mkdtemp(path.join(tmpdir(), "vpex-proj-")); + const outside = await mkdtemp(path.join(tmpdir(), "vpex-out-")); + try { + const pyproject = path.join(project, "pyproject.toml"); + await writeFile(pyproject, "conflicting\n"); + const foreign = path.join(outside, "secrets.bak"); + await writeFile(foreign, "SHOULD NOT LAND\n"); + + const deps = makePythonSetupDeps(makeWiring()); + let threw = false; + try { + await deps.restoreProjectFile(project, foreign); + } catch { + threw = true; + } + + expect(threw).to.equal(true); + // pyproject.toml is untouched; the foreign file never lands. + expect(await readFile(pyproject, "utf8")).to.equal("conflicting\n"); + } finally { + await rm(project, {recursive: true, force: true}); + await rm(outside, {recursive: true, force: true}); + } + }); + + it("leaves pyproject.toml untouched and cleans up when the copy fails", async () => { + // A missing backup (in-project path, so it passes the guard) makes the + // copy fail: the destination must be untouched and no temp left behind. + const dir = await mkdtemp(path.join(tmpdir(), "vpex-restore-")); + try { + const pyproject = path.join(dir, "pyproject.toml"); + await writeFile(pyproject, "conflicting\n"); + const missing = path.join(dir, "pyproject.toml.bak"); // never created + + const deps = makePythonSetupDeps(makeWiring()); + let threw = false; + try { + await deps.restoreProjectFile(dir, missing); + } catch { + threw = true; + } + + expect(threw).to.equal(true); + expect(await readFile(pyproject, "utf8")).to.equal("conflicting\n"); + // No *.tmp artifact survived the failed copy. + const entries = await readdir(dir); + expect(entries).to.deep.equal(["pyproject.toml"]); + } finally { + await rm(dir, {recursive: true, force: true}); + } + }); }); describe("makePythonSetupDeps showSuccess", () => { diff --git a/packages/databricks-vscode/src/python-setup/controllers/pythonSetupDeps.ts b/packages/databricks-vscode/src/python-setup/controllers/pythonSetupDeps.ts index adbf317f8..5e41e996a 100644 --- a/packages/databricks-vscode/src/python-setup/controllers/pythonSetupDeps.ts +++ b/packages/databricks-vscode/src/python-setup/controllers/pythonSetupDeps.ts @@ -1,4 +1,6 @@ +import {randomBytes} from "crypto"; import {existsSync} from "fs"; +import {copyFile, rename, rm} from "fs/promises"; import path from "path"; import {commands, ProgressLocation, Uri, window} from "vscode"; import {PackageManagerDetection} from "../../language/packageManagerDetection"; @@ -276,6 +278,44 @@ export function makePythonSetupDeps( Uri.file(projectRoot) ); }, + openProjectFile: async (projectRoot: string) => { + // Open the pyproject.toml the conflicting run merged into, so the + // user can inspect/adjust the dependencies that clashed. A + // constraint conflict always mutates disk (constraints are merged + // before provisioning fails), so the file exists. + await window.showTextDocument( + Uri.file(path.join(projectRoot, "pyproject.toml")) + ); + }, + restoreProjectFile: async (projectRoot: string, backupPath: string) => { + // Restore the CLI's pre-merge backup over pyproject.toml (the seam's + // doc covers why the DB Connect retry needs this). + const root = path.resolve(projectRoot); + // backupPath comes from the CLI result: refuse anything resolving + // outside the project so a malformed/unexpected path can't copy an + // arbitrary file over pyproject.toml. Lexical containment (path is + // from the trusted local CLI, so symlink canonicalization is not + // warranted). + const rel = path.relative(root, path.resolve(backupPath)); + if (rel === "" || rel.startsWith("..") || path.isAbsolute(rel)) { + throw new Error( + `Refusing to restore pyproject.toml from a backup outside the project: ${backupPath}` + ); + } + // Write atomically: copy to a temp sibling on the same filesystem, + // then rename over pyproject.toml, so an interrupted or failed copy + // can never leave the project file truncated. Clean the temp up if + // either step throws (rename consumes it on success). + const dest = path.join(root, "pyproject.toml"); + const tmp = `${dest}.${randomBytes(6).toString("hex")}.tmp`; + try { + await copyFile(backupPath, tmp); + await rename(tmp, dest); + } catch (e) { + await rm(tmp, {force: true}); + throw e; + } + }, // Stamp the persisted state with the completion time here (the // orchestrator supplies the env identity; the timestamp is a wiring // concern) and hand it to the injected store for drift detection. @@ -307,7 +347,8 @@ export function makePythonSetupDeps( showError: async ( message: string, detail?: string, - actions: PythonSetupErrorAction[] = [] + actions: PythonSetupErrorAction[] = [], + options?: {includeShowLogs?: boolean} ) => { // The mapped one-liner is deliberately concise and drops the CLI's // own explanation; write that detail into the channel so the log the @@ -336,10 +377,15 @@ export function makePythonSetupDeps( }); // Lead with the remediation buttons (e.g. "Install uv", then // "Installation guide") in order, so the action the user most likely - // wants comes first; "Show Logs" always trails. - const buttons = [...remediations.map((a) => a.label), showLogs]; + // wants comes first; "Show Logs" trails, unless the caller opted it + // out (a self-service toast whose own buttons are the remedy) — the + // channel is revealed above regardless, so the log stays reachable. + const includeShowLogs = options?.includeShowLogs !== false; + const buttons = includeShowLogs + ? [...remediations.map((a) => a.label), showLogs] + : remediations.map((a) => a.label); const picked = await window.showErrorMessage(message, ...buttons); - if (picked === showLogs) { + if (includeShowLogs && picked === showLogs) { wiring.log.show(); return; } @@ -369,11 +415,18 @@ export function makePythonSetupDeps( `\nCould not open ${chosen.url} in a browser.\n` ); } + } else if (chosen.run) { + // A run-action (the constraint-conflict "Retry DB Connect setup" + // / "Open pyproject.toml" buttons) invokes an in-process + // callback the orchestrator built with the run's live state. + await chosen.run(); } } catch (e) { const what = chosen.command ? `run ${chosen.command}` - : `open ${chosen.url}`; + : chosen.url + ? `open ${chosen.url}` + : `run the "${chosen.label}" action`; wiring.log.append( `\nFailed to ${what}: ${ e instanceof Error ? e.message : String(e) diff --git a/packages/databricks-vscode/src/python-setup/models/PythonSetupResult.ts b/packages/databricks-vscode/src/python-setup/models/PythonSetupResult.ts index 9f9e50976..3f7766f5a 100644 --- a/packages/databricks-vscode/src/python-setup/models/PythonSetupResult.ts +++ b/packages/databricks-vscode/src/python-setup/models/PythonSetupResult.ts @@ -34,6 +34,14 @@ export type PythonSetupPhaseStatus = "ok" | "error" | "pending"; * ErrorCode set. `E_AUTH` / `E_PYTHON_POLICY` appear in the spec but are never * emitted by the CLI (auth is handled by the shared workspace-client preflight * before a result object is built), so they are intentionally absent here. + * + * `E_PROVISION_CONFLICT` is the distinct code the CLI emits when `uv sync` fails + * specifically because the runtime's pinned dependencies conflict with the + * user's own (only the Full preset pins them); a generic provision failure stays + * `E_PROVISION`. The pins are already merged into pyproject.toml at the point of + * failure (`diskMutated: true`, with the pre-merge file saved to `backupPath`), + * which the extension's retry-as-DB-Connect recovery relies on: it restores that + * backup before re-running. */ export type PythonSetupErrorCode = | "E_USAGE" @@ -48,6 +56,7 @@ export type PythonSetupErrorCode = | "E_MERGE" | "E_PYTHON_INSTALL" | "E_PROVISION" + | "E_PROVISION_CONFLICT" | "E_VALIDATE"; export interface PythonSetupComputeInfo { diff --git a/packages/databricks-vscode/src/python-setup/utils/errorMessages.test.ts b/packages/databricks-vscode/src/python-setup/utils/errorMessages.test.ts index de1116533..20cc64fa3 100644 --- a/packages/databricks-vscode/src/python-setup/utils/errorMessages.test.ts +++ b/packages/databricks-vscode/src/python-setup/utils/errorMessages.test.ts @@ -139,6 +139,15 @@ describe("getPythonSetupErrorMessage", () => { expect(msg).to.not.match(/UV_INDEX_URL|pip\.conf/i); }); + it("maps E_PROVISION_CONFLICT to a cluster-vs-local conflict message", () => { + // The distinct constraint-conflict code (only the Full preset pins + // cluster deps) gets its own actionable copy, not E_PROVISION's generic + // "adjust your dependencies" text. + const msg = getPythonSetupErrorMessage(failure("E_PROVISION_CONFLICT")); + expect(msg).to.match(/cluster dependencies conflict/i); + expect(msg).to.match(/local dependencies/i); + }); + it("maps E_FETCH to an offline/unreachable message", () => { expect(getPythonSetupErrorMessage(failure("E_FETCH"))).to.match( /reach|offline|network/i @@ -340,6 +349,18 @@ describe("getPythonSetupErrorAction", () => { ); }); + it("points an E_PROVISION_CONFLICT at the uv resolution docs (generic fallback)", () => { + // The Full-preset flow builds its own retry/open buttons in the + // orchestrator; this code-keyed link is the fallback for a conflict that + // somehow arrives on a run that already dropped the pins. + expect( + getPythonSetupErrorAction(failure("E_PROVISION_CONFLICT")) + ).to.deep.equal({ + label: "Resolve dependency conflicts", + url: "https://docs.astral.sh/uv/concepts/resolution/", + }); + }); + it("points E_MANAGER_UNSUPPORTED at the uv projects docs", () => { expect( getPythonSetupErrorAction( @@ -641,6 +662,23 @@ describe("formatSetupFailureDetail", () => { ); }); + it("keeps the constraints-report hint for E_PROVISION_CONFLICT", () => { + // A constraint conflict was E_PROVISION before the CLI split out the + // distinct code; the soft "if you think it's the published constraints, + // report it" log pointer must not silently vanish, since a pins-vs-local + // conflict is exactly the case where the published constraints may be at + // fault. + const detail = formatSetupFailureDetail( + failure("E_PROVISION_CONFLICT", { + message: "No solution found when resolving dependencies", + }) + ); + expect(detail).to.match(/constraint/i); + expect(detail).to.contain( + "https://github.com/databricks/environments/issues/new" + ); + }); + it("adds no constraints-report hint for a blocked-index E_PROVISION", () => { // A blocked index is a local network condition, not a constraint defect. const detail = formatSetupFailureDetail( diff --git a/packages/databricks-vscode/src/python-setup/utils/errorMessages.ts b/packages/databricks-vscode/src/python-setup/utils/errorMessages.ts index 4f66c998f..ab01688c1 100644 --- a/packages/databricks-vscode/src/python-setup/utils/errorMessages.ts +++ b/packages/databricks-vscode/src/python-setup/utils/errorMessages.ts @@ -173,16 +173,26 @@ export const INSTALL_UV_COMMAND_ID = "databricks.environment.installUv"; /** * An optional remediation button to attach to a failure popup. Exactly one of - * `url` / `command` is set — a discriminated union (`?: never` on the other arm) - * forbids both/neither at compile time, while still letting callers read - * `action.url` / `action.command` as `string | undefined` without narrowing. - * `url` opens an external page (docs, issue); `command` runs a VS Code command - * (e.g. the one-click switch to manual setup). Kept alongside - * {@link getPythonSetupErrorMessage} so the copy and its call-to-action live together. + * `url` / `command` / `run` is set — a discriminated union (`?: never` on the + * other arms) forbids more than one at compile time, while still letting callers + * read `action.url` / `action.command` as `string | undefined` without + * narrowing. `url` opens an external page (docs, issue); `command` runs a VS + * Code command (e.g. the one-click switch to manual setup); `run` invokes an + * in-process callback for a button whose behavior needs runtime state and so + * can't be expressed as a static url/command (the constraint-conflict + * "Retry DB Connect setup" / "Open pyproject.toml" buttons, built by the + * orchestrator). Kept alongside {@link getPythonSetupErrorMessage} so the copy + * and its call-to-action live together. */ export type PythonSetupErrorAction = - | {label: string; url: string; command?: never} - | {label: string; command: string; url?: never}; + | {label: string; url: string; command?: never; run?: never} + | {label: string; command: string; url?: never; run?: never} + | { + label: string; + run: () => void | Promise; + url?: never; + command?: never; + }; /* eslint-disable @typescript-eslint/naming-convention */ const BASE_MESSAGE: Record< @@ -220,6 +230,9 @@ const BASE_MESSAGE: Record< E_PROVISION: () => "uv could not resolve the project's dependencies (a version conflict). " + "Review the conflict in the logs and adjust your dependencies.", + E_PROVISION_CONFLICT: () => + "The cluster dependencies conflict with your local dependencies, so uv " + + "sync couldn't resolve the environment.", E_VALIDATE: () => "The provisioned environment did not match the selected runtime.", }; @@ -296,6 +309,14 @@ const DOC_LINKS: Partial> = label: "Resolve dependency conflicts", url: UV_RESOLUTION_DOCS_URL, }, + // The Full-preset flow builds its own retry/open buttons in the + // orchestrator; this is the fallback link for a conflict that reaches the + // generic path instead — a run that already skipped constraints, or one + // with no backup to restore. + E_PROVISION_CONFLICT: { + label: "Resolve dependency conflicts", + url: UV_RESOLUTION_DOCS_URL, + }, E_NO_TARGET: { label: "Configure compute", url: DATABRICKS_CONFIGURE_DOCS_URL, @@ -463,11 +484,18 @@ export function formatSetupFailureDetail( 'setting to "manual". The extension then uses your existing interpreter/.venv as-is.' ); } - // A genuine E_PROVISION conflict gets no report button (it is usually the - // user's own dependencies). But if the *published constraints* are what - // conflict, that is a defect worth reporting — so offer a soft, conditional - // pointer here. Excludes the blocked-index variant, a local network issue. - if (err.code === "E_PROVISION" && !isIndexUnreachableFailure(result)) { + // A dependency conflict gets no report button (it is usually the user's own + // dependencies). But if the *published constraints* are what conflict, that + // is a defect worth reporting — so offer a soft, conditional pointer here. + // Covers both the generic E_PROVISION conflict and the distinct + // E_PROVISION_CONFLICT (a pins-vs-local conflict is exactly where the + // published constraints may be at fault, and it was E_PROVISION — carrying + // this pointer — before the CLI split the code out). Excludes the + // blocked-index variant, a local network issue. + if ( + (err.code === "E_PROVISION" || err.code === "E_PROVISION_CONFLICT") && + !isIndexUnreachableFailure(result) + ) { lines.push( "", "If you believe this conflict comes from the published runtime " + diff --git a/packages/databricks-vscode/src/telemetry/constants.ts b/packages/databricks-vscode/src/telemetry/constants.ts index 8e0c91736..e36223804 100644 --- a/packages/databricks-vscode/src/telemetry/constants.ts +++ b/packages/databricks-vscode/src/telemetry/constants.ts @@ -134,7 +134,7 @@ export type SetupTrigger = "auto_open" | "explicit_command" | "run" | "debug"; * again. One event, one enum dimension — so re-runs stay analysable without * fingerprinting on the command id. */ -export type PythonSetupRunTrigger = "initial" | "rerun"; +export type PythonSetupRunTrigger = "initial" | "rerun" | "conflict_retry"; /** Categorical outcome of Python acquisition and its user recovery path. */ export type PythonSetupFlow = @@ -557,9 +557,15 @@ export class EventTypes { "IDs/names, paths, or package names.", trigger: { comment: - "initial (first setup for the project this session) or rerun (re-running over an " + + "initial (first setup for the project this session), rerun (re-running over an " + "environment already provisioned this session, e.g. via the ready row's Re-run " + - "button). Session-scoped: a run after a window reload reads as initial again", + "button), or conflict_retry (a Full-preset run hit a cluster-vs-local dependency " + + "conflict and the user clicked 'Retry DB Connect setup', which re-runs with " + + "--no-constraints). conflict_retry counts conflict-recovery runs that started " + + "(a click whose pre-retry pyproject.toml restore fails, coalesces, or no-ops " + + "records none); pair it with the matching result's outcome for the recovery " + + "success rate. Session-scoped: a " + + "run after a window reload reads as initial again", }, packageManager: { comment: diff --git a/packages/databricks-vscode/src/telemetry/pythonSetupExtensions.ts b/packages/databricks-vscode/src/telemetry/pythonSetupExtensions.ts index a7e9a89dd..4af52c6cf 100644 --- a/packages/databricks-vscode/src/telemetry/pythonSetupExtensions.ts +++ b/packages/databricks-vscode/src/telemetry/pythonSetupExtensions.ts @@ -41,9 +41,11 @@ export interface PythonSetupAttempt { */ isGreenfield?: boolean; /** - * Whether this is the first setup for the project this session or a re-run - * over an environment already provisioned this session (session-scoped). - * Same event, one enum dimension. + * Whether this is the first setup for the project this session (`initial`), a + * re-run over an environment already provisioned this session (`rerun`), or a + * constraint-conflict recovery — the `Retry DB Connect setup` click on a + * failed Full-preset run (`conflict_retry`). Session-scoped; same event, one + * enum dimension. */ trigger: PythonSetupRunTrigger; } From dbc0ab1639a7864ad7d39633072468043c9f2f0a Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Thu, 10 Sep 2026 11:29:39 +0200 Subject: [PATCH 16/31] Release: v2.17.0 (#2187) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Release **v2.17.0** of the Databricks VS Code extension. ## What's included - Add a Python environment setup preset picker to choose a Full, DB Connect, or Python-only environment (#2179) - Recover from a dependency constraint conflict during Python setup by offering to retry as a DB Connect environment (#2186) - Add recovery UX for Python download failures (#2164) - Show an actionable error when Python setup hits a merge conflict on a `pyproject.toml` without a `[project]` table (#2180) - Preserve script stdout when an Upload-and-Run file fails (#2171) - Update Databricks CLI to v1.16.0 (#2175, #2183) — see the [CLI release notes](https://github.com/databricks/cli/releases) for changes Changelog curated from the generated output (stripped auto-close refs, dropped internal telemetry/CI-only items). Tracking: DECO-28498. --------- Co-authored-by: releasebot Co-authored-by: @rugpanov Co-authored-by: Isaac --- package.json | 2 +- packages/databricks-vscode-types/CHANGELOG.md | 6 ++++++ packages/databricks-vscode-types/package.json | 2 +- packages/databricks-vscode/CHANGELOG.md | 13 +++++++++++++ packages/databricks-vscode/package.json | 2 +- 5 files changed, 22 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index 855723427..219fbe00c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@databricks/databricks-vscode", - "version": "2.16.0", + "version": "2.17.0", "private": true, "workspaces": [ "packages/*" diff --git a/packages/databricks-vscode-types/CHANGELOG.md b/packages/databricks-vscode-types/CHANGELOG.md index b0e842498..0a1a79171 100644 --- a/packages/databricks-vscode-types/CHANGELOG.md +++ b/packages/databricks-vscode-types/CHANGELOG.md @@ -1,3 +1,9 @@ +# Release: v2.17.0 + +## packages/databricks-vscode-types + +## (2026-09-10) + # Release: v2.16.0 ## packages/databricks-vscode-types diff --git a/packages/databricks-vscode-types/package.json b/packages/databricks-vscode-types/package.json index 3d24b748a..b90f03260 100644 --- a/packages/databricks-vscode-types/package.json +++ b/packages/databricks-vscode-types/package.json @@ -1,6 +1,6 @@ { "name": "@databricks/databricks-vscode-types", - "version": "2.16.0", + "version": "2.17.0", "description": "Package with types and interfaces to develop extensions to the Databricks VSCode plugin", "main": "index.js", "types": "index.d.ts", diff --git a/packages/databricks-vscode/CHANGELOG.md b/packages/databricks-vscode/CHANGELOG.md index eef729243..c6e4fc305 100644 --- a/packages/databricks-vscode/CHANGELOG.md +++ b/packages/databricks-vscode/CHANGELOG.md @@ -1,3 +1,16 @@ +# Release: v2.17.0 + +## packages/databricks-vscode + +## (2026-09-10) + +- Add a Python environment setup preset picker to choose a Full, DB Connect, or Python-only environment (#2179) ([f7e0004](https://github.com/databricks/databricks-vscode/commit/f7e0004)) +- Recover from a dependency constraint conflict during Python setup by offering to retry as a DB Connect environment (#2186) ([06cfbf1](https://github.com/databricks/databricks-vscode/commit/06cfbf1)) +- Add recovery UX for Python download failures (#2164) ([ea38e82](https://github.com/databricks/databricks-vscode/commit/ea38e82)) +- Show an actionable error when Python setup hits a merge conflict on a `pyproject.toml` without a `[project]` table (#2180) ([685670e](https://github.com/databricks/databricks-vscode/commit/685670e)) +- Preserve script stdout when an Upload-and-Run file fails (#2171) ([05ebc1c](https://github.com/databricks/databricks-vscode/commit/05ebc1c)) +- Update Databricks CLI to v1.16.0 (#2175, #2183) ([51c8bc6](https://github.com/databricks/databricks-vscode/commit/51c8bc6)) — see the [CLI release notes](https://github.com/databricks/cli/releases) for changes + # Release: v2.16.0 ## packages/databricks-vscode diff --git a/packages/databricks-vscode/package.json b/packages/databricks-vscode/package.json index 0efc339b2..2cfecc18d 100644 --- a/packages/databricks-vscode/package.json +++ b/packages/databricks-vscode/package.json @@ -4,7 +4,7 @@ "description": "IDE support for Databricks", "publisher": "databricks", "license": "LicenseRef-LICENSE", - "version": "2.16.0", + "version": "2.17.0", "engines": { "vscode": "^1.86.0", "node": ">=22.0" From bf334c7250a66ca994129c01e61c636f812b2f5c Mon Sep 17 00:00:00 2001 From: eng-dev-ecosystem-bot <110475461+eng-dev-ecosystem-bot@users.noreply.github.com> Date: Thu, 10 Sep 2026 20:29:39 +0200 Subject: [PATCH 17/31] Update Databricks CLI to v1.16.1 (#2189) Update Databricks CLI to v1.16.1 --- packages/databricks-vscode/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/databricks-vscode/package.json b/packages/databricks-vscode/package.json index 2cfecc18d..3bed09df9 100644 --- a/packages/databricks-vscode/package.json +++ b/packages/databricks-vscode/package.json @@ -1880,7 +1880,7 @@ "useYarn": false }, "cli": { - "version": "1.16.0" + "version": "1.16.1" }, "scripts": { "vscode:prepublish": "rm -rf out && yarn run package:compile && yarn run package:wrappers:write && yarn run package:jupyter-init-script:write && yarn run package:copy-webview-toolkit && yarn run package:copy-markdown-it && yarn run package:copy-highlight && yarn run package:copy-windows-ca-certs && yarn run generate-telemetry", From b8d92e3b8faa192f57961c2ebf75e5fa414c55ce Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 11 Sep 2026 13:10:28 +0200 Subject: [PATCH 18/31] Release: v2.17.2 (#2191) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## packages/databricks-vscode ## (2026-09-11) - Update Databricks CLI to v1.16.1 (#2189) — fixes an SSH transfer regression affecting transfers larger than 1 MiB; see the [CLI release notes](https://github.com/databricks/cli/releases) for details ## packages/databricks-vscode-types ## (2026-09-11) --- Patch release. The only change since v2.17.1 is the bundled Databricks CLI bump to v1.16.1, which reverts the tunnel-resume layer that caused an SSH transfer regression (transfers larger than 1 MiB) in the previously bundled CLI. No extension code changes. This pull request and its description were written by Isaac. --------- Co-authored-by: releasebot Co-authored-by: Grigory Panov Co-authored-by: Isaac --- package.json | 2 +- packages/databricks-vscode-types/CHANGELOG.md | 6 ++++++ packages/databricks-vscode-types/package.json | 2 +- packages/databricks-vscode/CHANGELOG.md | 8 ++++++++ packages/databricks-vscode/package.json | 2 +- 5 files changed, 17 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index 219fbe00c..897d94e69 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@databricks/databricks-vscode", - "version": "2.17.0", + "version": "2.17.2", "private": true, "workspaces": [ "packages/*" diff --git a/packages/databricks-vscode-types/CHANGELOG.md b/packages/databricks-vscode-types/CHANGELOG.md index 0a1a79171..66c8bb200 100644 --- a/packages/databricks-vscode-types/CHANGELOG.md +++ b/packages/databricks-vscode-types/CHANGELOG.md @@ -1,3 +1,9 @@ +# Release: v2.17.2 + +## packages/databricks-vscode-types + +## (2026-09-11) + # Release: v2.17.0 ## packages/databricks-vscode-types diff --git a/packages/databricks-vscode-types/package.json b/packages/databricks-vscode-types/package.json index b90f03260..56c551112 100644 --- a/packages/databricks-vscode-types/package.json +++ b/packages/databricks-vscode-types/package.json @@ -1,6 +1,6 @@ { "name": "@databricks/databricks-vscode-types", - "version": "2.17.0", + "version": "2.17.2", "description": "Package with types and interfaces to develop extensions to the Databricks VSCode plugin", "main": "index.js", "types": "index.d.ts", diff --git a/packages/databricks-vscode/CHANGELOG.md b/packages/databricks-vscode/CHANGELOG.md index c6e4fc305..4ec88800e 100644 --- a/packages/databricks-vscode/CHANGELOG.md +++ b/packages/databricks-vscode/CHANGELOG.md @@ -1,3 +1,11 @@ +# Release: v2.17.2 + +## packages/databricks-vscode + +## (2026-09-11) + +- Update Databricks CLI to v1.16.1 (#2189) ([abc516c](https://github.com/databricks/databricks-vscode/commit/abc516c)) — fixes an SSH transfer regression affecting transfers larger than 1 MiB; see the [CLI release notes](https://github.com/databricks/cli/releases) for details + # Release: v2.17.0 ## packages/databricks-vscode diff --git a/packages/databricks-vscode/package.json b/packages/databricks-vscode/package.json index 3bed09df9..0e0103cfc 100644 --- a/packages/databricks-vscode/package.json +++ b/packages/databricks-vscode/package.json @@ -4,7 +4,7 @@ "description": "IDE support for Databricks", "publisher": "databricks", "license": "LicenseRef-LICENSE", - "version": "2.17.0", + "version": "2.17.2", "engines": { "vscode": "^1.86.0", "node": ">=22.0" From 5cbc47ff7ef079a1f8079aa12c0381d9b8415582 Mon Sep 17 00:00:00 2001 From: Grigory Panov Date: Fri, 11 Sep 2026 16:59:42 +0200 Subject: [PATCH 19/31] fix(python-setup): report the chosen preset in the setup success panel (#2192) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Why The Python-setup success panel ("View Details" log) derived its wording from `result.mode`, which encodes only the **databricks-connect** axis (`default` vs `constraints-only`) — not whether dependency pins were written. So it misreported two of the three presets: - A **DB Connect** run (`--no-constraints`) is byte-identical to **Full** in `mode`, so the panel always printed `• Added matching Databricks constraints to pyproject.toml` — false; DB Connect writes no pins. - The **Python** preset (`--no-constraints --no-dbconnect`) maps to `constraints-only`, which the headline mislabeled "constraints applied" — backwards. ## What Thread the run's resolved skip flags (`skipConstraints`/`skipDbconnect`, from `presetToFlags`) through `showSuccess` into `formatSetupLog`, and key the panel off those axes instead of `result.mode` (which it no longer reads): - headline: `Python environment ready.` when databricks-connect is skipped, else `… ready for Databricks Connect.` - databricks-connect version line: only when the run kept databricks-connect - constraints bullet: only when pins were actually written | Preset | Headline | `databricks-connect` line | Constraints bullet | |---|---|---|---| | Full | for Databricks Connect | yes | yes | | DB Connect (`--no-constraints`) | for Databricks Connect | yes | **no** | | Python (`--no-constraints --no-dbconnect`) | plain "ready" | no | no | No persisted state or CLI-contract change — the panel is transient output. ## Testing - Unit (42 passing): `formatSetupLog` three-preset matrix; per-preset flag wiring into `showSuccess`; and the Full→DB Connect **conflict-retry** case, asserting the panel describes the retry that actually ran (no pins), not the user's original Full pick. - `tsc` typecheck, prettier, and eslint clean on the changed files. - Not run locally: the full integration-test suite (covered by CI on this PR). ## Reviewer notes - The panel now reports the run's *requested* flags rather than a CLI-confirmed "pins written" signal — deliberate, because the `--output json` contract exposes no such field (the premise of this fix). On a successful run the CLI honors the flags, so there is no realistic divergence; a future CLI that silently skipped pins on a Full run would make the bullet wrong, and warnings remain the escape hatch. This pull request and its description were written by Isaac. --------- Co-authored-by: Isaac --- .../PythonSetupEnvironmentSetup.test.ts | 63 +++++++++++++++- .../PythonSetupEnvironmentSetup.ts | 24 +++++-- .../controllers/pythonSetupDeps.test.ts | 6 +- .../controllers/pythonSetupDeps.ts | 4 +- .../python-setup/utils/setupSummary.test.ts | 72 +++++++++++++++---- .../src/python-setup/utils/setupSummary.ts | 25 +++++-- 6 files changed, 167 insertions(+), 27 deletions(-) diff --git a/packages/databricks-vscode/src/python-setup/controllers/PythonSetupEnvironmentSetup.test.ts b/packages/databricks-vscode/src/python-setup/controllers/PythonSetupEnvironmentSetup.test.ts index f7913796a..97a5fe263 100644 --- a/packages/databricks-vscode/src/python-setup/controllers/PythonSetupEnvironmentSetup.test.ts +++ b/packages/databricks-vscode/src/python-setup/controllers/PythonSetupEnvironmentSetup.test.ts @@ -17,7 +17,7 @@ import { } from "../models/fixtures/setupLocalResults"; import {PythonSetupErrorAction} from "../utils/errorMessages"; import {SetupLocalInvocation} from "../utils/setupLocalArgs"; -import {SetupPreset} from "../utils/pythonSetupPresetPicker"; +import {SetupPreset, SetupPresetFlags} from "../utils/pythonSetupPresetPicker"; import { PythonSetupAttempt, PythonSetupOutcomeReport, @@ -1629,6 +1629,37 @@ describe("PythonSetupEnvironmentSetup.setup preset selection", () => { expect(invocation.skipDbconnect).to.equal(true); }); + /** Capture the flags handed to showSuccess on a successful run. */ + function flagsAtShowSuccess(preset: SetupPreset) { + let seen: SetupPresetFlags | undefined; + const setup = new PythonSetupEnvironmentSetup( + makeDeps({ + pickSetupPreset: async () => preset, + showSuccess: async (_r, flags) => { + seen = flags; + }, + }) + ); + return setup.setup().then(() => seen); + } + + it("hands showSuccess the Full preset's flags so the panel reports the pins", async () => { + expect(await flagsAtShowSuccess("full")).to.deep.equal({}); + }); + + it("hands showSuccess the DB Connect preset's flags so the panel omits the pins", async () => { + expect(await flagsAtShowSuccess("dbconnect")).to.deep.equal({ + skipConstraints: true, + }); + }); + + it("hands showSuccess the Python preset's flags so the panel omits pins and databricks-connect", async () => { + expect(await flagsAtShowSuccess("python")).to.deep.equal({ + skipConstraints: true, + skipDbconnect: true, + }); + }); + it("passes the resolved compute to the preset picker", async () => { const seen: Array = []; const setup = new PythonSetupEnvironmentSetup( @@ -1846,6 +1877,36 @@ describe("PythonSetupEnvironmentSetup constraint-conflict recovery", () => { expect(setup.ready).to.equal(true); }); + it("hands showSuccess the DB Connect flags after a Full-preset conflict retry, so the panel omits the pins line", async () => { + const cli = makeScriptedCli([conflictResult(), SUCCESS_REAL_RUN]); + let successFlags: SetupPresetFlags | undefined; + let retryAction: PythonSetupErrorAction | undefined; + const setup = new PythonSetupEnvironmentSetup( + makeDeps({ + cli, + pickSetupPreset: async () => "full", + showSuccess: async (_r, flags) => { + successFlags = flags; + }, + showError: async (_message, _detail, actions) => { + retryAction = actions?.find( + (a) => a.label === "Retry DB Connect setup" + ); + }, + }) + ); + + await setup.setup(); + await (retryAction as {run: () => Promise}).run(); + + // The success panel must describe the retry that actually ran (DB + // Connect, no pins), not the user's original Full pick. showSuccess + // fires only on the successful retry, and its flags come from the same + // presetToFlags the retry invocation used — this locks the regression + // the whole fix guards against. + expect(successFlags).to.deep.equal({skipConstraints: true}); + }); + it("records the retry as a dbconnect run with the conflict_retry trigger", async () => { const cli = makeScriptedCli([conflictResult(), SUCCESS_REAL_RUN]); const telemetry = makeTelemetryRecorder(); diff --git a/packages/databricks-vscode/src/python-setup/controllers/PythonSetupEnvironmentSetup.ts b/packages/databricks-vscode/src/python-setup/controllers/PythonSetupEnvironmentSetup.ts index cfe2f6063..5634444d1 100644 --- a/packages/databricks-vscode/src/python-setup/controllers/PythonSetupEnvironmentSetup.ts +++ b/packages/databricks-vscode/src/python-setup/controllers/PythonSetupEnvironmentSetup.ts @@ -29,7 +29,11 @@ import { } from "../utils/reportSetupIssue"; import {isReauthRequiredError} from "../utils/authErrors"; import {SetupLocalInvocation} from "../utils/setupLocalArgs"; -import {presetToFlags, SetupPreset} from "../utils/pythonSetupPresetPicker"; +import { + presetToFlags, + SetupPreset, + SetupPresetFlags, +} from "../utils/pythonSetupPresetPicker"; import { PythonSetupAttempt, PythonSetupResultReporter, @@ -205,7 +209,18 @@ export interface PythonSetupSetupDeps { options?: {includeShowLogs?: boolean} ) => Promise; - showSuccess: (result: PythonSetupResult) => Promise; + /** + * Present the success outcome. `flags` are the resolved skip flags of the + * run that actually happened (from {@link presetToFlags}), passed + * explicitly because `PythonSetupResult` alone cannot say which preset ran: + * `result.mode` encodes only the databricks-connect axis, so a Full and a + * DB Connect run are indistinguishable in it. The panel needs them to state + * truthfully whether constraints were written. + */ + showSuccess: ( + result: PythonSetupResult, + flags: SetupPresetFlags + ) => Promise; /** * Static build context (extension/CLI versions, OS) stamped into a @@ -446,9 +461,10 @@ export class PythonSetupEnvironmentSetup implements Disposable { ): Promise { const {cli, withProgress} = this.deps; + const flags = presetToFlags(preset); const invocation: SetupLocalInvocation = { compute, - ...presetToFlags(preset), + ...flags, }; // From here a run really happens, so the attempt is recorded and every @@ -683,7 +699,7 @@ export class PythonSetupEnvironmentSetup implements Disposable { warnings: result.warnings, }); - this.present(this.deps.showSuccess(result)); + this.present(this.deps.showSuccess(result, flags)); } /** diff --git a/packages/databricks-vscode/src/python-setup/controllers/pythonSetupDeps.test.ts b/packages/databricks-vscode/src/python-setup/controllers/pythonSetupDeps.test.ts index 79e316e5c..d373880d5 100644 --- a/packages/databricks-vscode/src/python-setup/controllers/pythonSetupDeps.test.ts +++ b/packages/databricks-vscode/src/python-setup/controllers/pythonSetupDeps.test.ts @@ -1192,7 +1192,7 @@ describe("makePythonSetupDeps showSuccess", () => { }) ); - await deps.showSuccess(SUCCESS_DEFAULT); + await deps.showSuccess(SUCCESS_DEFAULT, {}); expect(appended.join("")).to.have.length.greaterThan(0); // The automatic reveal fires regardless of what the user clicks. @@ -1205,7 +1205,7 @@ describe("makePythonSetupDeps showSuccess", () => { it("raises an info toast (never a warning) when the run had warnings", async () => { const deps = makePythonSetupDeps(makeWiring()); - await deps.showSuccess(SUCCESS_WITH_WARNINGS); + await deps.showSuccess(SUCCESS_WITH_WARNINGS, {}); // A successful run is informational even when it carried warnings; // the warning count is in the message and the details behind it. @@ -1229,7 +1229,7 @@ describe("makePythonSetupDeps showSuccess", () => { ); reply = "View Details"; - await deps.showSuccess(SUCCESS_DEFAULT); + await deps.showSuccess(SUCCESS_DEFAULT, {}); // Once on the automatic reveal, again when the button is picked. expect(shown).to.equal(2); diff --git a/packages/databricks-vscode/src/python-setup/controllers/pythonSetupDeps.ts b/packages/databricks-vscode/src/python-setup/controllers/pythonSetupDeps.ts index 5e41e996a..cd88cc9ba 100644 --- a/packages/databricks-vscode/src/python-setup/controllers/pythonSetupDeps.ts +++ b/packages/databricks-vscode/src/python-setup/controllers/pythonSetupDeps.ts @@ -434,7 +434,7 @@ export function makePythonSetupDeps( ); } }, - showSuccess: async (result) => { + showSuccess: async (result, flags) => { // Write the full breakdown to the log channel: in --output json // mode the CLI streams little or nothing to stderr on success, so // the channel would otherwise be empty. This is where the details @@ -444,7 +444,7 @@ export function makePythonSetupDeps( const projectName = result.venvPath ? await readVenvProjectName(result.venvPath) : undefined; - wiring.log.append(formatSetupLog(result, projectName)); + wiring.log.append(formatSetupLog(result, flags, projectName)); // Reveal the output channel automatically so those details are in // front of the user, then still raise the notification (with its // "View Details" button) as before. diff --git a/packages/databricks-vscode/src/python-setup/utils/setupSummary.test.ts b/packages/databricks-vscode/src/python-setup/utils/setupSummary.test.ts index c7fd8ff1e..ab60a9e80 100644 --- a/packages/databricks-vscode/src/python-setup/utils/setupSummary.test.ts +++ b/packages/databricks-vscode/src/python-setup/utils/setupSummary.test.ts @@ -1,12 +1,21 @@ import {expect} from "chai"; import {formatSetupLog, formatSetupNotification} from "./setupSummary"; import {PythonSetupResult} from "../models/PythonSetupResult"; +import {SetupPresetFlags} from "./pythonSetupPresetPicker"; import { SUCCESS_DEFAULT, SUCCESS_CONSTRAINTS_ONLY, SUCCESS_REAL_RUN, } from "../models/fixtures/setupLocalResults"; +// The three presets the picker resolves to, as the skip flags formatSetupLog +// keys its output off (see presetToFlags). Full writes constraints and adds +// databricks-connect; DB Connect adds databricks-connect but no pins; Python +// does neither. +const FULL: SetupPresetFlags = {}; +const DB_CONNECT: SetupPresetFlags = {skipConstraints: true}; +const PYTHON: SetupPresetFlags = {skipConstraints: true, skipDbconnect: true}; + describe("formatSetupNotification", () => { it("is a concise, use-case-neutral one-liner with no warnings", () => { expect(formatSetupNotification(SUCCESS_DEFAULT)).to.equal( @@ -55,21 +64,21 @@ describe("formatSetupNotification", () => { describe("formatSetupLog", () => { it("is non-empty and self-delimited with leading/trailing newlines", () => { - const log = formatSetupLog(SUCCESS_DEFAULT); + const log = formatSetupLog(SUCCESS_DEFAULT, FULL); expect(log.startsWith("\n")).to.equal(true); expect(log.endsWith("\n")).to.equal(true); expect(log.trim().length).to.be.greaterThan(0); }); it("includes the versions and capitalized compute label", () => { - const log = formatSetupLog(SUCCESS_DEFAULT); + const log = formatSetupLog(SUCCESS_DEFAULT, FULL); expect(log).to.contain("Python: 3.12"); expect(log).to.contain("databricks-connect: 17.2.0"); expect(log).to.contain("Compute: Serverless v4"); }); it("lists what was done, falling back to the bare .venv name", () => { - const log = formatSetupLog(SUCCESS_DEFAULT); + const log = formatSetupLog(SUCCESS_DEFAULT, FULL); expect(log).to.contain( " • Added matching Databricks constraints to pyproject.toml" ); @@ -82,7 +91,12 @@ describe("formatSetupLog", () => { }); it("shows the project name beside .venv when one is resolved", () => { - const log = formatSetupLog(SUCCESS_DEFAULT, "my-project", "linux"); + const log = formatSetupLog( + SUCCESS_DEFAULT, + FULL, + "my-project", + "linux" + ); expect(log).to.contain( " • Built a new virtual environment with uv sync called " + ".venv (my-project)" @@ -96,7 +110,9 @@ describe("formatSetupLog", () => { }); it("tells the user how to run notebooks with the venv", () => { - expect(formatSetupLog(SUCCESS_DEFAULT, undefined, "linux")).to.contain( + expect( + formatSetupLog(SUCCESS_DEFAULT, FULL, undefined, "linux") + ).to.contain( "To run notebooks using this virtual environment, click Select " + "Kernel in the upper right of a notebook and ensure that the " + "virtual environment is selected (`.venv/bin/python`)." @@ -104,7 +120,12 @@ describe("formatSetupLog", () => { }); it("uses the Windows interpreter path in the notebook hint", () => { - const log = formatSetupLog(SUCCESS_DEFAULT, "my-project", "win32"); + const log = formatSetupLog( + SUCCESS_DEFAULT, + FULL, + "my-project", + "win32" + ); expect(log).to.contain( "virtual environment is selected: my-project " + "(`.venv\\Scripts\\python.exe`)." @@ -112,16 +133,43 @@ describe("formatSetupLog", () => { expect(log).to.not.contain(".venv/bin/python"); }); - it("drops databricks-connect in constraints-only mode", () => { - const log = formatSetupLog(SUCCESS_CONSTRAINTS_ONLY); + it("headlines the Full preset for Databricks Connect and reports its pins", () => { + const log = formatSetupLog(SUCCESS_DEFAULT, FULL); + expect(log).to.contain( + "Python environment ready for Databricks Connect." + ); + expect(log).to.contain("databricks-connect: 17.2.0"); + expect(log).to.contain( + " • Added matching Databricks constraints to pyproject.toml" + ); + }); + + it("keeps databricks-connect but drops the pins line for the DB Connect preset", () => { + // --no-constraints: same CLI result shape as Full (mode "default", + // databricks-connect resolved), so only the flags tell the panel no + // pins were written. + const log = formatSetupLog(SUCCESS_DEFAULT, DB_CONNECT); expect(log).to.contain( - "Python environment ready — constraints applied." + "Python environment ready for Databricks Connect." + ); + expect(log).to.contain("databricks-connect: 17.2.0"); + expect(log).to.not.contain( + "Added matching Databricks constraints to pyproject.toml" ); + }); + + it("drops databricks-connect and the pins line for the Python preset", () => { + const log = formatSetupLog(SUCCESS_CONSTRAINTS_ONLY, PYTHON); + expect(log).to.contain("Python environment ready."); + expect(log).to.not.contain("for Databricks Connect"); expect(log).to.not.contain("databricks-connect"); + expect(log).to.not.contain( + "Added matching Databricks constraints to pyproject.toml" + ); }); it("shows the backup file on a real run", () => { - const log = formatSetupLog(SUCCESS_REAL_RUN); + const log = formatSetupLog(SUCCESS_REAL_RUN, FULL); expect(log).to.contain( " • Backed up your previous pyproject.toml (pyproject.toml.bak)" ); @@ -132,7 +180,7 @@ describe("formatSetupLog", () => { ...SUCCESS_REAL_RUN, backupPath: undefined, }; - expect(formatSetupLog(noBackup)).to.not.contain("Backed up"); + expect(formatSetupLog(noBackup, FULL)).to.not.contain("Backed up"); }); it("lists full warning messages when present", () => { @@ -140,7 +188,7 @@ describe("formatSetupLog", () => { ...SUCCESS_DEFAULT, warnings: [{code: "W_X", message: "pinned an older wheel"}], }; - const log = formatSetupLog(warned); + const log = formatSetupLog(warned, FULL); expect(log).to.contain("Warnings:"); expect(log).to.contain(" • pinned an older wheel"); }); diff --git a/packages/databricks-vscode/src/python-setup/utils/setupSummary.ts b/packages/databricks-vscode/src/python-setup/utils/setupSummary.ts index 8957f3d95..05e99ccfa 100644 --- a/packages/databricks-vscode/src/python-setup/utils/setupSummary.ts +++ b/packages/databricks-vscode/src/python-setup/utils/setupSummary.ts @@ -3,6 +3,7 @@ import { PythonSetupComputeInfo, PythonSetupResult, } from "../models/PythonSetupResult"; +import {SetupPresetFlags} from "./pythonSetupPresetPicker"; import {venvInterpreterPath} from "./venvInterpreterPath"; /** @@ -39,6 +40,14 @@ export function formatSetupNotification(result: PythonSetupResult): string { * messages) — necessary because in `--output json` mode the CLI streams little * or nothing to stderr on success, so without this the channel would be empty. * + * `flags` are the run's two orthogonal skip flags, resolved from the preset the + * user picked. They — not `result.mode` — decide what the panel claims was done: + * `mode` encodes only the databricks-connect axis (`default` vs + * `constraints-only`), so a DB Connect run (`--no-constraints`) is byte-identical + * to a Full run in that field and reading it would mis-report the constraints + * axis. `skipDbconnect` selects the databricks-connect vs plain-Python wording; + * `skipConstraints` gates the "added constraints" line. + * * `projectName` is the human-readable name uv associated with the venv (from * pyproject's `[project].name`, else the project folder name), surfaced by the * caller from `.venv/pyvenv.cfg`. It is shown in parentheses beside the venv @@ -53,23 +62,25 @@ export function formatSetupNotification(result: PythonSetupResult): string { */ export function formatSetupLog( result: PythonSetupResult, + flags: SetupPresetFlags, projectName?: string, platform: NodeJS.Platform = process.platform ): string { - const isDefault = result.mode === "default"; + const withDbconnect = !flags.skipDbconnect; + const constraintsApplied = !flags.skipConstraints; // The venv folder is always `.venv`; when the caller resolved the project // name, show it alongside so the line reads like the label VS Code puts on // the interpreter (e.g. ".venv (my-project)"). const venvLabel = projectName ? `.venv (${projectName})` : ".venv"; const lines: string[] = [ - isDefault + withDbconnect ? "Python environment ready for Databricks Connect." - : "Python environment ready — constraints applied.", + : "Python environment ready.", "", ]; lines.push(`Python: ${result.resolved?.pythonVersion ?? ""}`); - if (isDefault && result.resolved?.dbconnectVersion) { + if (withDbconnect && result.resolved?.dbconnectVersion) { lines.push(`databricks-connect: ${result.resolved.dbconnectVersion}`); } const compute = computeLabel(result.compute); @@ -78,7 +89,11 @@ export function formatSetupLog( } lines.push("", "What was done:"); - lines.push(" • Added matching Databricks constraints to pyproject.toml"); + if (constraintsApplied) { + lines.push( + " • Added matching Databricks constraints to pyproject.toml" + ); + } lines.push( ` • Built a new virtual environment with uv sync called ${venvLabel}` ); From cf2540e1b7dc8d163d7f12a51b0a17731d266781 Mon Sep 17 00:00:00 2001 From: Grigory Panov Date: Mon, 14 Sep 2026 15:00:42 +0200 Subject: [PATCH 20/31] feat(telemetry): emit setupPreset on the python_env.setup.result event (#2197) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Why `setupPreset` (full / dbconnect / python) was emitted only on `python_env.setup.attempt`. The `python_env.setup.result` event carries outcome/errorCode but only the legacy two-value `mode`, which can't separate **Full** from **DB Connect** (both report `default`). In `telemetry_refined` there is no run-correlation id and a session produces several attempt/result pairs (initial, rerun, conflict_retry), so splitting provision errors/outcomes by the three-way setup mode via an attempt↔result join is unreliable. ## What Emit `setupPreset` on the result event too — mirrored from the attempt the reporter already closes over — and add it to the `PYTHON_ENV_SETUP_RESULT` schema as an optional field. The standalone `no_compute` result (no attempt) omits it. This makes outcome / recovery split-by-mode a single-event slice, no join. ## Testing - `yarn test:unit` (1148 passing): the result event now carries `event.setupPreset`; `no_compute` still omits it; the schema-allowlist guard test updated to expect the new key. - `yarn test:lint`: clean. ## Reviewer notes - **`telemetryVersion` intentionally left at `1.0`.** The `index.ts` comment asks for a minor bump on additive fields, but that convention hasn't been followed in practice — the attempt event's own `setupPreset` / `trigger` / `isGreenfield` were all added at `1.0` — and the version is global across every event. A lone bump here would be inconsistent and churn every event's version assertion without making the version an accurate schema history. Treated as pre-existing stale convention. - **Only `setupPreset` is mirrored**, one of six attempt-only dimensions. A single run-correlation id on both events would make every dimension joinable and is the more general fix; deferred as a follow-up (higher cardinality, revisits the categorical-only telemetry discipline). ## Follow-up Unblocks the join-free outcome-by-mode / recovery-by-mode dashboard panels on the Deco IDE Usage / VPEX Usage page. This pull request and its description were written by Isaac. Co-authored-by: Isaac --- packages/databricks-vscode/src/telemetry/constants.ts | 9 +++++++++ .../src/telemetry/pythonSetupExtensions.test.ts | 4 ++++ .../src/telemetry/pythonSetupExtensions.ts | 6 ++++++ 3 files changed, 19 insertions(+) diff --git a/packages/databricks-vscode/src/telemetry/constants.ts b/packages/databricks-vscode/src/telemetry/constants.ts index e36223804..d183a1a6c 100644 --- a/packages/databricks-vscode/src/telemetry/constants.ts +++ b/packages/databricks-vscode/src/telemetry/constants.ts @@ -602,6 +602,7 @@ export class EventTypes { }; [Events.PYTHON_ENV_SETUP_RESULT]: EventType<{ outcome: PythonSetupOutcome; + setupPreset?: SetupPreset; pythonSetupFlow?: PythonSetupFlow; failurePhase?: PythonSetupFailurePhase; errorCode?: PythonSetupErrorCode; @@ -631,6 +632,14 @@ export class EventTypes { "ok | failed | cancelled (user aborted) | not_started (the CLI produced no " + "result) | no_compute (the CTA was a dead end: nothing was attached to set up for)", }, + setupPreset: { + comment: + "The preset tier the user picked (full / dbconnect / python), mirrored from the " + + "matching attempt so provision errors and outcomes can be split by setup mode " + + "without joining to python_env.setup.attempt. Present on every result except " + + "no_compute, which is emitted without a preceding attempt. See the attempt " + + "event's setupPreset for the tier semantics", + }, pythonSetupFlow: { comment: "Whether uv downloaded Python, an installed compatible Python was used, " + diff --git a/packages/databricks-vscode/src/telemetry/pythonSetupExtensions.test.ts b/packages/databricks-vscode/src/telemetry/pythonSetupExtensions.test.ts index 641e934f0..526c378b0 100644 --- a/packages/databricks-vscode/src/telemetry/pythonSetupExtensions.test.ts +++ b/packages/databricks-vscode/src/telemetry/pythonSetupExtensions.test.ts @@ -66,6 +66,7 @@ describe(__filename, () => { expect(events[1].props).to.deep.equal({ "version": "1.0", "event.outcome": "ok", + "event.setupPreset": "full", "event.envKey": "serverless/serverless-v5", }); }); @@ -124,6 +125,7 @@ describe(__filename, () => { expect(events[1].props).to.deep.equal({ "version": "1.0", "event.outcome": "cancelled", + "event.setupPreset": "python", }); // The failure mode this guards against: recordEvent stringifies an // explicit undefined, which would pollute the schema. @@ -154,6 +156,7 @@ describe(__filename, () => { expect(events[1].props).to.deep.equal({ "version": "1.0", "event.outcome": "failed", + "event.setupPreset": "full", "event.failurePhase": "provision", "event.errorCode": "E_PROVISION", "event.envKey": "dbr/15.4.x-scala2.12", @@ -442,6 +445,7 @@ describe(__filename, () => { expect(Object.keys(events[1].props).sort()).to.deep.equal([ "event.envKey", "event.outcome", + "event.setupPreset", "version", ]); }); diff --git a/packages/databricks-vscode/src/telemetry/pythonSetupExtensions.ts b/packages/databricks-vscode/src/telemetry/pythonSetupExtensions.ts index 4af52c6cf..609f304d8 100644 --- a/packages/databricks-vscode/src/telemetry/pythonSetupExtensions.ts +++ b/packages/databricks-vscode/src/telemetry/pythonSetupExtensions.ts @@ -309,6 +309,12 @@ Telemetry.prototype.recordPythonSetupAttempt = function ( reported = true; reportResult({ outcome: report.outcome, + // Also stamped on the result (not only the attempt) so provision + // errors and outcomes can be split by setup mode without an + // attempt<->result correlation join. Always present here -- the + // closure captured the attempt; only the standalone no_compute + // result (no attempt) omits it. + setupPreset: attempt.setupPreset, ...(report.pythonSetupFlow !== undefined ? {pythonSetupFlow: report.pythonSetupFlow} : {}), From 484a12b571914b787f578d4ada91a2a461a0546e Mon Sep 17 00:00:00 2001 From: Anton Nekipelov <226657+anton-107@users.noreply.github.com> Date: Tue, 15 Sep 2026 13:00:06 +0200 Subject: [PATCH 21/31] test(ssh): catch bundled CLI truncation and reconnect regressions (#2195) ## Changes Add a regression test to the unit-test suite that exercises the real bundled CLI through the extension's SSH command construction. A localhost HTTP/WebSocket peer replaces workspace provisioning and echoes an 8 MiB payload. Assert complete upload and download, byte equality, successful exit, and a single connection. Checking payload completeness catches CLI 1.16.0's truncated streams even when it exits zero. The test requires no workspace credentials and adds explicit WebSocket test dependencies. The peer advertises resume capability to exercise CLI 1.16.0's affected transport, but does not send ACK control frames. CLI 1.16.1 does not support those frames. A missing bundled binary skips the test locally and fails with a fetch instruction in CI. ## Tests - Revised test: CLI 1.16.0 fails on an incomplete transfer; 1.16.1 and 1.12.1 pass. - Verified missing-binary behavior: one skipped test locally, explicit failure in CI. - Lint, formatting, and diff checks passed for the revised sources. - Previous PR revision passed the full Linux and Windows unit-test jobs, including this regression test. The latest revision awaits fresh CI. - Earlier regression validation also confirmed CLI 1.16.0 fails and 1.16.1 passes on Windows and against extension v2.17.0 source. --- packages/databricks-vscode/package.json | 2 + .../src/ssh/SshCommands.transfer.test.ts | 243 ++++++++++++++++++ .../src/test/sshTunnelTestServer.ts | 124 +++++++++ yarn.lock | 2 + 4 files changed, 371 insertions(+) create mode 100644 packages/databricks-vscode/src/ssh/SshCommands.transfer.test.ts create mode 100644 packages/databricks-vscode/src/test/sshTunnelTestServer.ts diff --git a/packages/databricks-vscode/package.json b/packages/databricks-vscode/package.json index 0e0103cfc..b3245a252 100644 --- a/packages/databricks-vscode/package.json +++ b/packages/databricks-vscode/package.json @@ -1956,6 +1956,7 @@ "@types/tmp": "^0.2.6", "@types/triple-beam": "^1.3.5", "@types/vscode": "1.86.0", + "@types/ws": "^8.5.11", "@types/yargs": "^17.0.32", "@typescript-eslint/eslint-plugin": "^8.62.0", "@typescript-eslint/parser": "^8.62.0", @@ -1985,6 +1986,7 @@ "vsce": "^2.15.0", "wdio-video-reporter": "^6.2.0", "wdio-vscode-service": "^8.0.0", + "ws": "^8.18.0", "yargs": "^17.7.2" }, "nyc": { diff --git a/packages/databricks-vscode/src/ssh/SshCommands.transfer.test.ts b/packages/databricks-vscode/src/ssh/SshCommands.transfer.test.ts new file mode 100644 index 000000000..d7433a536 --- /dev/null +++ b/packages/databricks-vscode/src/ssh/SshCommands.transfer.test.ts @@ -0,0 +1,243 @@ +import assert from "node:assert/strict"; +import {spawn} from "node:child_process"; +import {randomBytes} from "node:crypto"; +import {existsSync} from "node:fs"; +import {mkdtemp, rm, writeFile} from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import {anything, instance, mock, reset, spy, verify, when} from "ts-mockito"; +import {env, EventEmitter, window} from "vscode"; +import type { + ExtensionContext, + QuickPick, + QuickPickItem, + Terminal, + TerminalOptions, +} from "vscode"; +import {CliWrapper} from "../cli/CliWrapper"; +import {ClusterModel} from "../cluster/ClusterModel"; +import {ConnectionManager} from "../configuration/ConnectionManager"; +import {DatabricksWorkspace} from "../configuration/DatabricksWorkspace"; +import type {AuthProvider} from "../configuration/auth/AuthProvider"; +import {LoggerManager} from "../logger"; +import {Cluster} from "../sdk-extensions/Cluster"; +import {createSshTunnelTestServer} from "../test/sshTunnelTestServer"; +import {SshCommands} from "./SshCommands"; + +// Remote VS Code startup transfers several MiB; CLI 1.16.0 cut streams off at 1 MiB. +const PAYLOAD_BYTES = 8 * 1024 * 1024; + +describe("SSH tunnel command transfer", function () { + this.timeout(30_000); + + it("transfers the complete IDE-sized payload through the bundled CLI without reconnecting", async function () { + const context = mock(); + when(context.asAbsolutePath(anything())).thenCall((relative: string) => + path.resolve(__dirname, "../..", relative) + ); + const cli = new CliWrapper( + instance(context), + instance(mock(LoggerManager)) + ); + if (!existsSync(cli.cliPath)) { + assert( + !process.env.CI, + "Bundled CLI missing: run yarn workspace databricks run package:cli:fetch" + ); + this.skip(); + } + const directory = await mkdtemp( + path.join(os.tmpdir(), "ssh-transfer-") + ); + const peer = await createSshTunnelTestServer(); + const accept = new EventEmitter(); + const hide = new EventEmitter(); + const changed = new EventEmitter(); + const windowSpy = spy(window); + const envSpy = spy(env); + const pickerMock = mock>(); + const picker = instance(pickerMock); + let ssh: SshCommands | undefined; + try { + const configFile = path.join(directory, "databrickscfg"); + await writeFile( + configFile, + `[ssh-test]\nhost = ${peer.host}\ntoken = local-test-token\nauth_type = pat\n` + ); + const auth = mock(); + /* eslint-disable @typescript-eslint/naming-convention */ + when(auth.toEnv()).thenReturn({ + DATABRICKS_HOST: peer.host, + DATABRICKS_TOKEN: "local-test-token", + DATABRICKS_AUTH_TYPE: "pat", + DATABRICKS_CONFIG_PROFILE: "ssh-test", + DATABRICKS_CONFIG_FILE: configFile, + }); + /* eslint-enable @typescript-eslint/naming-convention */ + const workspace = mock(DatabricksWorkspace); + when(workspace.authProvider).thenReturn(instance(auth)); + when(workspace.userName).thenReturn("ssh-test"); + const connection = mock(ConnectionManager); + when(connection.isInitialized).thenReturn(true); + when(connection.state).thenReturn("CONNECTED"); + when(connection.databricksWorkspace).thenReturn( + instance(workspace) + ); + const cluster = mock(Cluster); + when(cluster.id).thenReturn("test-cluster"); + when(cluster.name).thenReturn("Test cluster"); + when(cluster.state).thenReturn("RUNNING"); + when(cluster.isValidSingleUser("ssh-test")).thenReturn(true); + const clusters = mock(ClusterModel); + when(clusters.allRoots).thenReturn([instance(cluster)]); + when(clusters.onDidChange).thenReturn(changed.event); + + when(pickerMock.onDidAccept).thenReturn(accept.event); + when(pickerMock.onDidHide).thenReturn(hide.event); + let disposed = false; + when(pickerMock.dispose()).thenCall(() => { + if (!disposed) { + disposed = true; + hide.fire(); + } + }); + const shown = new Promise((resolve) => { + when(pickerMock.show()).thenCall(resolve); + }); + when(windowSpy.createQuickPick()).thenReturn(picker); + when(windowSpy.showErrorMessage(anything())).thenResolve(undefined); + when( + windowSpy.showWarningMessage(anything(), anything()) + ).thenResolve(undefined); + const terminal = mock(); + let command: string | undefined; + let terminalOptions: TerminalOptions | undefined; + when(terminal.sendText(anything())).thenCall((value: string) => { + command = value; + }); + when(windowSpy.createTerminal(anything())).thenCall( + (value: TerminalOptions) => { + terminalOptions = value; + return instance(terminal); + } + ); + const shell = process.platform === "win32" ? "cmd.exe" : "/bin/sh"; + when(envSpy.shell).thenReturn(shell); + ssh = new SshCommands( + cli, + instance(connection), + instance(clusters) + ); + const started = ssh.startTunnelCommand(); + await shown; + const selected = picker.items.find((item) => "cluster" in item); + assert.ok( + selected, + "the compute picker must offer the test cluster" + ); + picker.selectedItems = [selected]; + accept.fire(); + await started; + verify(windowSpy.showErrorMessage(anything())).never(); + verify(terminal.sendText(anything())).once(); + assert.ok(command, "accepting compute must launch the CLI"); + assert.ok(terminalOptions); + + // Enter the same ProxyCommand path Remote SSH uses after provisioning. + // Only cloud setup and the remote peer are replaced; the bundled CLI is real. + command += + " --proxy --metadata=ssh-test,7772,test-cluster --profile=ssh-test"; + const batch = path.join(directory, "launch.cmd"); + await writeFile(batch, `@echo off\r\n${command}\r\n`); + const shellArgs = + process.platform === "win32" + ? ["/d", "/c", batch] + : ["-c", command]; + const inherited = Object.fromEntries( + Object.entries(process.env).filter( + ([key]) => + !key.startsWith("DATABRICKS_") && + !key.toLowerCase().includes("proxy") + ) + ); + /* eslint-disable @typescript-eslint/naming-convention */ + const child = spawn(shell, shellArgs, { + cwd: directory, + detached: process.platform !== "win32", + env: { + ...inherited, + ...terminalOptions.env, + HOME: directory, + USERPROFILE: directory, + LOCALAPPDATA: path.join(directory, "local-app-data"), + APPDATA: path.join(directory, "app-data"), + XDG_CACHE_HOME: path.join(directory, "cache"), + NO_PROXY: "127.0.0.1", + } as NodeJS.ProcessEnv, + }); + /* eslint-enable @typescript-eslint/naming-convention */ + const payload = randomBytes(PAYLOAD_BYTES); + const output: Buffer[] = []; + let outputBytes = 0; + let stderr = ""; + child.stdin.on("error", () => {}); + child.stderr.on("data", (data: Buffer) => { + stderr = (stderr + data).slice(-16_384); + }); + child.stdout.on("data", (data: Buffer) => { + output.push(data); + outputBytes += data.length; + if (outputBytes >= payload.length) { + child.stdin.end(); + } + }); + const closed = new Promise<{ + code: number | null; + signal: NodeJS.Signals | null; + }>((resolve, reject) => { + child.once("error", reject); + child.once("close", (code, signal) => resolve({code, signal})); + }); + const timeout = setTimeout(() => { + if (!child.pid) { + return; + } + if (process.platform === "win32") { + spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { + stdio: "ignore", + }).on("error", () => child.kill("SIGKILL")); + } else { + process.kill(-child.pid, "SIGKILL"); + } + }, 20_000); + child.stdin.write(payload); + const result = await closed.finally(() => clearTimeout(timeout)); + const diagnostic = `CLI exit=${result.code}, signal=${result.signal}; uploaded=${peer.receivedBytes}, downloaded=${outputBytes}, expected=${PAYLOAD_BYTES}\n${stderr}`; + // The regressed CLI can exit successfully after truncating the stream. + assert.equal(peer.receivedBytes, PAYLOAD_BYTES, diagnostic); + assert.equal(outputBytes, PAYLOAD_BYTES, diagnostic); + assert.ok( + Buffer.concat(output).equals(payload), + "tunnel payload was corrupted" + ); + assert.equal(result.code, 0, diagnostic); + assert.equal(peer.connections, 1, "transfer must not reconnect"); + assert.deepEqual(peer.unexpectedRequests, []); + } finally { + picker.dispose(); + ssh?.dispose(); + reset(windowSpy); + reset(envSpy); + accept.dispose(); + hide.dispose(); + changed.dispose(); + await peer.dispose(); + await rm(directory, { + recursive: true, + force: true, + maxRetries: 5, + retryDelay: 200, + }); + } + }); +}); diff --git a/packages/databricks-vscode/src/test/sshTunnelTestServer.ts b/packages/databricks-vscode/src/test/sshTunnelTestServer.ts new file mode 100644 index 000000000..3bb873bce --- /dev/null +++ b/packages/databricks-vscode/src/test/sshTunnelTestServer.ts @@ -0,0 +1,124 @@ +import {generateKeyPairSync} from "node:crypto"; +import {createServer} from "node:http"; +import type {AddressInfo} from "node:net"; +import {WebSocketServer} from "ws"; + +/** Local workspace/driver-proxy peer; the CLI's byte-stream transport stays real. */ +export async function createSshTunnelTestServer() { + const {privateKey, publicKey} = generateKeyPairSync("ed25519"); + const rawPublicKey = publicKey + .export({type: "spki", format: "der"}) + .subarray(-32); + const sshString = (value: Buffer) => { + const length = Buffer.alloc(4); + length.writeUInt32BE(value.length); + return Buffer.concat([length, value]); + }; + const authorizedKey = `ssh-ed25519 ${Buffer.concat([ + sshString(Buffer.from("ssh-ed25519")), + sshString(rawPublicKey), + ]).toString("base64")}`; + const unexpectedRequests: string[] = []; + let receivedBytes = 0; + let connections = 0; + + const server = createServer((request, response) => { + const url = new URL(request.url!, "http://localhost"); + let body: unknown; + /* eslint-disable @typescript-eslint/naming-convention */ + switch (url.pathname) { + case "/.well-known/databricks-config": + response.statusCode = 404; + body = {}; + break; + case "/api/2.0/preview/scim/v2/Me": + body = {userName: "ssh-test", id: "1"}; + break; + case "/api/2.0/clusters/get": + case "/api/2.1/clusters/get": + body = { + cluster_id: "test-cluster", + state: "RUNNING", + data_security_mode: "SINGLE_USER", + single_user_name: "ssh-test", + }; + break; + case "/api/2.0/secrets/list": + body = {secrets: []}; + break; + case "/api/2.0/secrets/get": { + const value = + url.searchParams.get("key") === "client-private-key" + ? privateKey.export({type: "pkcs8", format: "pem"}) + : authorizedKey; + body = {value: Buffer.from(value).toString("base64")}; + break; + } + case "/telemetry-ext": + body = {}; + break; + case "/driver-proxy-api/o/1/test-cluster/7772/capabilities": + body = {resume: true}; + break; + default: + unexpectedRequests.push(`${request.method} ${url.pathname}`); + response.statusCode = 404; + body = { + error_code: "NOT_FOUND", + message: "Unexpected test request", + }; + } + /* eslint-enable @typescript-eslint/naming-convention */ + response.setHeader("Content-Type", "application/json"); + response.setHeader("X-Databricks-Org-Id", "1"); + response.end(JSON.stringify(body)); + }); + const sockets = new WebSocketServer({server}); + sockets.on("connection", (socket, request) => { + connections++; + const url = new URL(request.url!, "http://localhost"); + if (url.pathname !== "/driver-proxy-api/o/1/test-cluster/7772/ssh") { + unexpectedRequests.push(`WebSocket ${url.pathname}`); + } + if (request.headers.authorization !== "Bearer local-test-token") { + unexpectedRequests.push("WebSocket auth was not forwarded"); + } + socket.on("error", (error) => + unexpectedRequests.push(`WebSocket error: ${error.message}`) + ); + socket.on("message", (data, binary) => { + if (!binary) { + return; + } + const bytes = Buffer.isBuffer(data) + ? data + : Array.isArray(data) + ? Buffer.concat(data) + : Buffer.from(data); + receivedBytes += bytes.length; + socket.send(bytes, {binary: true}); + }); + }); + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", resolve); + }); + return { + host: `http://127.0.0.1:${(server.address() as AddressInfo).port}`, + unexpectedRequests, + get receivedBytes() { + return receivedBytes; + }, + get connections() { + return connections; + }, + async dispose() { + sockets.clients.forEach((socket) => socket.terminate()); + sockets.close(); + server.closeAllConnections(); + await new Promise((resolve, reject) => + server.close((error) => (error ? reject(error) : resolve())) + ); + }, + }; +} diff --git a/yarn.lock b/yarn.lock index 1eaad58ac..14458c33b 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4060,6 +4060,7 @@ __metadata: "@types/tmp": ^0.2.6 "@types/triple-beam": ^1.3.5 "@types/vscode": 1.86.0 + "@types/ws": ^8.5.11 "@types/yargs": ^17.0.32 "@typescript-eslint/eslint-plugin": ^8.62.0 "@typescript-eslint/parser": ^8.62.0 @@ -4105,6 +4106,7 @@ __metadata: wdio-video-reporter: ^6.2.0 wdio-vscode-service: ^8.0.0 winston: ^3.11.0 + ws: ^8.18.0 yaml: ^2.8.3 yargs: ^17.7.2 dependenciesMeta: From d2158c0555432b7f6d23612a70d8637205bbaa3e Mon Sep 17 00:00:00 2001 From: Anton Nekipelov <226657+anton-107@users.noreply.github.com> Date: Tue, 15 Sep 2026 14:17:26 +0200 Subject: [PATCH 22/31] docs: explain local CLI preview in the extension (#2196) ## Changes Document how to preview a locally built Databricks CLI in the development VS Code extension, and link the guide from the README. Cover the bundled binary override, rebuild/reload steps, matching SSH client and server snapshots, upload caching, and restoring the pinned CLI. ## Tests Documentation only. `yarn fix` passed; checked the six shell examples with `bash -n`, verified the documentation anchors, and ran `git diff --check`. Commands were checked against the CLI and extension build scripts. --- CONTRIBUTING.md | 114 ++++++++++++++++++++++++++++++++++++++++++++++++ README.md | 3 ++ 2 files changed, 117 insertions(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 44e661d6f..fa884c619 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -57,6 +57,120 @@ incremental rebuilds while you work: yarn workspace databricks run watch ``` +### Previewing local CLI changes + +The extension runs the CLI bundled at +`packages/databricks-vscode/bin/databricks` (`databricks.exe` on Windows). +Installing a different CLI on your `PATH` does not change this binary. You can +replace it locally without changing `cli.version` in `package.json`; `bin/` is +gitignored. Use a separate extension checkout or worktree if you also need to +develop against the pinned CLI. + +The following commands use a macOS/Linux shell. Check out the CLI branch you want +to test in a sibling [CLI repository](https://github.com/databricks/cli), with its +build prerequisites installed: + +```text +parent/ +├── cli/ # CLI source; ./task build produces cli/cli +└── databricks-vscode/ # this repository +``` + +From this repository's root, build and link the CLI: + +```sh +(cd ../cli && ./task build) +yarn workspace databricks run package:cli:link +./packages/databricks-vscode/bin/databricks version +``` + +`package:cli:link` replaces the bundled binary with a symlink to `../cli/cli`. +For another directory layout, create a symlink to your CLI checkout's built +binary instead. On Windows, copy the built executable to +`packages/databricks-vscode/bin/databricks.exe`. Remove any previous symlink +before copying a binary so the copy does not overwrite its target. + +Build the extension and launch its development host from this repository's root +(`code` must be available on your `PATH`): + +```sh +yarn build +code --new-window --extensionDevelopmentPath "$PWD/packages/databricks-vscode" +``` + +Exercise the extension action affected by your CLI change. For SSH, complete the +[client and server setup below](#previewing-ssh-client-and-server-changes) before +using **Databricks → Start SSH tunnel**. Check that the **Databricks SSH Tunnel** +terminal invokes the CLI in this checkout's `bin/` directory. + +After editing CLI code, rebuild the CLI and reload the Extension Development Host +with **Developer: Reload Window**. A symlink picks up the rebuilt binary; a copied +binary must be copied again. Restart existing CLI commands or SSH connections to +use the new build. Rebuild the extension only if its source also changed. + +The development host's bundled-CLI version warning is expected when deliberately +testing a different version. Do not run `package:cli:fetch` during the preview: +it replaces your local override with the pinned release. Commands that invoke it, +such as `package:bundle-schema:write`, also replace the override. + +#### Previewing SSH client and server changes + +SSH uses a local client and a Linux server uploaded to the workspace. `./task build` +only builds the local CLI; use `./task snapshot-release` to build the Linux server +archives. This requires the CLI repository's GoReleaser setup. + +Set the absolute CLI checkout path, then build the snapshot: + +```sh +CLI_CHECKOUT=/absolute/path/to/cli +(cd "$CLI_CHECKOUT" && ./task snapshot-release) +``` + +Before using the extension's SSH action, connect once with `--releases-dir` to +upload the snapshot's server binaries. The client built and linked above can be +used for this command. Choose an authenticated workspace profile explicitly. This +command starts a serverless SSH job and runs a smoke command: + +```sh +CLI_PROFILE=your-profile +./packages/databricks-vscode/bin/databricks ssh connect \ + --profile "$CLI_PROFILE" \ + --name cli-preview \ + --releases-dir "$CLI_CHECKOUT/dist" \ + --server-timeout 1h \ + --shutdown-delay 5m \ + -- 'echo CLI_PREVIEW_OK' +``` + +For dedicated compute, replace `--name cli-preview` with +`--cluster --auto-start-cluster`, using a dedicated single-user +cluster assigned to you. Then reload the development host and use **Start SSH +tunnel**, selecting that workspace/profile and compute. The extension does not +pass `--releases-dir`; it reuses the uploaded binaries for the bundled CLI's +version. Repeat the upload step for each workspace you test. + +Server uploads are cached by CLI version. Rebuilding uncommitted changes can keep +the same version and silently reuse an earlier server binary, even with a new +`--name`. For another server revision, create a new local CLI commit, run +`./task --force snapshot-release`, rebuild the linked client, and repeat the upload +step. Stop the previous preview's SSH job so a running server is not reused. + +If you launch VS Code with a custom `--user-data-dir`, also copy the Remote-SSH +settings the CLI adds to your normal VS Code user settings into that profile's +`User/settings.json`. These include `remote.SSH.remoteServerListenOnSocket`, the +host entries in `remote.SSH.remotePlatform` and +`remote.SSH.serverPickPortsFromRange`, and `remote.SSH.defaultExtensions`. + +#### Restoring the pinned CLI + +If you tested SSH, close the remote windows, cancel the preview job runs shown by +the CLI, and stop any dedicated compute you started. Restore the extension's +pinned CLI from this repository's root, then reload the development host: + +```sh +yarn workspace databricks run package:cli:fetch +``` + ## Testing Run the full check (lint + unit tests) across all workspaces from the repo root: diff --git a/README.md b/README.md index 836bb5791..93156b342 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,9 @@ yarn workspace databricks run package:cli:fetch After that you are ready to build and test the `databricks-vscode` extension. +To test changes from a local CLI checkout in the extension, see +[Previewing local CLI changes](CONTRIBUTING.md#previewing-local-cli-changes). + ### Found an issue? If you find an issue/bug or have a feature request, please file an issue here: https://github.com/databricks/databricks-vscode/issues/new From f1ad46a5095967cba74eff68092914a7c7417164 Mon Sep 17 00:00:00 2001 From: Anton Nekipelov <226657+anton-107@users.noreply.github.com> Date: Tue, 15 Sep 2026 16:29:03 +0200 Subject: [PATCH 23/31] test(e2e): verify serverless SSH remote window and file transfers (#2194) ## Changes Add a real-workspace serverless SSH end-to-end test. It invokes the extension's tunnel command, switches to the new Remote SSH window, dismisses onboarding, opens a file from Explorer, and checks the editor content. A small test extension verifies three complete 8 MiB remote file round trips with gaps between them and removes the test files afterward. Only the SSH spec uses a current VS Code release for Remote SSH compatibility; existing specs retain the extension's minimum supported editor version. The `.ucws.e2e.ts` suffix selects the existing serverless CI workspace credentials. Running this spec alone does not start a dedicated cluster. Remote SSH installs through the existing vendored-VSIX mechanism; its optional extension pack is excluded. Include an isolated local runner with explicit OAuth-profile support and WebdriverIO 9 executable resolution, generic single-spec documentation, and a packaging fix that preserves local package.json edits. The view-title lookup handles missing and empty title attributes in newer VS Code versions. ## Tests - Latest local serverless run passed: 1 test in 2m18s, including Explorer/editor assertions and all three large transfers, using the original Remote SSH 0.128.0 VSIX. - Verified the original Remote SSH package installs offline without its optional extension pack. - Lint, formatting, and diff checks passed for the changed test sources. - Validated full-suite, single-spec, mixed-spec, and glob routing with WebdriverIO 9.29.0: every selected spec runs once with the intended editor version. - CI validation is in progress. The serverless workspace rejects SSH port 7772 with `PERMISSION_DENIED: Traffic on this port is not permitted`, before the remote window opens. CI also needs Remote SSH available in its existing EXTENSION_VSIX_DIR. --------- Co-authored-by: Isaac --- CONTRIBUTING.md | 51 +++ packages/databricks-vscode/package.json | 3 +- .../scripts/list_integration_tests.ts | 5 + .../databricks-vscode/scripts/package-vsix.sh | 9 +- .../databricks-vscode/scripts/run-e2e.mjs | 162 ++++++++ .../e2e/resources/ssh-test-probe/extension.js | 163 ++++++++ .../e2e/resources/ssh-test-probe/package.json | 15 + .../src/test/e2e/ssh_connection.ucws.e2e.ts | 242 ++++++++++++ .../src/test/e2e/tsconfig.json | 1 + .../src/test/e2e/utils/commonUtils.ts | 4 +- .../src/test/e2e/utils/sshE2eUtils.ts | 65 ++++ .../src/test/e2e/wdio.conf.ts | 358 ++++++++++++------ 12 files changed, 965 insertions(+), 113 deletions(-) create mode 100644 packages/databricks-vscode/scripts/run-e2e.mjs create mode 100644 packages/databricks-vscode/src/test/e2e/resources/ssh-test-probe/extension.js create mode 100644 packages/databricks-vscode/src/test/e2e/resources/ssh-test-probe/package.json create mode 100644 packages/databricks-vscode/src/test/e2e/ssh_connection.ucws.e2e.ts create mode 100644 packages/databricks-vscode/src/test/e2e/utils/sshE2eUtils.ts diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fa884c619..09af24507 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -235,6 +235,57 @@ at an existing profile (for example `export DATABRICKS_CONFIG_PROFILE=DEFAULT`); also build a `.vsix` package as part of `test:integ:prepare`, so make sure you have run `yarn build` first. +### Running one end-to-end spec + +After `yarn build` and `yarn workspace databricks run test:integ:prepare`, use +`test:integ:run` to run a selected file. Replace the example path with any +`.e2e.ts` spec: + +```sh +yarn workspace databricks run test:integ:run \ + --spec src/test/e2e/auth.e2e.ts +``` + +For a local OAuth login, add `--profile `; the runner obtains a token from +that CLI profile. In CI, it uses the existing credential environment. Use +`test:integ:extension` instead to rebuild the test VSIX before running. + +To use an existing VS Code installation and locally downloaded extension VSIXs +(for example, when marketplace downloads fail), run: + +```sh +VSCODE_TEST_VERSION='' \ +VSCODE_TEST_BINARY='/absolute/path/to/Visual Studio Code.app/Contents/MacOS/Code' \ +EXTENSION_VSIX_DIR='/absolute/path/to/extension-vsixs' \ +yarn workspace databricks run test:integ:run \ + --profile \ + --spec src/test/e2e/auth.e2e.ts +``` + +Replace the placeholders with your local values and keep the quoted binary path +on one line. Without these overrides, the runner downloads VS Code and extensions. + +### Running the SSH spec + +`src/test/e2e/ssh_connection.ucws.e2e.ts` opens a real Remote SSH window over a +serverless tunnel, so it needs more than the other specs: a workspace that offers +Serverless SSH compute, a tunnel port that workspace permits, and an installable +`ms-vscode-remote.remote-ssh` (from the marketplace, or vendored into +`EXTENSION_VSIX_DIR`). It is therefore opt-in and is excluded from every run that +does not ask for it: + +```sh +TEST_SSH_E2E=true \ +yarn workspace databricks run test:integ:run \ + --profile \ + --spec src/test/e2e/ssh_connection.ucws.e2e.ts +``` + +With the flag set nothing is skipped: a Remote SSH that will not install fails +the run rather than reporting success with no SSH coverage. This spec also runs +on a current VS Code release rather than the extension's minimum supported +version, because Remote SSH requires one. + ## Code style Formatting and linting are enforced by prettier and eslint. Auto-fix diff --git a/packages/databricks-vscode/package.json b/packages/databricks-vscode/package.json index b3245a252..4d82b39e5 100644 --- a/packages/databricks-vscode/package.json +++ b/packages/databricks-vscode/package.json @@ -1910,7 +1910,8 @@ "test:unit": "yarn run build && node ./out/test/runTest.js", "test:python": "DATABRICKS_EXTENSION_UNIT_TESTS=1 python -B -m unittest discover -s ./src/test/python -p '*_test.py'", "test:integ:prepare": "./scripts/package-vsix-tests.sh", - "test:integ:extension": "yarn run test:integ:prepare && wdio run src/test/e2e/wdio.conf.ts --tsConfigPath src/test/e2e/tsconfig.json", + "test:integ:run": "node ./scripts/run-e2e.mjs", + "test:integ:extension": "yarn run test:integ:prepare && node ./scripts/run-e2e.mjs", "test:integ:sdk": "ts-mocha --type-check 'src/sdk-extensions/**/*.integ.ts'", "test:integ": "yarn run test:integ:extension && yarn run test:integ:sdk", "test:cov": "nyc yarn run test:unit", diff --git a/packages/databricks-vscode/scripts/list_integration_tests.ts b/packages/databricks-vscode/scripts/list_integration_tests.ts index 6a5bdaa74..e4469ab46 100644 --- a/packages/databricks-vscode/scripts/list_integration_tests.ts +++ b/packages/databricks-vscode/scripts/list_integration_tests.ts @@ -17,6 +17,11 @@ const integrationTests = glob nocase: process.platform === "win32", } ) + .filter( + (testPath) => + process.env.TEST_SSH_E2E === "true" || + path.basename(testPath) !== "ssh_connection.ucws.e2e.ts" + ) .map((testPath) => { return { path: toUnixPath(path.relative(process.cwd(), testPath)), diff --git a/packages/databricks-vscode/scripts/package-vsix.sh b/packages/databricks-vscode/scripts/package-vsix.sh index 088e35ea8..0ec00a853 100755 --- a/packages/databricks-vscode/scripts/package-vsix.sh +++ b/packages/databricks-vscode/scripts/package-vsix.sh @@ -5,6 +5,11 @@ set -ex # get path of the script cd $(dirname $(realpath $0))/.. +# Packaging temporarily edits metadata; preserve the caller's uncommitted changes. +PACKAGE_BACKUP=$(mktemp) +cp package.json "$PACKAGE_BACKUP" +trap 'cp "$PACKAGE_BACKUP" package.json; rm -f "$PACKAGE_BACKUP"' EXIT + ARCH=$1 case $ARCH in @@ -67,7 +72,3 @@ case $ARCH in esac TAG="release-v$(cat package.json | jq -r .version)" yarn run package -t $VSXI_ARCH - -git checkout -- package.json - - diff --git a/packages/databricks-vscode/scripts/run-e2e.mjs b/packages/databricks-vscode/scripts/run-e2e.mjs new file mode 100644 index 000000000..fe7069570 --- /dev/null +++ b/packages/databricks-vscode/scripts/run-e2e.mjs @@ -0,0 +1,162 @@ +import {execFileSync, spawn} from "node:child_process"; +import {existsSync, mkdtempSync, rmSync} from "node:fs"; +import {createRequire} from "node:module"; +import os from "node:os"; +import path from "node:path"; +import {fileURLToPath} from "node:url"; + +const require = createRequire(import.meta.url); +const packageRoot = path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + ".." +); +const args = process.argv.slice(2); +const profileIndex = args.indexOf("--profile"); +const profile = profileIndex < 0 ? undefined : args[profileIndex + 1]; +if (profileIndex >= 0) { + if (!profile || profile.startsWith("--")) { + throw new Error("--profile requires a Databricks profile name"); + } + args.splice(profileIndex, 2); +} + +const env = {...process.env}; +env.PATH = `${path.dirname(process.execPath)}${path.delimiter}${ + env.PATH || "" +}`; +// Only a root this script minted is ours to delete: a caller-supplied +// TEST_E2E_ROOT, and CI's unset one, are left alone. +const ownsTestRoot = !env.CI && !env.TEST_E2E_ROOT; +if (ownsTestRoot) { + env.TEST_E2E_ROOT = mkdtempSync(path.join(os.tmpdir(), "vscode-e2e-")); + // A run leaves a .databrickscfg holding a token or client secret under + // test-root, plus a few hundred MiB of editor and extension data, and + // nothing else removes them. Keep logs/ — that's why you run this locally. + process.on("exit", () => { + for (const dir of ["test-root", "user-data-dir", "extension test"]) { + rmSync(path.join(env.TEST_E2E_ROOT, dir), { + recursive: true, + force: true, + }); + } + }); +} + +// A fresh clone has only the package-local CLI (bin/ is gitignored, filled in by +// `package:cli:fetch`); a bare `databricks` may be absent or another version. +const cliBinary = path.join( + packageRoot, + "bin", + process.platform === "win32" ? "databricks.exe" : "databricks" +); +const cli = existsSync(cliBinary) ? cliBinary : "databricks"; + +function cliJson(cliArgs) { + let stdout; + try { + stdout = execFileSync(cli, cliArgs, { + encoding: "utf8", + timeout: 30_000, + stdio: ["ignore", "pipe", "pipe"], + }); + } catch (error) { + // Never include the captured output in these messages: `auth token` + // prints an access token. + if (error.code === "ENOENT") { + throw new Error( + `Cannot run the Databricks CLI at '${cli}'. Run yarn workspace databricks run package:cli:fetch and retry.` + ); + } + if (error.signal || error.code === "ETIMEDOUT") { + throw new Error( + `The Databricks CLI did not finish within 30s while resolving profile '${profile}'.` + ); + } + throw new Error( + `Cannot resolve profile '${profile}'. Run databricks auth login --profile ${profile} and retry.` + ); + } + try { + return JSON.parse(stdout); + } catch { + throw new Error( + `The Databricks CLI did not return JSON while resolving profile '${profile}'.` + ); + } +} + +if (profile) { + const description = cliJson([ + "auth", + "describe", + "--profile", + profile, + "--output", + "json", + ]); + const token = cliJson(["auth", "token", "--profile", profile]); + if (!description.details?.host || !token.access_token) { + throw new Error( + "The selected profile did not return a workspace host and access token" + ); + } + for (const key of Object.keys(env)) { + if (key.startsWith("DATABRICKS_")) { + delete env[key]; + } + } + env.DATABRICKS_HOST = description.details.host; + env.DATABRICKS_TOKEN = token.access_token; + env.DATABRICKS_AUTH_TYPE = "pat"; +} + +if ( + !env.DATABRICKS_CONFIG_PROFILE && + (!env.DATABRICKS_HOST || + !( + env.DATABRICKS_TOKEN || + (env.DATABRICKS_CLIENT_ID && env.DATABRICKS_CLIENT_SECRET) + )) +) { + throw new Error( + "Pass --profile for a local OAuth login, or set DATABRICKS_HOST and PAT/OAuth M2M credentials as in CI." + ); +} + +console.log(`E2E logs: ${env.TEST_E2E_ROOT || packageRoot}/logs`); +// WDIO 9 exports its entry point but keeps package.json private. +let runnerRoot = path.dirname(require.resolve("@wdio/cli")); +while (!existsSync(path.join(runnerRoot, "bin", "wdio.js"))) { + const parent = path.dirname(runnerRoot); + if (parent === runnerRoot) { + throw new Error("Cannot locate the WebdriverIO CLI executable"); + } + runnerRoot = parent; +} +const runner = path.join(runnerRoot, "bin", "wdio.js"); +const child = spawn( + process.execPath, + [ + runner, + "run", + "src/test/e2e/wdio.conf.ts", + "--tsConfigPath", + "src/test/e2e/tsconfig.json", + ...args, + ], + { + cwd: packageRoot, + env, + stdio: "inherit", + } +); +child.on("error", (error) => { + console.error(error.message); + process.exitCode = 1; +}); +child.on("exit", (code) => { + process.exitCode = code ?? 1; +}); +for (const signal of ["SIGINT", "SIGTERM"]) { + process.on(signal, () => child.kill(signal)); +} diff --git a/packages/databricks-vscode/src/test/e2e/resources/ssh-test-probe/extension.js b/packages/databricks-vscode/src/test/e2e/resources/ssh-test-probe/extension.js new file mode 100644 index 000000000..8ec8cb4fd --- /dev/null +++ b/packages/databricks-vscode/src/test/e2e/resources/ssh-test-probe/extension.js @@ -0,0 +1,163 @@ +const vscode = require("vscode"); +const fs = require("node:fs/promises"); +const {randomBytes, randomUUID, createHash} = require("node:crypto"); + +// A remote call that never settles would hang this probe past every wait the +// spec has, leaving the remote window and tunnel open with nothing left to close +// them. Bound each one so a stuck call still reaches the report and closeWindow +// below. Generous: a healthy 8 MiB round trip takes seconds. +const OP_TIMEOUT_MS = 60_000; + +async function withTimeout(operation, label) { + const seconds = OP_TIMEOUT_MS / 1000; + let timer; + const expiry = new Promise((resolve, reject) => { + timer = setTimeout(() => { + reject(new Error(`${label} did not finish within ${seconds}s`)); + }, OP_TIMEOUT_MS); + }); + try { + return await Promise.race([operation, expiry]); + } finally { + clearTimeout(timer); + } +} + +// UI placement keeps node:fs local; workspace.fs crosses the real SSH connection. +exports.activate = async function () { + const resultPath = process.env.TEST_SSH_RESULT_PATH; + if (!resultPath || vscode.env.remoteName !== "ssh-remote") { + return; + } + const report = async (result) => { + await fs.writeFile(`${resultPath}.tmp`, JSON.stringify(result)); + await fs.rename(`${resultPath}.tmp`, resultPath); + }; + let folder = vscode.workspace.workspaceFolders?.[0]; + const deadline = Date.now() + 60_000; + while ( + (!folder || folder.uri.scheme !== "vscode-remote") && + Date.now() < deadline + ) { + await report({ + phase: "waiting-for-folder", + folders: vscode.workspace.workspaceFolders?.map((f) => + f.uri.toString() + ), + }); + await new Promise((resolve) => setTimeout(resolve, 1000)); + folder = vscode.workspace.workspaceFolders?.[0]; + } + if (!folder || folder.uri.scheme !== "vscode-remote") { + await report({ + error: `SSH window has no remote workspace folder: ${JSON.stringify( + vscode.workspace.workspaceFolders?.map((f) => f.uri.toString()) + )}`, + }); + await vscode.commands.executeCommand("workbench.action.closeWindow"); + return; + } + const file = folder.uri.with({ + path: `/tmp/vscode-ssh-test-${randomUUID()}`, + }); + const textFile = file.with({path: `${file.path}.txt`}); + const editorText = `Remote SSH editor check ${randomUUID()}`; + const hash = (bytes) => createHash("sha256").update(bytes).digest("hex"); + const payload = randomBytes(8 * 1024 * 1024); + const expectedHash = hash(payload); + let failure; + try { + await report({phase: "connected", authority: folder.uri.authority}); + for (let round = 0; round < 3; round++) { + await withTimeout( + vscode.workspace.fs.writeFile(file, payload), + `Remote write ${round + 1}` + ); + const returned = await withTimeout( + vscode.workspace.fs.readFile(file), + `Remote read ${round + 1}` + ); + if ( + returned.length !== payload.length || + hash(returned) !== expectedHash + ) { + throw new Error( + `Remote transfer ${round + 1} was truncated or corrupted` + ); + } + await report({phase: "transferring", completedRounds: round + 1}); + if (round < 2) { + await new Promise((resolve) => setTimeout(resolve, 15_000)); + } + } + await withTimeout( + vscode.workspace.fs.writeFile(textFile, Buffer.from(editorText)), + "Remote write of the editor file" + ); + await withTimeout( + vscode.commands.executeCommand("revealInExplorer", textFile), + "revealInExplorer" + ); + await report({ + phase: "ui-ready", + fileName: textFile.path.split("/").pop(), + editorText, + authority: folder.uri.authority, + }); + const uiDeadline = Date.now() + 120_000; + while (true) { + try { + const outcome = await fs.readFile( + `${resultPath}.ui-complete`, + "utf8" + ); + if (outcome !== "passed") { + throw new Error("Remote Explorer/editor UI check failed"); + } + break; + } catch (error) { + if (error.code !== "ENOENT") { + throw error; + } + if (Date.now() >= uiDeadline) { + throw new Error( + "Remote Explorer/editor UI check timed out" + ); + } + await new Promise((resolve) => setTimeout(resolve, 250)); + } + } + } catch (error) { + failure = String(error); + } finally { + try { + await withTimeout( + vscode.workspace.fs.delete(file), + "Remote delete of the payload file" + ); + try { + await withTimeout( + vscode.workspace.fs.delete(textFile), + "Remote delete of the editor file" + ); + } catch (error) { + if (error.code !== "FileNotFound") { + throw error; + } + } + } catch (error) { + failure ??= `Remote file cleanup failed: ${error}`; + } + } + await report( + failure + ? {error: failure} + : { + phase: "passed", + bytesPerRound: payload.length, + completedRounds: 3, + authority: folder.uri.authority, + } + ); + await vscode.commands.executeCommand("workbench.action.closeWindow"); +}; diff --git a/packages/databricks-vscode/src/test/e2e/resources/ssh-test-probe/package.json b/packages/databricks-vscode/src/test/e2e/resources/ssh-test-probe/package.json new file mode 100644 index 000000000..f9f9edc32 --- /dev/null +++ b/packages/databricks-vscode/src/test/e2e/resources/ssh-test-probe/package.json @@ -0,0 +1,15 @@ +{ + "name": "ssh-test-probe", + "publisher": "vscode-tests", + "version": "0.0.1", + "engines": { + "vscode": "^1.95.0" + }, + "activationEvents": [ + "onStartupFinished" + ], + "extensionKind": [ + "ui" + ], + "main": "./extension.js" +} diff --git a/packages/databricks-vscode/src/test/e2e/ssh_connection.ucws.e2e.ts b/packages/databricks-vscode/src/test/e2e/ssh_connection.ucws.e2e.ts new file mode 100644 index 000000000..230990d24 --- /dev/null +++ b/packages/databricks-vscode/src/test/e2e/ssh_connection.ucws.e2e.ts @@ -0,0 +1,242 @@ +import assert from "node:assert/strict"; +import fs from "node:fs/promises"; +import path from "node:path"; +import { + dismissNotifications, + getUniqueResourceName, + waitForInput, + waitForLogin, +} from "./utils/commonUtils.ts"; +import {writeRootBundleConfig} from "./utils/dabsFixtures.ts"; + +describe("Remote SSH connection", function () { + // Above the sum of the waits below, so a slow but progressing run is + // reported by the wait that stalled — with its targeted timeoutMsg — and + // still runs the cleanup in the `finally`. Budget: login 120 + input 10 + + // picker 30 + window 180 + probe 480 + explorer 30 + editor 30 + close 30 + + // probe cleanup 30 = 940s. + this.timeout(18 * 60_000); + + it("opens a real remote window and preserves large transfers over time", async function () { + const root = process.env.WORKSPACE_PATH; + const resultPath = process.env.TEST_SSH_RESULT_PATH; + assert( + root && process.env.DATABRICKS_HOST && resultPath, + "SSH e2e runner configuration is missing" + ); + await dismissNotifications(); + await writeRootBundleConfig( + { + bundle: {name: getUniqueResourceName("ssh")}, + targets: { + test: { + default: true, + workspace: {host: process.env.DATABRICKS_HOST}, + }, + }, + }, + root + ); + await waitForLogin("DEFAULT"); + await browser.executeWorkbench((vscode, testPath) => { + // Electron resolves a login-shell PATH; keep the CLI's IDE launch isolated. + process.env.PATH = testPath; + void vscode.commands.executeCommand("databricks.ssh.startTunnel"); + }, process.env.PATH); + const picker = await waitForInput(); + await picker.setText("Serverless"); + const item = await browser.waitUntil( + () => picker.findQuickPick("Serverless"), + { + timeout: 30_000, + timeoutMsg: "Serverless SSH compute was not offered", + } + ); + assert(item, "Serverless SSH compute was not offered"); + const localWindow = await browser.getWindowHandle(); + const initialWindows = await browser.getWindowHandles(); + await item.select(); + + let result: { + phase?: string; + error?: string; + bytesPerRound?: number; + completedRounds?: number; + authority?: string; + fileName?: string; + editorText?: string; + } = {}; + let uiPassed = false; + let remoteWindow: string | undefined; + try { + remoteWindow = await browser.waitUntil( + async () => { + const handles = await browser.getWindowHandles(); + return handles.find( + (handle) => !initialWindows.includes(handle) + ); + }, + { + timeout: 180_000, + interval: 1000, + timeoutMsg: "Remote SSH did not open a new window", + } + ); + assert(remoteWindow); + await browser.switchToWindow(remoteWindow); + await browser.waitUntil( + async () => { + await dismissRemoteWelcome(); + try { + result = JSON.parse( + await fs.readFile(resultPath, "utf8") + ); + } catch (error) { + if ( + (error as NodeJS.ErrnoException).code === "ENOENT" + ) { + return false; + } + throw error; + } + return ( + result.phase === "ui-ready" || + result.error !== undefined + ); + }, + { + timeout: 8 * 60_000, + interval: 1000, + timeoutMsg: + "Remote SSH did not finish three 8 MiB round trips; inspect Remote SSH and tunnel logs", + } + ); + assert.equal(result.error, undefined); + assert(result.fileName && result.editorText); + await dismissRemoteWelcome(); + const file = browser.$( + `//div[contains(@class, 'explorer-folders-view')]//*[contains(@class, 'label-name') and normalize-space(.)='${result.fileName}']` + ); + const explorer = await (await browser.getWorkbench()) + .getActivityBar() + .getViewControl("Explorer"); + assert(explorer, "Remote window has no Explorer view"); + await explorer.openView(); + await browser.waitUntil( + async () => { + await dismissRemoteWelcome(); + return ( + (await file.isExisting()) && (await file.isDisplayed()) + ); + }, + { + timeout: 30_000, + interval: 500, + timeoutMsg: "Remote Explorer did not display the test file", + } + ); + await file.doubleClick(); + await browser.waitUntil( + async () => { + const tab = browser.$( + ".tabs-container .tab.active .label-name" + ); + const lines = browser.$(".monaco-editor .view-lines"); + return ( + (await tab.isDisplayed()) && + (await tab.getText()) === result.fileName && + (await lines.isDisplayed()) && + (await lines.getText()).includes(result.editorText!) + ); + }, + { + timeout: 30_000, + timeoutMsg: + "Remote file clicked in Explorer did not open with the expected text", + } + ); + uiPassed = true; + } catch (error) { + await browser + .saveScreenshot( + path.join( + process.env.TEST_E2E_ROOT || ".", + "logs", + "ssh-remote-ui-failure.png" + ) + ) + .catch(() => {}); + throw error; + } finally { + await fs.writeFile( + `${resultPath}.ui-complete`, + uiPassed ? "passed" : "failed" + ); + if (!uiPassed && remoteWindow) { + // The "failed" marker makes the probe delete its remote files + // and close this window itself, so wait for that first; force + // it shut only if the probe is wedged past its own watchdogs, + // since nothing else closes it on this path. The tunnel goes + // away with the local window's extension host. + try { + await browser.waitUntil( + async () => { + const handles = await browser.getWindowHandles(); + return !handles.includes(remoteWindow!); + }, + {timeout: 30_000, interval: 1000} + ); + } catch { + await browser.closeWindow().catch(() => {}); + } + } + await browser.switchToWindow(localWindow); + } + await browser.waitUntil( + async () => { + result = JSON.parse(await fs.readFile(resultPath, "utf8")); + return result.phase === "passed" || result.error !== undefined; + }, + { + timeout: 30_000, + interval: 500, + timeoutMsg: "Remote probe did not finish cleanup", + } + ); + assert.equal(result.error, undefined); + assert.equal(result.phase, "passed"); + assert.equal(result.bytesPerRound, 8 * 1024 * 1024); + assert.equal(result.completedRounds, 3); + assert.match(result.authority!, /^ssh-remote\+/); + }); +}); + +/** + * Dismiss optional VS Code onboarding without using a personal editor account. + * + * Best-effort: called from `waitUntil` conditions, where a rejection aborts the + * whole wait, and the onboarding UI is racy — elements go stale mid-click and + * buttons don't always vanish once clicked. Log and let the next poll retry. + */ +async function dismissRemoteWelcome() { + for (const label of ["continue without signing in", "get started"]) { + try { + const actions = await browser.$$( + `//*[self::button or @role='button' or self::a][translate(normalize-space(.), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')='${label}']` + ); + for (const action of actions) { + if (await action.isDisplayed()) { + await action.click(); + await action.waitForDisplayed({ + reverse: true, + timeout: 10_000, + }); + console.log(`Remote welcome: clicked "${label}"`); + break; + } + } + } catch (error) { + console.log(`Remote welcome: "${label}" not dismissed: ${error}`); + } + } +} diff --git a/packages/databricks-vscode/src/test/e2e/tsconfig.json b/packages/databricks-vscode/src/test/e2e/tsconfig.json index 19e364662..cdfa33cf6 100644 --- a/packages/databricks-vscode/src/test/e2e/tsconfig.json +++ b/packages/databricks-vscode/src/test/e2e/tsconfig.json @@ -8,6 +8,7 @@ "wdio-vscode-service" ], "noEmit": true, + "rootDir": "../../..", "moduleResolution": "bundler", "allowImportingTsExtensions": true, "resolveJsonModule": true, diff --git a/packages/databricks-vscode/src/test/e2e/utils/commonUtils.ts b/packages/databricks-vscode/src/test/e2e/utils/commonUtils.ts index 12ff5db80..2bcc4e7fb 100644 --- a/packages/databricks-vscode/src/test/e2e/utils/commonUtils.ts +++ b/packages/databricks-vscode/src/test/e2e/utils/commonUtils.ts @@ -45,8 +45,8 @@ export async function findViewSection(name: ViewSectionType) { (await (await control?.openView())?.getContent()?.getSections()) ?? []; for (const v of views) { let title = await v.getTitle(); - if (title === null) { - // VSCode 1.120+ no longer sets the 'title' HTML attribute on .title elements; + if (!title) { + // Newer VS Code versions leave the title attribute missing or empty; // fall back to reading the element's text content. title = await (v as any).title$.getText(); } diff --git a/packages/databricks-vscode/src/test/e2e/utils/sshE2eUtils.ts b/packages/databricks-vscode/src/test/e2e/utils/sshE2eUtils.ts new file mode 100644 index 000000000..9c5180f91 --- /dev/null +++ b/packages/databricks-vscode/src/test/e2e/utils/sshE2eUtils.ts @@ -0,0 +1,65 @@ +import fs from "node:fs/promises"; +import path from "node:path"; + +/** Route the CLI's real `code` invocation back to the isolated test editor. */ +export async function prepareSshEditor( + code: string, + extensionsDir: string, + storageDir: string, + resourcesDir: string +) { + const root = process.env.WORKSPACE_PATH!; + const home = path.join(root, "ssh-home"); + const bin = path.join(home, "bin"); + await fs.mkdir(bin, {recursive: true}); + const appData = path.join(home, "AppData", "Roaming"); + const settingsParent = + process.platform === "darwin" + ? path.join(home, "Library", "Application Support", "Code") + : process.platform === "win32" + ? path.join(appData, "Code") + : path.join(home, ".config", "Code"); + const settings = path.join(storageDir, "settings", "User"); + await fs.mkdir(settings, {recursive: true}); + await fs.mkdir(settingsParent, {recursive: true}); + // Let the CLI update the actual test editor's settings through its normal path. + await fs.symlink( + settings, + path.join(settingsParent, "User"), + process.platform === "win32" ? "junction" : "dir" + ); + const args = [ + code, + "--user-data-dir", + path.join(storageDir, "settings"), + "--extensions-dir", + extensionsDir, + "--extensionDevelopmentPath", + path.join(resourcesDir, "ssh-test-probe"), + ]; + if (process.platform === "win32") { + // Unexercised: the spec runs on posix, and wdio.conf.ts pins a default + // terminal profile only for linux and osx, so the tunnel's shell would + // not be pinned here either. Kept for whenever Windows is enabled. + const command = args.map((arg) => `"${arg}"`).join(" "); + await fs.writeFile( + path.join(bin, "code.cmd"), + `@echo off\r\nif "%~1"=="--remote" (\r\ncall ${command} %* --folder-uri "vscode-remote://%~2/tmp"\r\nexit /b\r\n)\r\ncall ${command} %*\r\n` + ); + } else { + const quote = (arg: string) => `'${arg.replaceAll("'", "'\\''")}'`; + const command = args.map(quote).join(" "); + // Development windows need an explicit folder URI; use a writable remote scratch directory. + await fs.writeFile( + path.join(bin, "code"), + `#!/bin/sh\nif [ "$1" = "--remote" ]; then\nexec ${command} "$@" --folder-uri "vscode-remote://$2/tmp"\nfi\nexec ${command} "$@"\n`, + {mode: 0o755} + ); + } + process.env.PATH = `${bin}${path.delimiter}${process.env.PATH}`; + process.env.HOME = home; + process.env.USERPROFILE = home; + process.env.APPDATA = appData; + process.env.TEST_SSH_RESULT_PATH = path.join(root, "ssh-result.json"); + return path.join(home, ".ssh", "config"); +} diff --git a/packages/databricks-vscode/src/test/e2e/wdio.conf.ts b/packages/databricks-vscode/src/test/e2e/wdio.conf.ts index 87b287893..08f926b1c 100644 --- a/packages/databricks-vscode/src/test/e2e/wdio.conf.ts +++ b/packages/databricks-vscode/src/test/e2e/wdio.conf.ts @@ -18,9 +18,9 @@ import { rmSync, } from "node:fs"; import {tmpdir} from "node:os"; -import packageJson from "../../../package.json" assert {type: "json"}; +import packageJson from "../../../package.json" with {type: "json"}; import {sleep} from "wdio-vscode-service"; -import {glob} from "glob"; +import {glob, globSync} from "glob"; import {getUniqueResourceName} from "./utils/commonUtils.ts"; import {promisify} from "node:util"; import { @@ -31,6 +31,7 @@ import { formatRecoveredSpecsReport, } from "../retry.ts"; import {SpecRetryTracker} from "../SpecRetryTracker.ts"; +import {prepareSshEditor} from "./utils/sshE2eUtils.ts"; // WebdriverIO v9 loads TypeScript by injecting `--import ` into // NODE_OPTIONS for every worker process. wdio-vscode-service installs the @@ -53,10 +54,14 @@ if ( ).trim(); } -const WORKSPACE_PATH = path.resolve(tmpdir(), "test-root"); +const TEST_ROOT = process.env.TEST_E2E_ROOT || tmpdir(); +const TEST_LOGS = process.env.TEST_E2E_ROOT + ? path.join(TEST_ROOT, "logs") + : "logs"; +const WORKSPACE_PATH = path.resolve(TEST_ROOT, "test-root"); // wdio's `outputDir`; also where onWorkerEnd parks a crashed attempt's logs. -const LOGS_DIR = "logs"; +const LOGS_DIR = TEST_LOGS; // Records spec outcomes across specFileRetries (see specFileRetriesForPlatform) // so a spec that passes only on a retry is surfaced in onComplete rather than @@ -66,9 +71,8 @@ const specRetryTracker = new SpecRetryTracker(); const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); -const {engines} = packageJson; -const EXTENSIONS_DIR = path.resolve(tmpdir(), "extension test", "extension"); +const EXTENSIONS_DIR = path.resolve(TEST_ROOT, "extension test", "extension"); const PACKAGE_ROOT = path.resolve(__dirname, "..", "..", ".."); const VSIX_PATH = path.resolve( PACKAGE_ROOT, @@ -77,7 +81,26 @@ const VSIX_PATH = path.resolve( "utf-8" ).trim() ); -const VSCODE_STORAGE_DIR = path.resolve(tmpdir(), "user-data-dir"); +const VSCODE_STORAGE_DIR = path.resolve(TEST_ROOT, "user-data-dir"); +const VSCODE_CACHE_DIR = path.join(process.cwd(), "tmp", "wdio-vscode-service"); +mkdirSync(VSCODE_CACHE_DIR, {recursive: true}); + +// The SSH spec needs a workspace that offers Serverless SSH compute, a tunnel +// port that workspace permits, and a Remote SSH install, so it is opt-in. That +// keeps apart two cases a skip inside the spec conflated: without the flag it is +// excluded outright, instead of being swept in by the default glob and failing +// at `findQuickPick("Serverless")`; with it nothing skips, so a missing Remote +// SSH fails the run instead of going green with no SSH coverage at all. +const SSH_SPEC_FILE = "ssh_connection.ucws.e2e.ts"; +const SSH_SPEC = path.join(__dirname, SSH_SPEC_FILE); +const SSH_E2E_ENABLED = process.env.TEST_SSH_E2E === "true"; + +/** + * Identify the SSH spec by file name, so the capability router and beforeSession + * cannot disagree about which spec it is where absolute paths differ — a + * symlinked temp root, a case-insensitive filesystem. + */ +const isSshSpec = (spec: string) => path.basename(spec) === SSH_SPEC_FILE; const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g; @@ -170,9 +193,9 @@ export const config: WebdriverIO.Config = { // specs: [path.join(__dirname, "**", "*.e2e.ts")], // Patterns to exclude. - exclude: [ - // 'path/to/excluded/files' - ], + // Keep the opt-in SSH spec out of any run that did not ask for it, however + // it got selected: the glob above, a directory glob, or `--spec`. + exclude: SSH_E2E_ENABLED ? [] : [SSH_SPEC], // // ============ @@ -198,42 +221,58 @@ export const config: WebdriverIO.Config = { // https://saucelabs.com/platform/platform-configurator // get capabilities() { - return [ - { - "browserName": "vscode", - "browserVersion": engines.vscode.replace("^", ""), - "wdio:vscodeOptions": { - extensionPath: path.resolve( - __dirname, - "resources", - "dummy-test" - ), - storagePath: VSCODE_STORAGE_DIR, - vscodeArgs: { - extensionsDir: EXTENSIONS_DIR, - disableExtensions: false, - }, - workspacePath: WORKSPACE_PATH, - userSettings: { - "editor.fontSize": 14, - "files.simpleDialog.enable": true, - "workbench.editor.enablePreview": true, - "window.newWindowDimensions": "default", - "window.openFoldersInNewWindow": "off", - "extensions.autoCheckUpdates": false, - "extensions.autoUpdate": false, - // ms-python.python is a hard extensionDependency, so its - // language server always loads. In the headless CI display - // the Jedi server repeatedly fails to connect and crashes, - // and its "Python Jedi server crashed" toasts overlay UI - // targets (e.g. the Output-channel ), + // intercepting clicks. We don't need language features in + // e2e, so disable the server (and experiments) at the source. + "python.languageServer": "None", + "python.experiments.enabled": false, }, }, + }); + // Existing specs keep their original editor; only SSH needs a newer Remote SSH host. + return [ + capability( + process.env.VSCODE_TEST_BINARY + ? process.env.VSCODE_TEST_VERSION || "stable" + : packageJson.engines.vscode.replace("^", ""), + [SSH_SPEC] + ), + capability(process.env.VSCODE_TEST_VERSION || "stable", otherSpecs), ]; }, @@ -287,15 +326,10 @@ export const config: WebdriverIO.Config = { // Services take over a specific job you don't want to take care of. They enhance // your test setup with almost no effort. Unlike plugins, they don't add new // commands. Instead, they hook themselves up into the test process. - services: [ - [ - "vscode", - {cachePath: path.join(process.cwd(), "tmp", "wdio-vscode-service")}, - ], - ], + services: [["vscode", {cachePath: VSCODE_CACHE_DIR}]], // cahePath above is for vscode binaries, this one is for the chromedriver - cacheDir: path.join(process.cwd(), "tmp", "wdio-vscode-service"), + cacheDir: VSCODE_CACHE_DIR, // Framework you want to run your specs with. // The following are supported: Mocha, Jasmine, and Cucumber @@ -351,7 +385,41 @@ export const config: WebdriverIO.Config = { * @param {Object} config wdio configuration object * @param {Array.} capabilities list of capabilities details */ - onPrepare: async function () { + onPrepare: async function (runnerConfig, capabilities) { + const selectedSpecs = (runnerConfig.specs ?? []) + .flat() + .flatMap((spec) => + spec.startsWith("file:") + ? [fileURLToPath(spec)] + : globSync(spec, {absolute: true}).map((file) => + path.resolve(file) + ) + ); + // `exclude` dropped it, so a run that asked for nothing else has no + // specs left. Name the missing flag rather than report an empty run. + if ( + !SSH_E2E_ENABLED && + selectedSpecs.length > 0 && + selectedSpecs.every(isSshSpec) + ) { + console.error( + `${SSH_SPEC_FILE} runs only with TEST_SSH_E2E=true, against a workspace that offers Serverless SSH compute and with Remote SSH installable (see CONTRIBUTING.md).` + ); + process.exit(1); + } + const sshOnly = + SSH_E2E_ENABLED && + selectedSpecs.length > 0 && + selectedSpecs.every(isSshSpec); + const includesSsh = SSH_E2E_ENABLED && selectedSpecs.some(isSshSpec); + if (Array.isArray(capabilities)) { + // Avoid downloading an unused editor for single-spec CI jobs. + if (sshOnly) { + capabilities.splice(0, 1); + } else if (!includesSsh) { + capabilities.splice(1, 1); + } + } try { console.log("Extensions dir:", EXTENSIONS_DIR); mkdirSync(EXTENSIONS_DIR, {recursive: true}); @@ -371,25 +439,26 @@ export const config: WebdriverIO.Config = { "Config must have a token or a clientId with clientSecret" ); - assert( - process.env["TEST_DEFAULT_CLUSTER_ID"], - "Environment variable TEST_DEFAULT_CLUSTER_ID must be set" - ); + if (!sshOnly) { + assert( + process.env.TEST_DEFAULT_CLUSTER_ID, + "Environment variable TEST_DEFAULT_CLUSTER_ID must be set" + ); + } await fs.rm(WORKSPACE_PATH, {recursive: true, force: true}); console.log(`Creating vscode workspace folder: ${WORKSPACE_PATH}`); await fs.mkdir(WORKSPACE_PATH, {recursive: true}); - const client = getWorkspaceClient(config); - // Import lazily (only in the launcher's onPrepare): a static import - // pulls startCluster's SDK deps into every worker's config load and - // breaks wdio-vscode-service registration ("Unknown browser name - // vscode"). onPrepare never runs in workers, so this keeps it out. - const {startCluster} = await import("../startCluster.ts"); - await startCluster( - client.apiClient, - process.env["TEST_DEFAULT_CLUSTER_ID"] - ); + if (!sshOnly) { + const client = getWorkspaceClient(config); + // Keep SDK imports out of worker config loading. + const {startCluster} = await import("../startCluster.ts"); + await startCluster( + client.apiClient, + process.env.TEST_DEFAULT_CLUSTER_ID! + ); + } process.env.DATABRICKS_HOST = config.host!; process.env.DATABRICKS_VSCODE_INTEGRATION_TEST = "true"; @@ -470,7 +539,8 @@ export const config: WebdriverIO.Config = { * @param {Array.} specs List of spec file paths that are to be run * @param {String} cid worker id (e.g. 0-0) */ - beforeSession: async function (config, capabilities) { + beforeSession: async function (config, capabilities, specs) { + const sshTest = specs.some(isSshSpec); const binary: string = capabilities["wdio:vscodeOptions"] .binary as string; let cli: string = ""; @@ -491,51 +561,127 @@ export const config: WebdriverIO.Config = { // When EXTENSION_VSIX_DIR is set (CI with vendored VSIX files), // resolve extensions from that directory instead of the marketplace. const vsixDir = process.env.EXTENSION_VSIX_DIR; - const extensionDependencies: string[] = []; - for (const extId of packageJson.extensionDependencies) { - if (vsixDir) { - const targetPlatform = `${process.platform}-${process.arch}`; - const files = readdirSync(vsixDir); - const prefix = `${extId}-`; - const vsix = - files.find( - (f) => - f.startsWith(prefix) && - f.endsWith(`-${targetPlatform}.vsix`) - ) ?? - files.find( - (f) => - f.startsWith(prefix) && - f.endsWith("-universal.vsix") - ); - if (vsix) { - console.log(`Using vendored VSIX for ${extId}: ${vsix}`); - extensionDependencies.push( - "--install-extension", - path.resolve(vsixDir, vsix) - ); - } else { - console.log( - `WARNING: no vendored VSIX for ${extId}, falling back to marketplace` - ); - extensionDependencies.push("--install-extension", extId); - } - } else { - extensionDependencies.push("--install-extension", extId); + const resolveExtension = (extId: string) => { + if (!vsixDir) { + return extId; } - } + const targetPlatform = `${process.platform}-${process.arch}`; + const files = readdirSync(vsixDir); + const prefix = `${extId}-`; + const vsix = + files.find( + (f) => + f.startsWith(prefix) && + f.endsWith(`-${targetPlatform}.vsix`) + ) ?? + files.find( + (f) => f.startsWith(prefix) && f.endsWith("-universal.vsix") + ); + if (!vsix) { + console.log( + `WARNING: no vendored VSIX for ${extId}, falling back to marketplace` + ); + return extId; + } + console.log(`Using vendored VSIX for ${extId}: ${vsix}`); + return path.resolve(vsixDir, vsix); + }; + // wdio only logs a beforeSession rejection, so the CLI's own output is + // the only explanation of an install failure that reaches the job log. + const install = async (args: string[]) => { + try { + const res = await execFile(cli, [ + "--extensions-dir", + EXTENSIONS_DIR, + ...args, + "--force", + ]); + console.log(res.stdout, res.stderr); + } catch (e) { + const {stdout, stderr} = e as { + stdout?: string; + stderr?: string; + }; + console.log(stdout ?? "", stderr ?? ""); + throw e; + } + }; console.log("running vscode cli"); - const res = await execFile(cli, [ - "--extensions-dir", - EXTENSIONS_DIR, - ...extensionDependencies, + await install([ + ...packageJson.extensionDependencies.flatMap((extId) => [ + "--install-extension", + resolveExtension(extId), + ]), "--install-extension", VSIX_PATH, - "--force", ]); - console.log(res.stdout, res.stderr); + if (!sshTest) { + return; + } + // Install Remote SSH on its own: batching it with the extensions above + // would let one failure take out every install, including the VSIX under + // test. CI has no marketplace and resolves it from EXTENSION_VSIX_DIR. + // Fatal on purpose — turning a missing dependency into a skip would let + // the job report success without exercising the tunnel at all. + await install([ + "--install-extension", + resolveExtension("ms-vscode-remote.remote-ssh"), + // The pack's other members are optional for the tunnel. + "--do-not-include-pack-dependencies", + ]); + + const sshConfig = await prepareSshEditor( + cli, + EXTENSIONS_DIR, + VSCODE_STORAGE_DIR, + path.join(__dirname, "resources") + ); + const sshSettings = { + "remote.SSH.configFile": sshConfig, + "security.workspace.trust.enabled": false, + "terminal.integrated.shellIntegration.enabled": false, + "terminal.integrated.profiles.osx": { + "SSH test": {path: "/bin/sh", args: []}, + }, + "terminal.integrated.defaultProfile.osx": "SSH test", + "terminal.integrated.profiles.linux": { + "SSH test": {path: "/bin/sh", args: []}, + }, + "terminal.integrated.defaultProfile.linux": "SSH test", + "terminal.integrated.env.linux": {PATH: process.env.PATH}, + "terminal.integrated.env.osx": {PATH: process.env.PATH}, + "terminal.integrated.env.windows": {PATH: process.env.PATH}, + }; + // wdio-vscode-service writes this same file from its own hooks, so put + // the settings in both places rather than depend on which runs first: + // the capability covers a service write after this hook, the file covers + // one that already happened. + const vscodeOptions = capabilities["wdio:vscodeOptions"]; + vscodeOptions.userSettings = { + ...vscodeOptions.userSettings, + ...sshSettings, + }; + const settingsFile = path.join( + VSCODE_STORAGE_DIR, + "settings", + "User", + "settings.json" + ); + const settings = await fs + .readFile(settingsFile, "utf8") + .then((raw) => JSON.parse(raw) as Record) + .catch((error) => { + // Not yet written, or unreadable. The capability copy above is + // what makes the settings arrive in that case. + console.log(`Could not read ${settingsFile}: ${error}`); + return {}; + }); + await fs.writeFile( + settingsFile, + JSON.stringify({...settings, ...sshSettings}) + ); }, /** @@ -679,7 +825,7 @@ export const config: WebdriverIO.Config = { cpSync( file, path.join( - "logs", + TEST_LOGS, `vscode-logs-${specs .map((spec) => spec.split(path.sep).at(-1)) .join("-")}`, From 737f4ecf746a8f79d68856c259f83d05a53b993f Mon Sep 17 00:00:00 2001 From: misha-db Date: Wed, 16 Sep 2026 18:34:30 +0400 Subject: [PATCH 24/31] Downgrade proxy-agent version so Node 18 can run it --- packages/databricks-vscode/package.json | 2 +- .../src/utils/network/proxyAgent.test.ts | 68 +++++----------- .../src/utils/network/proxyAgent.ts | 80 +++++++++---------- yarn.lock | 26 +++--- 4 files changed, 72 insertions(+), 104 deletions(-) diff --git a/packages/databricks-vscode/package.json b/packages/databricks-vscode/package.json index 4d82b39e5..3fbb6fe0d 100644 --- a/packages/databricks-vscode/package.json +++ b/packages/databricks-vscode/package.json @@ -1927,7 +1927,7 @@ "@types/shell-quote": "^1.7.5", "@vscode/debugadapter": "^1.64.0", "@vscode/extension-telemetry": "^1.5.2", - "@vscode/proxy-agent": "^0.44.0", + "@vscode/proxy-agent": "^0.28.0", "@vscode/webview-ui-toolkit": "^1.4.0", "add": "^2.0.6", "ansi-to-html": "^0.7.2", diff --git a/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts b/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts index cbb806667..4a242b8e2 100644 --- a/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts +++ b/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts @@ -14,8 +14,8 @@ import { applyProxyStrictSSLEnv, createWorkspaceClient, getDatabricksHttpAgent, - loadSystemCertificatesFromNode, resetProxyAgentCaches, + setSystemCertificatesLoaderForTests, strictSSL, } from "./proxyAgent"; @@ -41,6 +41,7 @@ describe(__filename, () => { afterEach(() => { reset(configsSpy); + setSystemCertificatesLoaderForTests(); process.env = existingEnv; }); @@ -197,29 +198,21 @@ describe(__filename, () => { }); it("falls back to Node's bundled CAs when the system store can't be read", async () => { - // @vscode/proxy-agent reads the store via tls.getCACertificates, - // which is absent/throws on older runtimes. Simulate that failure - // on the shared (required) tls module proxy-agent also sees. - // eslint-disable-next-line @typescript-eslint/no-require-imports - const tls = require("node:tls"); - const original = tls.getCACertificates; - tls.getCACertificates = () => { - throw new Error("getCACertificates unavailable"); - }; - try { - const agent = (await getDatabricksHttpAgent( - new URL("https://example.com") - )) as https.Agent; - // `ca` must be omitted (not [] / undefined) so Node keeps its - // bundled roots instead of trusting nothing. - assert.ok(!("ca" in (agent.options as https.AgentOptions))); - assert.strictEqual( - (agent.options as https.AgentOptions).rejectUnauthorized, - true - ); - } finally { - tls.getCACertificates = original; - } + // @vscode/proxy-agent's own reader catches internally and reads the + // host's real store, so swap the loader for one that rejects. + setSystemCertificatesLoaderForTests(async () => { + throw new Error("system store unavailable"); + }); + const agent = (await getDatabricksHttpAgent( + new URL("https://example.com") + )) as https.Agent; + // `ca` must be omitted (not [] / undefined) so Node keeps its + // bundled roots instead of trusting nothing. + assert.ok(!("ca" in (agent.options as https.AgentOptions))); + assert.strictEqual( + (agent.options as https.AgentOptions).rejectUnauthorized, + true + ); }); it("merges databricks.proxy.caCert onto the trust store", async () => { @@ -246,12 +239,9 @@ describe(__filename, () => { const pemPath = path.join(dir, "corp-ca.pem"); fs.writeFileSync(pemPath, FAKE_CA_PEM); when(configsSpy.proxyCaCert).thenReturn(pemPath); - // eslint-disable-next-line @typescript-eslint/no-require-imports - const tlsMod = require("node:tls"); - const original = tlsMod.getCACertificates; - tlsMod.getCACertificates = () => { - throw new Error("getCACertificates unavailable"); - }; + setSystemCertificatesLoaderForTests(async () => { + throw new Error("system store unavailable"); + }); try { const agent = (await getDatabricksHttpAgent( new URL("https://example.com") @@ -261,7 +251,6 @@ describe(__filename, () => { assert.ok(ca.includes(FAKE_CA_PEM)); assert.ok(ca.includes(tls.rootCertificates[0])); } finally { - tlsMod.getCACertificates = original; fs.rmSync(dir, {recursive: true, force: true}); } }); @@ -279,23 +268,6 @@ describe(__filename, () => { }); }); - describe("loadSystemCertificatesFromNode", () => { - it("is true when tls.getCACertificates exists, false when it doesn't", () => { - // eslint-disable-next-line @typescript-eslint/no-require-imports - const tlsMod = require("node:tls"); - const original = tlsMod.getCACertificates; - try { - tlsMod.getCACertificates = () => []; - assert.strictEqual(loadSystemCertificatesFromNode(), true); - - tlsMod.getCACertificates = undefined; - assert.strictEqual(loadSystemCertificatesFromNode(), false); - } finally { - tlsMod.getCACertificates = original; - } - }); - }); - describe("createWorkspaceClient", () => { it("builds a client tagged with the extension product and a proxy-aware agent", async () => { const client = await createWorkspaceClient( diff --git a/packages/databricks-vscode/src/utils/network/proxyAgent.ts b/packages/databricks-vscode/src/utils/network/proxyAgent.ts index da9c43d29..3fc67b48d 100644 --- a/packages/databricks-vscode/src/utils/network/proxyAgent.ts +++ b/packages/databricks-vscode/src/utils/network/proxyAgent.ts @@ -29,26 +29,6 @@ const extensionVersion = require("../../../package.json") const KEEP_ALIVE_MSECS = 15000; const DEFAULT_HTTP_TIMEOUT_SECONDS = 5; -/** - * Whether to let @vscode/proxy-agent read the OS trust store via Node's - * `tls.getCACertificates`. - * - * That API was added in Node 22.15. proxy-agent's "from Node" path calls it - * unconditionally, so on older runtimes (shipped by many supported VS Code - * builds) it throws and we lose the OS trust store. When it's missing we return - * `false` so proxy-agent instead uses its native readers (the - * `@vscode/windows-ca-certs` module on Windows, `security` on macOS, PEM bundle - * files on Linux), which work on every Node version. - * - * Evaluated per call (not cached) so tests can simulate an older runtime. - */ -export function loadSystemCertificatesFromNode(): boolean { - return ( - typeof (tls as {getCACertificates?: unknown}).getCACertificates === - "function" - ); -} - function getLog(): Log { const logger = logging.NamedLogger.getOrCreate(Loggers.Extension); return { @@ -68,8 +48,8 @@ function getLog(): Log { * Build the params @vscode/proxy-agent needs to resolve a proxy the same way * VS Code core does: `http.proxy` setting first, then the `http(s)_proxy` env * vars, honouring `http.noProxy` and `NO_PROXY`. System/PAC auto-detection is - * intentionally disabled (`isUseHostProxyEnabled: false`) — it needs Electron's - * proxy resolver, which the extension host doesn't expose. + * intentionally disabled (`useHostProxy: false`) — it needs Electron's proxy + * resolver, which the extension host doesn't expose. */ function getProxyAgentParams(): ProxyAgentParams { const log = getLog(); @@ -79,15 +59,13 @@ function getProxyAgentParams(): ProxyAgentParams { getProxySupport: () => "on", getNoProxyConfig: () => getNoProxyConfig(), isAdditionalFetchSupportEnabled: () => false, - isWebSocketPatchEnabled: () => false, addCertificatesV1: () => false, addCertificatesV2: () => true, - loadSystemCertificatesFromNode, loadAdditionalCertificates: async () => [], log, getLogLevel: () => LogLevel.Error, proxyResolveTelemetry: () => {}, - isUseHostProxyEnabled: () => false, + useHostProxy: false, env: process.env, }; } @@ -106,29 +84,32 @@ function getNoProxyConfig(): string[] { let systemCertificatesPromise: Promise | undefined; +// The system-certificate reader, indirected through a module-level binding so +// tests can simulate an unreadable OS store. @vscode/proxy-agent's own reader +// catches internally and reads the host machine's real store, so there's no +// other seam to force the failure path. +let loadSystemCertificatesImpl: (params: {log: Log}) => Promise = + loadSystemCertificates; + /** - * Load and cache the OS certificate trust store (Windows/macOS/Linux) plus - * Node's bundled CAs. Cached for the session; call {@link resetProxyAgentCaches} - * in tests. + * Load and cache the OS certificate trust store (Windows/macOS/Linux). Cached + * for the session; call {@link resetProxyAgentCaches} in tests. * - * Returns `undefined` (never a rejected/empty promise) when the store can't be - * read. @vscode/proxy-agent reads it either via Node's `tls.getCACertificates` - * (Node >= 22.15) or, on older runtimes, its native readers (the - * `@vscode/windows-ca-certs` module on Windows, `security` on macOS, PEM files - * on Linux) — see {@link loadSystemCertificatesFromNode}. If that native module is - * absent (e.g. not shipped for this platform) the read can still fail; swallowing - * it here lets the caller fall back to Node's bundled roots instead of failing - * the whole SDK request. A missing custom CA is recoverable (users can point - * `databricks.proxy.caCert` at their PEM, or opt out via - * `databricks.proxy.strictSSL`), a broken agent is not. + * Returns `undefined` (never a rejected promise) when the store can't be read. + * @vscode/proxy-agent reads it via its native readers — the + * `@vscode/windows-ca-certs` module on Windows, `security` on macOS, PEM bundle + * files on Linux — which work on every Node version the extension targets. If + * that native module is absent (e.g. not shipped for this platform) the read + * can still fail; swallowing it here lets the caller fall back to Node's bundled + * roots instead of failing the whole SDK request. A missing custom CA is + * recoverable (users can point `databricks.proxy.caCert` at their PEM, or opt + * out via `databricks.proxy.strictSSL`), a broken agent is not. */ async function getSystemCertificates( params: ProxyAgentParams ): Promise { if (!systemCertificatesPromise) { - systemCertificatesPromise = loadSystemCertificates({ - loadSystemCertificatesFromNode: - params.loadSystemCertificatesFromNode, + systemCertificatesPromise = loadSystemCertificatesImpl({ log: params.log, }).catch((e) => { params.log.error( @@ -150,6 +131,18 @@ export function resetProxyAgentCaches() { systemCertificatesPromise = undefined; } +/** + * Override the system-certificate loader (and drop the cache). Test-only: lets + * tests exercise the "OS store unreadable" fallback without depending on the + * host machine's real trust store. Pass `undefined` to restore the default. + */ +export function setSystemCertificatesLoaderForTests( + loader?: (params: {log: Log}) => Promise +) { + loadSystemCertificatesImpl = loader ?? loadSystemCertificates; + systemCertificatesPromise = undefined; +} + /** * Whether the SDK must verify TLS certificates. `false` only when the user * opted out via `databricks.proxy.strictSSL` or `http.proxyStrictSSL`. @@ -212,7 +205,10 @@ function buildCaBundle( systemCerts: string[] | undefined, configuredCaCert: string | undefined ): string[] | undefined { - if (!systemCerts && !configuredCaCert) { + // @vscode/proxy-agent swallows a failed OS-store read and returns `[]`, so + // treat empty the same as unreadable: nothing to add on top of Node's + // bundled roots. + if (!systemCerts?.length && !configuredCaCert) { return undefined; } return [ diff --git a/yarn.lock b/yarn.lock index 14458c33b..bed767cd3 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2073,9 +2073,9 @@ __metadata: languageName: node linkType: hard -"@vscode/proxy-agent@npm:^0.44.0": - version: 0.44.0 - resolution: "@vscode/proxy-agent@npm:0.44.0" +"@vscode/proxy-agent@npm:^0.28.0": + version: 0.28.0 + resolution: "@vscode/proxy-agent@npm:0.28.0" dependencies: "@tootallnate/once": ^3.0.0 "@vscode/windows-ca-certs": ^0.3.1 @@ -2084,11 +2084,11 @@ __metadata: http-proxy-agent: ^7.0.0 https-proxy-agent: ^7.0.2 socks-proxy-agent: ^8.0.1 - undici: ^7.2.0 + undici: ^6.20.1 dependenciesMeta: "@vscode/windows-ca-certs": optional: true - checksum: 4ebf8fd3c1764c1bb94665e4c70ff7c43eedfebac3a0af29e2912349076a530b3956908ab91b860745f49f64707717187b1d21c14445d8966c07195c2ffb5b7d + checksum: dc1124d52f9ab684a8e4c109b2e91598c069beebfe2826fb38ce6f8c7ef38e9e77843a7254dbb177d499ef9474bf7dbdf4240deb1f3ed5070b37dbd7b19031e3 languageName: node linkType: hard @@ -4067,7 +4067,7 @@ __metadata: "@typescript-eslint/utils": ^8.62.0 "@vscode/debugadapter": ^1.64.0 "@vscode/extension-telemetry": ^1.5.2 - "@vscode/proxy-agent": ^0.44.0 + "@vscode/proxy-agent": ^0.28.0 "@vscode/test-electron": ^3.1.0 "@vscode/webview-ui-toolkit": ^1.4.0 "@vscode/windows-ca-certs": ^0.3.1 @@ -10397,6 +10397,13 @@ __metadata: languageName: node linkType: hard +"undici@npm:^6.20.1": + version: 6.28.1 + resolution: "undici@npm:6.28.1" + checksum: 25f7398989c7f6d22b4120bb97ac2d8449e5bd30fe0c5eb9265537786a9950c35a0b363a74770729d94084784689f1304744e3e02cff32c614385d5dd4172af7 + languageName: node + linkType: hard + "undici@npm:^7.19.0": version: 7.28.0 resolution: "undici@npm:7.28.0" @@ -10404,13 +10411,6 @@ __metadata: languageName: node linkType: hard -"undici@npm:^7.2.0": - version: 7.29.0 - resolution: "undici@npm:7.29.0" - checksum: b3327e05259e66c61d3e05242bf63899c68d277302208f4fc1c7c0b880a9ba82651b8b3215584ffd424d8c8410f0114b6c3a89e6af604c703dc33009daa99ed3 - languageName: node - linkType: hard - "unicode-properties@npm:^1.4.1": version: 1.4.1 resolution: "unicode-properties@npm:1.4.1" From 158948d79a60f85acd76df952a13acc06801c863 Mon Sep 17 00:00:00 2001 From: misha-db Date: Thu, 17 Sep 2026 13:43:52 +0400 Subject: [PATCH 25/31] Fix test on Windows --- .../src/utils/network/proxyAgent.test.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts b/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts index 4a242b8e2..71daca744 100644 --- a/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts +++ b/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts @@ -162,6 +162,14 @@ describe(__filename, () => { }); it("merges the system trust store with Node's bundled roots (never replaces them)", async () => { + // Inject the system store instead of reading the host's: CI runners + // (notably headless Windows) can return an empty OS store, which + // would legitimately omit `ca` and make this merge assertion flaky. + // Re-listing a bundled root also exercises the dedupe path below. + setSystemCertificatesLoaderForTests(async () => [ + FAKE_CA_PEM, + tls.rootCertificates[0], + ]); const agent = (await getDatabricksHttpAgent( new URL("https://example.com") )) as https.Agent; From 5aa4d640d53b9f7a32d18e6f5c461f23d8b3a7a3 Mon Sep 17 00:00:00 2001 From: misha-db Date: Thu, 17 Sep 2026 18:40:50 +0400 Subject: [PATCH 26/31] refactor(proxy): route SDK proxy helpers through the utils barrel MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add a src/utils/network/index.ts namespace-barrel and re-export it from the top-level utils barrel so proxyAgent is consumed as ProxyAgent.* (per CODE_CONVENTIONS.md §7) instead of via deep relative imports in extension.ts and the auth checks. Also dedupe the http.noProxy + NO_PROXY merge: promote it to an exported mergeNoProxy() in proxyAgent.ts and have getProxyEnvVars() reuse it, so the in-process SDK resolver and the bundled-CLI env vars share one implementation. No behavior change. --- .../src/configuration/auth/AuthProvider.ts | 4 ++-- .../src/configuration/auth/AzureCliCheck.ts | 5 ++--- .../src/configuration/auth/DatabricksCliCheck.ts | 4 ++-- packages/databricks-vscode/src/extension.ts | 6 +++--- .../src/utils/envVarGenerators.ts | 15 +++++---------- packages/databricks-vscode/src/utils/index.ts | 1 + .../databricks-vscode/src/utils/network/index.ts | 1 + .../src/utils/network/proxyAgent.ts | 11 +++++++++-- 8 files changed, 25 insertions(+), 22 deletions(-) create mode 100644 packages/databricks-vscode/src/utils/network/index.ts diff --git a/packages/databricks-vscode/src/configuration/auth/AuthProvider.ts b/packages/databricks-vscode/src/configuration/auth/AuthProvider.ts index 4598a5860..bcb724fc8 100644 --- a/packages/databricks-vscode/src/configuration/auth/AuthProvider.ts +++ b/packages/databricks-vscode/src/configuration/auth/AuthProvider.ts @@ -8,7 +8,7 @@ import {AzureCliCheck} from "./AzureCliCheck"; import {DatabricksCliCheck} from "./DatabricksCliCheck"; import {Loggers} from "../../logger"; import {CliWrapper} from "../../cli/CliWrapper"; -import {createWorkspaceClient} from "../../utils/network/proxyAgent"; +import {ProxyAgent} from "../../utils"; // TODO: Resolve this with SDK's AuthType. export type AuthType = @@ -44,7 +44,7 @@ export abstract class AuthProvider { async getWorkspaceClient(): Promise { const config = await this.getSdkConfig(); - return createWorkspaceClient(config, this.host); + return ProxyAgent.createWorkspaceClient(config, this.host); } /** diff --git a/packages/databricks-vscode/src/configuration/auth/AzureCliCheck.ts b/packages/databricks-vscode/src/configuration/auth/AzureCliCheck.ts index c0f6837b7..ede9d14a3 100644 --- a/packages/databricks-vscode/src/configuration/auth/AzureCliCheck.ts +++ b/packages/databricks-vscode/src/configuration/auth/AzureCliCheck.ts @@ -3,13 +3,12 @@ import {CancellationToken, commands, Disposable, Uri, window} from "vscode"; import {Loggers} from "../../logger"; import {AzureCliAuthProvider} from "./AuthProvider"; import {orchestrate, OrchestrationLoopError, Step} from "./orchestrate"; -import {ShellUtils} from "../../utils"; +import {ProxyAgent, ShellUtils} from "../../utils"; import {cancellableExecFile} from "../../cli/CliWrapper"; import { FileNotFoundException, isFileNotFound, } from "@databricks/sdk-experimental/dist/config/execUtils"; -import {createWorkspaceClient} from "../../utils/network/proxyAgent"; // eslint-disable-next-line @typescript-eslint/naming-convention const {NamedLogger} = logging; @@ -204,7 +203,7 @@ export class AzureCliCheck implements Disposable { expired: boolean; error?: Error; }> { - const workspaceClient = await createWorkspaceClient( + const workspaceClient = await ProxyAgent.createWorkspaceClient( { host: host.toString(), authType: "azure-cli", diff --git a/packages/databricks-vscode/src/configuration/auth/DatabricksCliCheck.ts b/packages/databricks-vscode/src/configuration/auth/DatabricksCliCheck.ts index eaea1bc67..0aa2c0069 100644 --- a/packages/databricks-vscode/src/configuration/auth/DatabricksCliCheck.ts +++ b/packages/databricks-vscode/src/configuration/auth/DatabricksCliCheck.ts @@ -12,7 +12,7 @@ import {DatabricksCliAuthProvider} from "./AuthProvider"; import {orchestrate, OrchestrationLoopError, Step} from "./orchestrate"; import {Loggers} from "../../logger"; import {execFile} from "../../cli/CliWrapper"; -import {createWorkspaceClient} from "../../utils/network/proxyAgent"; +import {ProxyAgent} from "../../utils"; type StepName = "tryLogin" | "login"; @@ -106,7 +106,7 @@ export class DatabricksCliCheck implements Disposable { private async tryLogin( cancellationToken?: CancellationToken ): Promise { - const workspaceClient = await createWorkspaceClient( + const workspaceClient = await ProxyAgent.createWorkspaceClient( { host: this.authProvider.host.toString(), authType: "databricks-cli", diff --git a/packages/databricks-vscode/src/extension.ts b/packages/databricks-vscode/src/extension.ts index 58f090d02..7cb14583e 100644 --- a/packages/databricks-vscode/src/extension.ts +++ b/packages/databricks-vscode/src/extension.ts @@ -34,6 +34,7 @@ import {workspaceConfigs} from "./vscode-objs/WorkspaceConfigs"; import { FileUtils, PackageJsonUtils, + ProxyAgent, TerraformUtils, UrlUtils, UtilsCommands, @@ -109,7 +110,6 @@ import {BundleVariableModel} from "./bundle/models/BundleVariableModel"; import {BundleVariableTreeDataProvider} from "./ui/bundle-variables/BundleVariableTreeDataProvider"; import {ConfigurationTreeViewManager} from "./ui/configuration-view/ConfigurationTreeViewManager"; import {getCLIDependenciesEnvVars} from "./utils/envVarGenerators"; -import {applyProxyStrictSSLEnv} from "./utils/network/proxyAgent"; import {EnvironmentCommands} from "./language/EnvironmentCommands"; import {PackageManagerTelemetry} from "./language/PackageManagerTelemetry"; import {WorkspaceFolderManager} from "./vscode-objs/WorkspaceFolderManager"; @@ -681,11 +681,11 @@ export async function activate( // path uses (databricks.proxy.strictSSL -> http.proxyStrictSSL -> true), so // both writers of DATABRICKS_SDK_PROXY_STRICT_SSL agree and verification // stays on by default when nothing is configured. - applyProxyStrictSSLEnv(); + ProxyAgent.applyProxyStrictSSLEnv(); context.subscriptions.push( workspace.onDidChangeConfiguration(() => { updateFeatureContexts(); - applyProxyStrictSSLEnv(); + ProxyAgent.applyProxyStrictSSLEnv(); }) ); diff --git a/packages/databricks-vscode/src/utils/envVarGenerators.ts b/packages/databricks-vscode/src/utils/envVarGenerators.ts index f564fa711..5cdcb0ec8 100644 --- a/packages/databricks-vscode/src/utils/envVarGenerators.ts +++ b/packages/databricks-vscode/src/utils/envVarGenerators.ts @@ -5,6 +5,7 @@ import {logging, Headers} from "@databricks/sdk-experimental"; import {ConnectionManager} from "../configuration/ConnectionManager"; import {TerraformMetadata} from "./terraformUtils"; import {workspaceConfigs} from "../vscode-objs/WorkspaceConfigs"; +import {mergeNoProxy} from "./network/proxyAgent"; // eslint-disable-next-line @typescript-eslint/no-require-imports const packageJson = require("../../package.json"); @@ -166,16 +167,10 @@ export function getProxyEnvVars() { const httpsProxy = settingProxy || process.env.HTTPS_PROXY || process.env.https_proxy; - // Merge the `http.noProxy` setting (an array) with the comma-separated - // NO_PROXY env var, deduping at host granularity. - const envNoProxy = process.env.NO_PROXY || process.env.no_proxy || ""; - const noProxyParts = [ - ...workspaceConfigs.httpNoProxy, - ...envNoProxy.split(","), - ] - .map((v) => v.trim()) - .filter((v) => v.length > 0); - const noProxy = [...new Set(noProxyParts)].join(",") || undefined; + // Merge the `http.noProxy` setting with the NO_PROXY env var (shared with + // the in-process SDK proxy resolver), then join back to the comma-separated + // form the CLI expects. + const noProxy = mergeNoProxy().join(",") || undefined; return { /* eslint-disable @typescript-eslint/naming-convention */ diff --git a/packages/databricks-vscode/src/utils/index.ts b/packages/databricks-vscode/src/utils/index.ts index ed6f6af75..8ea67ea41 100644 --- a/packages/databricks-vscode/src/utils/index.ts +++ b/packages/databricks-vscode/src/utils/index.ts @@ -7,3 +7,4 @@ export * as EnvVarGenerators from "./envVarGenerators"; export * as DateUtils from "./DateUtils"; export * as TerraformUtils from "./terraformUtils"; export * as HostUtils from "./hostUtils"; +export * from "./network"; diff --git a/packages/databricks-vscode/src/utils/network/index.ts b/packages/databricks-vscode/src/utils/network/index.ts new file mode 100644 index 000000000..b925a5a94 --- /dev/null +++ b/packages/databricks-vscode/src/utils/network/index.ts @@ -0,0 +1 @@ +export * as ProxyAgent from "./proxyAgent"; diff --git a/packages/databricks-vscode/src/utils/network/proxyAgent.ts b/packages/databricks-vscode/src/utils/network/proxyAgent.ts index 3fc67b48d..b90444e18 100644 --- a/packages/databricks-vscode/src/utils/network/proxyAgent.ts +++ b/packages/databricks-vscode/src/utils/network/proxyAgent.ts @@ -57,7 +57,7 @@ function getProxyAgentParams(): ProxyAgentParams { resolveProxy: async () => undefined, getProxyURL: () => workspaceConfigs.httpProxy, getProxySupport: () => "on", - getNoProxyConfig: () => getNoProxyConfig(), + getNoProxyConfig: () => mergeNoProxy(), isAdditionalFetchSupportEnabled: () => false, addCertificatesV1: () => false, addCertificatesV2: () => true, @@ -70,7 +70,14 @@ function getProxyAgentParams(): ProxyAgentParams { }; } -function getNoProxyConfig(): string[] { +/** + * Merge the `http.noProxy` VS Code setting (an array) with the comma-separated + * `NO_PROXY`/`no_proxy` env var into a deduped host list. The two are *unioned* + * (not overridden) since a bypass list is only ever safer when it's broader. + * Shared by the in-process SDK proxy resolver here and the CLI env-var builder + * (`getProxyEnvVars` in envVarGenerators.ts) so both resolve the same list. + */ +export function mergeNoProxy(): string[] { const envNoProxy = process.env.NO_PROXY || process.env.no_proxy || ""; const noProxyParts = [ ...workspaceConfigs.httpNoProxy, From 7f86d182a7c02200710bbbf726f4569df960f5e4 Mon Sep 17 00:00:00 2001 From: misha-db Date: Thu, 17 Sep 2026 19:06:48 +0400 Subject: [PATCH 27/31] refactor(proxy): stop shipping the unused @vscode/windows-ca-certs reader --- packages/databricks-vscode/package.json | 8 +-- .../scripts/copy-windows-ca-certs.sh | 50 ------------------- .../databricks-vscode/scripts/package-vsix.sh | 7 --- .../src/utils/network/proxyAgent.ts | 22 ++++---- yarn.lock | 4 -- 5 files changed, 14 insertions(+), 77 deletions(-) delete mode 100755 packages/databricks-vscode/scripts/copy-windows-ca-certs.sh diff --git a/packages/databricks-vscode/package.json b/packages/databricks-vscode/package.json index b83432c02..7b6430c42 100644 --- a/packages/databricks-vscode/package.json +++ b/packages/databricks-vscode/package.json @@ -1863,7 +1863,7 @@ }, "databricks.proxy.caCert": { "type": "string", - "markdownDescription": "Absolute path to a PEM bundle of additional CA certificates to trust for the extension's Databricks SDK calls, merged with the OS trust store and Node's built-in roots. Use when a corporate CA cannot be read from the system store." + "markdownDescription": "Absolute path to a PEM bundle of additional CA certificates to trust for the extension's Databricks SDK calls, merged with the OS trust store and Node's built-in roots. Use when a corporate CA cannot be read from the system store — in particular on Windows, where the extension does not read the system certificate store and relies on this setting for internal CAs." } } } @@ -1883,7 +1883,7 @@ "version": "1.17.0" }, "scripts": { - "vscode:prepublish": "rm -rf out && yarn run package:compile && yarn run package:wrappers:write && yarn run package:jupyter-init-script:write && yarn run package:copy-webview-toolkit && yarn run package:copy-markdown-it && yarn run package:copy-highlight && yarn run package:copy-windows-ca-certs && yarn run generate-telemetry", + "vscode:prepublish": "rm -rf out && yarn run package:compile && yarn run package:wrappers:write && yarn run package:jupyter-init-script:write && yarn run package:copy-webview-toolkit && yarn run package:copy-markdown-it && yarn run package:copy-highlight && yarn run generate-telemetry", "package": "vsce package --baseContentUrl https://github.com/databricks/databricks-vscode/blob/${TAG:-main}/packages/databricks-vscode --baseImagesUrl https://github.com/_gh/raw/databricks/databricks-vscode/${TAG:-main}/packages/databricks-vscode", "package:linux:x64": "./scripts/package-vsix.sh linux-x64", "package:linux:arm64": "./scripts/package-vsix.sh linux-arm64", @@ -1901,7 +1901,6 @@ "package:copy-webview-toolkit": "cp ./node_modules/@vscode/webview-ui-toolkit/dist/toolkit.js ./out/toolkit.js", "package:copy-markdown-it": "cp ./node_modules/markdown-it/dist/browser/markdown-it.umd.min.js ./out/markdown-it.min.js", "package:copy-highlight": "esbuild ./node_modules/highlight.js/lib/common.js --bundle --format=iife --global-name=hljs --outfile=out/highlight.min.js --minify", - "package:copy-windows-ca-certs": "bash ./scripts/copy-windows-ca-certs.sh", "esbuild:base": "esbuild ./src/extension.ts --bundle --outfile=out/extension.js --external:vscode --external:@vscode/windows-ca-certs --format=cjs --platform=node --sourcemap --target=es2019", "build": "yarn run package:wrappers:write && yarn run package:jupyter-init-script:write && tsc --build --force", "watch": "yarn run package:wrappers:write && yarn run package:jupyter-init-script:write && yarn run package:copy-webview-toolkit && yarn run package:copy-markdown-it && yarn run package:copy-highlight && tsc --build --watch --verbose", @@ -1942,9 +1941,6 @@ "winston": "^3.11.0", "yaml": "^2.8.3" }, - "optionalDependencies": { - "@vscode/windows-ca-certs": "^0.3.1" - }, "devDependencies": { "@istanbuljs/nyc-config-typescript": "^1.0.2", "@sinonjs/fake-timers": "^15.4.0", diff --git a/packages/databricks-vscode/scripts/copy-windows-ca-certs.sh b/packages/databricks-vscode/scripts/copy-windows-ca-certs.sh deleted file mode 100755 index 6f74f84a9..000000000 --- a/packages/databricks-vscode/scripts/copy-windows-ca-certs.sh +++ /dev/null @@ -1,50 +0,0 @@ -#!/bin/bash -# -# Copy the native @vscode/windows-ca-certs module into out/node_modules so the -# esbuild bundle's runtime `require("@vscode/windows-ca-certs")` resolves in the -# packaged extension. The bundle marks the module external (a native .node can't -# be bundled) and the VSIX excludes the top-level node_modules/**, so the module -# has to live under out/ to ship — same approach as the other package:copy-* -# steps. It runs from vscode:prepublish (before vsce zips out/), which is the -# only point at which we can add files to the packaged output. -# -# The module is a win32-only optional dependency, so this is a no-op unless we're -# packaging a win32 VSIX. package-vsix.sh signals that by exporting -# INCLUDE_WINDOWS_CA_CERTS=1 for the win32-* targets; for any other invocation -# (dev builds, mac/linux VSIXs) we skip. -# -# Even for win32 targets the module may be absent when the VSIX is cross-built on -# a non-Windows host (yarn honours the os=win32 install condition and skips it -# there). We warn rather than fail: at runtime a missing module degrades to -# Node's bundled roots plus databricks.proxy.caCert, so the build should still -# succeed. To actually ship the native reader, build the win32 VSIX on a Windows -# host (or install a prebuilt @vscode/windows-ca-certs) so the module is present. - -set -euo pipefail - -# get path of the repo (parent of scripts/) -cd "$(dirname "$(realpath "$0")")/.." - -if [ "${INCLUDE_WINDOWS_CA_CERTS:-}" != "1" ]; then - # Not a win32 packaging target — nothing to do. - exit 0 -fi - -SRC="./node_modules/@vscode/windows-ca-certs" -DEST="./out/node_modules/@vscode/windows-ca-certs" - -if [ ! -d "$SRC" ]; then - echo "WARNING: $SRC not found — packaging a win32 VSIX without the native" >&2 - echo "Windows CA reader. On older Node the SDK will fall back to Node's" >&2 - echo "bundled roots (+ databricks.proxy.caCert). Build on a Windows host to" >&2 - echo "include it." >&2 - exit 0 -fi - -rm -rf "$DEST" -mkdir -p "$(dirname "$DEST")" -# Copy the whole module directory (index.js, package.json, build/Release/*.node, -# etc.) so its own require() calls and the native addon all resolve at runtime. -cp -R "$SRC" "$DEST" - -echo "Copied @vscode/windows-ca-certs -> $DEST" diff --git a/packages/databricks-vscode/scripts/package-vsix.sh b/packages/databricks-vscode/scripts/package-vsix.sh index 0ec00a853..0cb85bf68 100755 --- a/packages/databricks-vscode/scripts/package-vsix.sh +++ b/packages/databricks-vscode/scripts/package-vsix.sh @@ -64,11 +64,4 @@ fi yarn run prettier package.json --write -# Ship the native Windows CA reader (@vscode/windows-ca-certs) only in the win32 -# VSIXs. vscode:prepublish reads this to decide whether to copy the module into -# out/ (see scripts/copy-windows-ca-certs.sh). -case $ARCH in - win32-*) export INCLUDE_WINDOWS_CA_CERTS=1 ;; -esac - TAG="release-v$(cat package.json | jq -r .version)" yarn run package -t $VSXI_ARCH diff --git a/packages/databricks-vscode/src/utils/network/proxyAgent.ts b/packages/databricks-vscode/src/utils/network/proxyAgent.ts index b90444e18..1d72bd33e 100644 --- a/packages/databricks-vscode/src/utils/network/proxyAgent.ts +++ b/packages/databricks-vscode/src/utils/network/proxyAgent.ts @@ -99,18 +99,20 @@ let loadSystemCertificatesImpl: (params: {log: Log}) => Promise = loadSystemCertificates; /** - * Load and cache the OS certificate trust store (Windows/macOS/Linux). Cached - * for the session; call {@link resetProxyAgentCaches} in tests. + * Load and cache the OS certificate trust store. Cached for the session; call + * {@link resetProxyAgentCaches} in tests. * * Returns `undefined` (never a rejected promise) when the store can't be read. - * @vscode/proxy-agent reads it via its native readers — the - * `@vscode/windows-ca-certs` module on Windows, `security` on macOS, PEM bundle - * files on Linux — which work on every Node version the extension targets. If - * that native module is absent (e.g. not shipped for this platform) the read - * can still fail; swallowing it here lets the caller fall back to Node's bundled - * roots instead of failing the whole SDK request. A missing custom CA is - * recoverable (users can point `databricks.proxy.caCert` at their PEM, or opt - * out via `databricks.proxy.strictSSL`), a broken agent is not. + * @vscode/proxy-agent reads it via native readers: `security` on macOS and PEM + * bundle files on Linux, which work out of the box. On Windows the store is read + * through the native `@vscode/windows-ca-certs` addon — which we deliberately do + * *not* ship (it publishes no prebuilds and can't be cross-compiled on the Linux + * release runner), so on Windows that read throws and we fall back here. When the + * read fails we swallow it so the caller uses Node's bundled roots instead of + * failing the whole SDK request. Windows users behind an internal CA point + * `databricks.proxy.caCert` at their PEM (or opt out via + * `databricks.proxy.strictSSL`): a missing custom CA is recoverable, a broken + * agent is not. */ async function getSystemCertificates( params: ProxyAgentParams diff --git a/yarn.lock b/yarn.lock index bed767cd3..0e4b81944 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4070,7 +4070,6 @@ __metadata: "@vscode/proxy-agent": ^0.28.0 "@vscode/test-electron": ^3.1.0 "@vscode/webview-ui-toolkit": ^1.4.0 - "@vscode/windows-ca-certs": ^0.3.1 "@wdio/cli": ^9.29.0 "@wdio/local-runner": ^9.29.0 "@wdio/mocha-framework": ^9.29.0 @@ -4109,9 +4108,6 @@ __metadata: ws: ^8.18.0 yaml: ^2.8.3 yargs: ^17.7.2 - dependenciesMeta: - "@vscode/windows-ca-certs": - optional: true languageName: unknown linkType: soft From 569e5e6332fc347171a131395a92dcf9d6406803 Mon Sep 17 00:00:00 2001 From: misha-db Date: Thu, 17 Sep 2026 19:10:04 +0400 Subject: [PATCH 28/31] perf(proxy): read system and configured CA certs concurrently --- .../databricks-vscode/src/utils/network/proxyAgent.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/packages/databricks-vscode/src/utils/network/proxyAgent.ts b/packages/databricks-vscode/src/utils/network/proxyAgent.ts index 1d72bd33e..c9d0c1074 100644 --- a/packages/databricks-vscode/src/utils/network/proxyAgent.ts +++ b/packages/databricks-vscode/src/utils/network/proxyAgent.ts @@ -243,8 +243,12 @@ export async function getDatabricksHttpAgent( const params = getProxyAgentParams(); const isHttps = host.protocol === "https:"; - const systemCerts = await getSystemCertificates(params); - const configuredCaCert = await loadConfiguredCaCert(); + // Independent reads (OS trust store vs the configured PEM) — run them + // together rather than serially. + const [systemCerts, configuredCaCert] = await Promise.all([ + getSystemCertificates(params), + loadConfiguredCaCert(), + ]); const ca = buildCaBundle(systemCerts, configuredCaCert); const rejectUnauthorized = strictSSL(); From b7950ff3c86d5e1e55852e0c32b808bd28592f18 Mon Sep 17 00:00:00 2001 From: misha-db Date: Thu, 17 Sep 2026 19:26:35 +0400 Subject: [PATCH 29/31] Update index.ts --- packages/databricks-vscode/src/utils/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/databricks-vscode/src/utils/index.ts b/packages/databricks-vscode/src/utils/index.ts index 8ea67ea41..6e6b26ba1 100644 --- a/packages/databricks-vscode/src/utils/index.ts +++ b/packages/databricks-vscode/src/utils/index.ts @@ -7,4 +7,4 @@ export * as EnvVarGenerators from "./envVarGenerators"; export * as DateUtils from "./DateUtils"; export * as TerraformUtils from "./terraformUtils"; export * as HostUtils from "./hostUtils"; -export * from "./network"; +export {ProxyAgent} from "./network"; From 70cad6cc6458a0b28dbe8c47fd2e94ae3c996c83 Mon Sep 17 00:00:00 2001 From: misha-db Date: Thu, 17 Sep 2026 20:21:07 +0400 Subject: [PATCH 30/31] ix proxy handling for HTTP workspaces and HTTPS proxies --- .../src/utils/network/proxyAgent.test.ts | 39 +++++++++++++++++++ .../src/utils/network/proxyAgent.ts | 16 ++++++-- 2 files changed, 51 insertions(+), 4 deletions(-) diff --git a/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts b/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts index 71daca744..d006a9feb 100644 --- a/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts +++ b/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts @@ -96,6 +96,22 @@ describe(__filename, () => { assert.ok(agent instanceof HttpProxyAgent); }); + it("uses HTTP_PROXY for http hosts when env proxies differ", async () => { + process.env.HTTP_PROXY = "http://127.0.0.1:8080"; + process.env.HTTPS_PROXY = "http://127.0.0.1:8443"; + delete process.env.http_proxy; + delete process.env.https_proxy; + delete process.env.NO_PROXY; + delete process.env.no_proxy; + + const agent = (await getDatabricksHttpAgent( + new URL("http://example.com") + )) as HttpProxyAgent; + + assert.ok(agent instanceof HttpProxyAgent); + assert.strictEqual(agent.proxy.href, "http://127.0.0.1:8080/"); + }); + it("returns a plain agent when the host matches noProxy", async () => { when(configsSpy.httpProxy).thenReturn("http://127.0.0.1:8080"); when(configsSpy.httpNoProxy).thenReturn(["example.com"]); @@ -205,6 +221,29 @@ describe(__filename, () => { ); }); + it("applies TLS options when an http host uses an https proxy", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "dbx-ca-")); + const pemPath = path.join(dir, "corp-ca.pem"); + fs.writeFileSync(pemPath, FAKE_CA_PEM); + when(configsSpy.httpProxy).thenReturn("https://127.0.0.1:8443"); + when(configsSpy.proxyCaCert).thenReturn(pemPath); + when(configsSpy.proxyStrictSSL).thenReturn(false); + setSystemCertificatesLoaderForTests(async () => []); + + try { + const agent = (await getDatabricksHttpAgent( + new URL("http://example.com") + )) as HttpProxyAgent; + const ca = agent.connectOpts.ca as string[]; + + assert.ok(agent instanceof HttpProxyAgent); + assert.ok(ca.includes(FAKE_CA_PEM)); + assert.strictEqual(agent.connectOpts.rejectUnauthorized, false); + } finally { + fs.rmSync(dir, {recursive: true, force: true}); + } + }); + it("falls back to Node's bundled CAs when the system store can't be read", async () => { // @vscode/proxy-agent's own reader catches internally and reads the // host's real store, so swap the loader for one that rejects. diff --git a/packages/databricks-vscode/src/utils/network/proxyAgent.ts b/packages/databricks-vscode/src/utils/network/proxyAgent.ts index c9d0c1074..2bff15b99 100644 --- a/packages/databricks-vscode/src/utils/network/proxyAgent.ts +++ b/packages/databricks-vscode/src/utils/network/proxyAgent.ts @@ -51,8 +51,13 @@ function getLog(): Log { * intentionally disabled (`useHostProxy: false`) — it needs Electron's proxy * resolver, which the extension host doesn't expose. */ -function getProxyAgentParams(): ProxyAgentParams { +function getProxyAgentParams(host: URL): ProxyAgentParams { const log = getLog(); + const env = {...process.env}; + if (host.protocol === "http:") { + delete env.HTTPS_PROXY; + delete env.https_proxy; + } return { resolveProxy: async () => undefined, getProxyURL: () => workspaceConfigs.httpProxy, @@ -66,7 +71,7 @@ function getProxyAgentParams(): ProxyAgentParams { getLogLevel: () => LogLevel.Error, proxyResolveTelemetry: () => {}, useHostProxy: false, - env: process.env, + env, }; } @@ -240,7 +245,7 @@ export async function getDatabricksHttpAgent( host: URL, httpTimeoutSeconds?: number ): Promise { - const params = getProxyAgentParams(); + const params = getProxyAgentParams(host); const isHttps = host.protocol === "https:"; // Independent reads (OS trust store vs the configured PEM) — run them @@ -254,6 +259,9 @@ export async function getDatabricksHttpAgent( const resolver = createProxyResolver(params); const proxyUrl = await resolver.resolveProxyURL(host.toString()); + const usesTls = + isHttps || + (proxyUrl !== undefined && new URL(proxyUrl).protocol === "https:"); // Only set `ca` when we have certs to add on top of Node's bundled roots // (which `buildCaBundle` already folds in). On the fallback path `ca` is @@ -263,7 +271,7 @@ export async function getDatabricksHttpAgent( keepAlive: true, keepAliveMsecs: KEEP_ALIVE_MSECS, timeout: (httpTimeoutSeconds || DEFAULT_HTTP_TIMEOUT_SECONDS) * 1000, - ...(isHttps ? {rejectUnauthorized, ...(ca ? {ca} : {})} : {}), + ...(usesTls ? {rejectUnauthorized, ...(ca ? {ca} : {})} : {}), }; if (proxyUrl) { From 9ebf46f76d77b1b3aaede83006880abf6a88daf7 Mon Sep 17 00:00:00 2001 From: misha-db Date: Fri, 18 Sep 2026 18:09:28 +0400 Subject: [PATCH 31/31] fix(proxy): apply corp CA to endpoint TLS handshake through a proxy MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The merged CA bundle (Node roots + OS store + databricks.proxy.caCert) was passed to the HttpsProxyAgent constructor, but https-proxy-agent@7.0.6 uses those options only for the TLS socket to the proxy. The final handshake to the Databricks host is tls.connect({...opts, socket}), where opts is the SDK's per-request object and carries no `ca` — so with a proxy configured, the endpoint was validated against Node's bundled roots only and an internal CA was silently ignored. Users behind a TLS-intercepting proxy could keep verification on only by disabling it (strictSSL=false). Add a CaAwareHttpsProxyAgent subclass that folds the trust material and rejectUnauthorized into the per-request opts (which do flow to the endpoint tls.connect) for the secure-endpoint case. The no-proxy and http-endpoint paths are unchanged. Also: - Fold NODE_EXTRA_CA_CERTS file contents into the CA bundle. Setting an explicit `ca` replaces Node's default store, and NODE_EXTRA_CA_CERTS only merges into that default store (at startup), so users trusting a corp CA solely via that env var would silently lose trust after upgrade. Restores that trust. - Declare http-proxy-agent and https-proxy-agent as explicit dependencies; they were resolved only transitively via @vscode/proxy-agent. - Replace the misleading test that asserted proxy-side connectOpts with regression tests that drive an https:// target through a proxy and assert the CA / rejectUnauthorized on the endpoint tunnel, plus tests for the NODE_EXTRA_CA_CERTS merge and its unreadable-path fallback. --- packages/databricks-vscode/package.json | 2 + .../src/utils/network/proxyAgent.test.ts | 105 +++++++++++++--- .../src/utils/network/proxyAgent.ts | 115 +++++++++++++++--- yarn.lock | 2 + 4 files changed, 191 insertions(+), 33 deletions(-) diff --git a/packages/databricks-vscode/package.json b/packages/databricks-vscode/package.json index 503ae9d66..bc6b1bc98 100644 --- a/packages/databricks-vscode/package.json +++ b/packages/databricks-vscode/package.json @@ -1932,6 +1932,8 @@ "ansi-to-html": "^0.7.2", "bcryptjs": "^3.0.3", "highlight.js": "^11.10.0", + "http-proxy-agent": "^7.0.2", + "https-proxy-agent": "^7.0.6", "lodash": "^4.18.1", "markdown-it": "^15.0.0", "minimatch": "^10.2.3", diff --git a/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts b/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts index d006a9feb..deabe9649 100644 --- a/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts +++ b/packages/databricks-vscode/src/utils/network/proxyAgent.test.ts @@ -221,27 +221,64 @@ describe(__filename, () => { ); }); - it("applies TLS options when an http host uses an https proxy", async () => { - const dir = fs.mkdtempSync(path.join(os.tmpdir(), "dbx-ca-")); - const pemPath = path.join(dir, "corp-ca.pem"); - fs.writeFileSync(pemPath, FAKE_CA_PEM); - when(configsSpy.httpProxy).thenReturn("https://127.0.0.1:8443"); - when(configsSpy.proxyCaCert).thenReturn(pemPath); - when(configsSpy.proxyStrictSSL).thenReturn(false); - setSystemCertificatesLoaderForTests(async () => []); - + // Drive an https:// target through a proxy and assert the CA / strict-SSL + // land on the *endpoint* tunnel (the per-request `opts` that reach + // `tls.connect` for the Databricks host), not just the proxy socket + // (`connectOpts`). The base agent applies constructor options only to the + // proxy connection, so a merged `ca` there never verifies the host — this + // is the regression the CA-aware subclass fixes. + async function captureEndpointConnectOpts( + agent: HttpsProxyAgent + ) { + let capturedOpts: https.AgentOptions | undefined; + const superConnect = HttpsProxyAgent.prototype.connect; + // `super.connect` in the subclass resolves to this at call time; stub + // it so no real proxy connection is attempted. + HttpsProxyAgent.prototype.connect = async function (_req, opts) { + capturedOpts = opts as https.AgentOptions; + return {} as never; + }; try { - const agent = (await getDatabricksHttpAgent( - new URL("http://example.com") - )) as HttpProxyAgent; - const ca = agent.connectOpts.ca as string[]; - - assert.ok(agent instanceof HttpProxyAgent); - assert.ok(ca.includes(FAKE_CA_PEM)); - assert.strictEqual(agent.connectOpts.rejectUnauthorized, false); + await agent.connect( + {} as never, + { + secureEndpoint: true, + host: "example.com", + port: 443, + } as never + ); } finally { - fs.rmSync(dir, {recursive: true, force: true}); + HttpsProxyAgent.prototype.connect = superConnect; } + return capturedOpts; + } + + it("applies the CA to the endpoint TLS handshake through a proxy", async () => { + when(configsSpy.httpProxy).thenReturn("http://127.0.0.1:8080"); + setSystemCertificatesLoaderForTests(async () => [FAKE_CA_PEM]); + + const agent = (await getDatabricksHttpAgent( + new URL("https://example.com") + )) as HttpsProxyAgent; + assert.ok(agent instanceof HttpsProxyAgent); + + const opts = await captureEndpointConnectOpts(agent); + const ca = opts?.ca as string[]; + assert.ok(Array.isArray(ca)); + assert.ok(ca.includes(FAKE_CA_PEM)); + assert.strictEqual(opts?.rejectUnauthorized, true); + }); + + it("disables endpoint verification through a proxy when strict SSL is off", async () => { + when(configsSpy.httpProxy).thenReturn("http://127.0.0.1:8080"); + when(configsSpy.proxyStrictSSL).thenReturn(false); + + const agent = (await getDatabricksHttpAgent( + new URL("https://example.com") + )) as HttpsProxyAgent; + + const opts = await captureEndpointConnectOpts(agent); + assert.strictEqual(opts?.rejectUnauthorized, false); }); it("falls back to Node's bundled CAs when the system store can't be read", async () => { @@ -313,6 +350,38 @@ describe(__filename, () => { const ca = (agent.options as https.AgentOptions).ca as string[]; assert.ok(!ca || !ca.includes(FAKE_CA_PEM)); }); + + it("folds NODE_EXTRA_CA_CERTS into the trust store", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "dbx-ca-")); + const pemPath = path.join(dir, "extra-ca.pem"); + fs.writeFileSync(pemPath, FAKE_CA_PEM); + process.env.NODE_EXTRA_CA_CERTS = pemPath; + try { + const agent = (await getDatabricksHttpAgent( + new URL("https://example.com") + )) as https.Agent; + const ca = (agent.options as https.AgentOptions).ca as string[]; + assert.ok(Array.isArray(ca)); + assert.ok(ca.includes(FAKE_CA_PEM)); + // Still anchored on the bundled roots. + assert.ok(ca.includes(tls.rootCertificates[0])); + } finally { + fs.rmSync(dir, {recursive: true, force: true}); + } + }); + + it("ignores an unreadable NODE_EXTRA_CA_CERTS path", async () => { + process.env.NODE_EXTRA_CA_CERTS = path.join( + os.tmpdir(), + "does-not-exist-extra-xyz.pem" + ); + // Must not throw; falls back to the rest of the trust store. + const agent = (await getDatabricksHttpAgent( + new URL("https://example.com") + )) as https.Agent; + const ca = (agent.options as https.AgentOptions).ca as string[]; + assert.ok(!ca || !ca.includes(FAKE_CA_PEM)); + }); }); describe("createWorkspaceClient", () => { diff --git a/packages/databricks-vscode/src/utils/network/proxyAgent.ts b/packages/databricks-vscode/src/utils/network/proxyAgent.ts index 2bff15b99..7c868f927 100644 --- a/packages/databricks-vscode/src/utils/network/proxyAgent.ts +++ b/packages/databricks-vscode/src/utils/network/proxyAgent.ts @@ -201,28 +201,57 @@ async function loadConfiguredCaCert(): Promise { } } +/** + * Read the PEM bundle(s) named by `NODE_EXTRA_CA_CERTS`, if set. Node only + * merges this file into its *default* trust store, and only at process startup — + * so once we set an explicit `ca` (which replaces the default store), any CA a + * user trusts solely via `NODE_EXTRA_CA_CERTS` would silently stop being trusted + * after upgrade. Folding it back into the bundle preserves that trust. + * + * A bad path shouldn't break every TLS handshake, so we log and fall back to the + * rest of the trust store (same policy as {@link loadConfiguredCaCert}). + */ +async function loadNodeExtraCaCerts(): Promise { + const extraCaCertsPath = process.env.NODE_EXTRA_CA_CERTS; + if (!extraCaCertsPath) { + return undefined; + } + try { + return await readFile(extraCaCertsPath, "utf8"); + } catch (e) { + getLog().error( + `Failed to read NODE_EXTRA_CA_CERTS from "${extraCaCertsPath}"; ` + + "ignoring it. The certificate it points at will not be trusted.", + e + ); + return undefined; + } +} + /** * Assemble the CA trust list for the SDK's HTTPS agent, or `undefined` to leave * Node's default store in place. * * Any list we build is anchored on `tls.rootCertificates` (Node's bundled public - * roots) and then extended with the OS trust store and the configured PEM. - * Setting `ca` *replaces* Node's defaults, so if we set it to only the extra - * certs, public-root TLS would break — hence the merge. When we have nothing to - * add (system store unreadable and no `caCert`), return `undefined` so the - * caller omits `ca` and Node keeps its defaults. + * roots) and then extended with the OS trust store, the configured PEM, and the + * `NODE_EXTRA_CA_CERTS` bundle. Setting `ca` *replaces* Node's defaults, so if we + * set it to only the extra certs, public-root TLS would break — hence the merge. + * When we have nothing to add (system store unreadable, no `caCert`, no + * `NODE_EXTRA_CA_CERTS`), return `undefined` so the caller omits `ca` and Node + * keeps its defaults. * * Deduped because the OS store commonly re-lists the public roots already in * `tls.rootCertificates`; a `Set` keeps the handed-off list minimal. */ function buildCaBundle( systemCerts: string[] | undefined, - configuredCaCert: string | undefined + configuredCaCert: string | undefined, + nodeExtraCaCerts: string | undefined ): string[] | undefined { // @vscode/proxy-agent swallows a failed OS-store read and returns `[]`, so // treat empty the same as unreadable: nothing to add on top of Node's // bundled roots. - if (!systemCerts?.length && !configuredCaCert) { + if (!systemCerts?.length && !configuredCaCert && !nodeExtraCaCerts) { return undefined; } return [ @@ -230,10 +259,54 @@ function buildCaBundle( ...tls.rootCertificates, ...(systemCerts ?? []), ...(configuredCaCert ? [configuredCaCert] : []), + ...(nodeExtraCaCerts ? [nodeExtraCaCerts] : []), ]), ]; } +// The per-request options `agent-base` hands to `connect`. Derived from the +// agent's own `connect` signature so we don't take a direct dependency on +// `agent-base` (it resolves only transitively via the proxy agents). +type ProxyConnectOpts = Parameters["connect"]>[1]; + +/** + * `HttpsProxyAgent`, but with the CA bundle / strict-SSL setting applied to the + * *endpoint* TLS handshake, not just the connection to the proxy. + * + * `https-proxy-agent`'s constructor options only govern the TLS socket to the + * proxy (`this.connectOpts`). The final handshake to the Databricks host is + * `tls.connect({...opts, socket})`, where `opts` is the SDK's per-request object + * — which carries no `ca`. So a merged `ca` passed to the constructor never + * reaches the endpoint, and an internal CA is silently ignored whenever a proxy + * is set. We fold the trust material into `opts` here (which *does* flow to the + * endpoint `tls.connect`) before delegating to the base implementation. + */ +class CaAwareHttpsProxyAgent extends HttpsProxyAgent { + constructor( + proxy: string, + opts: https.AgentOptions, + private readonly endpointCa: string[] | undefined, + private readonly endpointRejectUnauthorized: boolean + ) { + super(proxy, opts); + } + + override async connect( + req: Parameters["connect"]>[0], + opts: ProxyConnectOpts + ) { + // Only for the endpoint TLS handshake (`secureEndpoint`); the proxy + // socket already trusts the same bundle via the constructor options. + if (opts.secureEndpoint) { + opts.rejectUnauthorized = this.endpointRejectUnauthorized; + if (this.endpointCa) { + opts.ca = this.endpointCa; + } + } + return super.connect(req, opts); + } +} + /** * Build the HTTP(S) agent the Databricks SDK should use, wiring in the proxy * (VS Code `http.proxy` setting + `http(s)_proxy` env vars, honouring @@ -248,13 +321,16 @@ export async function getDatabricksHttpAgent( const params = getProxyAgentParams(host); const isHttps = host.protocol === "https:"; - // Independent reads (OS trust store vs the configured PEM) — run them - // together rather than serially. - const [systemCerts, configuredCaCert] = await Promise.all([ - getSystemCertificates(params), - loadConfiguredCaCert(), - ]); - const ca = buildCaBundle(systemCerts, configuredCaCert); + // Independent reads (OS trust store, the configured PEM, the + // NODE_EXTRA_CA_CERTS bundle) — run them together rather than serially. + const [systemCerts, configuredCaCert, nodeExtraCaCerts] = await Promise.all( + [ + getSystemCertificates(params), + loadConfiguredCaCert(), + loadNodeExtraCaCerts(), + ] + ); + const ca = buildCaBundle(systemCerts, configuredCaCert, nodeExtraCaCerts); const rejectUnauthorized = strictSSL(); const resolver = createProxyResolver(params); @@ -275,8 +351,17 @@ export async function getDatabricksHttpAgent( }; if (proxyUrl) { + // For an https endpoint the CA/strict-SSL must also land on the endpoint + // handshake, not just the proxy socket — the base agent only applies the + // constructor options to the proxy connection. An http endpoint through a + // proxy never does an endpoint TLS handshake, so the plain agent is fine. return isHttps - ? new HttpsProxyAgent(proxyUrl, agentOptions) + ? new CaAwareHttpsProxyAgent( + proxyUrl, + agentOptions, + ca, + rejectUnauthorized + ) : new HttpProxyAgent(proxyUrl, agentOptions); } diff --git a/yarn.lock b/yarn.lock index 0e4b81944..653561ced 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4086,6 +4086,8 @@ __metadata: fs-extra: ^11.2.0 glob: ^13.0.6 highlight.js: ^11.10.0 + http-proxy-agent: ^7.0.2 + https-proxy-agent: ^7.0.6 lodash: ^4.18.1 markdown-it: ^15.0.0 minimatch: ^10.2.3