From 1c166066a403f74ed7f5c9ea74c5b859c9f2ab70 Mon Sep 17 00:00:00 2001 From: Ehab Younes Date: Mon, 9 Nov 2026 14:35:48 +0300 Subject: [PATCH] feat(workspaces): add targeted agent diagnostics Generated by Coder Agents on behalf of @EhabY. --- CHANGELOG.md | 2 + packages/shared/src/index.ts | 1 + packages/shared/src/workspaces/api.ts | 3 + packages/shared/src/workspaces/diagnostics.ts | 13 ++ packages/shared/src/workspaces/types.ts | 8 + .../src/components/AgentActions.tsx | 49 +++++ .../workspaces/src/components/RowActions.tsx | 62 ++++++ .../src/components/WorkspaceActions.tsx | 166 ++++++--------- .../components/WorkspacesPanel.stories.tsx | 16 ++ .../src/components/WorkspacesPanel.tsx | 18 +- src/api/models.ts | 9 + src/commands.ts | 200 ++++++++++++------ src/instrumentation/EVENTS.md | 34 +-- src/instrumentation/diagnostics.ts | 1 + .../workspaces/workspacesPanelProvider.ts | 57 +++-- test/unit/commands.agentDiagnostics.test.ts | 111 ++++++++++ test/unit/commands.supportBundle.test.ts | 53 ++++- .../workspacesPanelProvider.test.ts | 52 ++++- .../shared/workspaces/diagnostics.test.ts | 25 +++ .../components/WorkspacesPanel.test.tsx | 62 +++++- 20 files changed, 716 insertions(+), 226 deletions(-) create mode 100644 packages/shared/src/workspaces/diagnostics.ts create mode 100644 packages/workspaces/src/components/AgentActions.tsx create mode 100644 packages/workspaces/src/components/RowActions.tsx create mode 100644 test/unit/commands.agentDiagnostics.test.ts create mode 100644 test/webview/shared/workspaces/diagnostics.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 131bd03122..7a971bf6d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ - SSH config `Host` patterns containing regular expression characters such as `+`, `(` or `[` are now matched literally instead of mismatching or failing. +- Ping and speed test from an agent in the sidebar now target that agent + instead of the workspace's first agent. ## [v1.18.0](https://github.com/coder/vscode-coder/releases/tag/v1.18.0) 2026-11-13 diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 711137cb6b..c708d8b8ae 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -32,4 +32,5 @@ export type { // Workspaces types and API export * from "./workspaces/types"; +export * from "./workspaces/diagnostics"; export { WorkspacesApi } from "./workspaces/api"; diff --git a/packages/shared/src/workspaces/api.ts b/packages/shared/src/workspaces/api.ts index f6219c58f4..0d8f9ab41a 100644 --- a/packages/shared/src/workspaces/api.ts +++ b/packages/shared/src/workspaces/api.ts @@ -8,6 +8,7 @@ import { defineCommand, defineNotification } from "../ipc/protocol"; import type { + AgentDiagnosticParams, OpenWorkspaceParams, SetFilterParams, ViewInDashboardParams, @@ -25,6 +26,8 @@ export const WorkspacesApi = { login: defineCommand("login"), openWorkspace: defineCommand("openWorkspace"), viewInDashboard: defineCommand("viewInDashboard"), + runAgentDiagnostic: + defineCommand("runAgentDiagnostic"), refresh: defineCommand("refresh"), setFilter: defineCommand("setFilter"), /** Watch metadata for these agents only, so idle rows cost nothing */ diff --git a/packages/shared/src/workspaces/diagnostics.ts b/packages/shared/src/workspaces/diagnostics.ts new file mode 100644 index 0000000000..3dfbfa90f8 --- /dev/null +++ b/packages/shared/src/workspaces/diagnostics.ts @@ -0,0 +1,13 @@ +import type { WorkspaceAgent } from "coder/site/src/api/typesGenerated"; + +export type AgentDiagnostic = "ping" | "speedTest" | "supportBundle"; + +export function agentDiagnostics( + agent: WorkspaceAgent, +): readonly AgentDiagnostic[] { + if (agent.status === "connected") { + return ["ping", "speedTest", "supportBundle"]; + } + // A support bundle is still useful without a connection. + return ["supportBundle"]; +} diff --git a/packages/shared/src/workspaces/types.ts b/packages/shared/src/workspaces/types.ts index 907e7248cd..b84551d460 100644 --- a/packages/shared/src/workspaces/types.ts +++ b/packages/shared/src/workspaces/types.ts @@ -4,6 +4,8 @@ import type { WorkspaceAgentMetadata, } from "coder/site/src/api/typesGenerated"; +import type { AgentDiagnostic } from "./diagnostics"; + // Re-export SDK types for convenience export type { Workspace, WorkspaceAgent, WorkspaceAgentMetadata }; @@ -67,6 +69,12 @@ export interface ViewInDashboardParams { readonly page: DashboardPage; } +export interface AgentDiagnosticParams { + readonly workspaceId: string; + readonly agentId: string; + readonly diagnostic: AgentDiagnostic; +} + export interface SetFilterParams { readonly filter: WorkspaceFilter; } diff --git a/packages/workspaces/src/components/AgentActions.tsx b/packages/workspaces/src/components/AgentActions.tsx new file mode 100644 index 0000000000..fbf62721a8 --- /dev/null +++ b/packages/workspaces/src/components/AgentActions.tsx @@ -0,0 +1,49 @@ +import { + agentDiagnostics, + type AgentDiagnostic, + type WorkspaceAgent, +} from "@repo/shared"; +import { Icon, MenuItem, type CodiconName } from "@repo/ui"; + +import { RowActions } from "./RowActions"; + +import type { WorkspaceCommands } from "./WorkspacesPanel"; + +interface MenuEntry { + readonly label: string; + readonly icon: CodiconName; +} + +const DIAGNOSTIC_ENTRIES: Readonly> = { + ping: { label: "Ping", icon: "pulse" }, + speedTest: { label: "Speed Test", icon: "dashboard" }, + supportBundle: { label: "Support Bundle", icon: "archive" }, +}; + +export function AgentActions({ + workspaceId, + agent, + api, +}: { + workspaceId: string; + agent: WorkspaceAgent; + api: WorkspaceCommands; +}) { + const target = { workspaceId, agentId: agent.id }; + return ( + + {agentDiagnostics(agent).map((diagnostic) => { + const { label, icon } = DIAGNOSTIC_ENTRIES[diagnostic]; + return ( + api.runAgentDiagnostic({ ...target, diagnostic })} + > + + {label} + + ); + })} + + ); +} diff --git a/packages/workspaces/src/components/RowActions.tsx b/packages/workspaces/src/components/RowActions.tsx new file mode 100644 index 0000000000..1e0877b36d --- /dev/null +++ b/packages/workspaces/src/components/RowActions.tsx @@ -0,0 +1,62 @@ +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuTrigger, + IconButton, +} from "@repo/ui"; + +import type { OpenWorkspaceParams } from "@repo/shared"; +import type { ReactNode } from "react"; + +import type { WorkspaceCommands } from "./WorkspacesPanel"; + +/** Open, dashboard and overflow menu buttons; `children` fill the menu. */ +export function RowActions({ + name, + target, + api, + menuDescription, + children, +}: { + name: string; + target: OpenWorkspaceParams; + api: Pick; + menuDescription?: string; + children: ReactNode; +}) { + return ( + <> + api.openWorkspace(target)} + /> + + api.viewInDashboard({ + workspaceId: target.workspaceId, + page: "workspace", + }) + } + /> + + + } + /> + + {children} + + + + ); +} diff --git a/packages/workspaces/src/components/WorkspaceActions.tsx b/packages/workspaces/src/components/WorkspaceActions.tsx index 5e3f8a106e..1704cc0023 100644 --- a/packages/workspaces/src/components/WorkspaceActions.tsx +++ b/packages/workspaces/src/components/WorkspaceActions.tsx @@ -1,117 +1,73 @@ -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuTrigger, - Icon, - IconButton, - MenuItem, - MenuSeparator, -} from "@repo/ui"; +import { Icon, MenuItem, MenuSeparator, type CodiconName } from "@repo/ui"; + +import { RowActions } from "./RowActions"; import type { Workspace } from "@repo/shared"; +import type { WorkspaceStatus } from "coder/site/src/api/typesGenerated"; import type { WorkspaceCommands } from "./WorkspacesPanel"; +type LifecycleAction = "Start" | "Stop" | "Restart" | "Retry"; + +const LIFECYCLE_ICONS: Readonly> = { + Start: "play", + Stop: "primitive-square", + Restart: "debug-restart", + Retry: "debug-restart", +}; + +function lifecycleActions(status: WorkspaceStatus): readonly LifecycleAction[] { + switch (status) { + case "running": + return ["Stop", "Restart"]; + case "stopped": + return ["Start"]; + case "failed": + case "canceled": + return ["Retry"]; + default: + return []; + } +} + export function WorkspaceActions({ - workspaceId, - name, - agentId, - status, + workspace, api, }: { - workspaceId: string; - name: string; - agentId?: string; - status?: Workspace["latest_build"]["status"]; - api: Pick; + workspace: Workspace; + api: WorkspaceCommands; }) { - const lifecycleActions = - status === "running" - ? ["Stop", "Restart"] - : status === "stopped" - ? ["Start"] - : status === "failed" || status === "canceled" - ? ["Retry"] - : []; + const workspaceId = workspace.id; + const actions = lifecycleActions(workspace.latest_build.status); return ( - <> - - api.openWorkspace({ workspaceId, ...(agentId ? { agentId } : {}) }) - } - /> - api.viewInDashboard({ workspaceId, page: "workspace" })} - /> - {!agentId && ( - - - } - /> - - {lifecycleActions.map((label) => ( - - - {label} - - ))} - {lifecycleActions.length > 0 && } - - - Share - - - api.viewInDashboard({ workspaceId, page: "settings" }) - } - > - - Settings - - - - - Ping - - - - Speed Test - - - - Support Bundle - - - - - Delete... - - - - )} - + + {actions.map((action) => ( + + + {action} + + ))} + {actions.length > 0 && } + + + Share + + api.viewInDashboard({ workspaceId, page: "settings" })} + > + + Settings + + + + + Delete... + + ); } diff --git a/packages/workspaces/src/components/WorkspacesPanel.stories.tsx b/packages/workspaces/src/components/WorkspacesPanel.stories.tsx index 2afd7f690c..ee4fe89cd9 100644 --- a/packages/workspaces/src/components/WorkspacesPanel.stories.tsx +++ b/packages/workspaces/src/components/WorkspacesPanel.stories.tsx @@ -161,6 +161,7 @@ const api = { login: fn(), openWorkspace: fn(), viewInDashboard: fn(), + runAgentDiagnostic: fn(), refresh: fn(), setFilter: fn(), watchAgents: fn(), @@ -222,6 +223,21 @@ export const MenuOpen: Story = { }, }; +export const AgentMenuOpen: Story = { + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await userEvent.click( + canvas.getByRole("treeitem", { name: "frontend alice" }), + ); + // Row actions stay hidden until the row is focused, selected or hovered. + await userEvent.keyboard("{ArrowDown}"); + await userEvent.click( + await canvas.findByRole("button", { name: "More actions for main" }), + ); + await screen.findByRole("menuitem", { name: "Ping" }); + }, +}; + export const FilterOpen: Story = { play: async ({ canvasElement }) => { await userEvent.click( diff --git a/packages/workspaces/src/components/WorkspacesPanel.tsx b/packages/workspaces/src/components/WorkspacesPanel.tsx index 7ba23a60f3..7dcd3a89de 100644 --- a/packages/workspaces/src/components/WorkspacesPanel.tsx +++ b/packages/workspaces/src/components/WorkspacesPanel.tsx @@ -19,6 +19,7 @@ import { import { format, formatISO } from "date-fns"; import { useEffect, useEffectEvent, useState } from "react"; +import { AgentActions } from "./AgentActions"; import { AgentHover, AgentRow, @@ -37,6 +38,7 @@ export type WorkspaceCommands = Pick< | "login" | "openWorkspace" | "viewInDashboard" + | "runAgentDiagnostic" | "refresh" | "setFilter" | "watchAgents" @@ -86,12 +88,7 @@ export function WorkspacesPanel({ tooltip: , label: , action: ( - + ), children: [ ...appStatusNodes(agent), @@ -127,14 +124,7 @@ export function WorkspacesPanel({ hasAgentChat={hasAgentChat} /> ), - action: ( - - ), + action: , children: children.length ? children : [{ id: `agents:${workspace.id}`, label: "No workspace agents" }], diff --git a/src/api/models.ts b/src/api/models.ts index f95634d228..c6482f9571 100644 --- a/src/api/models.ts +++ b/src/api/models.ts @@ -55,3 +55,12 @@ export function extractAgents( return acc.concat(resource.agents ?? []); }, [] as WorkspaceAgent[]); } + +export function findAgent( + workspace: Workspace, + agentId: string, +): WorkspaceAgent | undefined { + return extractAgents(workspace.latest_build.resources).find( + (agent) => agent.id === agentId, + ); +} diff --git a/src/commands.ts b/src/commands.ts index d265a8f713..f6306b1bfc 100644 --- a/src/commands.ts +++ b/src/commands.ts @@ -4,8 +4,15 @@ import * as path from "node:path"; import * as semver from "semver"; import * as vscode from "vscode"; +import { + agentDiagnostics, + type AgentDiagnostic, + type DashboardPage, +} from "@repo/shared"; + import { extractAgents, + findAgent, createWorkspaceIdentifier, workspaceStatusLabel, } from "./api/models"; @@ -13,6 +20,7 @@ import * as cliExec from "./cli/cliExec"; import { runDiagnosticCli } from "./command/diagnosticFlow"; import { escapeNotificationLinks } from "./common/strings"; import { openInBrowser, toSafeHost } from "./common/url"; +import { validateAgentName } from "./common/validation"; import { raceWithAbort } from "./error/abort"; import { CertificateError } from "./error/certificateError"; import { toError } from "./error/normalize"; @@ -77,8 +85,6 @@ import type { WorkspaceAgent, } from "coder/site/src/api/typesGenerated"; -import type { DashboardPage } from "@repo/shared"; - import type { CoderApi } from "./api/coderApi"; import type { CliManager } from "./cli/cliManager"; import type { ServiceContainer } from "./container"; @@ -122,6 +128,12 @@ interface LoginArgs { readonly autoLogin?: boolean; } +/** A workspace, and optionally the agent within it, that a command acts on. */ +interface WorkspaceTarget { + readonly workspace: Workspace; + readonly agent?: WorkspaceAgent; +} + type WorkspaceResolution = | { readonly status: "selected"; @@ -132,22 +144,39 @@ type WorkspaceResolution = readonly remoteAuthority?: string; } | { readonly status: "cancelled" } + /** The target changed and can no longer run this. */ + | { readonly status: "unavailable" } | { readonly status: "failed"; readonly category: WorkspacePickerErrorCategory; }; +type SelectedWorkspace = Extract; + type OpenWorkspaceResult = | { readonly status: "opened"; readonly handoff: "folder" | "empty_window" } | { readonly status: "cancelled"; readonly stage: "recent_folder_picker" }; const UPDATE_AND_RESTART_ACTION = "Update and Restart"; +const DIAGNOSTIC_VERBS: Readonly> = { + ping: "ping", + speedTest: "run a speed test on", + supportBundle: "create a support bundle for", +}; + const openDefaults = { openRecent: false, useDefaultDirectory: true, } as const satisfies Partial; +/** `owner/name.agent` for CLI commands that target one agent. */ +function toAgentIdentifier(resolved: SelectedWorkspace): string { + return resolved.agentName + ? `${resolved.workspaceId}.${validateAgentName(resolved.agentName)}` + : resolved.workspaceId; +} + export class Commands { private readonly logger: Logger; private readonly pathResolver: PathResolver; @@ -296,27 +325,27 @@ export class Commands { * Run a speed test against a workspace and display the results in a new * editor document. Can be triggered from the sidebar or command palette. */ - public async speedTest(item?: OpenableTreeItem): Promise { + public async speedTest(target?: WorkspaceTarget): Promise { await this.diagnosticTelemetry.trace("speed_test", (telemetry) => - this.runSpeedTest(item, telemetry), + this.runSpeedTest(target, telemetry), ); } private async runSpeedTest( - item: OpenableTreeItem | undefined, + target: WorkspaceTarget | undefined, telemetry: DiagnosticTrace, ): Promise { - const resolved = await this.resolveClientAndWorkspace(item); - if (resolved.status === "cancelled") { - telemetry.abort("workspace_picker"); - return; - } - if (resolved.status === "failed") { - telemetry.error(resolved.category); + const resolved = await this.resolveDiagnosticWorkspace( + target, + "speedTest", + telemetry, + ); + if (!resolved) { return; } - const { client, workspaceId } = resolved; + const { client } = resolved; + const agentId = toAgentIdentifier(resolved); const input = await vscode.window.showInputBox({ title: "Speed Test Duration", @@ -341,7 +370,7 @@ export class Commands { telemetry, logger: this.logger, name: "Speed test", - progressTitle: `Running speed test for ${workspaceId}`, + progressTitle: `Running speed test for ${agentId}`, exec: async ({ signal, progress }) => { progress.report({ message: "Connecting..." }); const env = await this.resolveCliEnv(client); @@ -355,12 +384,7 @@ export class Commands { : `${Math.floor(elapsedMs / 1000)}s / ${seconds}s`, }); try { - return await cliExec.speedtest( - env, - workspaceId, - `${seconds}s`, - signal, - ); + return await cliExec.speedtest(env, agentId, `${seconds}s`, signal); } finally { stopProgress(); } @@ -370,7 +394,7 @@ export class Commands { this.speedtestPanelFactory.show({ result: parsed, rawJson, - workspaceId, + workspaceId: agentId, }); // Record success after the panel shows, so a display failure is an // error rather than a contradictory success span. @@ -426,23 +450,22 @@ export class Commands { }); } - public async supportBundle(item?: OpenableTreeItem): Promise { + public async supportBundle(target?: WorkspaceTarget): Promise { await this.diagnosticTelemetry.trace("support_bundle", (telemetry) => - this.runSupportBundle(item, telemetry), + this.runSupportBundle(target, telemetry), ); } private async runSupportBundle( - item: OpenableTreeItem | undefined, + target: WorkspaceTarget | undefined, telemetry: DiagnosticTrace, ): Promise { - const resolved = await this.resolveClientAndWorkspace(item); - if (resolved.status === "cancelled") { - telemetry.abort("workspace_picker"); - return; - } - if (resolved.status === "failed") { - telemetry.error(resolved.category); + const resolved = await this.resolveDiagnosticWorkspace( + target, + "supportBundle", + telemetry, + ); + if (!resolved) { return; } @@ -1359,49 +1382,60 @@ export class Commands { await vscode.commands.executeCommand("workbench.action.reloadWindow"); } - public async pingWorkspace(item?: OpenableTreeItem): Promise { - const resolved = await this.resolveClientAndWorkspace(item); + public async pingWorkspace(target?: WorkspaceTarget): Promise { + const resolved = await this.resolveClientAndWorkspace(target, "ping"); if (resolved.status !== "selected") { return; } - const { client, workspaceId } = resolved; + const { client } = resolved; + const agentId = toAgentIdentifier(resolved); return withProgress( { location: vscode.ProgressLocation.Notification, - title: `Starting ping for ${workspaceId}...`, + title: `Starting ping for ${agentId}...`, }, async (progress) => { progress.report({ message: "Resolving CLI..." }); const env = await this.resolveCliEnv(client); progress.report({ message: "Starting..." }); - cliExec.ping(env, workspaceId); + cliExec.ping(env, agentId); }, ); } + /** Like `resolveClientAndWorkspace`, recording why nothing was selected. */ + private async resolveDiagnosticWorkspace( + target: WorkspaceTarget | undefined, + diagnostic: AgentDiagnostic, + telemetry: DiagnosticTrace, + ): Promise { + const resolved = await this.resolveClientAndWorkspace(target, diagnostic); + switch (resolved.status) { + case "selected": + return resolved; + case "cancelled": + telemetry.abort("workspace_picker"); + return undefined; + case "unavailable": + telemetry.abort("unavailable"); + return undefined; + case "failed": + telemetry.error(resolved.category); + return undefined; + } + } + /** - * Resolve the API client and workspace identifier from a sidebar item, + * Resolve the API client and workspace identifier from a target, * the currently connected workspace, or by prompting the user to pick one. - * Returns cancelled/failed if the user cancels the picker or the picker cannot load. */ private async resolveClientAndWorkspace( - item?: OpenableTreeItem, + target: WorkspaceTarget | undefined, + diagnostic: AgentDiagnostic, ): Promise { - if (item) { - const agentName = - item instanceof AgentTreeItem ? item.agent.name : undefined; - return { - status: "selected", - agentName, - client: this.extensionClient, - workspaceId: createWorkspaceIdentifier(item.workspace), - remoteAuthority: await this.toWorkspaceAuthority( - this.extensionClient, - item.workspace, - agentName, - ), - }; + if (target) { + return this.resolveTarget(target, diagnostic); } if (this.workspace && this.remoteWorkspaceClient) { return { @@ -1418,18 +1452,56 @@ export class Commands { placeholder: "Search running workspaces...", filter: (w) => w.latest_build.status === "running", }); - if (pick.status === "selected") { - return { - status: "selected", - client: this.extensionClient, - workspaceId: createWorkspaceIdentifier(pick.workspace), - remoteAuthority: await this.toWorkspaceAuthority( - this.extensionClient, - pick.workspace, - ), - }; + if (pick.status !== "selected") { + return pick; } - return pick; + return this.selectWorkspace(pick.workspace); + } + + /** Re-read the target, since the caller's copy may be stale. */ + private async resolveTarget( + target: WorkspaceTarget, + diagnostic: AgentDiagnostic, + ): Promise { + const workspace = await this.extensionClient.getWorkspace( + target.workspace.id, + ); + if (!target.agent) { + return this.selectWorkspace(workspace); + } + + const workspaceId = createWorkspaceIdentifier(workspace); + const agent = findAgent(workspace, target.agent.id); + if (!agent) { + void vscode.window.showInformationMessage( + `${workspaceId}'s selected agent is no longer available. Refresh and try again.`, + ); + return { status: "unavailable" }; + } + if (!agentDiagnostics(agent).includes(diagnostic)) { + void vscode.window.showInformationMessage( + `Cannot ${DIAGNOSTIC_VERBS[diagnostic]} ${workspaceId}.${agent.name} while it is ${agent.status}.`, + ); + return { status: "unavailable" }; + } + return this.selectWorkspace(workspace, agent.name); + } + + private async selectWorkspace( + workspace: Workspace, + agentName?: string, + ): Promise { + return { + status: "selected", + agentName, + client: this.extensionClient, + workspaceId: createWorkspaceIdentifier(workspace), + remoteAuthority: await this.toWorkspaceAuthority( + this.extensionClient, + workspace, + agentName, + ), + }; } /** diff --git a/src/instrumentation/EVENTS.md b/src/instrumentation/EVENTS.md index 606a4a1d32..e70b87428c 100644 --- a/src/instrumentation/EVENTS.md +++ b/src/instrumentation/EVENTS.md @@ -289,20 +289,20 @@ Emitted by `CommandManager` around every registered `coder.*` command. Emitted by `DiagnosticTelemetry` around each diagnostic command. -| Attribute | Values | -| ------------------------------------------ | ---------------------------------------------------------------- | -| `command` | `speed_test`, `netcheck`, `support_bundle`, `export_telemetry` | -| `abort_stage` | `workspace_picker`, `input`, `prompt`, `save_dialog`, `progress` | -| `error.type` | `fetch_error`, `parse_error`, `error` | -| `format` | `json`, `otlp` (telemetry export only) | -| `severity` | `ok`, `warning`, `error` (netcheck only) | -| `requested_duration_seconds` (measurement) | speed test only | -| `interval.count` (measurement) | speed test only | -| `throughput_mbits` (measurement) | speed test only | -| `region.count` (measurement) | netcheck only; DERP regions in the report | -| `warning.count` (measurement) | netcheck only; warnings across report sections | -| `event.count` (measurement) | telemetry export only | -| `file.skipped_count` (measurement) | telemetry export only; unreadable files skipped, omitted at zero | +| Attribute | Values | +| ------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------- | +| `command` | `speed_test`, `netcheck`, `support_bundle`, `export_telemetry` | +| `abort_stage` | `workspace_picker`, `unavailable` (the agent changed since it was listed), `input`, `prompt`, `save_dialog`, `progress` | +| `error.type` | `fetch_error`, `parse_error`, `error` | +| `format` | `json`, `otlp` (telemetry export only) | +| `severity` | `ok`, `warning`, `error` (netcheck only) | +| `requested_duration_seconds` (measurement) | speed test only | +| `interval.count` (measurement) | speed test only | +| `throughput_mbits` (measurement) | speed test only | +| `region.count` (measurement) | netcheck only; DERP regions in the report | +| `warning.count` (measurement) | netcheck only; warnings across report sections | +| `event.count` (measurement) | telemetry export only | +| `file.skipped_count` (measurement) | telemetry export only; unreadable files skipped, omitted at zero | ## Deployment @@ -334,9 +334,9 @@ No attributes. Emitted by `RemoteSetupTelemetry` around connecting to a remote workspace. -| Attribute | Values | -| --------- | -------------------------------------------------------------------- | -| `outcome` | `workspace_not_found` (non-throwing early exit; the span is aborted) | +| Attribute | Values | +| --------- | -------------------------------------------------------------------------------------------- | +| `outcome` | `workspace_not_found`, `incompatible_server` (non-throwing early exits; the span is aborted) | Phases (`remote.setup.`): `cli_resolve`, `compatibility_check`, `cli_configure`, `workspace_lookup`, `workspace_monitor_setup`, diff --git a/src/instrumentation/diagnostics.ts b/src/instrumentation/diagnostics.ts index be754bba32..c2c6111b45 100644 --- a/src/instrumentation/diagnostics.ts +++ b/src/instrumentation/diagnostics.ts @@ -24,6 +24,7 @@ export type DiagnosticErrorCategory = | "error"; export type DiagnosticAbortStage = | "workspace_picker" + | "unavailable" | "input" | "prompt" | "save_dialog" diff --git a/src/webviews/workspaces/workspacesPanelProvider.ts b/src/webviews/workspaces/workspacesPanelProvider.ts index 8112a5f5b6..a9b0d8d3d5 100644 --- a/src/webviews/workspaces/workspacesPanelProvider.ts +++ b/src/webviews/workspaces/workspacesPanelProvider.ts @@ -3,10 +3,11 @@ import * as vscode from "vscode"; import { buildCommandHandlers, WorkspacesApi, + type AgentDiagnosticParams, type OpenWorkspaceParams, } from "@repo/shared"; -import { extractAgents } from "../../api/models"; +import { findAgent } from "../../api/models"; import { dispatchWebviewMessage, notifyWebview, @@ -14,7 +15,10 @@ import { } from "../dispatch"; import { getWebviewHtml } from "../html"; -import type { Workspace } from "coder/site/src/api/typesGenerated"; +import type { + Workspace, + WorkspaceAgent, +} from "coder/site/src/api/typesGenerated"; import type { Commands } from "../../commands"; import type { Logger } from "../../logging/logger"; @@ -25,8 +29,27 @@ import type { WorkspaceStore } from "./workspaceStore"; const USER_ACTION_METHODS: ReadonlySet = new Set([ WorkspacesApi.openWorkspace.method, WorkspacesApi.viewInDashboard.method, + WorkspacesApi.runAgentDiagnostic.method, ]); +type PanelCommands = Pick< + Commands, + | "login" + | "openWorkspaceFromSidebar" + | "openWorkspaceInDashboard" + | "pingWorkspace" + | "speedTest" + | "supportBundle" +>; + +function requireAgent(workspace: Workspace, agentId: string): WorkspaceAgent { + const agent = findAgent(workspace, agentId); + if (!agent) { + throw new Error("Agent is no longer available"); + } + return agent; +} + /** * Renders the workspaces of the current deployment in a webview. All state * lives in the store: every change is pushed whole, and a webview that just @@ -55,6 +78,7 @@ export class WorkspacesPanelProvider this.requireWorkspace(p.workspaceId), p.page, ), + runAgentDiagnostic: (p) => this.runAgentDiagnostic(p), }), }; @@ -64,10 +88,7 @@ export class WorkspacesPanelProvider constructor( private readonly extensionUri: vscode.Uri, private readonly store: WorkspaceStore, - private readonly commands: Pick< - Commands, - "login" | "openWorkspaceFromSidebar" | "openWorkspaceInDashboard" - >, + private readonly commands: PanelCommands, private readonly logger: Logger, ) {} @@ -151,15 +172,27 @@ export class WorkspacesPanelProvider agentId, }: OpenWorkspaceParams): Promise { const workspace = this.requireWorkspace(workspaceId); - const agent = extractAgents(workspace.latest_build.resources).find( - (candidate) => candidate.id === agentId, - ); - if (agentId && !agent) { - throw new Error("Agent is no longer available"); - } + const agent = agentId ? requireAgent(workspace, agentId) : undefined; await this.commands.openWorkspaceFromSidebar(workspace, agent); } + private async runAgentDiagnostic({ + workspaceId, + agentId, + diagnostic, + }: AgentDiagnosticParams): Promise { + const workspace = this.requireWorkspace(workspaceId); + const agent = requireAgent(workspace, agentId); + switch (diagnostic) { + case "ping": + return this.commands.pingWorkspace({ workspace, agent }); + case "speedTest": + return this.commands.speedTest({ workspace, agent }); + case "supportBundle": + return this.commands.supportBundle({ workspace, agent }); + } + } + private requireWorkspace(workspaceId: string): Workspace { const workspace = this.store.findWorkspace(workspaceId); if (!workspace) { diff --git a/test/unit/commands.agentDiagnostics.test.ts b/test/unit/commands.agentDiagnostics.test.ts new file mode 100644 index 0000000000..8e8017c7d0 --- /dev/null +++ b/test/unit/commands.agentDiagnostics.test.ts @@ -0,0 +1,111 @@ +import { describe, expect, it, vi } from "vitest"; +import * as vscode from "vscode"; + +import * as cliExec from "@/cli/cliExec"; + +import { agent, workspace } from "@repo/mocks"; + +import { createTestCommands } from "../mocks/commands"; +import { + MockConfigurationProvider, + MockProgressReporter, +} from "../mocks/testHelpers"; + +import type { Workspace } from "coder/site/src/api/typesGenerated"; + +vi.mock("@/cli/cliExec", async (importOriginal) => ({ + ...(await importOriginal()), + version: vi.fn(), + ping: vi.fn(), + speedtest: vi.fn(), +})); + +const NAME = "testuser/test-workspace"; +const listed = agent({ id: "agent-main", name: "main" }); + +/** Commands whose deployment re-reads the workspace as `latest`. */ +function setup(latest: Workspace) { + vi.clearAllMocks(); + new MockConfigurationProvider(); + new MockProgressReporter(); + vi.mocked(cliExec.version).mockResolvedValue("v2.36.0"); + vi.mocked(cliExec.speedtest).mockResolvedValue( + JSON.stringify({ + overall: { + start_time_seconds: 0, + end_time_seconds: 5, + throughput_mbits: 42, + }, + intervals: [], + }), + ); + vi.mocked(vscode.window.showInputBox).mockResolvedValue("5"); + return createTestCommands({ + baseUrl: "https://coder.test", + client: { getWorkspace: vi.fn(() => Promise.resolve(latest)) }, + services: { + getCliManager: { + locateBinary: vi.fn(() => Promise.resolve("/bin/coder")), + configure: vi.fn(() => Promise.resolve()), + }, + getPathResolver: { getGlobalConfigDir: () => "/cfg" }, + getSpeedtestPanelFactory: { show: vi.fn() }, + }, + }); +} + +describe("agent diagnostics", () => { + it("pings the agent by its current name", async () => { + const latest = workspace({ agents: [{ ...listed, name: "renamed" }] }); + + await setup(latest).pingWorkspace({ workspace: latest, agent: listed }); + + expect(cliExec.ping).toHaveBeenCalledWith( + expect.anything(), + `${NAME}.renamed`, + ); + }); + + it("runs a speed test on the agent", async () => { + const latest = workspace({ agents: [listed] }); + + await setup(latest).speedTest({ workspace: latest, agent: listed }); + + expect(cliExec.speedtest).toHaveBeenCalledWith( + expect.anything(), + `${NAME}.main`, + "5s", + expect.anything(), + ); + }); + + it.each([ + { method: "pingWorkspace", verb: "ping" }, + { method: "speedTest", verb: "run a speed test on" }, + ] as const)( + "refuses $method on a disconnected agent", + async ({ method, verb }) => { + const latest = workspace({ + agents: [{ ...listed, status: "disconnected" }], + }); + + await setup(latest)[method]({ workspace: latest, agent: listed }); + + expect(vscode.window.showInformationMessage).toHaveBeenCalledWith( + `Cannot ${verb} ${NAME}.main while it is disconnected.`, + ); + expect(cliExec.ping).not.toHaveBeenCalled(); + expect(cliExec.speedtest).not.toHaveBeenCalled(); + }, + ); + + it("does not ping an agent whose name the CLI cannot address", async () => { + const latest = workspace({ agents: [{ ...listed, name: "main.other" }] }); + + await expect( + setup(latest).pingWorkspace({ workspace: latest, agent: listed }), + ).rejects.toThrow("Cannot use this agent name"); + + expect(cliExec.ping).not.toHaveBeenCalled(); + }); +}); diff --git a/test/unit/commands.supportBundle.test.ts b/test/unit/commands.supportBundle.test.ts index c1dc387e16..903749a22d 100644 --- a/test/unit/commands.supportBundle.test.ts +++ b/test/unit/commands.supportBundle.test.ts @@ -54,7 +54,14 @@ const TEST_WORKSPACE = workspace({ name: "ws", latest_build: { status: "running", - resources: [resource({ agents: [agent({ name: "main" })] })], + resources: [ + resource({ + agents: [ + agent({ id: "agent-main", name: "main" }), + agent({ id: "agent-dev", name: "dev" }), + ], + }), + ], }, }); @@ -63,7 +70,7 @@ function setup(options: { cliVersion?: string } = {}) { new MockProgressReporter(); config({}); setRemoteAuthority(undefined); - const { service } = createTelemetryHarness(); + const { sink, service } = createTelemetryHarness(); vi.mocked(vscode.window.showSaveDialog).mockResolvedValue( vscode.Uri.file(OUTPUT_PATH), @@ -104,6 +111,7 @@ function setup(options: { cliVersion?: string } = {}) { const client = createTestCoderApi({ baseUrl: "https://coder.test", token: "token", + overrides: { getWorkspace: vi.fn(() => Promise.resolve(TEST_WORKSPACE)) }, }); const commands = new Commands( @@ -112,7 +120,7 @@ function setup(options: { cliVersion?: string } = {}) { {} as DeploymentManager, ); - return { commands, client, logger, interaction }; + return { commands, client, logger, interaction, sink }; } function setRemoteAuthority(value: string | undefined): void { @@ -120,7 +128,10 @@ function setRemoteAuthority(value: string | undefined): void { } function agentItem(agentName: string): AgentTreeItem { - return new AgentTreeItem(agent({ name: agentName }), TEST_WORKSPACE); + return new AgentTreeItem( + agent({ id: `agent-${agentName}`, name: agentName }), + TEST_WORKSPACE, + ); } function connectToWorkspace( @@ -168,6 +179,40 @@ describe("Commands.supportBundle", () => { ); }); + it("skips an agent the workspace no longer has", async () => { + const { commands, sink } = setup(); + + await commands.supportBundle(agentItem("gone")); + + expect(vscode.window.showInformationMessage).toHaveBeenCalledWith( + "owner/ws's selected agent is no longer available. Refresh and try again.", + ); + expect(cliExec.supportBundle).not.toHaveBeenCalled(); + expect( + sink.eventsNamed("command.diagnostic.completed")[0].properties, + ).toMatchObject({ abort_stage: "unavailable", result: "aborted" }); + }); + + it("collects from an agent that is no longer connected", async () => { + const { commands, client } = setup(); + vi.mocked(client.getWorkspace).mockResolvedValueOnce( + workspace({ + ...TEST_WORKSPACE, + agents: [ + agent({ id: "agent-dev", name: "dev", status: "disconnected" }), + ], + }), + ); + + await commands.supportBundle(agentItem("dev")); + + expect(cliExec.supportBundle).toHaveBeenCalledWith( + expect.anything(), + "owner/ws", + expect.objectContaining({ agentName: "dev" }), + ); + }); + it("prefers the selected item over the active connection", async () => { const { commands, client } = setup(); connectToWorkspace( diff --git a/test/unit/webviews/workspaces/workspacesPanelProvider.test.ts b/test/unit/webviews/workspaces/workspacesPanelProvider.test.ts index 408be11d7d..958af0123d 100644 --- a/test/unit/webviews/workspaces/workspacesPanelProvider.test.ts +++ b/test/unit/webviews/workspaces/workspacesPanelProvider.test.ts @@ -13,6 +13,7 @@ import { } from "@repo/mocks"; import { WorkspacesApi, + type AgentDiagnostic, type CommandDef, type OpenWorkspaceParams, type WorkspacesState, @@ -30,8 +31,6 @@ import { import type { Workspace } from "coder/site/src/api/typesGenerated"; -import type { Commands } from "@/commands"; - const alice = () => workspace({ id: "workspace-1", @@ -60,10 +59,10 @@ function setup() { login: vi.fn(() => Promise.resolve()), openWorkspaceFromSidebar: vi.fn(() => Promise.resolve()), openWorkspaceInDashboard: vi.fn(() => Promise.resolve()), - } satisfies Pick< - Commands, - "login" | "openWorkspaceFromSidebar" | "openWorkspaceInDashboard" - >; + pingWorkspace: vi.fn(() => Promise.resolve()), + speedTest: vi.fn(() => Promise.resolve()), + supportBundle: vi.fn(() => Promise.resolve()), + } satisfies ConstructorParameters[2]; const provider = new WorkspacesPanelProvider( vscode.Uri.file("/test"), store, @@ -280,6 +279,47 @@ describe("WorkspacesPanelProvider", () => { ); }); + interface DiagnosticCase { + diagnostic: AgentDiagnostic; + command: "pingWorkspace" | "speedTest" | "supportBundle"; + } + + it.each([ + { diagnostic: "ping", command: "pingWorkspace" }, + { diagnostic: "speedTest", command: "speedTest" }, + { diagnostic: "supportBundle", command: "supportBundle" }, + ])("runs $diagnostic on the agent", async ({ diagnostic, command }) => { + const h = await shown([alice()]); + await h.send(WorkspacesApi.runAgentDiagnostic, { + workspaceId: "workspace-1", + agentId: "agent-1", + diagnostic, + }); + expect(h.commands[command]).toHaveBeenCalledWith({ + workspace: expect.objectContaining({ id: "workspace-1" }), + agent: expect.objectContaining({ name: "main" }), + }); + }); + + it("refuses a diagnostic on an agent of another workspace", async () => { + const bob = workspace({ + id: "workspace-2", + name: "other", + owner_name: "bob", + agents: [agent({ id: "agent-2", name: "main" })], + }); + const h = await shown([alice(), bob]); + await h.send(WorkspacesApi.runAgentDiagnostic, { + workspaceId: "workspace-1", + agentId: "agent-2", + diagnostic: "ping", + }); + expect(h.commands.pingWorkspace).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( + "Agent is no longer available", + ); + }); + interface FailedOpenCase { name: string; params: OpenWorkspaceParams; diff --git a/test/webview/shared/workspaces/diagnostics.test.ts b/test/webview/shared/workspaces/diagnostics.test.ts new file mode 100644 index 0000000000..825b10f149 --- /dev/null +++ b/test/webview/shared/workspaces/diagnostics.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from "vitest"; + +import { agent } from "@repo/mocks"; +import { agentDiagnostics, type AgentDiagnostic } from "@repo/shared"; + +import type { WorkspaceAgentStatus } from "coder/site/src/api/typesGenerated"; + +interface DiagnosticsCase { + status: WorkspaceAgentStatus; + diagnostics: AgentDiagnostic[]; +} + +describe("agentDiagnostics", () => { + it.each([ + { + status: "connected", + diagnostics: ["ping", "speedTest", "supportBundle"], + }, + { status: "connecting", diagnostics: ["supportBundle"] }, + { status: "disconnected", diagnostics: ["supportBundle"] }, + { status: "timeout", diagnostics: ["supportBundle"] }, + ])("offers $diagnostics while $status", ({ status, diagnostics }) => { + expect(agentDiagnostics(agent({ status }))).toEqual(diagnostics); + }); +}); diff --git a/test/webview/workspaces/components/WorkspacesPanel.test.tsx b/test/webview/workspaces/components/WorkspacesPanel.test.tsx index 3cd42ee51a..8cb3f21a42 100644 --- a/test/webview/workspaces/components/WorkspacesPanel.test.tsx +++ b/test/webview/workspaces/components/WorkspacesPanel.test.tsx @@ -4,7 +4,11 @@ import { format, formatISO } from "date-fns"; import { describe, expect, it, onTestFinished, vi } from "vitest"; import { agent, agentMetadata, app, appStatus, workspace } from "@repo/mocks"; -import { WorkspacesApi, type WorkspacesState } from "@repo/shared"; +import { + WorkspacesApi, + type AgentDiagnostic, + type WorkspacesState, +} from "@repo/shared"; import App from "@repo/workspaces/App"; import { @@ -14,6 +18,8 @@ import { } from "../../ui/components/Tree/treeTestHelpers"; import { captureSent, pushState } from "../ipc"; +import type { WorkspaceAgentStatus } from "coder/site/src/api/typesGenerated"; + const ALPHA = workspace({ id: "ws-alpha", name: "alpha", @@ -172,9 +178,6 @@ describe("WorkspacesPanel", () => { await user.click( screen.getByRole("button", { name: "Open dev in VS Code" }), ); - expect( - screen.queryByRole("button", { name: "More actions for dev" }), - ).not.toBeInTheDocument(); expect(drain(WorkspacesApi.openWorkspace.method)).toEqual([ { workspaceId: "ws-alpha" }, @@ -224,6 +227,57 @@ describe("WorkspacesPanel", () => { }, ); + interface DiagnosticMenuCase { + status: WorkspaceAgentStatus; + items: string[]; + item: string; + diagnostic: AgentDiagnostic; + } + + it.each([ + { + status: "connected", + items: ["Ping", "Speed Test", "Support Bundle"], + item: "Ping", + diagnostic: "ping", + }, + { + status: "disconnected", + items: ["Support Bundle"], + item: "Support Bundle", + diagnostic: "supportBundle", + }, + ])( + "runs diagnostics a $status agent allows from its menu", + async ({ status, items, item, diagnostic }) => { + const { user, drain } = await setup({ + ...STATE, + workspaces: [ + workspace({ + id: "ws-alpha", + name: "alpha", + agents: [agent({ id: "agent-main", name: "main", status })], + }), + ], + }); + await user.click(row("alpha")); + await user.click( + screen.getByRole("button", { name: "More actions for main" }), + ); + const menu = await screen.findByRole("menu"); + expect( + within(menu) + .getAllByRole("menuitem") + .map((menuItem) => menuItem.textContent), + ).toEqual(items); + + await user.click(within(menu).getByRole("menuitem", { name: item })); + expect(drain(WorkspacesApi.runAgentDiagnostic.method)).toEqual([ + { workspaceId: "ws-alpha", agentId: "agent-main", diagnostic }, + ]); + }, + ); + it("describes workspaces, workspace agents and metadata on hover", async () => { stubElementBoxes(); vi.useFakeTimers({ toFake: ["Date"] });