Skip to content

Commit 3994517

Browse files
committed
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. Read new lines from that log and offer a support bundle when VS Code gives up. Store the failure per deployment until the user answers, so a reload before then offers it again for up to a day. Support bundles now include the window log and logs from Cursor Glass workspaces.
1 parent 06cbf57 commit 3994517

15 files changed

Lines changed: 738 additions & 11 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,19 @@
55
from published versions since it shows up in the VS Code extension changelog
66
tab and is confusing to users. Add it back between releases if needed. -->
77

8+
## Unreleased
9+
10+
### Added
11+
12+
- Support bundles include the VS Code window log, which records the editor's
13+
remote connection and reconnect attempts.
14+
- When VS Code gives up on the remote connection, the extension offers to
15+
create a support bundle, and offers it again after a reload for up to a day.
16+
17+
### Fixed
18+
19+
- Support bundles include logs from Cursor Glass workspaces.
20+
821
## [v1.18.4](https://github.com/coder/vscode-coder/releases/tag/v1.18.4) 2026-12-03
922

1023
### Added

‎src/commands.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -578,6 +578,7 @@ export class Commands {
578578
"",
579579
"\u2022 Deployment and workspace diagnostics",
580580
"\u2022 Coder extension and connection logs from recent VS Code windows",
581+
"\u2022 VS Code window logs, including remote connection events",
581582
"\u2022 Remote SSH extension logs",
582583
"\u2022 Locally recorded telemetry",
583584
"\u2022 Coder extension settings",

‎src/instrumentation/EVENTS.md‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ new ones live in `CONVENTIONS.md`.
1414
| [Commands](#commands) | `command.invoked`, `command.diagnostic.completed` |
1515
| [Deployment](#deployment) | `deployment.suspended`, `deployment.recovered`, `deployment.cross_window.detected`, `deployment.auth_config.recovery_failed` |
1616
| [Remote setup](#remote-setup) | `remote.setup` |
17-
| [SSH](#ssh) | `ssh.process.discovered`, `ssh.process.lost`, `ssh.process.recovered`, `ssh.process.replaced`, `ssh.process.disposed`, `ssh.network.sampled` |
17+
| [SSH](#ssh) | `ssh.process.discovered`, `ssh.process.lost`, `ssh.process.recovered`, `ssh.process.replaced`, `ssh.process.disposed`, `ssh.connection.failed`, `ssh.network.sampled` |
1818
| [HTTP](#http) | `http.requests` |
1919
| [WebSocket connections](#websocket-connections) | `connection.state_transitioned`, `connection.opened`, `connection.dropped`, `connection.reconnect_resolved`, `connection.unreachable` |
2020
| [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`.
358358

359359
### Logs
360360

361+
#### `ssh.connection.failed`
362+
363+
VS Code gave up on the remote connection, read from the window log. The
364+
extension then offers a support bundle.
365+
366+
| Attribute | Values |
367+
| --------- | ------------------------------------------------------------------------------------------- |
368+
| `kind` | `initial_connection_failed`, `management_connection_lost`, `extension_host_connection_lost` |
369+
361370
#### `ssh.process.lost`
362371

363372
| Attribute | Values |

‎src/instrumentation/ssh.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import type { ConnectionFailure } from "../remote/connectionFailureWatcher";
12
import type { NetworkInfo } from "../remote/sshProcess";
23
import type { TelemetryReporter } from "../telemetry/reporter";
34

@@ -114,6 +115,10 @@ export class SshTelemetry {
114115
this.#lastNetworkSample = undefined;
115116
}
116117

118+
public connectionFailed(kind: ConnectionFailure): void {
119+
this.#telemetry.log("ssh.connection.failed", { kind });
120+
}
121+
117122
public networkSampled(network: NetworkInfo): void {
118123
const now = performance.now();
119124
const previous = this.#lastNetworkSample;
Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
1+
import * as vscode from "vscode";
2+
3+
import { vscodeProposed } from "../vscode/proposed";
4+
5+
import { WindowLogReader, type WindowLogEvent } from "./windowLog";
6+
7+
import type { SshTelemetry } from "../instrumentation/ssh";
8+
import type { Logger } from "../logging/logger";
9+
import type { MementoManager } from "../storage/mementoManager";
10+
11+
export type ConnectionFailure = Exclude<
12+
WindowLogEvent,
13+
"extension_host_restarted"
14+
>;
15+
16+
export interface ConnectionFailureWatcherOptions {
17+
readonly safeHostname: string;
18+
readonly remoteAuthority: string;
19+
readonly workspaceName: string;
20+
readonly codeLogDir: string;
21+
readonly mementoManager: MementoManager;
22+
readonly telemetry: SshTelemetry;
23+
readonly logger: Logger;
24+
}
25+
26+
/**
27+
* Longer than the 2s VS Code waits for the extension host's exit info before
28+
* it logs a restart:
29+
* https://github.com/microsoft/vscode/blob/e54c42b3917fa85e6f8e7c1eef3853f4db66cef6/src/vs/workbench/services/extensions/common/abstractExtensionService.ts#L899-L925
30+
*/
31+
const EXTENSION_HOST_RESTART_WAIT_MS = 3000;
32+
const POLL_INTERVAL_MS = 250;
33+
34+
/**
35+
* Offers a support bundle when VS Code gives up on the remote connection. The
36+
* failure stays stored until the user answers, so a reload offers it again.
37+
*/
38+
export class ConnectionFailureWatcher implements vscode.Disposable {
39+
private disposed = false;
40+
private timer: NodeJS.Timeout | undefined;
41+
private extensionHostLostAt: number | undefined;
42+
43+
private constructor(
44+
private readonly options: ConnectionFailureWatcherOptions,
45+
) {}
46+
47+
public static start(
48+
options: ConnectionFailureWatcherOptions,
49+
): ConnectionFailureWatcher {
50+
const watcher = new ConnectionFailureWatcher(options);
51+
void watcher.watch();
52+
return watcher;
53+
}
54+
55+
public dispose(): void {
56+
this.disposed = true;
57+
clearTimeout(this.timer);
58+
}
59+
60+
private async watch(): Promise<void> {
61+
const { mementoManager, safeHostname, remoteAuthority, codeLogDir } =
62+
this.options;
63+
if (mementoManager.getConnectionFailure(safeHostname) === remoteAuthority) {
64+
this.offerSupportBundle(
65+
`The previous connection to ${this.options.workspaceName} failed. Create a support bundle to capture diagnostics?`,
66+
);
67+
}
68+
const reader = await WindowLogReader.open(codeLogDir);
69+
if (!reader) {
70+
this.options.logger.debug(
71+
"Unrecognized log directory layout; not watching for connection failures",
72+
);
73+
return;
74+
}
75+
this.schedulePoll(reader);
76+
}
77+
78+
private schedulePoll(reader: WindowLogReader): void {
79+
if (!this.disposed) {
80+
this.timer = setTimeout(() => void this.poll(reader), POLL_INTERVAL_MS);
81+
}
82+
}
83+
84+
private async poll(reader: WindowLogReader): Promise<void> {
85+
try {
86+
for (const event of await reader.readEvents()) {
87+
this.handle(event);
88+
}
89+
} catch (error) {
90+
this.options.logger.debug("Could not read the VS Code window log", error);
91+
}
92+
if (
93+
this.extensionHostLostAt !== undefined &&
94+
Date.now() - this.extensionHostLostAt >= EXTENSION_HOST_RESTART_WAIT_MS
95+
) {
96+
void this.report("extension_host_connection_lost");
97+
}
98+
this.schedulePoll(reader);
99+
}
100+
101+
private handle(event: WindowLogEvent): void {
102+
switch (event) {
103+
case "extension_host_connection_lost":
104+
// Restarts are logged at info level; without them a recovery looks like a failure.
105+
if (vscode.env.logLevel <= vscode.LogLevel.Info) {
106+
this.extensionHostLostAt ??= Date.now();
107+
}
108+
return;
109+
case "extension_host_restarted":
110+
this.extensionHostLostAt = undefined;
111+
this.options.logger.info("VS Code restarted the remote extension host");
112+
return;
113+
default:
114+
void this.report(event);
115+
}
116+
}
117+
118+
/** Reports the first failure only, and stores it before the prompt shows. */
119+
private async report(failure: ConnectionFailure): Promise<void> {
120+
if (this.disposed) {
121+
return;
122+
}
123+
this.dispose();
124+
const { logger, telemetry, mementoManager, safeHostname, remoteAuthority } =
125+
this.options;
126+
logger.warn(`VS Code gave up on the remote connection: ${failure}`);
127+
logger.flush("remote_connection_failed");
128+
telemetry.connectionFailed(failure);
129+
await this.persist(
130+
mementoManager.setConnectionFailure(safeHostname, remoteAuthority),
131+
);
132+
this.offerSupportBundle(
133+
`The connection to ${this.options.workspaceName} failed. Create a support bundle to capture diagnostics?`,
134+
);
135+
}
136+
137+
/**
138+
* Never awaited: the notification can go away without resolving. The stored
139+
* failure clears only on an answer, so an unanswered one shows after a reload.
140+
*/
141+
private offerSupportBundle(message: string): void {
142+
void vscodeProposed.window
143+
.showErrorMessage(message, "Create Support Bundle")
144+
.then(
145+
(choice) => this.onAnswer(choice),
146+
(error: unknown) =>
147+
this.options.logger.warn("Could not offer a support bundle", error),
148+
);
149+
}
150+
151+
private async onAnswer(choice: string | undefined): Promise<void> {
152+
const { mementoManager, safeHostname, logger } = this.options;
153+
await this.persist(mementoManager.clearConnectionFailure(safeHostname));
154+
if (choice !== "Create Support Bundle") {
155+
return;
156+
}
157+
try {
158+
await vscodeProposed.commands.executeCommand("coder.supportBundle");
159+
} catch (error) {
160+
logger.warn("Could not create a support bundle", error);
161+
}
162+
}
163+
164+
/** Best effort: a failed write only changes whether a reload prompts again. */
165+
private async persist(write: Promise<void>): Promise<void> {
166+
try {
167+
await write;
168+
} catch (error) {
169+
this.options.logger.warn("Could not store the connection failure", error);
170+
}
171+
}
172+
}

‎src/remote/remote.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ import {
3939
RemoteSetupTelemetry,
4040
type RemoteSetupTracer,
4141
} from "../instrumentation/remoteSetup";
42+
import { SshTelemetry } from "../instrumentation/ssh";
4243
import { OAuthSessionManager } from "../oauth/sessionManager";
4344
import {
4445
type CliAuth,
@@ -59,6 +60,7 @@ import {
5960
parseRemoteAuthority,
6061
sshHostOf,
6162
} from "./authority";
63+
import { ConnectionFailureWatcher } from "./connectionFailureWatcher";
6264
import {
6365
applySshEnvironment,
6466
SESSION_TYPE_ENV,
@@ -477,6 +479,20 @@ export class Remote {
477479
);
478480
disposables.push(sshMonitor);
479481

482+
disposables.push(
483+
ConnectionFailureWatcher.start({
484+
safeHostname: parts.safeHostname,
485+
remoteAuthority: args.remoteAuthority,
486+
workspaceName,
487+
codeLogDir: this.pathResolver.getCodeLogDir(),
488+
mementoManager: this.serviceContainer.getMementoManager(),
489+
telemetry: new SshTelemetry(
490+
this.serviceContainer.getTelemetryService(),
491+
),
492+
logger: this.logger,
493+
}),
494+
);
495+
480496
this.commands.workspaceLogPath = sshMonitor.getLogFilePath();
481497

482498
const reregisterLabelFormatter = () => {

‎src/remote/windowLog.ts‎

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
import * as fs from "node:fs/promises";
2+
import * as path from "node:path";
3+
4+
import { resolveLogContext } from "../supportBundle/logFiles";
5+
6+
/** A remote connection event that VS Code writes to the window log. */
7+
export type WindowLogEvent =
8+
| "initial_connection_failed"
9+
| "management_connection_lost"
10+
| "extension_host_connection_lost"
11+
| "extension_host_restarted";
12+
13+
const MAX_BYTES_PER_READ = 1024 * 1024;
14+
15+
/**
16+
* Window log lines VS Code writes in
17+
* [remoteAgentConnection.ts](https://github.com/microsoft/vscode/blob/e54c42b3917fa85e6f8e7c1eef3853f4db66cef6/src/vs/platform/remote/common/remoteAgentConnection.ts)
18+
* and [abstractExtensionService.ts](https://github.com/microsoft/vscode/blob/e54c42b3917fa85e6f8e7c1eef3853f4db66cef6/src/vs/workbench/services/extensions/common/abstractExtensionService.ts#L925).
19+
*/
20+
const WINDOW_LOG_PATTERNS: ReadonlyArray<{
21+
readonly event: WindowLogEvent;
22+
readonly pattern: RegExp;
23+
}> = [
24+
// Every initial connection attempt failed. Cursor logs one space after the
25+
// attempt number, VS Code two.
26+
{
27+
event: "initial_connection_failed",
28+
pattern:
29+
/\[remote-connection\]\[attempt \d+\]\s+An error occurred in initial connection! It will be treated as a permanent error/,
30+
},
31+
// The reconnect loop hit a permanent error or ran out of grace time, or the
32+
// grace time is zero. Cursor appends the error to the same line.
33+
{
34+
event: "management_connection_lost",
35+
pattern:
36+
/\[remote-connection\]\[Management\s*\].*(?:Will give up now!|will not attempt to reconnect)/,
37+
},
38+
{
39+
event: "extension_host_connection_lost",
40+
pattern:
41+
/\[remote-connection\]\[ExtensionHost\s*\].*(?:Will give up now!|will not attempt to reconnect)/,
42+
},
43+
// Logged at info level: "Automatically" in VS Code, "Quietly" in Cursor.
44+
{
45+
event: "extension_host_restarted",
46+
pattern: /(?:Automatically|Quietly) restarting the remote extension host\./,
47+
},
48+
];
49+
50+
export function parseWindowLogLine(line: string): WindowLogEvent | undefined {
51+
return WINDOW_LOG_PATTERNS.find(({ pattern }) => pattern.test(line))?.event;
52+
}
53+
54+
/** Reads the events appended to the VS Code window log (`renderer.log`). */
55+
export class WindowLogReader {
56+
private offset = 0;
57+
58+
private constructor(private readonly logPath: string) {}
59+
60+
/**
61+
* Opens the log at its current end. Returns undefined when `codeLogDir`
62+
* is not in VS Code's log directory layout.
63+
*/
64+
public static async open(
65+
codeLogDir: string,
66+
): Promise<WindowLogReader | undefined> {
67+
const logContext = resolveLogContext(codeLogDir);
68+
if (!logContext) {
69+
return undefined;
70+
}
71+
const reader = new WindowLogReader(
72+
path.join(logContext.currentWindowPath, "renderer.log"),
73+
);
74+
reader.offset = await reader.size();
75+
return reader;
76+
}
77+
78+
/** Events in complete lines since the last read; starts over after rotation. */
79+
public async readEvents(): Promise<WindowLogEvent[]> {
80+
const size = await this.size();
81+
if (size < this.offset) {
82+
this.offset = 0;
83+
}
84+
const length = Math.min(size - this.offset, MAX_BYTES_PER_READ);
85+
if (length <= 0) {
86+
return [];
87+
}
88+
const handle = await fs.open(this.logPath, "r");
89+
try {
90+
const buffer = Buffer.alloc(length);
91+
const { bytesRead } = await handle.read(buffer, 0, length, this.offset);
92+
const end = buffer.lastIndexOf("\n", bytesRead - 1) + 1;
93+
// Leave a partial line for the next read, unless it fills the buffer.
94+
this.offset +=
95+
end === 0 && bytesRead === MAX_BYTES_PER_READ ? bytesRead : end;
96+
return buffer
97+
.toString("utf8", 0, end)
98+
.split(/\r?\n/)
99+
.map(parseWindowLogLine)
100+
.filter((event) => event !== undefined);
101+
} finally {
102+
await handle.close();
103+
}
104+
}
105+
106+
private async size(): Promise<number> {
107+
try {
108+
return (await fs.stat(this.logPath)).size;
109+
} catch {
110+
return 0;
111+
}
112+
}
113+
}

0 commit comments

Comments
 (0)