Skip to content

Commit 21d7f97

Browse files
authored
feat(workspaces): add workspace lifecycle actions behind the panel IPC (#1168)
Add Start, Stop, Restart, Update, Delete, and Share for workspaces listed in the Workspaces panel. Actions run over the REST API without the CLI, and each one aborts when the session changes. - Queue every build through one helper that streams logs to the Coder output, warns when no provisioner is available, and waits for the build to settle. - Poll builds by ID so that Delete reports success instead of failing on the by-name 404. Retry up to 3 network or 5xx failures in a row. - Match `coder start` for Start: activate dormant workspaces, clean up failed starts, and use the active version when the template requires it. - Restart on the build's template version, and refuse to start if another build replaced the stop. - Ask for any parameters the new template version adds during Update, and refuse if the workspace or template version changed in the meantime. - Track pending actions per workspace so that actions on different workspaces run in parallel, and re-read only that workspace when an action ends.
1 parent dd9dc38 commit 21d7f97

37 files changed

Lines changed: 1974 additions & 216 deletions

‎CHANGELOG.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@
1515
instead of the workspace's first agent.
1616
- Deep links that specify a query parameter more than once now show an error
1717
instead of silently using the first value.
18+
- If the workspace starts, stops, or gets a newer template version while you're
19+
entering parameters for an update, the update is now skipped and the
20+
workspace starts on its current version, the same as dismissing the prompt.
1821

1922
## [v1.18.0](https://github.com/coder/vscode-coder/releases/tag/v1.18.0) 2026-11-13
2023

‎packages/shared/src/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,4 +33,5 @@ export type {
3333
// Workspaces types and API
3434
export * from "./workspaces/types";
3535
export * from "./workspaces/diagnostics";
36+
export * from "./workspaces/actions";
3637
export { WorkspacesApi } from "./workspaces/api";
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import type {
2+
Workspace,
3+
WorkspaceStatus,
4+
} from "coder/site/src/api/typesGenerated";
5+
6+
export type WorkspaceAction =
7+
| "start"
8+
| "stop"
9+
| "restart"
10+
| "update"
11+
| "delete";
12+
13+
/** Builds in flight, or a workspace that is gone, allow no action. */
14+
const INACTIVE_STATUSES: ReadonlySet<WorkspaceStatus> = new Set([
15+
"pending",
16+
"starting",
17+
"stopping",
18+
"canceling",
19+
"deleting",
20+
"deleted",
21+
]);
22+
23+
/** Actions allowed now, in display order, as in the dashboard's `abilitiesByWorkspaceStatus`. */
24+
export function workspaceActions(
25+
workspace: Workspace,
26+
): readonly WorkspaceAction[] {
27+
if (INACTIVE_STATUSES.has(workspace.latest_build.status)) {
28+
return [];
29+
}
30+
// `coder start` reactivates a dormant workspace before starting it.
31+
if (workspace.dormant_at) {
32+
return ["start", "delete"];
33+
}
34+
if (workspace.latest_build.has_external_agent) {
35+
return ["delete"];
36+
}
37+
const { status, transition } = workspace.latest_build;
38+
// A policy that forces the active version leaves only an update.
39+
const updateOnly =
40+
workspace.outdated &&
41+
(workspace.template_require_active_version ||
42+
workspace.automatic_updates === "always");
43+
const actions: WorkspaceAction[] = workspace.outdated ? ["update"] : [];
44+
if (status === "running") {
45+
actions.push("stop");
46+
if (!updateOnly) {
47+
actions.push("restart");
48+
}
49+
} else if (status === "stopped" && !updateOnly) {
50+
actions.push("start");
51+
} else if (status === "canceled") {
52+
actions.push("start", "stop");
53+
} else if (
54+
status === "failed" &&
55+
(transition === "start" || transition === "stop")
56+
) {
57+
actions.push(transition);
58+
}
59+
actions.push("delete");
60+
return actions;
61+
}

‎packages/shared/src/workspaces/api.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import type {
1313
SetFilterParams,
1414
ViewInDashboardParams,
1515
WatchAgentsParams,
16+
WorkspaceActionParams,
1617
WorkspacesState,
1718
} from "./types";
1819

@@ -28,6 +29,8 @@ export const WorkspacesApi = {
2829
viewInDashboard: defineCommand<ViewInDashboardParams>("viewInDashboard"),
2930
runAgentDiagnostic:
3031
defineCommand<AgentDiagnosticParams>("runAgentDiagnostic"),
32+
runWorkspaceAction:
33+
defineCommand<WorkspaceActionParams>("runWorkspaceAction"),
3134
refresh: defineCommand<void>("refresh"),
3235
setFilter: defineCommand<SetFilterParams>("setFilter"),
3336
/** Watch metadata for these agents only, so idle rows cost nothing */

‎packages/shared/src/workspaces/types.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import type {
44
WorkspaceAgentMetadata,
55
} from "coder/site/src/api/typesGenerated";
66

7+
import type { WorkspaceAction } from "./actions";
78
import type { AgentDiagnostic } from "./diagnostics";
89

910
// Re-export SDK types for convenience
@@ -12,7 +13,7 @@ export type { Workspace, WorkspaceAgent, WorkspaceAgentMetadata };
1213
export type WorkspaceFilter = "mine" | "shared" | "all";
1314

1415
/** A workspace page in the dashboard, opened in the browser. */
15-
export type DashboardPage = "workspace" | "settings";
16+
export type DashboardPage = "workspace" | "settings" | "sharing";
1617

1718
/** What the panel may offer for the current session. */
1819
export interface WorkspacesCapabilities {
@@ -56,6 +57,8 @@ export interface WorkspacesState {
5657
readonly listedAt?: number;
5758
/** Listed workspace IDs associated with Agent chats. */
5859
readonly agentWorkspaceIds?: readonly string[];
60+
/** Keyed by workspace ID: the action running there, prompts included. */
61+
readonly pendingActions?: Readonly<Record<string, WorkspaceAction>>;
5962
}
6063

6164
export interface OpenWorkspaceParams {
@@ -75,6 +78,11 @@ export interface AgentDiagnosticParams {
7578
readonly diagnostic: AgentDiagnostic;
7679
}
7780

81+
export interface WorkspaceActionParams {
82+
readonly workspaceId: string;
83+
readonly action: WorkspaceAction;
84+
}
85+
7886
export interface SetFilterParams {
7987
readonly filter: WorkspaceFilter;
8088
}

‎src/api/coderApi.ts‎

Lines changed: 46 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
import {
22
isAxiosError,
3+
isCancel,
34
type AxiosHeaders,
45
type AxiosInstance,
56
type AxiosResponseHeaders,
67
type AxiosResponseTransformer,
78
} from "axios";
89
import { Api } from "coder/site/src/api/api";
10+
import { setTimeout as sleep } from "node:timers/promises";
911
import * as vscode from "vscode";
1012

1113
import { isSameOrigin } from "../common/url";
@@ -172,27 +174,52 @@ export class CoderApi extends Api implements vscode.Disposable {
172174
/**
173175
* Reimplemented because the SDK version polls inside a voided IIFE that
174176
* swallows errors, hanging callers forever if a poll throws (e.g. on
175-
* failed response validation).
177+
* failed response validation). Builds outlast network blips, so up to
178+
* `MAX_POLL_FAILURES` transient failures in a row are polled through.
176179
*/
177180
override waitForBuild = async (
178181
build: WorkspaceBuild,
182+
signal?: AbortSignal,
179183
): Promise<ProvisionerJob | undefined> => {
184+
let failures = 0;
180185
while (true) {
181-
const { job } = await this.getWorkspaceBuildByNumber(
182-
build.workspace_owner_name,
183-
build.workspace_name,
184-
build.build_number,
186+
const job = await this.getWorkspaceBuild(build.id, signal).then(
187+
(polled) => {
188+
failures = 0;
189+
return polled.job;
190+
},
191+
(error: unknown) => {
192+
if (!isTransientError(error) || ++failures > MAX_POLL_FAILURES) {
193+
throw error;
194+
}
195+
return undefined;
196+
},
185197
);
186-
if (job.status === "failed") {
198+
if (job?.status === "failed") {
187199
throw new Error(`Build ${build.build_number} failed`);
188200
}
189-
if (job.status === "succeeded" || job.status === "canceled") {
201+
if (job?.status === "succeeded" || job?.status === "canceled") {
190202
return job;
191203
}
192-
await new Promise((resolve) => setTimeout(resolve, 1000));
204+
await sleep(1000, undefined, { signal });
193205
}
194206
};
195207

208+
/**
209+
* Reads a build by ID, as `coder` does while it waits. Reads by owner and
210+
* name 404 once a delete completes, because they skip deleted workspaces.
211+
*/
212+
getWorkspaceBuild = async (
213+
buildId: string,
214+
signal?: AbortSignal,
215+
): Promise<WorkspaceBuild> => {
216+
const { data } = await this.getAxiosInstance().get<WorkspaceBuild>(
217+
`/api/v2/workspacebuilds/${buildId}`,
218+
{ signal },
219+
);
220+
return data;
221+
};
222+
196223
hasAuthConfigChangedSince(version: number | undefined): boolean {
197224
return this.authConfigTracker.hasChangedSince(version);
198225
}
@@ -738,6 +765,17 @@ function wrapWithValidation(api: CoderApi): void {
738765
}
739766
}
740767

768+
const MAX_POLL_FAILURES = 3;
769+
770+
/** No response, or a 5xx; a cancelled request is not transient. */
771+
function isTransientError(error: unknown): boolean {
772+
return (
773+
isAxiosError(error) &&
774+
!isCancel(error) &&
775+
(!error.response || error.response.status >= 500)
776+
);
777+
}
778+
741779
function getSize(headers: AxiosHeaders, data: unknown): number | undefined {
742780
const contentLength = headers["content-length"] as unknown;
743781
if (typeof contentLength === "string") {

‎src/api/responseValidation.ts‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -75,10 +75,9 @@ export const WorkspaceSchema = z.looseObject({
7575
}),
7676
});
7777

78-
/** waitForBuild reads the identifiers to poll and the job status to stop. */
78+
/** waitForBuild polls by `id`, names `build_number` in errors, and stops on the job status. */
7979
export const WorkspaceBuildSchema = z.looseObject({
80-
workspace_owner_name: z.string(),
81-
workspace_name: z.string(),
80+
id: z.string(),
8281
build_number: z.number(),
8382
job: z.looseObject({ status: z.string() }),
8483
});
@@ -106,7 +105,7 @@ export const VALIDATED_RESPONSES = [
106105
["getTemplateVersionResources", WorkspaceResourcesSchema],
107106
["getWorkspace", WorkspaceSchema],
108107
["getWorkspaceByOwnerAndName", WorkspaceSchema],
109-
["getWorkspaceBuildByNumber", WorkspaceBuildSchema],
108+
["getWorkspaceBuild", WorkspaceBuildSchema],
110109
["startWorkspace", WorkspaceBuildSchema],
111110
["stopWorkspace", WorkspaceBuildSchema],
112111
] as const satisfies ReadonlyArray<readonly [keyof CoderApi, z.ZodType]>;

‎src/api/updateParameters.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,10 @@ interface PromptSpec {
1717
preselect?: string[];
1818
}
1919

20-
/** Thrown when the user dismisses a parameter prompt. */
20+
/** Thrown when an update is dismissed or no longer matches its confirmation. */
2121
export class WorkspaceUpdateCancelledError extends Error {
22-
constructor() {
23-
super("Workspace update cancelled");
22+
constructor(public readonly reason?: string) {
23+
super(reason ?? "Workspace update cancelled");
2424
this.name = "WorkspaceUpdateCancelledError";
2525
}
2626
}

0 commit comments

Comments
 (0)