diff --git a/CHANGELOG.md b/CHANGELOG.md index e69c2f1521..b127909395 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 16916a0224..385bd7969a 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -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 diff --git a/package.json b/package.json index ead870b336..000572862f 100644 --- a/package.json +++ b/package.json @@ -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", @@ -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", @@ -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" diff --git a/src/extension.ts b/src/extension.ts index 3cef29c3d2..8ec73ead80 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -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"; @@ -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, ); @@ -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), diff --git a/src/instrumentation/EVENTS.md b/src/instrumentation/EVENTS.md index bc1eb3d18a..772415f3ab 100644 --- a/src/instrumentation/EVENTS.md +++ b/src/instrumentation/EVENTS.md @@ -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: @@ -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 | diff --git a/src/instrumentation/memory.ts b/src/instrumentation/memory.ts new file mode 100644 index 0000000000..70d631295f --- /dev/null +++ b/src/instrumentation/memory.ts @@ -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 = { from, to: status.state }; + const measurements: Record = {}; + 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); + } +} diff --git a/src/memory/monitor.ts b/src/memory/monitor.ts new file mode 100644 index 0000000000..ad0a47397e --- /dev/null +++ b/src/memory/monitor.ts @@ -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(); + private readonly timer: ReturnType; + 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 { + 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 { + try { + return await this.readUsage(); + } catch (error) { + this.logger.debug(`Failed to read workspace memory: ${errToStr(error)}`); + return undefined; + } + } +} diff --git a/src/memory/pressure.ts b/src/memory/pressure.ts new file mode 100644 index 0000000000..612eeeae29 --- /dev/null +++ b/src/memory/pressure.ts @@ -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; + 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"; +} diff --git a/src/memory/remoteFiles.ts b/src/memory/remoteFiles.ts new file mode 100644 index 0000000000..ee70a4f91e --- /dev/null +++ b/src/memory/remoteFiles.ts @@ -0,0 +1,425 @@ +// A port of coder/clistat's memory reading (`coder stat mem`), following +// https://github.com/coder/clistat/tree/3a2651d6a78ed5b70332fb50bc99d1e553a28e15 +// except where parseMemorySample notes a difference. Keep it in step with +// clistat. + +import * as vscode from "vscode"; + +import { vscodeProposed } from "../vscode/proposed"; + +import type { MemorySample, MemoryUsageSource } from "./usage"; + +// Docker writes 2^63 - 1 rounded to a page for "no limit"; anything this +// large cannot be a real limit, and Number cannot represent it exactly. +const CGROUP_V1_UNLIMITED = 2 ** 62; +const PROC_SELF_CGROUP = "/proc/self/cgroup"; +const PROC_SELF_MOUNTINFO = "/proc/self/mountinfo"; +const MEMINFO = "/proc/meminfo"; +const HOST_PRESSURE = "/proc/pressure/memory"; +const HOST_FILES = [MEMINFO, HOST_PRESSURE] as const; +const CGROUP_V1_FILES = [ + "memory.limit_in_bytes", + "memory.usage_in_bytes", + "memory.stat", +] as const; +const CGROUP_V2_FILES = [ + "memory.max", + "memory.current", + "memory.stat", + "memory.pressure", +] as const; +/** + * Sums the keys that make up `memory.current` from one `memory.stat` read, + * since mixing in the exact `memory.current` jumps by gigabytes during fast + * I/O while `memory.stat` lags. + */ +const CGROUP_V2_CHARGED = ["anon", "file", "kernel", "sock"] as const; +/** + * `memory.stat` keys the kernel reclaims before an OOM kill: the file LRU + * lists and reclaimable slab. tmpfs and shared memory sit on the anon lists, + * so they stay counted. + */ +const CGROUP_V2_RECLAIMABLE = [ + "active_file", + "inactive_file", + "slab_reclaimable", +] as const; +const CGROUP_V1_RECLAIMABLE = [ + "total_active_file", + "total_inactive_file", +] as const; + +/** Reads a file on the workspace; undefined when it is missing or unreadable. */ +export type ReadWorkspaceFile = (path: string) => Promise; + +/** + * Reads files on the machine this remote window is connected to, through + * the VS Code server's file system. Uses the window's own authority, which + * for a dev container is the container, not the workspace host. + */ +export async function readRemoteFile( + path: string, +): Promise { + const authority = vscodeProposed.env.remoteAuthority; + if (!authority) { + return undefined; + } + const uri = vscode.Uri.from({ scheme: "vscode-remote", authority, path }); + try { + return new TextDecoder().decode(await vscode.workspace.fs.readFile(uri)); + } catch { + return undefined; + } +} + +/** + * Memory read from the cgroup and `/proc` files of the machine the window is + * connected to. A poll reads every file it may need in one parallel batch, + * which is one round trip to the remote, then parses them. + */ +export function createRemoteFileUsage( + read: ReadWorkspaceFile = readRemoteFile, +): MemoryUsageSource { + let cgroups: Cgroups = { v2: [], v1: [] }; + return async () => { + let file = await readFiles(read, batchPaths(cgroups)); + // The batch read the cgroup files of the last poll's cgroups. When the + // server is in others (first poll, or it moved), read them again. + const current = findCgroups( + file(PROC_SELF_CGROUP), + file(PROC_SELF_MOUNTINFO), + ); + if (JSON.stringify(current) !== JSON.stringify(cgroups)) { + cgroups = current; + file = await readFiles(read, batchPaths(cgroups)); + } + return parseMemorySample(file, cgroups); + }; +} + +type Files = (path: string) => string | undefined; + +async function readFiles( + read: ReadWorkspaceFile, + paths: readonly string[], +): Promise { + const texts = await Promise.all(paths.map((path) => read(path))); + const files = new Map(paths.map((path, i) => [path, texts[i]])); + return (path) => files.get(path); +} + +/** Every file a poll may need, given the cgroups of the last poll. */ +function batchPaths({ v2, v1 }: Cgroups): string[] { + return [ + PROC_SELF_CGROUP, + PROC_SELF_MOUNTINFO, + ...HOST_FILES, + ...v1.flatMap((dir) => CGROUP_V1_FILES.map((f) => `${dir}/${f}`)), + ...v2.flatMap((dir) => CGROUP_V2_FILES.map((f) => `${dir}/${f}`)), + ]; +} + +interface Limit { + readonly used: number; + readonly total: number; + /** Undefined for a cgroup v1 limit, which has no PSI of its own. */ + readonly pressureFile: string | undefined; +} + +/** + * Used is memory the kernel cannot reclaim without killing or swapping: + * `MemTotal - MemAvailable` on the host (as `free` and `top` report it), and usage + * minus the file LRU lists and reclaimable slab in a cgroup. Each cgroup + * limit and the host is a candidate; the one with the least room left is hit + * first. Ties go to the nearest cgroup. + * + * Follows clistat's `cgroupV2Statter.memory` (usage at the limit owner, else + * the nearest cgroup with usage files), `cgroupV1Statter.memory` and + * `Statter.HostMemory`, except: + * - clistat subtracts only `inactive_file`, mixing `memory.current` with + * `memory.stat`. + * - The host is always a candidate, with no `IsContainerized` check, so no + * limit or one above host memory reports the host; clistat reports the + * cgroup's own usage with no total. + * - It reads PSI, except for a cgroup v1 limit, which has none of its own. + * - It finds cgroups through `/proc/self/mountinfo` and reads cgroup v1 at + * every level, like v2; clistat reads fixed paths. + */ +function parseMemorySample( + file: Files, + cgroups: Cgroups, +): MemorySample | undefined { + const cgroup = + cgroupV2Limit(file, cgroups.v2) ?? cgroupV1Limit(file, cgroups.v1); + const host = hostLimit(file(MEMINFO) ?? ""); + const limit = cgroup && (!host || room(cgroup) <= room(host)) ? cgroup : host; + if (!limit) { + return undefined; + } + return { + usedBytes: limit.used, + totalBytes: limit.total, + pressure: limit.pressureFile + ? parsePressure(file(limit.pressureFile)) + : undefined, + source: limit === cgroup ? "cgroup" : "host", + }; +} + +function room(limit: Limit): number { + return limit.total - limit.used; +} + +function hostLimit(meminfo: string): Limit | undefined { + const total = parseMeminfoBytes(meminfo, "MemTotal"); + const available = parseMeminfoBytes(meminfo, "MemAvailable"); + if (!total || available === undefined) { + return undefined; + } + return { + used: Math.max(total - available, 0), + total, + pressureFile: HOST_PRESSURE, + }; +} + +/** A cgroup level's own limit and usage, either undefined when unreadable. */ +interface Level { + readonly total: number | undefined; + readonly used: number | undefined; + readonly pressureFile: string | undefined; +} + +/** + * Every limit from the process up to the root applies; the one with the + * least room left is hit first. Ties go to the nearest level. Usage at the + * limit owner counts sibling cgroups under it; like clistat, a level without + * usage files falls back to the nearest level that has them. + */ +function leastRoom(levels: readonly Level[]): Limit | undefined { + const nearestUsed = levels.find((l) => l.used !== undefined)?.used; + let best: Limit | undefined; + for (const { total, used = nearestUsed, pressureFile } of levels) { + if (total === undefined || used === undefined) { + continue; + } + if (!best || total - used < room(best)) { + best = { used, total, pressureFile }; + } + } + return best; +} + +function cgroupV2Limit( + file: Files, + dirs: readonly string[], +): Limit | undefined { + return leastRoom( + dirs.map((dir) => ({ + // `max`, meaning no limit, does not parse as a number. + total: parseNumber(file(`${dir}/memory.max`)), + used: cgroupV2Used( + file(`${dir}/memory.current`), + file(`${dir}/memory.stat`), + ), + pressureFile: `${dir}/memory.pressure`, + })), + ); +} + +/** Used from one `memory.stat` read; before Linux 5.18 (no `kernel` key), from `memory.current`. */ +function cgroupV2Used( + current: string | undefined, + stat: string | undefined, +): number | undefined { + if (stat === undefined) { + return undefined; + } + if (parseKeyedValue(stat, "kernel") === undefined) { + return usedBytes(current, stat, CGROUP_V2_RECLAIMABLE); + } + const charged = CGROUP_V2_CHARGED.reduce( + (sum, key) => sum + (parseKeyedValue(stat, key) ?? 0), + 0, + ); + return withoutReclaimable(charged, stat, CGROUP_V2_RECLAIMABLE); +} + +/** + * Like v2, each level's `memory.limit_in_bytes` with that level's usage. + * A limit above the mount, which a container cannot see, still shows in + * `hierarchical_memory_limit` (the lowest limit up to the root), so it is a + * candidate too, with the nearest usage. + */ +function cgroupV1Limit( + file: Files, + dirs: readonly string[], +): Limit | undefined { + const [nearest] = dirs; + if (nearest === undefined) { + return undefined; + } + const levels = dirs.map((dir) => ({ + total: cgroupV1Total(parseNumber(file(`${dir}/memory.limit_in_bytes`))), + used: usedBytes( + file(`${dir}/memory.usage_in_bytes`), + file(`${dir}/memory.stat`), + CGROUP_V1_RECLAIMABLE, + ), + pressureFile: undefined, + })); + const hierarchical = parseKeyedValue( + file(`${nearest}/memory.stat`), + "hierarchical_memory_limit", + ); + // Last, so a visible owner of the same limit wins the tie. + return leastRoom([ + ...levels, + { + total: cgroupV1Total(hierarchical), + used: undefined, + pressureFile: undefined, + }, + ]); +} + +function cgroupV1Total(bytes: number | undefined): number | undefined { + return bytes === undefined || bytes >= CGROUP_V1_UNLIMITED + ? undefined + : bytes; +} + +/** Usage minus memory the kernel can reclaim; a missing key counts as 0. */ +function usedBytes( + usage: string | undefined, + stat: string | undefined, + reclaimableKeys: readonly string[], +): number | undefined { + const current = parseNumber(usage); + if (current === undefined || stat === undefined) { + return undefined; + } + return withoutReclaimable(current, stat, reclaimableKeys); +} + +function withoutReclaimable( + bytes: number, + stat: string, + reclaimableKeys: readonly string[], +): number { + const reclaimable = reclaimableKeys.reduce( + (sum, key) => sum + (parseKeyedValue(stat, key) ?? 0), + 0, + ); + return Math.max(bytes - reclaimable, 0); +} + +/** Where the process's memory cgroups are mounted. */ +interface Cgroups { + /** cgroup v2 directories from the process's cgroup up to the mount. */ + readonly v2: readonly string[]; + /** cgroup v1 memory directories from the process's cgroup up to the mount. */ + readonly v1: readonly string[]; +} + +/** + * Maps the process's cgroups (`/proc/self/cgroup`) to directories through + * the cgroup mounts (`/proc/self/mountinfo`). Both name cgroups from the + * cgroup namespace root, so a mount whose root is `/docker/abc` shows + * `/docker/abc/x` at `/x`. + */ +function findCgroups( + procCgroup: string | undefined, + mountinfo: string | undefined, +): Cgroups { + // Lines are `id:controllers:path`; v2 has id 0 and no controllers. + const entries = (procCgroup ?? "").split("\n").map((l) => l.split(":")); + const v2Path = entries + .find(([id]) => id === "0") + ?.slice(2) + .join(":"); + const v1Path = entries + .find(([, controllers]) => controllers?.split(",").includes("memory")) + ?.slice(2) + .join(":"); + return { + v2: cgroupDirs(findMount(mountinfo, "cgroup2"), v2Path), + v1: cgroupDirs(findMount(mountinfo, "cgroup", "memory"), v1Path), + }; +} + +interface Mount { + readonly root: string; + readonly point: string; +} + +/** The first mount of `type`, with `option` among its super options. */ +function findMount( + mountinfo: string | undefined, + type: string, + option?: string, +): Mount | undefined { + // `id parent dev root point options... - type source superOptions` + for (const line of (mountinfo ?? "").split("\n")) { + const [mount = "", fs = ""] = line.split(" - "); + const [, , , root, point] = mount.split(" "); + const [fsType, , superOptions = ""] = fs.split(" "); + const hasOption = !option || superOptions.split(",").includes(option); + if (fsType === type && hasOption && root && point) { + return { root, point }; + } + } + return undefined; +} + +/** + * The cgroup's directory and its parents up to the mount point, nearest + * first. Empty when the mount does not contain the cgroup. + */ +function cgroupDirs( + mount: Mount | undefined, + path: string | undefined, +): string[] { + if (!mount || path === undefined) { + return []; + } + const root = mount.root === "/" ? "" : mount.root; + if (path !== root && !path.startsWith(`${root}/`)) { + return []; + } + const parts = path.slice(root.length).split("/").filter(Boolean); + return parts + .map((_, i) => [mount.point, ...parts.slice(0, parts.length - i)].join("/")) + .concat(mount.point); +} + +function parseNumber(text: string | undefined): number | undefined { + const trimmed = text?.trim(); + const value = Number(trimmed); + return trimmed && Number.isFinite(value) ? value : undefined; +} + +function parseMeminfoBytes(meminfo: string, key: string): number | undefined { + const match = new RegExp(`^${key}:\\s+(\\d+)\\s*kB`, "m").exec(meminfo); + return match ? Number(match[1]) * 1024 : undefined; +} + +/** A `key value` line, as in `memory.stat`. */ +function parseKeyedValue( + text: string | undefined, + key: string, +): number | undefined { + for (const line of text?.split("\n") ?? []) { + const [name, value] = line.trim().split(/\s+/); + if (name === key) { + return parseNumber(value); + } + } + return undefined; +} + +/** The `some avg10` percentage of a PSI file. */ +function parsePressure(text: string | undefined): number | undefined { + const match = /^some\b.*\bavg10=([\d.]+)/m.exec(text ?? ""); + return match ? parseNumber(match[1]) : undefined; +} diff --git a/src/memory/topProcesses.ts b/src/memory/topProcesses.ts new file mode 100644 index 0000000000..1f7f92b3fd --- /dev/null +++ b/src/memory/topProcesses.ts @@ -0,0 +1,45 @@ +import * as vscode from "vscode"; + +import { vscodeProposed } from "../vscode/proposed"; + +// procps top sorts by memory with -o; BusyBox and old procps have no -o, so +// probe it once and fall back to the default order. Without top, wait for a +// key and exit 0, so the message stays readable instead of VS Code reporting +// a failed launch. +const TOP_SCRIPT = [ + "if ! command -v top >/dev/null 2>&1; then", + ' echo "top is not installed on this workspace."', + ' printf "Press Enter to close."; read -r _; exit 0', + "fi", + "if top -b -n 1 -o %MEM >/dev/null 2>&1; then exec top -o %MEM; fi", + "exec top", +].join("\n"); + +let terminal: vscode.Terminal | undefined; + +/** + * Shows `top`, sorted by memory, in a terminal on the connected workspace, + * reusing the one already open. A terminal without a `cwd` runs on the + * window's remote, and the script is fixed, so no deployment-provided value + * reaches a shell. + */ +export function showTopProcesses(): void { + if (!vscodeProposed.env.remoteAuthority) { + void vscode.window.showInformationMessage( + "Connect to a workspace to show its top processes.", + ); + return; + } + if ( + !terminal || + terminal.exitStatus !== undefined || + !vscode.window.terminals.includes(terminal) + ) { + terminal = vscode.window.createTerminal({ + name: "Top Processes", + shellPath: "/bin/sh", + shellArgs: ["-c", TOP_SCRIPT], + }); + } + terminal.show(); +} diff --git a/src/memory/usage.ts b/src/memory/usage.ts new file mode 100644 index 0000000000..4de1c7e7bd --- /dev/null +++ b/src/memory/usage.ts @@ -0,0 +1,25 @@ +const GIB = 1024 ** 3; +const MIB = 1024 ** 2; + +/** Memory of the cgroup (or host) whose limit the workspace runs under. */ +export interface MemorySample { + readonly usedBytes: number; + readonly totalBytes: number; + /** PSI `some avg10` in percent; undefined when it is not known. */ + readonly pressure?: number; + /** Whether a cgroup limit or the host's memory bounds usage. */ + readonly source: "cgroup" | "host"; +} + +/** + * Takes one memory sample of the connected workspace; undefined when memory + * cannot be read. `MemoryMonitor` polls whichever source the window uses. + */ +export type MemoryUsageSource = () => Promise; + +/** `6.12/16 GiB`, like the RAM line of `coder stat mem`. */ +export function formatUsage(sample: MemorySample): string { + const [unit, size] = sample.totalBytes >= GIB ? ["GiB", GIB] : ["MiB", MIB]; + const format = (bytes: number) => String(Number((bytes / size).toFixed(2))); + return `${format(sample.usedBytes)}/${format(sample.totalBytes)} ${unit}`; +} diff --git a/src/remote/agentStatusBar.ts b/src/remote/agentStatusBar.ts new file mode 100644 index 0000000000..671444d735 --- /dev/null +++ b/src/remote/agentStatusBar.ts @@ -0,0 +1,165 @@ +import * as vscode from "vscode"; + +import { + formatEventLabel, + getEventValue, + type AgentMetadataEvent, +} from "../api/agentMetadata"; +import { + isWarning, + type MemoryState, + type MemoryStatus, +} from "../memory/pressure"; +import { formatUsage } from "../memory/usage"; + +const SHOW_TOP_PROCESSES_COMMAND = "coder.workspace.showTopProcesses"; +const RESTART_COMMAND = "coder.workspace.restart"; + +const BACKGROUNDS: Readonly>> = { + high: new vscode.ThemeColor("statusBarItem.warningBackground"), +}; + +/** What the template's agent metadata currently provides. */ +export type AgentMetadataState = + | { readonly kind: "none" } + | { readonly kind: "values"; readonly events: readonly AgentMetadataEvent[] } + | { readonly kind: "error"; readonly message: string }; + +/** + * The agent status bar item combines server-supplied agent metadata with + * memory measured by the extension. Memory joins the text only when it needs + * attention or there is no metadata; the background color is reserved for + * memory, so color always means the user should act. + */ +export class AgentStatusBar implements vscode.Disposable { + private metadata: AgentMetadataState = { kind: "none" }; + private memory: MemoryStatus = { state: "unavailable" }; + + public constructor(private readonly item: vscode.StatusBarItem) {} + + public setMetadata(metadata: AgentMetadataState): void { + this.metadata = metadata; + this.render(); + } + + public setMemory(memory: MemoryStatus): void { + this.memory = memory; + this.render(); + } + + public dispose(): void { + this.item.dispose(); + } + + private render(): void { + const metadataText = renderMetadataText(this.metadata); + const memoryText = renderMemoryText( + this.memory, + metadataText === undefined, + ); + const parts = [metadataText, memoryText].filter((p) => p !== undefined); + if (parts.length === 0) { + this.item.hide(); + return; + } + this.item.text = parts.join(" · "); + this.item.tooltip = renderTooltip(this.metadata, this.memory); + this.item.backgroundColor = BACKGROUNDS[this.memory.state]; + this.item.command = isWarning(this.memory) + ? SHOW_TOP_PROCESSES_COMMAND + : undefined; + this.item.show(); + } +} + +function renderMetadataText(metadata: AgentMetadataState): string | undefined { + switch (metadata.kind) { + case "values": + return metadata.events.length > 0 + ? `$(dashboard) ${getEventValue(metadata.events[0])}` + : undefined; + case "error": + return "$(warning) Agent Status Unavailable"; + case "none": + return undefined; + } +} + +function renderMetadataLines(metadata: AgentMetadataState): string[] { + switch (metadata.kind) { + case "values": + return metadata.events.map((event) => formatEventLabel(event)); + case "error": + return [metadata.message]; + case "none": + return []; + } +} + +function renderMemoryText( + memory: MemoryStatus, + onlyPart: boolean, +): string | undefined { + switch (memory.state) { + case "high": + return `$(warning) Memory ${memory.percent}%`; + case "normal": + return onlyPart ? `$(dashboard) Memory ${memory.percent}%` : undefined; + case "unavailable": + return undefined; + } +} + +function renderTooltip( + metadata: AgentMetadataState, + memory: MemoryStatus, +): vscode.MarkdownString { + const md = new vscode.MarkdownString(); + md.isTrusted = { + enabledCommands: [SHOW_TOP_PROCESSES_COMMAND, RESTART_COMMAND], + }; + md.supportThemeIcons = true; + + const metadataLines = renderMetadataLines(metadata); + if (metadataLines.length > 0) { + md.appendMarkdown("**Agent metadata**"); + // Template-defined values are untrusted, so they go in as plain text. + for (const line of metadataLines) { + md.appendMarkdown(" \n").appendText(line); + } + } + + if (memory.state === "unavailable") { + return md; + } + if (md.value) { + md.appendMarkdown("\n\n"); + } + md.appendMarkdown( + `**Workspace usage** \nMemory: ${formatUsage(memory.sample)} (${memory.percent}%)`, + ); + if (memory.sample.pressure !== undefined) { + md.appendMarkdown( + ` \nPressure: ${memory.sample.pressure}% of time stalled`, + ); + } + const warning = memoryWarningSentence(memory); + if (warning) { + md.appendMarkdown( + `\n\n${warning} \n[$(list-flat) Top processes](command:${SHOW_TOP_PROCESSES_COMMAND} "Open top. Its memory summary covers the whole machine.") · [$(debug-restart) Restart](command:${RESTART_COMMAND} "Restart the workspace")`, + ); + } + return md; +} + +function memoryWarningSentence(memory: MemoryStatus): string | undefined { + switch (memory.state) { + case "high": + return memory.trigger === "pressure" + ? "$(warning) **Memory pressure is high.** \nThe workspace is slowing down." + : "$(warning) **Memory is running low.** \nProcesses may be killed soon."; + case "normal": + case "unavailable": + return undefined; + } +} diff --git a/src/remote/remote.ts b/src/remote/remote.ts index e17a0bb955..614901d935 100644 --- a/src/remote/remote.ts +++ b/src/remote/remote.ts @@ -7,8 +7,6 @@ import * as vscode from "vscode"; import { createAgentMetadataWatcher, - getEventValue, - formatEventLabel, formatMetadataError, } from "../api/agentMetadata"; import { AuthInterceptor } from "../api/authInterceptor"; @@ -31,10 +29,13 @@ import { } from "../featureSet"; import { Inbox } from "../inbox"; import { AuthTelemetry } from "../instrumentation/auth"; +import { MemoryTelemetry } from "../instrumentation/memory"; import { RemoteSetupTelemetry, type RemoteSetupTracer, } from "../instrumentation/remoteSetup"; +import { MemoryMonitor } from "../memory/monitor"; +import { createRemoteFileUsage } from "../memory/remoteFiles"; import { OAuthSessionManager } from "../oauth/sessionManager"; import { type CliAuth, @@ -48,6 +49,7 @@ import { createStatusBarItem } from "../ui/statusBar"; import { vscodeProposed } from "../vscode/proposed"; import { WorkspaceMonitor } from "../workspace/workspaceMonitor"; +import { AgentStatusBar } from "./agentStatusBar"; import { type AuthorityParts, classifySshHost, @@ -1025,50 +1027,43 @@ export class Remote { } /** - * Creates and manages a status bar item that displays metadata information for a given workspace agent. - * The status bar item updates dynamically based on changes to the agent's metadata, - * and hides itself if no metadata is available or an error occurs. + * Creates the agent status bar item, fed by the agent's metadata and by the + * workspace memory this window measures. */ private async createAgentMetadataStatusBar( agent: WorkspaceAgent, client: CoderApi, ): Promise { - const statusBarItem = createStatusBarItem("agentMetadata"); + const statusBar = new AgentStatusBar(createStatusBarItem("agentMetadata")); const agentWatcher = await createAgentMetadataWatcher(agent.id, client); - - const onChangeDisposable = agentWatcher.onChange(() => { + const onMetadataChange = agentWatcher.onChange(() => { if (agentWatcher.error) { - const errMessage = formatMetadataError(agentWatcher.error); - this.logger.warn(errMessage); - - statusBarItem.text = "$(warning) Agent Status Unavailable"; - statusBarItem.tooltip = errMessage; - statusBarItem.color = new vscode.ThemeColor( - "statusBarItem.warningForeground", - ); - statusBarItem.backgroundColor = new vscode.ThemeColor( - "statusBarItem.warningBackground", - ); - statusBarItem.show(); - return; - } - - if (agentWatcher.metadata && agentWatcher.metadata.length > 0) { - statusBarItem.text = - "$(dashboard) " + getEventValue(agentWatcher.metadata[0]); - statusBarItem.tooltip = agentWatcher.metadata - .map((metadata) => formatEventLabel(metadata)) - .join("\n"); - statusBarItem.color = undefined; - statusBarItem.backgroundColor = undefined; - statusBarItem.show(); + const message = formatMetadataError(agentWatcher.error); + this.logger.warn(message); + statusBar.setMetadata({ kind: "error", message }); + } else if (agentWatcher.metadata && agentWatcher.metadata.length > 0) { + statusBar.setMetadata({ + kind: "values", + events: agentWatcher.metadata, + }); } else { - statusBarItem.hide(); + statusBar.setMetadata({ kind: "none" }); } }); - return [statusBarItem, agentWatcher, onChangeDisposable]; + const monitor = new MemoryMonitor( + createRemoteFileUsage(), + new MemoryTelemetry(this.serviceContainer.getTelemetryService()), + this.logger, + ); + return [ + statusBar, + agentWatcher, + onMetadataChange, + monitor, + monitor.onDidChange((status) => statusBar.setMemory(status)), + ]; } // closeRemote ends the current remote session. diff --git a/src/remote/workspaceStateMachine.ts b/src/remote/workspaceStateMachine.ts index 8e3613355e..a7d93811c4 100644 --- a/src/remote/workspaceStateMachine.ts +++ b/src/remote/workspaceStateMachine.ts @@ -107,6 +107,13 @@ export class WorkspaceStateMachine implements vscode.Disposable { case "stopped": case "failed": { this.buildLogStream.close(); + if (this.startupMode === "restart") { + this.startupMode = "start"; + // The restart queued its start behind this stop. + if (workspace.latest_build.status === "stopped") { + this.queuedStopBuild = workspace.latest_build.id; + } + } if (workspace.latest_build.id === this.queuedStopBuild) { if (workspace.latest_build.status === "failed") { throw new Error( diff --git a/src/settings/memoryMonitor.ts b/src/settings/memoryMonitor.ts new file mode 100644 index 0000000000..dd7577d8b8 --- /dev/null +++ b/src/settings/memoryMonitor.ts @@ -0,0 +1,18 @@ +import type { WorkspaceConfiguration } from "vscode"; + +export const MEMORY_WARNING_THRESHOLD_SETTING = + "coder.memoryMonitor.warningThreshold"; +const DEFAULT_WARNING_THRESHOLD = 80; + +/** The memory warning threshold in percent; `0` turns warnings off. */ +export function getMemoryWarningThreshold( + cfg: Pick, +): number { + const value = cfg.get( + MEMORY_WARNING_THRESHOLD_SETTING, + DEFAULT_WARNING_THRESHOLD, + ); + return Number.isFinite(value) + ? Math.min(Math.max(value, 0), 99) + : DEFAULT_WARNING_THRESHOLD; +} diff --git a/src/storage/mementoManager.ts b/src/storage/mementoManager.ts index e479654ea7..941ba3db06 100644 --- a/src/storage/mementoManager.ts +++ b/src/storage/mementoManager.ts @@ -22,8 +22,10 @@ const PENDING_TTL_MS = 5 * 60 * 1000; * - "start": User-initiated open/restart; auto-start without prompting. * - "update": User-initiated restart + update; use `coder update` to apply * the latest template version, auto-starting without prompting. + * - "restart": A stop was queued with the start to follow it; wait for the + * server's start instead of starting it again. */ -export type StartupMode = "none" | "start" | "update"; +export type StartupMode = "none" | "start" | "update" | "restart"; interface Stamped { value: T; diff --git a/src/supportBundle/settings.ts b/src/supportBundle/settings.ts index 9a543997e8..b9ccafbac1 100644 --- a/src/supportBundle/settings.ts +++ b/src/supportBundle/settings.ts @@ -25,6 +25,7 @@ const COLLECTED_SETTINGS: readonly string[] = [ "coder.enableDownloads", "coder.httpClientLogLevel", "coder.insecure", + "coder.memoryMonitor.warningThreshold", "coder.networkThreshold.latencyMs", "coder.oauth.enabled", "coder.proxyBypass", diff --git a/src/vscode/commandManager.ts b/src/vscode/commandManager.ts index a83a87a66b..280bfdf2fc 100644 --- a/src/vscode/commandManager.ts +++ b/src/vscode/commandManager.ts @@ -19,6 +19,8 @@ export const CODER_COMMAND_IDS = [ "coder.openFromSidebar", "coder.openAppStatus", "coder.workspace.update", + "coder.workspace.showTopProcesses", + "coder.workspace.restart", "coder.createWorkspace", "coder.navigateToWorkspace", "coder.navigateToWorkspaceSettings", diff --git a/src/webviews/workspaces/workspaceActionRunner.ts b/src/webviews/workspaces/workspaceActionRunner.ts index 9e3273772f..05b6e3bd48 100644 --- a/src/webviews/workspaces/workspaceActionRunner.ts +++ b/src/webviews/workspaces/workspaceActionRunner.ts @@ -12,6 +12,7 @@ import { WorkspaceUpdateCancelledError, } from "../../api/updateParameters"; import { + postBuild, restartWorkspace, runBuild, startWorkspaceViaApi, @@ -26,12 +27,16 @@ import { serverFeatureSet } from "../../featureSet"; import { WorkspaceOperationTelemetry } from "../../instrumentation/workspace"; import { vscodeProposed } from "../../vscode/proposed"; -import type { Workspace } from "coder/site/src/api/typesGenerated"; +import type { + Workspace, + WorkspaceBuild, +} from "coder/site/src/api/typesGenerated"; import type { CoderApi } from "../../api/coderApi"; import type { Commands } from "../../commands"; import type { SessionState } from "../../deployment/sessionStore"; import type { Logger } from "../../logging/logger"; +import type { MementoManager } from "../../storage/mementoManager"; import type { TelemetryReporter } from "../../telemetry/reporter"; const RESTART_WARNING = @@ -47,6 +52,7 @@ export class WorkspaceActionRunner { private readonly client: CoderApi, private readonly session: SessionState, private readonly connected: Pick, + private readonly mementoManager: Pick, private readonly telemetry: TelemetryReporter, private readonly logger: Logger, ) {} @@ -74,7 +80,7 @@ export class WorkspaceActionRunner { } const latest = await this.reread(listed, action, abort.signal); if (latest) { - await this.perform(ctx, latest, action, telemetry); + await this.perform(ctx, latest, action, connected, telemetry); } } catch (error) { if (abort.signal.aborted) { @@ -171,6 +177,7 @@ export class WorkspaceActionRunner { ctx: BuildContext, workspace: Workspace, action: WorkspaceAction, + connected: boolean, telemetry: WorkspaceOperationTelemetry, ): Promise { if (action === "update") { @@ -186,12 +193,42 @@ export class WorkspaceActionRunner { const builds = { start: () => startWorkspaceViaApi(ctx, workspace), stop: () => runBuild(ctx, workspace.id, { transition: "stop" }), - restart: () => restartWorkspace(ctx, workspace), + restart: () => + connected + ? this.restartConnected(ctx, workspace) + : restartWorkspace(ctx, workspace), delete: () => runBuild(ctx, workspace.id, { transition: "delete" }), }[action]; await telemetry.traceAction(action, builds); } + /** + * Queues the stop, with the start behind it where the server supports + * that, then reloads so the remote setup reconnects once it is running, + * instead of this window losing its connection. + */ + private async restartConnected( + ctx: BuildContext, + workspace: Workspace, + ): Promise { + const { version } = await this.client.getBuildInfo(); + const queuesStart = serverFeatureSet(semver.parse(version)).onSuccessBuild; + const stop = await postBuild( + ctx.client, + workspace.id, + queuesStart + ? { transition: "stop", on_success: { transition: "start" } } + : { transition: "stop" }, + ctx.signal, + ); + if (stop.transition !== "stop") { + throw new Error(`The server queued a ${stop.transition}, not a stop`); + } + await this.mementoManager.setStartupMode(queuesStart ? "restart" : "start"); + await vscode.commands.executeCommand("workbench.action.reloadWindow"); + return stop; + } + /** Writes each line to the Coder output, tagged with the workspace. */ private writer(name: string): Write { return (data) => { diff --git a/test/unit/memory/monitor.test.ts b/test/unit/memory/monitor.test.ts new file mode 100644 index 0000000000..1db2ade8ff --- /dev/null +++ b/test/unit/memory/monitor.test.ts @@ -0,0 +1,99 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { MemoryTelemetry } from "@/instrumentation/memory"; +import { MemoryMonitor } from "@/memory/monitor"; + +import { createTelemetryHarness, type TestSink } from "../../mocks/telemetry"; +import { + createMockLogger, + MockConfigurationProvider, +} from "../../mocks/testHelpers"; + +import type { MemoryStatus } from "@/memory/pressure"; +import type { MemorySample } from "@/memory/usage"; + +const sample = (percent: number): MemorySample => ({ + usedBytes: percent, + totalBytes: 100, + source: "host", +}); + +describe("MemoryMonitor", () => { + let config: MockConfigurationProvider; + let sink: TestSink; + let telemetry: MemoryTelemetry; + let next: () => Promise; + let polls: number; + + beforeEach(() => { + vi.useFakeTimers(); + const harness = createTelemetryHarness(); + sink = harness.sink; + telemetry = new MemoryTelemetry(harness.service); + config = new MockConfigurationProvider(); + config.set("coder.telemetry.level", "local"); + next = () => Promise.resolve(sample(50)); + polls = 0; + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + function start() { + const monitor = new MemoryMonitor( + () => { + polls++; + return next(); + }, + telemetry, + createMockLogger(), + ); + const statuses: MemoryStatus[] = []; + monitor.onDidChange((s) => statuses.push(s)); + return { monitor, statuses }; + } + + it("polls right away and every 10 seconds, logging each state change", async () => { + const { monitor, statuses } = start(); + await vi.advanceTimersByTimeAsync(0); + next = () => Promise.resolve(sample(90)); + await vi.advanceTimersByTimeAsync(20_000); + monitor.dispose(); + await vi.advanceTimersByTimeAsync(60_000); + + expect(statuses.map((s) => s.state)).toEqual(["normal", "normal", "high"]); + expect( + sink.eventsNamed("memory.state_transitioned").map((e) => e.properties), + ).toEqual([ + { from: "unavailable", to: "normal", source: "host" }, + { from: "normal", to: "high", source: "host", trigger: "usage" }, + ]); + }); + + it("skips a poll while the previous read is still pending", async () => { + let release = (): void => undefined; + next = () => + new Promise((resolve) => { + release = () => resolve(undefined); + }); + const { monitor, statuses } = start(); + + await vi.advanceTimersByTimeAsync(30_000); + expect(polls).toBe(1); + release(); + await vi.advanceTimersByTimeAsync(10_000); + expect(polls).toBe(2); + expect(statuses).toHaveLength(1); + monitor.dispose(); + }); + + it("re-polls as soon as the threshold changes", async () => { + const { monitor } = start(); + await vi.advanceTimersByTimeAsync(0); + config.set("coder.memoryMonitor.warningThreshold", 0); + await vi.advanceTimersByTimeAsync(0); + expect(polls).toBe(2); + monitor.dispose(); + }); +}); diff --git a/test/unit/memory/pressure.test.ts b/test/unit/memory/pressure.test.ts new file mode 100644 index 0000000000..58fe1842bd --- /dev/null +++ b/test/unit/memory/pressure.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, it } from "vitest"; + +import { MemoryPressureTracker } from "@/memory/pressure"; + +import type { MemorySample } from "@/memory/usage"; + +/** `percent` used; `p` is PSI. */ +function s(percent: number, p?: number): MemorySample { + return { usedBytes: percent, totalBytes: 100, pressure: p, source: "cgroup" }; +} + +describe("MemoryPressureTracker", () => { + it.each([ + { + name: "ignores a single spike", + samples: [s(50), s(95), s(50), s(50)], + states: ["normal", "normal", "normal", "normal"], + }, + { + name: "enters High when 2 of the last 3 samples reach the threshold", + samples: [s(85), s(70), s(80)], + states: ["normal", "normal", "high"], + }, + { + name: "stays High just under the threshold, leaves after 2 samples 5 points under", + samples: [s(85), s(85), s(78), s(74), s(70)], + states: ["normal", "high", "high", "high", "normal"], + }, + { + name: "enters High on pressure and leaves once it calms", + samples: [s(40, 30), s(40, 12), s(40, 5), s(40, 5)], + states: ["high", "high", "high", "normal"], + }, + { + name: "keeps a warning while calm samples arrive close together", + gapMs: 500, + samples: [s(90), s(90), s(50), s(50)], + states: ["normal", "high", "high", "high"], + }, + { + name: "never warns with a threshold of 0", + threshold: 0, + samples: [s(99, 90), s(99, 90)], + states: ["normal", "normal"], + }, + ])("$name", ({ samples, states, threshold = 80, gapMs = 10_000 }) => { + let now = 0; + const tracker = new MemoryPressureTracker(() => now); + const actual = samples.map((x) => { + now += gapMs; + return tracker.update(x, threshold).state; + }); + expect(actual).toEqual(states); + }); + + it("reports percent and trigger", () => { + const tracker = new MemoryPressureTracker(); + expect(tracker.update(s(40, 25), 80)).toMatchObject({ + state: "high", + trigger: "pressure", + percent: 40, + }); + }); +}); diff --git a/test/unit/memory/remoteFiles.test.ts b/test/unit/memory/remoteFiles.test.ts new file mode 100644 index 0000000000..474084f5b6 --- /dev/null +++ b/test/unit/memory/remoteFiles.test.ts @@ -0,0 +1,284 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import * as vscode from "vscode"; + +import { createRemoteFileUsage, readRemoteFile } from "@/memory/remoteFiles"; + +import type { MemorySample } from "@/memory/usage"; + +const GiB = 1024 ** 3; +const MEMINFO_16G = + "MemTotal: 16777216 kB\nMemFree: 1 kB\nMemAvailable: 12582912 kB\n"; +const PSI = + "some avg10=25.50 avg60=3.00 avg300=1.00 total=1\nfull avg10=9.00\n"; +const V2_MOUNT = "30 1 0:26 / /sys/fs/cgroup rw - cgroup2 cgroup2 rw\n"; +const V1_MOUNT = + "40 1 0:30 / /sys/fs/cgroup/memory rw - cgroup cgroup rw,memory\n"; + +/** Reads `files`, with cgroups mounted at their usual places unless overridden. */ +function reader(files: Record) { + const all: Record = { + "/proc/self/mountinfo": V2_MOUNT + V1_MOUNT, + ...files, + }; + return (path: string) => Promise.resolve(all[path]); +} + +describe("createRemoteFileUsage", () => { + it.each<{ + name: string; + files: Record; + expected: MemorySample | undefined; + }>([ + { + name: "Kata VM: no cgroup limit, host memory, no PSI", + files: { + "/proc/self/cgroup": "0::/init\n", + "/sys/fs/cgroup/init/memory.max": "max\n", + "/proc/meminfo": MEMINFO_16G, + }, + expected: { + usedBytes: 4 * GiB, + totalBytes: 16 * GiB, + pressure: undefined, + source: "host", + }, + }, + { + name: "cgroup v2: used is summed from one memory.stat read, not the fresher memory.current", + files: { + "/proc/self/cgroup": "0::/\n", + "/sys/fs/cgroup/memory.max": String(8 * GiB), + "/sys/fs/cgroup/memory.current": String(6 * GiB), + // shmem stays counted: it is in file but not on the file LRU lists. + "/sys/fs/cgroup/memory.stat": `anon ${GiB}\nfile ${2 * GiB}\nkernel ${0.5 * GiB}\nsock 0\nshmem ${0.5 * GiB}\nactive_file ${GiB}\ninactive_file ${0.5 * GiB}\nslab_reclaimable ${0.25 * GiB}`, + "/sys/fs/cgroup/memory.pressure": PSI, + "/proc/meminfo": MEMINFO_16G, + }, + expected: { + usedBytes: 1.75 * GiB, + totalBytes: 8 * GiB, + pressure: 25.5, + source: "cgroup", + }, + }, + { + name: "cgroup v2 without the kernel key (Linux before 5.18): limit with least room wins, usage at the limit owner", + files: { + "/proc/self/cgroup": "0::/user/app\n", + "/sys/fs/cgroup/user/app/memory.max": "max", + // 0.75 GiB of room, counting siblings under the limit owner. + "/sys/fs/cgroup/user/memory.max": String(2 * GiB), + "/sys/fs/cgroup/user/memory.current": String(2 * GiB), + "/sys/fs/cgroup/user/memory.stat": `anon 1\nshmem ${0.25 * GiB}\nactive_file ${0.25 * GiB}\ninactive_file ${0.25 * GiB}\nslab_reclaimable ${0.25 * GiB}`, + "/sys/fs/cgroup/user/memory.pressure": PSI, + // 1 GiB of room, so it is not hit first. + "/sys/fs/cgroup/memory.max": String(8 * GiB), + "/sys/fs/cgroup/memory.current": String(7 * GiB), + "/sys/fs/cgroup/memory.stat": "inactive_file 0", + }, + expected: { + usedBytes: 1.25 * GiB, + totalBytes: 2 * GiB, + pressure: 25.5, + source: "cgroup", + }, + }, + { + name: "cgroup v2 limit above host memory (overcommit): the host has less room, with host PSI", + files: { + "/proc/self/cgroup": "0::/\n", + "/sys/fs/cgroup/memory.max": String(64 * GiB), + "/sys/fs/cgroup/memory.current": String(GiB), + "/sys/fs/cgroup/memory.stat": "anon 1", + "/proc/meminfo": MEMINFO_16G, + "/proc/pressure/memory": PSI, + }, + expected: { + usedBytes: 4 * GiB, + totalBytes: 16 * GiB, + pressure: 25.5, + source: "host", + }, + }, + { + name: "cgroup v2: the limit owner has no usage files, so the nearest cgroup's usage counts", + files: { + "/proc/self/cgroup": "0::/app\n", + "/sys/fs/cgroup/app/memory.current": String(3 * GiB), + "/sys/fs/cgroup/app/memory.stat": `inactive_file ${GiB}`, + "/sys/fs/cgroup/memory.max": String(4 * GiB), + }, + expected: { + usedBytes: 2 * GiB, + totalBytes: 4 * GiB, + pressure: undefined, + source: "cgroup", + }, + }, + { + name: "cgroup v1 limit (sysbox, older Docker): host PSI is machine-wide, so it is left out", + files: { + "/proc/self/cgroup": + "5:cpu,cpuacct:/docker/abc\n4:memory:/docker/abc\n", + // Docker mounts the container's own cgroup. + "/proc/self/mountinfo": + "40 1 0:30 /docker/abc /sys/fs/cgroup/memory rw - cgroup cgroup rw,memory\n", + "/sys/fs/cgroup/memory/memory.limit_in_bytes": String(8 * GiB), + "/sys/fs/cgroup/memory/memory.usage_in_bytes": String(3 * GiB), + "/sys/fs/cgroup/memory/memory.stat": `cache 1\ntotal_active_file ${0.5 * GiB}\ntotal_inactive_file ${0.5 * GiB}\n`, + "/proc/meminfo": MEMINFO_16G, + "/proc/pressure/memory": PSI, + }, + expected: { + usedBytes: 2 * GiB, + totalBytes: 8 * GiB, + pressure: undefined, + source: "cgroup", + }, + }, + ...["9223372036854771712", String(32 * GiB)].map((limit) => ({ + name: `cgroup v1 limit ${limit} has more room than the host, so host memory counts`, + files: { + "/proc/self/cgroup": "4:memory:/\n", + "/sys/fs/cgroup/memory/memory.limit_in_bytes": limit, + "/sys/fs/cgroup/memory/memory.usage_in_bytes": String(GiB), + "/sys/fs/cgroup/memory/memory.stat": "total_inactive_file 0", + "/proc/meminfo": MEMINFO_16G, + }, + expected: { + usedBytes: 4 * GiB, + totalBytes: 16 * GiB, + pressure: undefined, + source: "host" as const, + }, + })), + { + name: "cgroup v2 mounted at a parent of the process's cgroup: the mount root maps the path", + files: { + "/proc/self/cgroup": "0::/kubepods/pod/ctr\n", + "/proc/self/mountinfo": + "30 1 0:26 /kubepods/pod /sys/fs/cgroup rw - cgroup2 cgroup2 rw\n", + "/sys/fs/cgroup/ctr/memory.max": String(2 * GiB), + "/sys/fs/cgroup/ctr/memory.current": String(GiB), + "/sys/fs/cgroup/ctr/memory.stat": "anon 1", + }, + expected: { + usedBytes: GiB, + totalBytes: 2 * GiB, + pressure: undefined, + source: "cgroup", + }, + }, + { + name: "hybrid: memory is on cgroup v1, with the limit set on a parent cgroup that is not readable", + files: { + "/proc/self/cgroup": "4:memory:/user.slice/job\n0::/user.slice/job\n", + "/proc/self/mountinfo": + "30 1 0:26 / /sys/fs/cgroup/unified rw - cgroup2 cgroup2 rw\n" + + V1_MOUNT, + "/sys/fs/cgroup/memory/user.slice/job/memory.limit_in_bytes": + "9223372036854771712", + "/sys/fs/cgroup/memory/user.slice/job/memory.usage_in_bytes": String( + 3 * GiB, + ), + "/sys/fs/cgroup/memory/user.slice/job/memory.stat": `hierarchical_memory_limit ${4 * GiB}\ntotal_inactive_file ${GiB}`, + "/proc/meminfo": MEMINFO_16G, + }, + expected: { + usedBytes: 2 * GiB, + totalBytes: 4 * GiB, + pressure: undefined, + source: "cgroup", + }, + }, + { + name: "cgroup v1 limit on a readable parent: usage at the parent counts sibling cgroups", + files: { + "/proc/self/cgroup": "4:memory:/user.slice/job\n", + "/sys/fs/cgroup/memory/user.slice/job/memory.limit_in_bytes": + "9223372036854771712", + "/sys/fs/cgroup/memory/user.slice/job/memory.usage_in_bytes": + String(GiB), + "/sys/fs/cgroup/memory/user.slice/job/memory.stat": `hierarchical_memory_limit ${4 * GiB}\ntotal_inactive_file 0`, + "/sys/fs/cgroup/memory/user.slice/memory.limit_in_bytes": String( + 4 * GiB, + ), + "/sys/fs/cgroup/memory/user.slice/memory.usage_in_bytes": String( + 3.5 * GiB, + ), + "/sys/fs/cgroup/memory/user.slice/memory.stat": `total_inactive_file ${0.5 * GiB}`, + "/proc/meminfo": MEMINFO_16G, + }, + expected: { + usedBytes: 3 * GiB, + totalBytes: 4 * GiB, + pressure: undefined, + source: "cgroup", + }, + }, + { + name: "nothing readable", + files: { "/proc/self/cgroup": "0::/\n" }, + expected: undefined, + }, + ])("$name", async ({ files, expected }) => { + expect(await createRemoteFileUsage(reader(files))()).toEqual(expected); + }); + + it("reads one batch per poll and follows the server to a new cgroup", async () => { + const files: Record = { + "/proc/self/cgroup": "0::/a\n", + "/sys/fs/cgroup/a/memory.max": String(4 * GiB), + "/sys/fs/cgroup/a/memory.current": String(GiB), + "/sys/fs/cgroup/a/memory.stat": "inactive_file 0", + "/sys/fs/cgroup/b/memory.max": String(8 * GiB), + "/sys/fs/cgroup/b/memory.current": String(2 * GiB), + "/sys/fs/cgroup/b/memory.stat": "inactive_file 0", + }; + let batches = 0; + const usage = createRemoteFileUsage((path) => { + if (path === "/proc/self/cgroup") { + batches++; + } + return reader(files)(path); + }); + + // The first poll learns the cgroup, then reads its files. + expect(await usage()).toMatchObject({ totalBytes: 4 * GiB }); + expect(batches).toBe(2); + expect(await usage()).toMatchObject({ totalBytes: 4 * GiB }); + expect(batches).toBe(3); + + files["/proc/self/cgroup"] = "0::/b\n"; + expect(await usage()).toMatchObject({ totalBytes: 8 * GiB }); + expect(batches).toBe(5); + }); +}); + +describe("readRemoteFile", () => { + const env = vscode.env as { remoteAuthority?: string }; + + afterEach(() => { + delete env.remoteAuthority; + vi.mocked(vscode.workspace.fs.readFile).mockReset(); + }); + + it("reads through the window's remote authority", async () => { + expect(await readRemoteFile("/proc/meminfo")).toBeUndefined(); + + env.remoteAuthority = "dev-container+abc@coder-vscode--alice--dev"; + vi.mocked(vscode.workspace.fs.readFile).mockResolvedValue( + new TextEncoder().encode("0::/\n"), + ); + expect(await readRemoteFile("/proc/self/cgroup")).toBe("0::/\n"); + expect(vi.mocked(vscode.workspace.fs.readFile).mock.calls).toEqual([ + [ + expect.objectContaining({ + scheme: "vscode-remote", + authority: "dev-container+abc@coder-vscode--alice--dev", + path: "/proc/self/cgroup", + }), + ], + ]); + }); +}); diff --git a/test/unit/memory/usage.test.ts b/test/unit/memory/usage.test.ts new file mode 100644 index 0000000000..dfa42581c2 --- /dev/null +++ b/test/unit/memory/usage.test.ts @@ -0,0 +1,15 @@ +import { describe, expect, it } from "vitest"; + +import { formatUsage } from "@/memory/usage"; + +const GiB = 1024 ** 3; + +describe("formatUsage", () => { + it.each([ + [6.12 * GiB, 16 * GiB, "6.12/16 GiB"], + [1.5 * GiB, 2 * GiB, "1.5/2 GiB"], + [300 * 1024 ** 2, 512 * 1024 ** 2, "300/512 MiB"], + ])("formats %d of %d as %s", (usedBytes, totalBytes, text) => { + expect(formatUsage({ usedBytes, totalBytes, source: "host" })).toBe(text); + }); +}); diff --git a/test/unit/remote/agentStatusBar.test.ts b/test/unit/remote/agentStatusBar.test.ts new file mode 100644 index 0000000000..6e1aa51b81 --- /dev/null +++ b/test/unit/remote/agentStatusBar.test.ts @@ -0,0 +1,168 @@ +import { describe, expect, it } from "vitest"; + +import { + AgentStatusBar, + type AgentMetadataState, +} from "@/remote/agentStatusBar"; + +import { MockStatusBarItem } from "../../mocks/testHelpers"; + +import type { AgentMetadataEvent } from "@/api/agentMetadata"; +import type { MemoryStatus, MemoryTrigger } from "@/memory/pressure"; + +const GiB = 1024 ** 3; + +function metadataEvent(name: string, value: string): AgentMetadataEvent { + return { + result: { collected_at: "", age: 0, value, error: "" }, + description: { + display_name: name, + key: name, + script: "", + interval: 10, + timeout: 5, + }, + }; +} + +const VALUES: AgentMetadataState = { + kind: "values", + events: [ + metadataEvent("CPU Usage", "0.006/4 cores (0%)"), + metadataEvent("RAM Usage", "1.32/16 GiB (8%)"), + ], +}; +const ERROR: AgentMetadataState = { + kind: "error", + message: "Failed to query metadata: closed", +}; +const NONE: AgentMetadataState = { kind: "none" }; + +function memory( + state: MemoryStatus["state"], + percent = 25, + trigger?: MemoryTrigger, +): MemoryStatus { + if (state === "unavailable") { + return { state }; + } + return { + state, + percent, + trigger, + sample: { + usedBytes: (percent / 100) * 16 * GiB, + totalBytes: 16 * GiB, + source: "host", + }, + }; +} + +function render(metadata: AgentMetadataState, status: MemoryStatus) { + const item = new MockStatusBarItem(); + const bar = new AgentStatusBar(item); + bar.setMetadata(metadata); + bar.setMemory(status); + const tooltip = item.tooltip; + return { + item, + text: item.text, + tooltip: typeof tooltip === "string" ? tooltip : (tooltip?.value ?? ""), + background: item.backgroundColor?.id, + command: item.command, + }; +} + +const TOP = "coder.workspace.showTopProcesses"; + +describe("AgentStatusBar", () => { + it.each([ + { + name: "metadata with normal memory keeps today's text", + metadata: VALUES, + status: memory("normal"), + text: "$(dashboard) 0.006/4 cores (0%)", + }, + { + name: "high memory joins the metadata text", + metadata: VALUES, + status: memory("high", 92, "usage"), + text: "$(dashboard) 0.006/4 cores (0%) · $(warning) Memory 92%", + background: "statusBarItem.warningBackground", + command: TOP, + }, + { + name: "a metadata error alone is not colored", + metadata: ERROR, + status: memory("normal"), + text: "$(warning) Agent Status Unavailable", + }, + { + name: "a metadata error still shows high memory", + metadata: ERROR, + status: memory("high", 92, "usage"), + text: "$(warning) Agent Status Unavailable · $(warning) Memory 92%", + background: "statusBarItem.warningBackground", + command: TOP, + }, + { + name: "without metadata, memory is the only part", + metadata: NONE, + status: memory("normal"), + text: "$(dashboard) Memory 25%", + }, + { + name: "unreadable memory leaves the metadata as is", + metadata: VALUES, + status: memory("unavailable"), + text: "$(dashboard) 0.006/4 cores (0%)", + }, + ])("$name", ({ metadata, status, text, background, command }) => { + const view = render(metadata, status); + expect(view).toMatchObject({ text, background, command }); + expect(view.item.show).toHaveBeenCalled(); + }); + + it("hides when there is no metadata and memory cannot be read", () => { + const { item } = render(NONE, memory("unavailable")); + expect(item.hide).toHaveBeenCalled(); + expect(item.show).not.toHaveBeenCalled(); + }); + + it("puts the warning and its actions under the IDE measurement", () => { + const { tooltip } = render(VALUES, memory("high", 92, "usage")); + expect(tooltip).toBe( + [ + "**Agent metadata** ", + "CPU Usage: 0.006/4 cores \\(0%\\) ", + "RAM Usage: 1.32/16 GiB \\(8%\\)", + "", + "**Workspace usage** ", + "Memory: 14.72/16 GiB (92%)", + "", + "$(warning) **Memory is running low.** ", + "Processes may be killed soon. ", + `[$(list-flat) Top processes](command:${TOP} "Open top. Its memory summary covers the whole machine.") · [$(debug-restart) Restart](command:coder.workspace.restart "Restart the workspace")`, + ].join("\n"), + ); + }); + + it("shows a metadata error in the tooltip without a memory section", () => { + const { tooltip } = render(ERROR, memory("unavailable")); + expect(tooltip).toBe( + "**Agent metadata** \nFailed to query metadata: closed", + ); + }); + + it("shows template values as text, so they cannot add links or icons", () => { + const { tooltip } = render( + { + kind: "values", + events: [metadataEvent("Note", "[click](command:evil) $(zap)")], + }, + memory("normal"), + ); + expect(tooltip).not.toContain("[click](command:evil)"); + expect(tooltip).toContain("\\$\\(zap\\)"); + }); +}); diff --git a/test/unit/remote/workspaceStateMachine.test.ts b/test/unit/remote/workspaceStateMachine.test.ts index 06b718b138..832f235a43 100644 --- a/test/unit/remote/workspaceStateMachine.test.ts +++ b/test/unit/remote/workspaceStateMachine.test.ts @@ -235,6 +235,23 @@ describe("WorkspaceStateMachine", () => { }); } + it("waits for the start a restart queued behind its stop", async () => { + const { sm, progress } = setup("restart"); + const ws = workspaceAtBuild(2, { status: "stopped", transition: "stop" }); + + expect(await sm.processWorkspace(ws, progress)).toBe(false); + expect(await sm.processWorkspace(ws, progress)).toBe(false); + expect(startWorkspace).not.toHaveBeenCalled(); + }); + + it("starts the workspace itself when the restart's stop failed", async () => { + const { sm, progress } = setup("restart"); + const ws = workspaceAtBuild(2, { status: "failed", transition: "stop" }); + + expect(await sm.processWorkspace(ws, progress)).toBe(false); + expect(startWorkspace).toHaveBeenCalledOnce(); + }); + it("triggers update instead of start when mode is 'update'", async () => { const { sm, progress } = setup("update"); const ws = createWorkspace({ latest_build: { status: "stopped" } }); diff --git a/test/unit/webviews/workspaces/workspaceActionRunner.test.ts b/test/unit/webviews/workspaces/workspaceActionRunner.test.ts index f267a919a8..d891915a16 100644 --- a/test/unit/webviews/workspaces/workspaceActionRunner.test.ts +++ b/test/unit/webviews/workspaces/workspaceActionRunner.test.ts @@ -12,13 +12,18 @@ import { startWorkspaceViaApi, updateWorkspaceViaApi, } from "@/api/workspace"; +import { MementoManager } from "@/storage/mementoManager"; import { WorkspaceActionRunner } from "@/webviews/workspaces/workspaceActionRunner"; import { workspace } from "@repo/mocks"; import { createTestCoderApi } from "../../../mocks/coderApi"; import { createTelemetryHarness } from "../../../mocks/telemetry"; -import { createMockLogger, TestSessionStore } from "../../../mocks/testHelpers"; +import { + createMockLogger, + InMemoryMemento, + TestSessionStore, +} from "../../../mocks/testHelpers"; import type { Workspace, @@ -74,10 +79,12 @@ function setup(latest: Workspace, warningChoice?: string) { workspace: undefined as Workspace | undefined, updateWorkspace: vi.fn(() => Promise.resolve()), }; + const mementoManager = new MementoManager(new InMemoryMemento()); const runner = new WorkspaceActionRunner( createTestCoderApi({ overrides: client }), session, connected, + mementoManager, service, createMockLogger(), ); @@ -91,7 +98,15 @@ function setup(latest: Workspace, warningChoice?: string) { restart: vi.mocked(restartWorkspace).mock.calls.length, update: vi.mocked(updateWorkspaceViaApi).mock.calls.length, }); - return { runner, client, connected, session, triggered, writes }; + return { + runner, + client, + connected, + session, + mementoManager, + triggered, + writes, + }; } const NO_WRITES = { post: 0, build: 0, start: 0, restart: 0, update: 0 }; @@ -183,6 +198,49 @@ describe("WorkspaceActionRunner", () => { expect(client.getWorkspace).not.toHaveBeenCalled(); }); + it.each([ + ["v2.36.0", { on_success: { transition: "start" } }, "restart"], + ["v2.35.0", {}, "start"], + ] as const)( + "restarts the connected workspace on %s by queueing a stop, then reloading", + async (version, followUp, mode) => { + const latest = withStatus("running"); + const h = setup(latest, "Restart"); + h.connected.workspace = latest; + h.client.getBuildInfo.mockResolvedValue({ version } as never); + h.client.postWorkspaceBuild.mockResolvedValue({ + ...latest.latest_build, + transition: "stop", + }); + + await h.runner.run(latest, "restart"); + + expect(h.client.postWorkspaceBuild).toHaveBeenCalledWith(latest.id, { + transition: "stop", + ...followUp, + reason: "vscode_connection", + }); + expect(await h.mementoManager.getAndClearStartupMode()).toBe(mode); + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + "workbench.action.reloadWindow", + ); + expect(h.writes()).toEqual({ ...NO_WRITES, post: 1 }); + expect(h.triggered("restart")).toHaveLength(1); + }, + ); + + it("does not reload when the server queued something other than a stop", async () => { + const latest = withStatus("running"); + const h = setup(latest, "Restart"); + h.connected.workspace = latest; + + await expect(h.runner.run(latest, "restart")).rejects.toThrow( + "queued a start, not a stop", + ); + expect(await h.mementoManager.getAndClearStartupMode()).toBe("none"); + expect(vscode.commands.executeCommand).not.toHaveBeenCalled(); + }); + it.each([ ["starting becomes restarting during confirmation", false], ["a parameter prompt is dismissed", true],