From fe3ac000ca7a5b962dc32eeaf4b8c0151a3c68ab Mon Sep 17 00:00:00 2001 From: Ehab Younes Date: Fri, 4 Dec 2026 21:36:38 +0300 Subject: [PATCH 1/2] feat(remote): offer a support bundle when the remote connection fails VS Code has no API that reports a lost remote connection, but it logs the decision to give up in the window log. ConnectionFailureMonitor reads new lines from that log and reports the first failure, and ConnectionFailurePrompt offers a support bundle. The failure stays stored per deployment until a bundle is saved or the user dismisses the offer, and the next successful connection offers it again for up to a day. Support bundles now include the window log and logs from Cursor Glass workspaces. --- CHANGELOG.md | 13 ++ src/commands.ts | 33 ++-- src/common/fs.ts | 10 ++ .../connectionFailureMonitor.ts | 137 ++++++++++++++++ .../connectionFailurePrompt.ts | 114 +++++++++++++ src/connectionFailure/logFileReader.ts | 77 +++++++++ src/connectionFailure/windowLog.ts | 42 +++++ src/instrumentation/EVENTS.md | 11 +- src/instrumentation/diagnostics.ts | 6 +- src/instrumentation/ssh.ts | 5 + src/remote/remote.ts | 21 +++ src/storage/mementoManager.ts | 42 ++++- src/supportBundle/files.ts | 9 +- src/supportBundle/logFiles.ts | 36 ++++- .../workspaces/workspacesPanelProvider.ts | 3 +- test/mocks/vscode.runtime.ts | 9 ++ .../connectionFailureMonitor.test.ts | 107 +++++++++++++ .../connectionFailurePrompt.test.ts | 151 ++++++++++++++++++ .../connectionFailure/logFileReader.test.ts | 62 +++++++ test/unit/connectionFailure/windowLog.test.ts | 82 ++++++++++ test/unit/connectionFailure/windowLogLines.ts | 58 +++++++ test/unit/storage/mementoManager.test.ts | 6 +- test/unit/supportBundle/logFiles.test.ts | 66 ++++++++ .../workspacesPanelProvider.test.ts | 2 +- 24 files changed, 1066 insertions(+), 36 deletions(-) create mode 100644 src/connectionFailure/connectionFailureMonitor.ts create mode 100644 src/connectionFailure/connectionFailurePrompt.ts create mode 100644 src/connectionFailure/logFileReader.ts create mode 100644 src/connectionFailure/windowLog.ts create mode 100644 test/unit/connectionFailure/connectionFailureMonitor.test.ts create mode 100644 test/unit/connectionFailure/connectionFailurePrompt.test.ts create mode 100644 test/unit/connectionFailure/logFileReader.test.ts create mode 100644 test/unit/connectionFailure/windowLog.test.ts create mode 100644 test/unit/connectionFailure/windowLogLines.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index fa56f31662..ef90a040f4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,19 @@ from published versions since it shows up in the VS Code extension changelog tab and is confusing to users. Add it back between releases if needed. --> +## Unreleased + +### Added + +- Support bundles include the VS Code window log, which records the editor's + remote connection and reconnect attempts. +- When VS Code gives up on the remote connection, the extension offers to + create a support bundle, and offers it again after a reload for up to a day. + +### Fixed + +- Support bundles include logs from Cursor Glass workspaces. + ## [v1.18.4](https://github.com/coder/vscode-coder/releases/tag/v1.18.4) 2026-12-03 ### Added diff --git a/src/commands.ts b/src/commands.ts index 7d25a9f956..ece44d8a73 100644 --- a/src/commands.ts +++ b/src/commands.ts @@ -456,8 +456,11 @@ export class Commands { }); } - public async supportBundle(target?: WorkspaceTarget): Promise { - await this.diagnosticTelemetry.trace("support_bundle", (telemetry) => + /** Returns the saved bundle, or undefined if none was created. */ + public supportBundle( + target?: WorkspaceTarget, + ): Promise { + return this.diagnosticTelemetry.trace("support_bundle", (telemetry) => this.runSupportBundle(target, telemetry), ); } @@ -465,7 +468,7 @@ export class Commands { private async runSupportBundle( target: WorkspaceTarget | undefined, telemetry: DiagnosticTrace, - ): Promise { + ): Promise { const resolved = await this.resolveDiagnosticWorkspace( target, "supportBundle", @@ -554,14 +557,25 @@ export class Commands { return; } - const action = await vscode.window.showInformationMessage( - `Support bundle saved to ${result.value.fsPath}`, - "Reveal in File Explorer", - ); - if (action === "Reveal in File Explorer") { - await vscode.commands.executeCommand("revealFileInOS", result.value); + // Not awaited: the notification can close without resolving. + void this.offerToRevealSupportBundle(result.value); + return result.value; + } + + private async offerToRevealSupportBundle(bundle: vscode.Uri): Promise { + try { + const action = await vscode.window.showInformationMessage( + `Support bundle saved to ${bundle.fsPath}`, + "Reveal in File Explorer", + ); + if (action === "Reveal in File Explorer") { + await vscode.commands.executeCommand("revealFileInOS", bundle); + } + } catch (error) { + this.logger.warn("Could not reveal the support bundle", error); } } + private promptSupportBundlePath(): Thenable { const defaultName = `coder-support-${Math.floor(Date.now() / 1000)}.zip`; return vscode.window.showSaveDialog({ @@ -578,6 +592,7 @@ export class Commands { "", "\u2022 Deployment and workspace diagnostics", "\u2022 Coder extension and connection logs from recent VS Code windows", + "\u2022 VS Code window logs, including remote connection events", "\u2022 Remote SSH extension logs", "\u2022 Locally recorded telemetry", "\u2022 Coder extension settings", diff --git a/src/common/fs.ts b/src/common/fs.ts index 8b25edb77b..77aaf15ade 100644 --- a/src/common/fs.ts +++ b/src/common/fs.ts @@ -4,6 +4,16 @@ import * as path from "node:path"; import type { Logger } from "../logging/logger"; +/** Whether a file system call failed because the path does not exist. */ +export function isEnoent(error: unknown): boolean { + return ( + typeof error === "object" && + error !== null && + "code" in error && + error.code === "ENOENT" + ); +} + const transientRenameCodes: ReadonlySet = new Set([ "EPERM", "EACCES", diff --git a/src/connectionFailure/connectionFailureMonitor.ts b/src/connectionFailure/connectionFailureMonitor.ts new file mode 100644 index 0000000000..7b8f71798e --- /dev/null +++ b/src/connectionFailure/connectionFailureMonitor.ts @@ -0,0 +1,137 @@ +import * as path from "node:path"; +import * as vscode from "vscode"; + +import { resolveLogContext } from "../supportBundle/logFiles"; + +import { LogFileReader } from "./logFileReader"; +import { parseWindowLogLine, type WindowLogEvent } from "./windowLog"; + +import type { SshTelemetry } from "../instrumentation/ssh"; +import type { Logger } from "../logging/logger"; + +export type ConnectionFailure = Exclude< + WindowLogEvent, + "extension_host_restarted" +>; + +export interface ConnectionFailureMonitorOptions { + readonly codeLogDir: string; + readonly telemetry: SshTelemetry; + readonly logger: Logger; +} + +/** + * VS Code waits up to 2s for the extension host's exit info before it logs a restart: + * https://github.com/microsoft/vscode/blob/e54c42b3917fa85e6f8e7c1eef3853f4db66cef6/src/vs/workbench/services/extensions/common/abstractExtensionService.ts#L899-L925 + */ +const EXTENSION_HOST_RESTART_WAIT_MS = 3000; +const POLL_INTERVAL_MS = 250; + +/** + * Watches the window log and fires `onDidFail` once, when VS Code gives up on + * the remote connection. + */ +export class ConnectionFailureMonitor implements vscode.Disposable { + private readonly failEmitter = new vscode.EventEmitter(); + public readonly onDidFail = this.failEmitter.event; + + private disposed = false; + private timer: NodeJS.Timeout | undefined; + private extensionHostLostAt: number | undefined; + private readFailing = false; + + private constructor( + private readonly options: ConnectionFailureMonitorOptions, + ) {} + + public static start( + options: ConnectionFailureMonitorOptions, + ): ConnectionFailureMonitor { + const monitor = new ConnectionFailureMonitor(options); + const logContext = resolveLogContext(options.codeLogDir); + if (logContext) { + const logPath = path.join(logContext.currentWindowPath, "renderer.log"); + void monitor.poll(new LogFileReader(logPath)); + } else { + options.logger.debug( + "Unrecognized log directory layout; not monitoring connection failures", + ); + } + return monitor; + } + + public dispose(): void { + this.disposed = true; + clearTimeout(this.timer); + this.failEmitter.dispose(); + } + + private async poll(reader: LogFileReader): Promise { + const lines = await this.readNewLines(reader); + if (this.disposed) { + return; + } + const failure = this.findFailure(lines); + if (failure) { + this.fail(failure); + } else { + this.timer = setTimeout(() => void this.poll(reader), POLL_INTERVAL_MS); + } + } + + /** + * Reads the lines added since the last poll. Never throws: a failed read + * returns no lines, is retried next poll, and is logged once per outage. + */ + private async readNewLines(reader: LogFileReader): Promise { + try { + const lines = await reader.readNewLines(); + this.readFailing = false; + return lines; + } catch (error) { + if (!this.readFailing) { + this.options.logger.debug( + "Could not read the VS Code window log", + error, + ); + } + this.readFailing = true; + return []; + } + } + + /** + * A lost extension host only counts as a failure if VS Code does not + * restart it within the wait. + */ + private findFailure(lines: readonly string[]): ConnectionFailure | undefined { + for (const line of lines) { + const event = parseWindowLogLine(line); + if (event === "extension_host_restarted") { + this.extensionHostLostAt = undefined; + } else if (event === "extension_host_connection_lost") { + // Restarts are logged at info level; above it a recovery looks like a failure. + if (vscode.env.logLevel <= vscode.LogLevel.Info) { + this.extensionHostLostAt ??= Date.now(); + } + } else if (event) { + return event; + } + } + const lostAt = this.extensionHostLostAt; + return lostAt !== undefined && + Date.now() - lostAt >= EXTENSION_HOST_RESTART_WAIT_MS + ? "extension_host_connection_lost" + : undefined; + } + + private fail(failure: ConnectionFailure): void { + const { logger, telemetry } = this.options; + logger.warn(`VS Code gave up on the remote connection: ${failure}`); + // Write out buffered debug logs before a reload can drop them. + logger.flush("remote_connection_failed"); + telemetry.connectionFailed(failure); + this.failEmitter.fire(failure); + this.dispose(); + } +} diff --git a/src/connectionFailure/connectionFailurePrompt.ts b/src/connectionFailure/connectionFailurePrompt.ts new file mode 100644 index 0000000000..27c319a84c --- /dev/null +++ b/src/connectionFailure/connectionFailurePrompt.ts @@ -0,0 +1,114 @@ +import * as vscode from "vscode"; + +import { vscodeProposed } from "../vscode/proposed"; + +import type { Logger } from "../logging/logger"; +import type { MementoManager } from "../storage/mementoManager"; + +export interface ConnectionFailurePromptOptions { + readonly safeHostname: string; + readonly remoteAuthority: string; + readonly workspaceName: string; + readonly mementoManager: MementoManager; + readonly logger: Logger; +} + +/** + * Offers a support bundle after a connection failure. The failure stays + * stored until a bundle is saved or the user dismisses the offer, so the + * next successful connection offers it again. + */ +export class ConnectionFailurePrompt { + public constructor( + private readonly options: ConnectionFailurePromptOptions, + ) {} + + /** + * Offers a bundle for a failure stored by an earlier window, once VS Code + * connects to the remote. Never throws. + */ + public async offerForPreviousFailure(): Promise { + const { mementoManager, safeHostname, remoteAuthority, workspaceName } = + this.options; + if (mementoManager.getConnectionFailure(safeHostname) !== remoteAuthority) { + return; + } + try { + await this.waitForConnection(); + } catch (error) { + this.options.logger.debug( + "Not offering a support bundle for the previous failure; the connection failed", + error, + ); + return; + } + this.showPrompt( + `The previous connection to ${workspaceName} failed. Create a support bundle to capture diagnostics?`, + ); + } + + /** Stores the failure, then offers a support bundle. Never throws. */ + public async offerForFailure(): Promise { + const { mementoManager, safeHostname, remoteAuthority, workspaceName } = + this.options; + try { + await mementoManager.setConnectionFailure(safeHostname, remoteAuthority); + } catch (error) { + this.options.logger.warn("Could not store the connection failure", error); + } + this.showPrompt( + `The connection to ${workspaceName} failed. Create a support bundle to capture diagnostics?`, + ); + } + + /** + * Shows the notification without awaiting it: it can close without + * resolving, which keeps the failure stored for the next connection. + */ + private showPrompt(message: string): void { + void vscodeProposed.window + .showErrorMessage(message, "Create Support Bundle") + .then( + (choice) => this.handleChoice(choice), + (error: unknown) => + this.options.logger.warn( + "Could not show the support bundle prompt", + error, + ), + ); + } + + /** Keeps the failure stored if the user chose a bundle but none was saved. */ + private async handleChoice(choice: string | undefined): Promise { + const { mementoManager, safeHostname, logger } = this.options; + try { + if (choice === "Create Support Bundle") { + const bundle = await vscodeProposed.commands.executeCommand< + vscode.Uri | undefined + >("coder.supportBundle"); + if (!bundle) { + return; + } + } + await mementoManager.clearConnectionFailure(safeHostname); + } catch (error) { + logger.warn("Could not create the support bundle", error); + } + } + + /** + * Resolves once VS Code is connected, and rejects if it cannot connect. + * VS Code registers the remote file system after its first request over + * the connection, and holds file system calls until then: + * https://github.com/microsoft/vscode/blob/e54c42b3917fa85e6f8e7c1eef3853f4db66cef6/src/vs/workbench/services/remote/common/remoteFileSystemProviderClient.ts#L20-L49 + */ + private async waitForConnection(): Promise { + await vscode.workspace.fs.stat( + vscode.Uri.from({ + scheme: "vscode-remote", + authority: this.options.remoteAuthority, + path: "/", + }), + ); + } +} diff --git a/src/connectionFailure/logFileReader.ts b/src/connectionFailure/logFileReader.ts new file mode 100644 index 0000000000..a7f62a2e4d --- /dev/null +++ b/src/connectionFailure/logFileReader.ts @@ -0,0 +1,77 @@ +import * as fs from "node:fs/promises"; + +import { isEnoent } from "../common/fs"; + +/** Logs grow a few lines at a time, so a read rarely comes close. */ +const MAX_BYTES_PER_READ = 1024 * 1024; + +/** + * Reads the lines appended to a log file. A file that shrank was rotated, + * so reading starts over from its beginning. + */ +export class LogFileReader { + /** Undefined until the first read, which skips the existing content. */ + private offset: number | undefined; + private pendingRead: Promise = Promise.resolve(); + + public constructor(private readonly logPath: string) {} + + /** Lines completed since the last call. Concurrent calls run in turn. */ + public readNewLines(): Promise { + const read = this.pendingRead.then(() => this.readFromOffset()); + this.pendingRead = read.catch(() => undefined); + return read; + } + + private async readFromOffset(): Promise { + const size = await this.getFileSize(); + if (this.offset === undefined) { + this.offset = size; + return []; + } + if (size < this.offset) { + this.offset = 0; + } + const length = Math.min(size - this.offset, MAX_BYTES_PER_READ); + if (length === 0) { + return []; + } + const bytes = await this.readBytes(this.offset, length); + const end = bytes.lastIndexOf("\n") + 1; + // Leave a partial line for the next read, unless it fills the whole read. + this.offset += + end === 0 && bytes.length === MAX_BYTES_PER_READ ? bytes.length : end; + return bytes.toString("utf8", 0, end).split(/\r?\n/).slice(0, -1); + } + + /** + * Opens the file only for the read. On Windows, Node opens files with + * FILE_SHARE_DELETE, so the handle never blocks a rotation's rename: + * https://github.com/libuv/libuv/blob/38a2ba80088ef38d968cfbf05455adcedd35919f/src/win/fs.c#L510 + */ + private async readBytes(position: number, length: number): Promise { + const handle = await fs.open(this.logPath, "r"); + try { + const buffer = Buffer.alloc(length); + const { bytesRead } = await handle.read(buffer, 0, length, position); + return buffer.subarray(0, bytesRead); + } finally { + await handle.close(); + } + } + + /** + * A missing file (not created yet, or mid-rotation) has size 0. Other + * errors, like EBUSY on Windows, throw so the offset is kept. + */ + private async getFileSize(): Promise { + try { + return (await fs.stat(this.logPath)).size; + } catch (error) { + if (isEnoent(error)) { + return 0; + } + throw error; + } + } +} diff --git a/src/connectionFailure/windowLog.ts b/src/connectionFailure/windowLog.ts new file mode 100644 index 0000000000..66d80be468 --- /dev/null +++ b/src/connectionFailure/windowLog.ts @@ -0,0 +1,42 @@ +/** A remote connection event that VS Code writes to the window log. */ +export type WindowLogEvent = + | "initial_connection_failed" + | "management_connection_lost" + | "extension_host_connection_lost" + | "extension_host_restarted"; + +const WINDOW_LOG_PATTERNS: ReadonlyArray<{ + readonly event: WindowLogEvent; + readonly pattern: RegExp; +}> = [ + // Every initial attempt failed. Cursor logs one space after `]`, not two. + // https://github.com/microsoft/vscode/blob/e54c42b3917fa85e6f8e7c1eef3853f4db66cef6/src/vs/platform/remote/common/remoteAgentConnection.ts#L451 + { + event: "initial_connection_failed", + pattern: + /\[remote-connection\]\[attempt \d+\]\s+An error occurred in initial connection! It will be treated as a permanent error/, + }, + // The reconnect loop gave up, or the grace time is zero. Cursor appends + // the error to the line. + // https://github.com/microsoft/vscode/blob/e54c42b3917fa85e6f8e7c1eef3853f4db66cef6/src/vs/platform/remote/common/remoteAgentConnection.ts#L664-L741 + { + event: "management_connection_lost", + pattern: + /\[remote-connection\]\[Management\s*\].*(?:Will give up now!|will not attempt to reconnect)/, + }, + { + event: "extension_host_connection_lost", + pattern: + /\[remote-connection\]\[ExtensionHost\s*\].*(?:Will give up now!|will not attempt to reconnect)/, + }, + // Logged at info level. Cursor says "Quietly". + // https://github.com/microsoft/vscode/blob/e54c42b3917fa85e6f8e7c1eef3853f4db66cef6/src/vs/workbench/services/extensions/common/abstractExtensionService.ts#L925 + { + event: "extension_host_restarted", + pattern: /(?:Automatically|Quietly) restarting the remote extension host\./, + }, +]; + +export function parseWindowLogLine(line: string): WindowLogEvent | undefined { + return WINDOW_LOG_PATTERNS.find(({ pattern }) => pattern.test(line))?.event; +} diff --git a/src/instrumentation/EVENTS.md b/src/instrumentation/EVENTS.md index bc1eb3d18a..eecbb16aac 100644 --- a/src/instrumentation/EVENTS.md +++ b/src/instrumentation/EVENTS.md @@ -14,7 +14,7 @@ new ones live in `CONVENTIONS.md`. | [Commands](#commands) | `command.invoked`, `command.diagnostic.completed` | | [Deployment](#deployment) | `deployment.suspended`, `deployment.recovered`, `deployment.cross_window.detected`, `deployment.auth_config.recovery_failed` | | [Remote setup](#remote-setup) | `remote.setup` | -| [SSH](#ssh) | `ssh.process.discovered`, `ssh.process.lost`, `ssh.process.recovered`, `ssh.process.replaced`, `ssh.process.disposed`, `ssh.network.sampled` | +| [SSH](#ssh) | `ssh.process.discovered`, `ssh.process.lost`, `ssh.process.recovered`, `ssh.process.replaced`, `ssh.process.disposed`, `ssh.connection.failed`, `ssh.network.sampled` | | [HTTP](#http) | `http.requests` | | [WebSocket connections](#websocket-connections) | `connection.state_transitioned`, `connection.opened`, `connection.dropped`, `connection.reconnect_resolved`, `connection.unreachable` | | [Workspace](#workspace) | `workspace.{start,stop,restart,update,delete}.triggered`, `workspace.start.prompted`, `workspace.update.prompted`, `workspace.open`, `workspace.picker.prompted`, `workspace.dev_container.open`, `workspace.state_transitioned`, `workspace.agent.state_transitioned` | @@ -358,6 +358,15 @@ Emitted by `SshTelemetry`. ### Logs +#### `ssh.connection.failed` + +VS Code gave up on the remote connection, read from the window log. The +extension then offers a support bundle. + +| Attribute | Values | +| --------- | ------------------------------------------------------------------------------------------- | +| `kind` | `initial_connection_failed`, `management_connection_lost`, `extension_host_connection_lost` | + #### `ssh.process.lost` | Attribute | Values | diff --git a/src/instrumentation/diagnostics.ts b/src/instrumentation/diagnostics.ts index c2c6111b45..c92deb30ba 100644 --- a/src/instrumentation/diagnostics.ts +++ b/src/instrumentation/diagnostics.ts @@ -43,10 +43,10 @@ export interface DiagnosticTrace { export class DiagnosticTelemetry { public constructor(private readonly telemetry: TelemetryReporter) {} - public trace( + public trace( command: DiagnosticCommand, - fn: (trace: DiagnosticTrace) => Promise, - ): Promise { + fn: (trace: DiagnosticTrace) => Promise, + ): Promise { return this.telemetry.trace( "command.diagnostic.completed", (span) => fn(new SpanDiagnosticTrace(span)), diff --git a/src/instrumentation/ssh.ts b/src/instrumentation/ssh.ts index e3898ba240..1d981f4433 100644 --- a/src/instrumentation/ssh.ts +++ b/src/instrumentation/ssh.ts @@ -1,3 +1,4 @@ +import type { ConnectionFailure } from "../connectionFailure/connectionFailureMonitor"; import type { NetworkInfo } from "../remote/sshProcess"; import type { TelemetryReporter } from "../telemetry/reporter"; @@ -114,6 +115,10 @@ export class SshTelemetry { this.#lastNetworkSample = undefined; } + public connectionFailed(kind: ConnectionFailure): void { + this.#telemetry.log("ssh.connection.failed", { kind }); + } + public networkSampled(network: NetworkInfo): void { const now = performance.now(); const previous = this.#lastNetworkSample; diff --git a/src/remote/remote.ts b/src/remote/remote.ts index 685684f905..e4797f1def 100644 --- a/src/remote/remote.ts +++ b/src/remote/remote.ts @@ -26,6 +26,8 @@ import { CONFIG_CHANGE_DEBOUNCE_MS, watchConfigurationChanges, } from "../configWatcher"; +import { ConnectionFailureMonitor } from "../connectionFailure/connectionFailureMonitor"; +import { ConnectionFailurePrompt } from "../connectionFailure/connectionFailurePrompt"; import { raceWithAbort, throwIfAborted } from "../error/abort"; import { toError } from "../error/normalize"; import { @@ -39,6 +41,7 @@ import { RemoteSetupTelemetry, type RemoteSetupTracer, } from "../instrumentation/remoteSetup"; +import { SshTelemetry } from "../instrumentation/ssh"; import { OAuthSessionManager } from "../oauth/sessionManager"; import { type CliAuth, @@ -477,6 +480,24 @@ export class Remote { ); disposables.push(sshMonitor); + const failurePrompt = new ConnectionFailurePrompt({ + safeHostname: parts.safeHostname, + remoteAuthority: args.remoteAuthority, + workspaceName, + mementoManager: this.serviceContainer.getMementoManager(), + logger: this.logger, + }); + void failurePrompt.offerForPreviousFailure(); + const failureMonitor = ConnectionFailureMonitor.start({ + codeLogDir: this.pathResolver.getCodeLogDir(), + telemetry: new SshTelemetry( + this.serviceContainer.getTelemetryService(), + ), + logger: this.logger, + }); + failureMonitor.onDidFail(() => void failurePrompt.offerForFailure()); + disposables.push(failureMonitor); + this.commands.workspaceLogPath = sshMonitor.getLogFilePath(); const reregisterLabelFormatter = () => { diff --git a/src/storage/mementoManager.ts b/src/storage/mementoManager.ts index 59a3e12bf6..02d7f955f5 100644 --- a/src/storage/mementoManager.ts +++ b/src/storage/mementoManager.ts @@ -10,9 +10,12 @@ const MAX_URLS = 10; const DEPLOYMENT_ACCESS_PREFIX = "coder.access."; const SURFACED_BANNERS_PREFIX = "coder.surfacedBanners."; const DISMISSED_SSH_OPTIONS_PREFIX = "coder.dismissedSshOptions."; +const CONNECTION_FAILURE_PREFIX = "coder.connectionFailure."; const KeysSchema = z.array(z.string()); +const CONNECTION_FAILURE_TTL_MS = 24 * 60 * 60 * 1000; + /** Pending values expire after this duration to guard against stale * state from crashes or interrupted reloads. */ const PENDING_TTL_MS = 5 * 60 * 1000; @@ -78,7 +81,7 @@ export class MementoManager { * Returns "none" (the default) when no mode was explicitly set. */ public async getAndClearStartupMode(): Promise { - const value = this.getStamped("startupMode"); + const value = this.getStamped("startupMode", PENDING_TTL_MS); if (value !== undefined) { await this.memento.update("startupMode", undefined); } @@ -130,17 +133,44 @@ export class MementoManager { return this.addKeys(DISMISSED_SSH_OPTIONS_PREFIX + safeHostname, options); } - /** Clear all per-deployment state (access timestamp, stored key sets). */ + /** Clear all per-deployment state (access timestamp, stored key sets, connection failure). */ public async clearDeploymentData(safeHostname: string): Promise { await Promise.all( [ DEPLOYMENT_ACCESS_PREFIX, SURFACED_BANNERS_PREFIX, DISMISSED_SSH_OPTIONS_PREFIX, + CONNECTION_FAILURE_PREFIX, ].map((prefix) => this.memento.update(prefix + safeHostname, undefined)), ); } + /** Record a failed connection so the next activation offers a support bundle. */ + public async setConnectionFailure( + safeHostname: string, + remoteAuthority: string, + ): Promise { + await this.setStamped( + CONNECTION_FAILURE_PREFIX + safeHostname, + remoteAuthority, + ); + } + + /** The remote authority whose connection failed within the last day. */ + public getConnectionFailure(safeHostname: string): string | undefined { + return this.getStamped( + CONNECTION_FAILURE_PREFIX + safeHostname, + CONNECTION_FAILURE_TTL_MS, + ); + } + + public async clearConnectionFailure(safeHostname: string): Promise { + await this.memento.update( + CONNECTION_FAILURE_PREFIX + safeHostname, + undefined, + ); + } + private getKeys(key: string): string[] { const result = KeysSchema.safeParse(this.memento.get(key)); return result.success ? result.data : []; @@ -162,14 +192,14 @@ export class MementoManager { await this.memento.update(key, { value, setAt: Date.now() }); } - private getStamped(key: string): T | undefined { + private getStamped(key: string, ttlMs: number): T | undefined { const raw = this.memento.get>(key); - if (raw?.setAt !== undefined && Date.now() - raw.setAt <= PENDING_TTL_MS) { + if (raw?.setAt !== undefined && Date.now() - raw.setAt <= ttlMs) { return raw.value; } - // Expired or legacy, clean up. + // Expired or legacy, clean up. Best effort: the value is ignored either way. if (raw !== undefined) { - void this.memento.update(key, undefined); + void this.memento.update(key, undefined).then(undefined, () => undefined); } return undefined; } diff --git a/src/supportBundle/files.ts b/src/supportBundle/files.ts index f5669258c2..6bf13b01c6 100644 --- a/src/supportBundle/files.ts +++ b/src/supportBundle/files.ts @@ -2,6 +2,7 @@ import { type Dirent } from "node:fs"; import * as fs from "node:fs/promises"; import * as path from "node:path"; +import { isEnoent } from "../common/fs"; import { type Logger } from "../logging/logger"; export interface CollectedFile { @@ -138,14 +139,6 @@ export async function collectMatchingFiles( return results; } -function isEnoent(error: unknown): boolean { - return ( - typeof error === "object" && - error !== null && - (error as { code?: unknown }).code === "ENOENT" - ); -} - /** Read the last `length` bytes of `filePath`. */ async function readTail(filePath: string, length: number): Promise { const handle = await fs.open(filePath, "r"); diff --git a/src/supportBundle/logFiles.ts b/src/supportBundle/logFiles.ts index f1a1176235..d94db5025e 100644 --- a/src/supportBundle/logFiles.ts +++ b/src/supportBundle/logFiles.ts @@ -81,10 +81,7 @@ export function resolveLogContext( const sessionDir = path.dirname(windowDir); // Match the layout, not the id: forks rebrand it. - if ( - path.basename(exthostDir) !== "exthost" || - !/^window\d+$/i.test(windowName) - ) { + if (path.basename(exthostDir) !== "exthost" || !isWindowDirName(windowName)) { return undefined; } @@ -107,12 +104,12 @@ export async function collectWindowLogDirs( (await readDirents(logsRoot, logger)).map(async (entry) => { if (!entry.isDirectory()) return; const entryPath = path.join(logsRoot, entry.name); - if (/^window\d+$/i.test(entry.name)) { + if (isWindowDirName(entry.name)) { windows.push({ relativePath: entry.name, windowPath: entryPath }); return; } for (const sub of await readDirents(entryPath, logger)) { - if (sub.isDirectory() && /^window\d+$/i.test(sub.name)) { + if (sub.isDirectory() && isWindowDirName(sub.name)) { windows.push({ relativePath: `${entry.name}/${sub.name}`, windowPath: path.join(entryPath, sub.name), @@ -227,6 +224,19 @@ async function collectVsCodeWindowLogs( extLogs, ), ); + // The window log holds VS Code's own remote connection and reconnect lines. + addFiles( + files, + prefixFiles( + `vscode-logs/window/${normalizeZipPath(window.relativePath)}`, + await collectDirFiles( + window.windowPath, + logger, + isWindowLogFile, + false, + ), + ), + ); const isCurrent = window.windowPath === context.currentWindowPath; for (const sshLog of await collectMatchingFiles( @@ -255,6 +265,20 @@ async function collectVsCodeWindowLogs( return files; } +/** + * `window`, or Cursor Glass's per-workspace `window_wb`: + * https://github.com/microsoft/vscode/blob/e54c42b3917fa85e6f8e7c1eef3853f4db66cef6/src/vs/workbench/services/environment/electron-browser/environmentService.ts#L113-L116 + */ +const isWindowDirName = (name: string): boolean => + /^window\d+(_wb\d+)?$/i.test(name); + +/** + * `renderer.log`, plus spdlog's rotated `renderer.N.log`: + * https://github.com/gabime/spdlog/blob/71ab85cdcde1de4c4ab824305ec8cbde8f30c483/include/spdlog/sinks/rotating_file_sink-inl.h#L52-L53 + */ +const isWindowLogFile = (name: string): boolean => + /^renderer(\.\d+)?\.log$/.test(name); + // Coder CLI logs: `coder-ssh-*.log` or bare `.log`. const isProxyLogFile = (name: string): boolean => isLogFile(name) && (name.startsWith("coder-ssh") || /^\d+\.log$/.test(name)); diff --git a/src/webviews/workspaces/workspacesPanelProvider.ts b/src/webviews/workspaces/workspacesPanelProvider.ts index 0aa4a411d3..4a0ed58db1 100644 --- a/src/webviews/workspaces/workspacesPanelProvider.ts +++ b/src/webviews/workspaces/workspacesPanelProvider.ts @@ -232,7 +232,8 @@ export class WorkspacesPanelProvider case "speedTest": return this.commands.speedTest({ workspace, agent }); case "supportBundle": - return this.commands.supportBundle({ workspace, agent }); + await this.commands.supportBundle({ workspace, agent }); + return; } } diff --git a/test/mocks/vscode.runtime.ts b/test/mocks/vscode.runtime.ts index e40d7036f1..2468608c6b 100644 --- a/test/mocks/vscode.runtime.ts +++ b/test/mocks/vscode.runtime.ts @@ -42,6 +42,12 @@ export const LogLevel = E({ Error: 5, }); export const UIKind = E({ Desktop: 1, Web: 2 }); +export const FileType = E({ + Unknown: 0, + File: 1, + Directory: 2, + SymbolicLink: 64, +}); export const InputBoxValidationSeverity = E({ Info: 1, Warning: 2, @@ -290,6 +296,9 @@ export const env = { sessionId: "test-session-id", remoteName: undefined as string | undefined, shell: "/bin/bash", + get logLevel(): number { + return LogLevel.Info; + }, get uriScheme(): string { return uriScheme; }, diff --git a/test/unit/connectionFailure/connectionFailureMonitor.test.ts b/test/unit/connectionFailure/connectionFailureMonitor.test.ts new file mode 100644 index 0000000000..3d14a0b0b9 --- /dev/null +++ b/test/unit/connectionFailure/connectionFailureMonitor.test.ts @@ -0,0 +1,107 @@ +import { vol } from "memfs"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import * as vscode from "vscode"; + +import { + type ConnectionFailure, + ConnectionFailureMonitor, +} from "@/connectionFailure/connectionFailureMonitor"; +import { SshTelemetry } from "@/instrumentation/ssh"; + +import { createTelemetryHarness } from "../../mocks/telemetry"; +import { createMockLogger } from "../../mocks/testHelpers"; + +import { + EXTENSION_HOST_GAVE_UP, + EXTENSION_HOST_RESTARTED, + MANAGEMENT_GAVE_UP, + MANAGEMENT_RECONNECTING, +} from "./windowLogLines"; + +vi.mock("node:fs/promises", async () => (await import("memfs")).fs.promises); + +const WINDOW_DIR = "/logs/20261203T100000/window1"; +const LOG_PATH = `${WINDOW_DIR}/renderer.log`; + +async function setup() { + // An earlier failure in this window, which must not be reported. + vol.fromJSON({ [LOG_PATH]: MANAGEMENT_GAVE_UP }); + const { sink, service } = createTelemetryHarness(); + const logger = createMockLogger(); + const failures: ConnectionFailure[] = []; + const monitor = ConnectionFailureMonitor.start({ + codeLogDir: `${WINDOW_DIR}/exthost/coder.coder-remote`, + telemetry: new SshTelemetry(service), + logger, + }); + monitor.onDidFail((failure) => failures.push(failure)); + await vi.advanceTimersByTimeAsync(0); + const writeLog = async (text: string): Promise => { + vol.appendFileSync(LOG_PATH, text); + await vi.advanceTimersByTimeAsync(500); + }; + return { sink, logger, failures, writeLog }; +} + +describe("ConnectionFailureMonitor", () => { + beforeEach(() => { + vi.useFakeTimers(); + vol.reset(); + }); + + afterEach(() => { + vi.clearAllTimers(); + vi.restoreAllMocks(); + vi.useRealTimers(); + }); + + it("reports the first failure once", async () => { + const { sink, logger, failures, writeLog } = await setup(); + + await writeLog(EXTENSION_HOST_GAVE_UP + MANAGEMENT_RECONNECTING); + await writeLog(MANAGEMENT_GAVE_UP + MANAGEMENT_GAVE_UP); + await vi.advanceTimersByTimeAsync(5000); + + expect(failures).toEqual(["management_connection_lost"]); + expect(logger.flush).toHaveBeenCalledWith("remote_connection_failed"); + expect(sink.expectOne("ssh.connection.failed").properties).toMatchObject({ + kind: "management_connection_lost", + }); + }); + + it("reports a remote extension host that stays down", async () => { + const { failures, writeLog } = await setup(); + + await writeLog(EXTENSION_HOST_GAVE_UP); + expect(failures).toEqual([]); + await vi.advanceTimersByTimeAsync(3000); + + expect(failures).toEqual(["extension_host_connection_lost"]); + }); + + interface ExtensionHostRecovery { + name: string; + logLevel: vscode.LogLevel; + log: string; + } + it.each([ + { + name: "VS Code restarts the remote extension host", + logLevel: vscode.LogLevel.Info, + log: EXTENSION_HOST_GAVE_UP + EXTENSION_HOST_RESTARTED, + }, + { + name: "the log level hides restarts", + logLevel: vscode.LogLevel.Warning, + log: EXTENSION_HOST_GAVE_UP, + }, + ])("reports nothing when $name", async ({ logLevel, log }) => { + vi.spyOn(vscode.env, "logLevel", "get").mockReturnValue(logLevel); + const { failures, writeLog } = await setup(); + + await writeLog(log); + await vi.advanceTimersByTimeAsync(5000); + + expect(failures).toEqual([]); + }); +}); diff --git a/test/unit/connectionFailure/connectionFailurePrompt.test.ts b/test/unit/connectionFailure/connectionFailurePrompt.test.ts new file mode 100644 index 0000000000..4816c3e288 --- /dev/null +++ b/test/unit/connectionFailure/connectionFailurePrompt.test.ts @@ -0,0 +1,151 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import * as vscode from "vscode"; + +import { ConnectionFailurePrompt } from "@/connectionFailure/connectionFailurePrompt"; +import { MementoManager } from "@/storage/mementoManager"; + +import { + createMockLogger, + flushPromises, + InMemoryMemento, +} from "../../mocks/testHelpers"; + +const HOSTNAME = "example.com"; +const AUTHORITY = `ssh-remote+coder-vscode.${HOSTNAME}--alice--dev`; +const CREATE_BUNDLE = "Create Support Bundle"; +const FAILED = + "The connection to alice/dev failed. Create a support bundle to capture diagnostics?"; +/** `stat` of the remote root, which resolves once VS Code connects. */ +const REMOTE_ROOT: vscode.FileStat = { + type: vscode.FileType.Directory, + ctime: 0, + mtime: 0, + size: 0, +}; +const PREVIOUSLY_FAILED = + "The previous connection to alice/dev failed. Create a support bundle to capture diagnostics?"; + +function setup() { + const mementoManager = new MementoManager(new InMemoryMemento()); + /** A prompt in a newly activated window. */ + const activate = () => + new ConnectionFailurePrompt({ + safeHostname: HOSTNAME, + remoteAuthority: AUTHORITY, + workspaceName: "alice/dev", + mementoManager, + logger: createMockLogger(), + }); + return { mementoManager, activate }; +} + +function prompts(): unknown[][] { + return vi.mocked(vscode.window.showErrorMessage).mock.calls; +} + +describe("ConnectionFailurePrompt", () => { + beforeEach(() => { + vi.useFakeTimers(); + vi.clearAllMocks(); + vi.mocked(vscode.window.showErrorMessage).mockResolvedValue(undefined); + // The next window connects. + vi.mocked(vscode.workspace.fs.stat).mockResolvedValue(REMOTE_ROOT); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + it("creates a support bundle and stops offering it", async () => { + vi.mocked(vscode.window.showErrorMessage).mockResolvedValue( + CREATE_BUNDLE as never, + ); + vi.mocked(vscode.commands.executeCommand).mockResolvedValue( + vscode.Uri.file("/home/alice/coder-support.zip"), + ); + const { activate } = setup(); + + await activate().offerForFailure(); + await flushPromises(); + await activate().offerForPreviousFailure(); + + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + "coder.supportBundle", + ); + expect(prompts()).toEqual([[FAILED, CREATE_BUNDLE]]); + }); + + interface UnsavedBundle { + name: string; + answer: () => Promise; + } + it.each([ + { + name: "the window reloads before the user answers", + answer: () => new Promise(() => undefined), + }, + { + name: "creating the bundle fails", + answer: () => Promise.resolve(CREATE_BUNDLE), + }, + ])( + "offers the bundle on the next connection when $name", + async ({ answer }) => { + vi.mocked(vscode.window.showErrorMessage).mockReturnValueOnce( + answer() as never, + ); + vi.mocked(vscode.commands.executeCommand).mockResolvedValue(undefined); + const { activate } = setup(); + await activate().offerForFailure(); + await flushPromises(); + + await activate().offerForPreviousFailure(); + + expect(prompts()).toEqual([ + [FAILED, CREATE_BUNDLE], + [PREVIOUSLY_FAILED, CREATE_BUNDLE], + ]); + }, + ); + + it("offers a previous failure only after VS Code connects", async () => { + let connect = (): void => undefined; + vi.mocked(vscode.workspace.fs.stat).mockReturnValue( + new Promise((resolve) => { + connect = () => resolve(REMOTE_ROOT); + }), + ); + const { mementoManager, activate } = setup(); + await mementoManager.setConnectionFailure(HOSTNAME, AUTHORITY); + + const offered = activate().offerForPreviousFailure(); + await flushPromises(); + expect(prompts()).toEqual([]); + connect(); + await offered; + + expect(prompts()).toEqual([[PREVIOUSLY_FAILED, CREATE_BUNDLE]]); + }); + + it("does not offer a previous failure when the connection fails", async () => { + vi.mocked(vscode.workspace.fs.stat).mockRejectedValue( + new Error("ENOPRO: No file system provider found"), + ); + const { mementoManager, activate } = setup(); + await mementoManager.setConnectionFailure(HOSTNAME, AUTHORITY); + + await activate().offerForPreviousFailure(); + + expect(prompts()).toEqual([]); + }); + + it("stops offering the bundle a day after the failure", async () => { + const { mementoManager, activate } = setup(); + await mementoManager.setConnectionFailure(HOSTNAME, AUTHORITY); + vi.advanceTimersByTime(24 * 60 * 60 * 1000 + 1); + + await activate().offerForPreviousFailure(); + + expect(prompts()).toEqual([]); + }); +}); diff --git a/test/unit/connectionFailure/logFileReader.test.ts b/test/unit/connectionFailure/logFileReader.test.ts new file mode 100644 index 0000000000..b30a9227ce --- /dev/null +++ b/test/unit/connectionFailure/logFileReader.test.ts @@ -0,0 +1,62 @@ +import { fs as memfs, vol } from "memfs"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import { LogFileReader } from "@/connectionFailure/logFileReader"; + +vi.mock("node:fs/promises", async () => (await import("memfs")).fs.promises); + +const LOG_PATH = "/logs/window1/renderer.log"; + +/** A reader that has skipped the log's existing line. */ +async function setup(): Promise { + vol.fromJSON({ [LOG_PATH]: "2026-12-03 10:00:00.000 [info] earlier\n" }); + const reader = new LogFileReader(LOG_PATH); + expect(await reader.readNewLines()).toEqual([]); + return reader; +} + +describe("LogFileReader", () => { + beforeEach(() => { + vol.reset(); + vi.restoreAllMocks(); + }); + + it("returns lines once they are complete, across a rotation", async () => { + const reader = await setup(); + + vol.appendFileSync(LOG_PATH, "first\r\nsec"); + expect(await reader.readNewLines()).toEqual(["first"]); + vol.appendFileSync(LOG_PATH, "ond\n"); + expect(await reader.readNewLines()).toEqual(["second"]); + + vol.renameSync(LOG_PATH, "/logs/window1/renderer.1.log"); + expect(await reader.readNewLines()).toEqual([]); + vol.writeFileSync(LOG_PATH, "after rotation\n"); + expect(await reader.readNewLines()).toEqual(["after rotation"]); + }); + + it("returns each line once to concurrent reads", async () => { + const reader = await setup(); + + vol.appendFileSync(LOG_PATH, "one\ntwo\n"); + const reads = await Promise.all([ + reader.readNewLines(), + reader.readNewLines(), + ]); + + expect(reads.flat()).toEqual(["one", "two"]); + }); + + it("keeps its place while the file is locked", async () => { + const reader = await setup(); + vi.spyOn(memfs.promises, "stat").mockRejectedValueOnce( + Object.assign(new Error("EBUSY: resource busy or locked"), { + code: "EBUSY", + }), + ); + + await expect(reader.readNewLines()).rejects.toThrow("EBUSY"); + vol.appendFileSync(LOG_PATH, "new\n"); + expect(await reader.readNewLines()).toEqual(["new"]); + }); +}); diff --git a/test/unit/connectionFailure/windowLog.test.ts b/test/unit/connectionFailure/windowLog.test.ts new file mode 100644 index 0000000000..b51b42c349 --- /dev/null +++ b/test/unit/connectionFailure/windowLog.test.ts @@ -0,0 +1,82 @@ +import { describe, expect, it } from "vitest"; + +import { + parseWindowLogLine, + type WindowLogEvent, +} from "@/connectionFailure/windowLog"; + +import { + CURSOR_EXTENSION_HOST_NOT_RESTARTED, + CURSOR_EXTENSION_HOST_RESTARTED, + CURSOR_INITIAL_CONNECTION_FAILED, + CURSOR_MANAGEMENT_GAVE_UP, + EXTENSION_HOST_GAVE_UP, + EXTENSION_HOST_RESTARTED, + INITIAL_CONNECTION_FAILED, + MANAGEMENT_GAVE_UP, + MANAGEMENT_NO_GRACE_TIME, + MANAGEMENT_RECONNECTING, +} from "./windowLogLines"; + +describe("parseWindowLogLine", () => { + interface WindowLogExcerpt { + name: string; + log: string; + events: WindowLogEvent[]; + } + it.each([ + { + name: "a failed initial connection (VS Code)", + log: INITIAL_CONNECTION_FAILED, + events: ["initial_connection_failed"], + }, + { + name: "a failed initial connection (Cursor)", + log: CURSOR_INITIAL_CONNECTION_FAILED, + events: ["initial_connection_failed"], + }, + { + name: "a reconnect that gave up (VS Code)", + log: MANAGEMENT_RECONNECTING + MANAGEMENT_GAVE_UP, + events: ["management_connection_lost"], + }, + { + name: "a reconnect that gave up (Cursor)", + log: CURSOR_MANAGEMENT_GAVE_UP, + events: ["management_connection_lost"], + }, + { + name: "a zero grace time", + log: MANAGEMENT_NO_GRACE_TIME, + events: ["management_connection_lost"], + }, + { + name: "an extension host reconnect that gave up", + log: EXTENSION_HOST_GAVE_UP, + events: ["extension_host_connection_lost"], + }, + { + name: "an extension host restart (VS Code)", + log: EXTENSION_HOST_RESTARTED, + events: ["extension_host_restarted"], + }, + { + name: "an extension host restart (Cursor)", + log: CURSOR_EXTENSION_HOST_RESTARTED, + events: ["extension_host_restarted"], + }, + { + name: "a refused extension host restart (Cursor)", + log: CURSOR_EXTENSION_HOST_NOT_RESTARTED, + events: [], + }, + { + name: "a reconnect in progress", + log: MANAGEMENT_RECONNECTING, + events: [], + }, + ])("finds the events in $name", ({ log, events }) => { + const found = log.split("\n").map(parseWindowLogLine); + expect(found.filter((event) => event !== undefined)).toEqual(events); + }); +}); diff --git a/test/unit/connectionFailure/windowLogLines.ts b/test/unit/connectionFailure/windowLogLines.ts new file mode 100644 index 0000000000..45cf5311ce --- /dev/null +++ b/test/unit/connectionFailure/windowLogLines.ts @@ -0,0 +1,58 @@ +/** `renderer.log` excerpts, written the way VS Code and Cursor log them. */ + +const MANAGEMENT = "[remote-connection][Management ][a1b2c…][reconnect]"; +const EXTENSION_HOST = "[remote-connection][ExtensionHost][d3e4f…][reconnect]"; + +/** Timestamps each entry; continuation lines like stack frames have none. */ +function logEntries(...entries: string[]): string { + return entries.map((entry) => `2026-12-03 10:00:00.000 ${entry}\n`).join(""); +} + +export const MANAGEMENT_RECONNECTING = logEntries( + `[info] ${MANAGEMENT} starting reconnecting loop. You can get more information with the trace log level.`, + `[info] ${MANAGEMENT} starting reconnection with grace time: 10800000ms (10800s)`, + `[info] ${MANAGEMENT} resolving connection...`, + `[info] ${MANAGEMENT} connecting to 127.0.0.1:4100...`, + `[info] ${MANAGEMENT} A network error occurred while trying to reconnect, will try again...`, +); + +export const MANAGEMENT_GAVE_UP = logEntries( + `[error] ${MANAGEMENT} A permanent error occurred in the reconnecting loop! Will give up now! Error:`, + "[error] Error: Connection error: Unknown reconnection token (seen before)\n at RemoteSocketFactoryService.connect (file:///app/out/main.js:1:2)", +); + +export const MANAGEMENT_NO_GRACE_TIME = logEntries( + `[info] ${MANAGEMENT} starting reconnection with grace time: 0ms (0s)`, + `[error] ${MANAGEMENT} reconnection grace time is set to 0ms, will not attempt to reconnect.`, +); + +export const CURSOR_MANAGEMENT_GAVE_UP = logEntries( + `[error] ${MANAGEMENT} A RemoteAuthorityResolverError occurred while trying to reconnect. Will give up now! Error: Connection to Cursor server failed`, +); + +export const EXTENSION_HOST_GAVE_UP = logEntries( + `[error] ${EXTENSION_HOST} An unknown error occurred while trying to reconnect, since this is an unknown case, it will be treated as a permanent error! Will give up now! Error:`, + "[error] Error: read ECONNRESET", +); + +export const EXTENSION_HOST_RESTARTED = logEntries( + "[error] Extension host (Remote) terminated unexpectedly. No extensions were activated.", + "[info] Automatically restarting the remote extension host.", +); + +export const CURSOR_EXTENSION_HOST_RESTARTED = logEntries( + "[info] Remote extension host connection was lost without a crash on record. Quietly restarting the remote extension host.", +); + +export const CURSOR_EXTENSION_HOST_NOT_RESTARTED = logEntries( + "[error] Remote extension host connection was lost repeatedly without a crash on record. Not restarting the remote extension host again.", +); + +export const INITIAL_CONNECTION_FAILED = logEntries( + "[error] [remote-connection][attempt 1] An error occurred in initial connection! Will retry... Error:", + "[error] [remote-connection][attempt 5] An error occurred in initial connection! It will be treated as a permanent error. Error:", +); + +export const CURSOR_INITIAL_CONNECTION_FAILED = logEntries( + "[error] [remote-connection][attempt 5] An error occurred in initial connection! It will be treated as a permanent error. Error: timed out", +); diff --git a/test/unit/storage/mementoManager.test.ts b/test/unit/storage/mementoManager.test.ts index 5c728eac38..54727289ad 100644 --- a/test/unit/storage/mementoManager.test.ts +++ b/test/unit/storage/mementoManager.test.ts @@ -135,8 +135,9 @@ describe("MementoManager", () => { }); describe("deployment data", () => { - it("clears access timestamp and stored key sets together", async () => { + it("clears access timestamp, stored key sets and connection failure together", async () => { await mementoManager.updateDeploymentAccess("example.com"); + await mementoManager.setConnectionFailure("example.com", "authority"); await mementoManager.addSurfacedBanners("example.com", ["one"]); await mementoManager.addDismissedSshOptions("example.com", ["user"]); expect(mementoManager.getDeploymentAccess("example.com")).toBeDefined(); @@ -146,6 +147,9 @@ describe("MementoManager", () => { expect(mementoManager.getDeploymentAccess("example.com")).toBeUndefined(); expect(mementoManager.getSurfacedBanners("example.com")).toEqual([]); expect(mementoManager.getDismissedSshOptions("example.com")).toEqual([]); + expect( + mementoManager.getConnectionFailure("example.com"), + ).toBeUndefined(); }); }); diff --git a/test/unit/supportBundle/logFiles.test.ts b/test/unit/supportBundle/logFiles.test.ts index 6133a86f3d..1fa32fe6c8 100644 --- a/test/unit/supportBundle/logFiles.test.ts +++ b/test/unit/supportBundle/logFiles.test.ts @@ -216,6 +216,39 @@ describe("collectSupportLogFiles", () => { }); }); + it("collects window logs only for windows with Coder extension logs", async () => { + const sessionDir = path.join(tmpDir, "logs", "20240101T000000"); + const currentExtDir = path.join( + sessionDir, + "window1", + "exthost", + "coder.coder-remote", + ); + await fs.mkdir(currentExtDir, { recursive: true }); + await fs.mkdir(path.join(sessionDir, "window2")); + await fs.writeFile(path.join(currentExtDir, "Coder.log"), "coder"); + await fs.writeFile(path.join(sessionDir, "window1", "renderer.log"), "w1"); + await fs.writeFile( + path.join(sessionDir, "window1", "renderer.1.log"), + "w1 rotated", + ); + await fs.writeFile(path.join(sessionDir, "window1", "views.log"), "views"); + await fs.writeFile(path.join(sessionDir, "window2", "renderer.log"), "w2"); + + const files = await collectTextFiles({ extensionLogDir: currentExtDir }); + + expect( + Object.fromEntries( + Object.entries(files).filter(([name]) => + name.startsWith("vscode-logs/window/"), + ), + ), + ).toEqual({ + "vscode-logs/window/20240101T000000/window1/renderer.log": "w1", + "vscode-logs/window/20240101T000000/window1/renderer.1.log": "w1 rotated", + }); + }); + it("collects Remote-SSH logs only for windows with Coder extension logs", async () => { const logsRoot = path.join(tmpDir, "logs"); const currentExtDir = path.join( @@ -469,6 +502,29 @@ describe("resolveLogContext", () => { }); }); + it("resolves a Cursor Glass workspace log layout", () => { + const extensionLogDir = path.join( + tmpDir, + "20240101T000000", + "window1_wb2", + "exthost", + "coder.coder-remote", + ); + + expect(resolveLogContext(extensionLogDir)).toEqual({ + currentWindowPath: path.join(tmpDir, "20240101T000000", "window1_wb2"), + logsRoot: tmpDir, + }); + }); + + it("ignores window directories with an unknown suffix", () => { + expect( + resolveLogContext( + path.join(tmpDir, "window1_foo", "exthost", "coder.coder-remote"), + ), + ).toBeUndefined(); + }); + it("ignores paths outside the Coder extension log layout", () => { expect( resolveLogContext(path.join(tmpDir, "window1", "other")), @@ -515,6 +571,12 @@ describe("collectWindowLogDirs", () => { recursive: true, }); await fs.mkdir(path.join(tmpDir, "window3"), { recursive: true }); + await fs.mkdir(path.join(tmpDir, "20240101T000000", "window1_wb0"), { + recursive: true, + }); + await fs.mkdir(path.join(tmpDir, "20240101T000000", "window1_x"), { + recursive: true, + }); await fs.writeFile(path.join(tmpDir, "not-a-window.log"), "ignore"); await expect(collectWindowLogDirs(tmpDir, logger)).resolves.toEqual([ @@ -522,6 +584,10 @@ describe("collectWindowLogDirs", () => { relativePath: "20240101T000000/window1", windowPath: path.join(tmpDir, "20240101T000000", "window1"), }, + { + relativePath: "20240101T000000/window1_wb0", + windowPath: path.join(tmpDir, "20240101T000000", "window1_wb0"), + }, { relativePath: "20240102T000000/window2", windowPath: path.join(tmpDir, "20240102T000000", "window2"), diff --git a/test/unit/webviews/workspaces/workspacesPanelProvider.test.ts b/test/unit/webviews/workspaces/workspacesPanelProvider.test.ts index 900a9d6954..1bc7406e14 100644 --- a/test/unit/webviews/workspaces/workspacesPanelProvider.test.ts +++ b/test/unit/webviews/workspaces/workspacesPanelProvider.test.ts @@ -66,7 +66,7 @@ function setup() { openWorkspaceInDashboard: vi.fn(() => Promise.resolve()), pingWorkspace: vi.fn(() => Promise.resolve()), speedTest: vi.fn(() => Promise.resolve()), - supportBundle: vi.fn(() => Promise.resolve()), + supportBundle: vi.fn(() => Promise.resolve(undefined)), } satisfies ConstructorParameters[2]; const actions = { run: vi.fn(() => Promise.resolve()) }; const provider = new WorkspacesPanelProvider( From 0c7ea14163040d2a9e554d667cdb9e3e20abea7d Mon Sep 17 00:00:00 2001 From: Ehab Younes Date: Sun, 6 Dec 2026 16:12:54 +0300 Subject: [PATCH 2/2] fix(remote): offer the support bundle only when the deployment responds The support bundle needs the deployment, so offering it while the deployment is unreachable can only fail. When VS Code gives up on the connection, the failure is still stored, but the prompt waits for the next successful connection if the deployment does not respond. --- .../connectionFailurePrompt.ts | 28 ++++++++++++++++--- src/remote/remote.ts | 1 + .../connectionFailurePrompt.test.ts | 15 +++++++++- 3 files changed, 39 insertions(+), 5 deletions(-) diff --git a/src/connectionFailure/connectionFailurePrompt.ts b/src/connectionFailure/connectionFailurePrompt.ts index 27c319a84c..a02afacbf3 100644 --- a/src/connectionFailure/connectionFailurePrompt.ts +++ b/src/connectionFailure/connectionFailurePrompt.ts @@ -2,6 +2,7 @@ import * as vscode from "vscode"; import { vscodeProposed } from "../vscode/proposed"; +import type { CoderApi } from "../api/coderApi"; import type { Logger } from "../logging/logger"; import type { MementoManager } from "../storage/mementoManager"; @@ -9,6 +10,7 @@ export interface ConnectionFailurePromptOptions { readonly safeHostname: string; readonly remoteAuthority: string; readonly workspaceName: string; + readonly client: Pick; readonly mementoManager: MementoManager; readonly logger: Logger; } @@ -47,14 +49,32 @@ export class ConnectionFailurePrompt { ); } - /** Stores the failure, then offers a support bundle. Never throws. */ + /** + * Stores the failure, then offers a support bundle if the deployment is + * reachable, since the bundle needs it. Never throws. + */ public async offerForFailure(): Promise { - const { mementoManager, safeHostname, remoteAuthority, workspaceName } = - this.options; + const { + client, + mementoManager, + safeHostname, + remoteAuthority, + workspaceName, + logger, + } = this.options; try { await mementoManager.setConnectionFailure(safeHostname, remoteAuthority); } catch (error) { - this.options.logger.warn("Could not store the connection failure", error); + logger.warn("Could not store the connection failure", error); + } + try { + await client.getBuildInfo(); + } catch (error) { + logger.info( + "Deployment is unreachable; offering a support bundle on the next connection", + error, + ); + return; } this.showPrompt( `The connection to ${workspaceName} failed. Create a support bundle to capture diagnostics?`, diff --git a/src/remote/remote.ts b/src/remote/remote.ts index e4797f1def..6dc8f855af 100644 --- a/src/remote/remote.ts +++ b/src/remote/remote.ts @@ -484,6 +484,7 @@ export class Remote { safeHostname: parts.safeHostname, remoteAuthority: args.remoteAuthority, workspaceName, + client: workspaceClient, mementoManager: this.serviceContainer.getMementoManager(), logger: this.logger, }); diff --git a/test/unit/connectionFailure/connectionFailurePrompt.test.ts b/test/unit/connectionFailure/connectionFailurePrompt.test.ts index 4816c3e288..55895abbeb 100644 --- a/test/unit/connectionFailure/connectionFailurePrompt.test.ts +++ b/test/unit/connectionFailure/connectionFailurePrompt.test.ts @@ -27,16 +27,18 @@ const PREVIOUSLY_FAILED = function setup() { const mementoManager = new MementoManager(new InMemoryMemento()); + const getBuildInfo = vi.fn().mockResolvedValue({}); /** A prompt in a newly activated window. */ const activate = () => new ConnectionFailurePrompt({ safeHostname: HOSTNAME, remoteAuthority: AUTHORITY, workspaceName: "alice/dev", + client: { getBuildInfo }, mementoManager, logger: createMockLogger(), }); - return { mementoManager, activate }; + return { mementoManager, getBuildInfo, activate }; } function prompts(): unknown[][] { @@ -108,6 +110,17 @@ describe("ConnectionFailurePrompt", () => { }, ); + it("waits for the next connection when the deployment is unreachable", async () => { + const { getBuildInfo, activate } = setup(); + getBuildInfo.mockRejectedValueOnce(new Error("getaddrinfo ENOTFOUND")); + + await activate().offerForFailure(); + expect(prompts()).toEqual([]); + await activate().offerForPreviousFailure(); + + expect(prompts()).toEqual([[PREVIOUSLY_FAILED, CREATE_BUNDLE]]); + }); + it("offers a previous failure only after VS Code connects", async () => { let connect = (): void => undefined; vi.mocked(vscode.workspace.fs.stat).mockReturnValue(