Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,25 @@
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

- The agent status bar item warns before a workspace runs out of memory. It
turns yellow at `coder.memoryMonitor.warningThreshold` (80% of the memory
limit by default) or when memory pressure slows the workspace. Click it to
open `top`, or restart the workspace from its tooltip.
- **Coder: Show Top Processes** and **Coder: Restart Workspace** for the
connected workspace.

### Changed

- A failed agent metadata load no longer turns the status bar item yellow;
that color now means memory needs attention.
- Restarting the workspace this window is connected to, from the Workspaces
panel or the memory warning, reloads the window and reconnects once the
workspace is back, instead of leaving the window disconnected.

## [v1.18.2](https://github.com/coder/vscode-coder/releases/tag/v1.18.2) (Pre-release) 2026-11-20

### Added
Expand Down
19 changes: 19 additions & 0 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,25 @@ The extension provides several sidebar panels:
There are also notifications for outdated workspace templates and for workspaces
that are close to shutting down.

## Workspace memory

In a remote window, `MemoryMonitor` ([`src/memory/`](../src/memory/)) polls a
`MemoryUsageSource` every 10 seconds and feeds the agent status bar item. Only
the source knows where samples come from:

- `createRemoteFileUsage` ([`src/memory/remoteFiles.ts`](../src/memory/remoteFiles.ts))
ports [coder/clistat](https://github.com/coder/clistat)'s memory reading
(`coder stat mem`) to cgroup and `/proc` files read over `vscode-remote://`,
since the extension runs on the client. The file header names the clistat
commit it follows; update the port when clistat changes. Used memory is what
the kernel cannot reclaim: `MemTotal - MemAvailable` on the host (as `free`
and `top` report it), and usage minus the file LRU lists and reclaimable slab in a
cgroup, from one `memory.stat` read. Each cgroup limit and the host is a
candidate; the one with the least room left wins. clistat differs today;
aligning it is planned.
- A server endpoint (coder/coder#32542) would be another source, chosen in
`src/remote/remote.ts`. Nothing else changes.

## Logging

The extension logs to the "Coder" output channel, a `LogOutputChannel` that gates
Expand Down
26 changes: 26 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,14 @@
"minimum": 0,
"default": 250
},
"coder.memoryMonitor.warningThreshold": {
"markdownDescription": "Percent of the workspace memory limit at which the Coder status bar item warns you. It also warns when memory pressure slows the workspace. Set to `0` to turn off memory warnings; usage is still shown in the tooltip.",
"type": "number",
"minimum": 0,
"maximum": 99,
"default": 80,
"scope": "application"
},
"coder.connectionLogBuffer.size": {
"markdownDescription": "Maximum number of log entries below the Coder output channel's log level to keep in memory. When a connection fails terminally or you collect a support bundle, the extension replays them into the channel so a bundle can carry the detail leading up to the failure without debug logging enabled beforehand. Capture is best-effort, since the channel writes on its own schedule. Set to `0` to disable.",
"type": "number",
Expand Down Expand Up @@ -469,6 +477,16 @@
"title": "Update Workspace",
"category": "Coder"
},
{
"command": "coder.workspace.showTopProcesses",
"title": "Show Top Processes",
"category": "Coder"
},
{
"command": "coder.workspace.restart",
"title": "Restart Workspace",
"category": "Coder"
},
{
"command": "coder.speedTest",
"title": "Speed Test Workspace",
Expand Down Expand Up @@ -646,6 +664,14 @@
"command": "coder.workspace.update",
"when": "coder.workspace.updatable"
},
{
"command": "coder.workspace.showTopProcesses",
"when": "coder.workspace.connected"
},
{
"command": "coder.workspace.restart",
"when": "coder.workspace.connected"
},
{
"command": "coder.viewLogs",
"when": "true"
Expand Down
23 changes: 16 additions & 7 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
ActivationTelemetry,
type ActivationTracer,
} from "./instrumentation/activation";
import { showTopProcesses } from "./memory/topProcesses";
import { OAuthSessionManager } from "./oauth/sessionManager";
import { Remote } from "./remote/remote";
import { getRemoteSshExtension } from "./remote/sshExtension";
Expand Down Expand Up @@ -252,17 +253,19 @@ async function doActivate(
contextManager.set("coder.loaded", true);
void workspaceStore.markSessionRestored();
};
const workspaceActions = new WorkspaceActionRunner(
client,
deploymentManager.session,
commands,
mementoManager,
telemetryService,
output,
);
const workspacesPanelProvider = new WorkspacesPanelProvider(
ctx.extensionUri,
workspaceStore,
commands,
new WorkspaceActionRunner(
client,
deploymentManager.session,
commands,
telemetryService,
output,
),
workspaceActions,
output,
);

Expand Down Expand Up @@ -365,6 +368,12 @@ async function doActivate(
"coder.workspace.update",
commands.updateWorkspace.bind(commands),
);
commandManager.register("coder.workspace.showTopProcesses", showTopProcesses);
commandManager.register("coder.workspace.restart", async () => {
if (commands.workspace) {
await workspaceActions.run(commands.workspace, "restart");
}
});
commandManager.register(
"coder.createWorkspace",
commands.createWorkspace.bind(commands),
Expand Down
17 changes: 17 additions & 0 deletions src/instrumentation/EVENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ new ones live in `CONVENTIONS.md`.
| [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` |
| [Memory](#memory) | `memory.state_transitioned` |

Signal kinds, which each category groups its events by:

Expand Down Expand Up @@ -577,3 +578,19 @@ monitored session (not only the connected agent during connection setup).
| `status.from`, `status.to` | WorkspaceAgentStatus (`from` is `none` initially) |
| `lifecycle_state.from`, `lifecycle_state.to` | WorkspaceAgentLifecycle (`from` is `none` initially) |
| `observed_duration_ms` (measurement) | omitted on first observation |

## Memory

### Logs

#### `memory.state_transitioned`

Emitted by `MemoryTelemetry` when the polled workspace memory changes state.

| Attribute | Values |
| -------------------------------- | ---------------------------------------------- |
| `from`, `to` | `unavailable`, `normal`, `high` |
| `trigger` | `usage`, `pressure` (for `high`) |
| `source` | `cgroup`, `host` (what bounds the memory) |
| `usage_percent` (measurement) | memory used, in percent of the limit |
| `pressure_percent` (measurement) | PSI `some avg10`; omitted when it is not known |
24 changes: 24 additions & 0 deletions src/instrumentation/memory.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import type { MemoryState, MemoryStatus } from "../memory/pressure";
import type { TelemetryReporter } from "../telemetry/reporter";

/** Telemetry for workspace memory monitoring. */
export class MemoryTelemetry {
public constructor(private readonly telemetry: TelemetryReporter) {}

/** Emits `memory.state_transitioned` when the memory state changes. */
public stateTransitioned(from: MemoryState, status: MemoryStatus): void {
const properties: Record<string, string> = { from, to: status.state };
const measurements: Record<string, number> = {};
if (status.state !== "unavailable") {
properties.source = status.sample.source;
measurements.usage_percent = status.percent;
if (status.trigger) {
properties.trigger = status.trigger;
}
if (status.sample.pressure !== undefined) {
measurements.pressure_percent = status.sample.pressure;
}
}
this.telemetry.log("memory.state_transitioned", properties, measurements);
}
}
91 changes: 91 additions & 0 deletions src/memory/monitor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import * as vscode from "vscode";

import { errToStr } from "../error/normalize";
import {
getMemoryWarningThreshold,
MEMORY_WARNING_THRESHOLD_SETTING,
} from "../settings/memoryMonitor";

import {
MemoryPressureTracker,
type MemoryState,
type MemoryStatus,
} from "./pressure";

import type { MemoryTelemetry } from "../instrumentation/memory";
import type { Logger } from "../logging/logger";

import type { MemorySample, MemoryUsageSource } from "./usage";

const POLL_INTERVAL_MS = 10_000;

/**
* Polls workspace memory and reports its state. Keeps polling while the
* window is unfocused, since workspaces often run out of memory while the
* user is away. A poll is skipped while the previous one is still reading,
* because reads stall when the workspace is short on memory.
*/
export class MemoryMonitor implements vscode.Disposable {
private readonly tracker = new MemoryPressureTracker();
private readonly emitter = new vscode.EventEmitter<MemoryStatus>();
private readonly timer: ReturnType<typeof setInterval>;
private readonly configListener: vscode.Disposable;
private polling = false;
private disposed = false;
private state: MemoryState = "unavailable";

/** Fires after every poll with the latest status. */
public readonly onDidChange = this.emitter.event;

public constructor(
private readonly readUsage: MemoryUsageSource,
private readonly telemetry: MemoryTelemetry,
private readonly logger: Logger,
) {
this.timer = setInterval(() => void this.poll(), POLL_INTERVAL_MS);
this.configListener = vscode.workspace.onDidChangeConfiguration((e) => {
if (e.affectsConfiguration(MEMORY_WARNING_THRESHOLD_SETTING)) {
void this.poll();
}
});
void this.poll();
}

public dispose(): void {
this.disposed = true;
clearInterval(this.timer);
this.configListener.dispose();
this.emitter.dispose();
}

private async poll(): Promise<void> {
if (this.polling || this.disposed) {
return;
}
this.polling = true;
const sample = await this.readSample();
this.polling = false;
if (this.disposed) {
return;
}
const threshold = getMemoryWarningThreshold(
vscode.workspace.getConfiguration(),
);
const status = this.tracker.update(sample, threshold);
if (status.state !== this.state) {
this.logger.debug(`Workspace memory is ${status.state}`);
this.telemetry.stateTransitioned(this.state, status);
this.state = status.state;
}
this.emitter.fire(status);
}

private async readSample(): Promise<MemorySample | undefined> {
try {
return await this.readUsage();
} catch (error) {
this.logger.debug(`Failed to read workspace memory: ${errToStr(error)}`);
return undefined;
}
}
}
106 changes: 106 additions & 0 deletions src/memory/pressure.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import type { MemorySample } from "./usage";

/** PSI `some avg10` at or above this enters High. */
const PRESSURE_HIGH_PERCENT = 20;
/** PSI must be below this to leave High. */
const PRESSURE_CALM_PERCENT = 10;
/** Usage must drop this many points under the threshold to leave High. */
const EXIT_GAP_PERCENT = 5;
/** High usage needs this many of the last `USAGE_WINDOW` samples. */
const USAGE_HITS = 2;
const USAGE_WINDOW = 3;
/**
* How long samples must stay calm to return to Normal. Time-based so polls
* close together cannot clear a warning the user has not seen yet.
*/
const CALM_MS = 10_000;

export type MemoryState = "unavailable" | "normal" | "high";

/** What put memory in its current non-normal state. */
export type MemoryTrigger = "usage" | "pressure";

/** A state computed from a successful read. */
export interface MemoryReading {
readonly state: Exclude<MemoryState, "unavailable">;
readonly sample: MemorySample;
/** Usage in percent of the limit, rounded like `coder stat mem`. */
readonly percent: number;
readonly trigger?: MemoryTrigger;
}

export type MemoryStatus = { readonly state: "unavailable" } | MemoryReading;

/**
* Turns memory samples into a state with hysteresis, so a single spike does
* not warn and usage hovering at the threshold does not flap.
*/
export class MemoryPressureTracker {
private status: MemoryStatus = { state: "unavailable" };
private recentHigh: boolean[] = [];
private calmSince: number | undefined;
private threshold: number | undefined;

public constructor(private readonly now: () => number = Date.now) {}

/** `threshold` is a percent of the limit; `0` turns warnings off. */
public update(
sample: MemorySample | undefined,
threshold: number,
): MemoryStatus {
this.status = this.nextStatus(sample, threshold);
return this.status;
}

private nextStatus(
sample: MemorySample | undefined,
threshold: number,
): MemoryStatus {
if (!sample || sample.totalBytes <= 0) {
this.recentHigh = [];
this.calmSince = undefined;
return { state: "unavailable" };
}
if (threshold !== this.threshold) {
this.threshold = threshold;
this.recentHigh = [];
}

const percent = Math.round((sample.usedBytes / sample.totalBytes) * 100);
const base = { sample, percent };
if (threshold <= 0) {
return { ...base, state: "normal" };
}

// Unknown pressure counts as none.
const pressure = sample.pressure ?? 0;
this.recentHigh = [...this.recentHigh, percent >= threshold].slice(
-USAGE_WINDOW,
);
const calm =
percent < threshold - EXIT_GAP_PERCENT &&
pressure < PRESSURE_CALM_PERCENT;
this.calmSince = calm ? (this.calmSince ?? this.now()) : undefined;

const previous = this.status;
if (isWarning(previous)) {
return this.calmSince !== undefined &&
this.now() - this.calmSince >= CALM_MS
? { ...base, state: "normal" }
: { ...base, state: previous.state, trigger: previous.trigger };
}
if (this.recentHigh.filter(Boolean).length >= USAGE_HITS) {
return { ...base, state: "high", trigger: "usage" };
}
if (pressure >= PRESSURE_HIGH_PERCENT) {
return { ...base, state: "high", trigger: "pressure" };
}
return { ...base, state: "normal" };
}
}

export function isWarning(
status: MemoryStatus,
): status is MemoryReading & { state: "high" } {
return status.state === "high";
}
Loading