-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathextension.ts
More file actions
459 lines (421 loc) · 14.3 KB
/
extension.ts
File metadata and controls
459 lines (421 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
"use strict";
import axios, { isAxiosError } from "axios";
import { getErrorMessage } from "coder/site/src/api/errors";
import { createRequire } from "node:module";
import * as path from "node:path";
import * as vscode from "vscode";
import { errToStr } from "./api/api-helper";
import { AuthInterceptor } from "./api/authInterceptor";
import { CoderApi } from "./api/coderApi";
import { Commands } from "./commands";
import { ServiceContainer } from "./core/container";
import { DeploymentManager } from "./deployment/deploymentManager";
import { CertificateError } from "./error/certificateError";
import { getErrorDetail, toError } from "./error/errorUtils";
import { OAuthSessionManager } from "./oauth/sessionManager";
import { Remote } from "./remote/remote";
import { getRemoteSshExtension } from "./remote/sshExtension";
import { registerUriHandler } from "./uri/uriHandler";
import { initVscodeProposed } from "./vscodeProposed";
import { ChatPanelProvider } from "./webviews/chat/chatPanelProvider";
import { TasksPanelProvider } from "./webviews/tasks/tasksPanelProvider";
import {
WorkspaceProvider,
WorkspaceQuery,
} from "./workspace/workspacesProvider";
const MY_WORKSPACES_TREE_ID = "myWorkspaces";
const ALL_WORKSPACES_TREE_ID = "allWorkspaces";
export async function activate(ctx: vscode.ExtensionContext): Promise<void> {
// The Remote SSH extension's proposed APIs are used to override the SSH host
// name in VS Code itself. It's visually unappealing having a lengthy name!
//
// This is janky, but that's alright since it provides such minimal
// functionality to the extension.
//
// Cursor and VSCode are covered by ms remote, and the only other is windsurf for now
// Means that vscodium is not supported by this for now
const remoteSshExtension = getRemoteSshExtension();
let vscodeProposed: typeof vscode = vscode;
if (remoteSshExtension) {
const extensionRequire = createRequire(
path.join(remoteSshExtension.extensionPath, "package.json"),
);
vscodeProposed = extensionRequire("vscode") as typeof vscode;
} else {
vscode.window.showErrorMessage(
"Remote SSH extension not found, this may not work as expected.\n" +
// NB should we link to documentation or marketplace?
"Please install your choice of Remote SSH extension from the VS Code Marketplace.",
);
}
// Initialize the global vscodeProposed module for use throughout the extension
initVscodeProposed(vscodeProposed);
const serviceContainer = new ServiceContainer(ctx);
ctx.subscriptions.push(serviceContainer);
const output = serviceContainer.getLogger();
const mementoManager = serviceContainer.getMementoManager();
const secretsManager = serviceContainer.getSecretsManager();
const contextManager = serviceContainer.getContextManager();
// Migrate auth storage from old flat format to new label-based format
await migrateAuthStorage(serviceContainer);
// Try to clear this flag ASAP
const isFirstConnect = await mementoManager.getAndClearFirstConnect();
const deployment = await secretsManager.getCurrentDeployment();
// Shared handler for auth failures (used by interceptor + session manager)
const handleAuthFailure = (): Promise<void> => {
deploymentManager.suspendSession();
vscode.window
.showWarningMessage(
"Session expired. You have been signed out.",
"Log In",
)
.then(async (action) => {
if (action === "Log In") {
try {
await commands.login({
url: deploymentManager.getCurrentDeployment()?.url,
});
} catch (err) {
output.error("Login failed", err);
}
}
});
return Promise.resolve();
};
// Create OAuth session manager - callback handles background refresh failures
const oauthSessionManager = OAuthSessionManager.create(
deployment,
serviceContainer,
handleAuthFailure,
);
ctx.subscriptions.push(oauthSessionManager);
// This client tracks the current login and will be used through the life of
// the plugin to poll workspaces for the current login, as well as being used
// in commands that operate on the current login.
const client = CoderApi.create(
deployment?.url || "",
(await secretsManager.getSessionAuth(deployment?.safeHostname ?? ""))
?.token,
output,
);
ctx.subscriptions.push(client);
// Handles 401 responses (OAuth and otherwise)
const authInterceptor = new AuthInterceptor(
client,
output,
oauthSessionManager,
secretsManager,
async () => {
await handleAuthFailure();
return false;
},
);
ctx.subscriptions.push(authInterceptor);
const isAuthenticated = () => contextManager.get("coder.authenticated");
const myWorkspacesProvider = new WorkspaceProvider(
WorkspaceQuery.Mine,
client,
output,
isAuthenticated,
5,
);
ctx.subscriptions.push(myWorkspacesProvider);
const allWorkspacesProvider = new WorkspaceProvider(
WorkspaceQuery.All,
client,
output,
isAuthenticated,
);
ctx.subscriptions.push(allWorkspacesProvider);
// createTreeView, unlike registerTreeDataProvider, gives us the tree view API
// (so we can see when it is visible) but otherwise they have the same effect.
const myWsTree = vscode.window.createTreeView(MY_WORKSPACES_TREE_ID, {
treeDataProvider: myWorkspacesProvider,
});
ctx.subscriptions.push(myWsTree);
myWorkspacesProvider.setVisibility(myWsTree.visible);
myWsTree.onDidChangeVisibility(
(event) => {
myWorkspacesProvider.setVisibility(event.visible);
},
undefined,
ctx.subscriptions,
);
const allWsTree = vscode.window.createTreeView(ALL_WORKSPACES_TREE_ID, {
treeDataProvider: allWorkspacesProvider,
});
ctx.subscriptions.push(allWsTree);
allWorkspacesProvider.setVisibility(allWsTree.visible);
allWsTree.onDidChangeVisibility(
(event) => {
allWorkspacesProvider.setVisibility(event.visible);
},
undefined,
ctx.subscriptions,
);
// Create deployment manager to centralize deployment state management
const deploymentManager = DeploymentManager.create(
serviceContainer,
client,
oauthSessionManager,
[myWorkspacesProvider, allWorkspacesProvider],
);
ctx.subscriptions.push(deploymentManager);
// Register globally available commands. Many of these have visibility
// controlled by contexts, see `when` in the package.json.
const commands = new Commands(serviceContainer, client, deploymentManager);
// Placeholder tree view for the coderTasks container when not authenticated.
// Works around a Cursor bug where containers with all views hidden via `when`
// clauses never re-appear after the context changes.
ctx.subscriptions.push(
vscode.window.createTreeView("coder.tasksLogin", {
treeDataProvider: {
getTreeItem: () => new vscode.TreeItem(""),
getChildren: () => [],
},
}),
);
// Register Tasks webview panel with dependencies
const tasksPanelProvider = new TasksPanelProvider(
ctx.extensionUri,
client,
output,
);
ctx.subscriptions.push(
tasksPanelProvider,
vscode.window.registerWebviewViewProvider(
TasksPanelProvider.viewType,
tasksPanelProvider,
{ webviewOptions: { retainContextWhenHidden: true } },
),
vscode.commands.registerCommand("coder.tasks.refresh", () =>
tasksPanelProvider.refresh(),
),
// Refresh tasks panel when deployment changes (login/logout/switch)
secretsManager.onDidChangeCurrentDeployment(() =>
tasksPanelProvider.refresh(),
),
);
// Register Chat embed panel with dependencies
const chatPanelProvider = new ChatPanelProvider(client, output);
ctx.subscriptions.push(
chatPanelProvider,
vscode.window.registerWebviewViewProvider(
ChatPanelProvider.viewType,
chatPanelProvider,
{ webviewOptions: { retainContextWhenHidden: true } },
),
vscode.commands.registerCommand("coder.chat.refresh", () =>
chatPanelProvider.refresh(),
),
);
ctx.subscriptions.push(
registerUriHandler({
serviceContainer,
deploymentManager,
commands,
chatPanelProvider,
}),
vscode.commands.registerCommand(
"coder.login",
commands.login.bind(commands),
),
vscode.commands.registerCommand(
"coder.logout",
commands.logout.bind(commands),
),
vscode.commands.registerCommand(
"coder.switchDeployment",
commands.switchDeployment.bind(commands),
),
vscode.commands.registerCommand("coder.open", commands.open.bind(commands)),
vscode.commands.registerCommand(
"coder.openDevContainer",
commands.openDevContainer.bind(commands),
),
vscode.commands.registerCommand(
"coder.openFromSidebar",
commands.openFromSidebar.bind(commands),
),
vscode.commands.registerCommand(
"coder.openAppStatus",
commands.openAppStatus.bind(commands),
),
vscode.commands.registerCommand(
"coder.workspace.update",
commands.updateWorkspace.bind(commands),
),
vscode.commands.registerCommand(
"coder.createWorkspace",
commands.createWorkspace.bind(commands),
),
vscode.commands.registerCommand(
"coder.navigateToWorkspace",
commands.navigateToWorkspace.bind(commands),
),
vscode.commands.registerCommand(
"coder.navigateToWorkspaceSettings",
commands.navigateToWorkspaceSettings.bind(commands),
),
vscode.commands.registerCommand("coder.refreshWorkspaces", () => {
void myWorkspacesProvider.fetchAndRefresh();
void allWorkspacesProvider.fetchAndRefresh();
}),
vscode.commands.registerCommand(
"coder.viewLogs",
commands.viewLogs.bind(commands),
),
vscode.commands.registerCommand("coder.searchMyWorkspaces", async () =>
showTreeViewSearch(MY_WORKSPACES_TREE_ID),
),
vscode.commands.registerCommand("coder.searchAllWorkspaces", async () =>
showTreeViewSearch(ALL_WORKSPACES_TREE_ID),
),
vscode.commands.registerCommand(
"coder.manageCredentials",
commands.manageCredentials.bind(commands),
),
vscode.commands.registerCommand(
"coder.applyRecommendedSettings",
commands.applyRecommendedSettings.bind(commands),
),
);
const remote = new Remote(serviceContainer, commands, ctx);
// Since the "onResolveRemoteAuthority:ssh-remote" activation event exists
// in package.json we're able to perform actions before the authority is
// resolved by the remote SSH extension.
//
// In addition, if we don't have a remote SSH extension, we skip this
// activation event. This may allow the user to install the extension
// after the Coder extension is installed, instead of throwing a fatal error
// (this would require the user to uninstall the Coder extension and
// reinstall after installing the remote SSH extension, which is annoying)
if (remoteSshExtension && vscodeProposed.env.remoteAuthority) {
try {
const details = await remote.setup(
vscodeProposed.env.remoteAuthority,
isFirstConnect,
remoteSshExtension.id,
);
if (details) {
ctx.subscriptions.push(details);
await deploymentManager.setDeploymentIfValid({
safeHostname: details.safeHostname,
url: details.url,
token: details.token,
});
// If a deep link stored a chat agent ID before the
// remote-authority reload, open it now that the
// deployment is configured.
const pendingChatId = await mementoManager.getAndClearPendingChatId();
if (pendingChatId) {
// Enable eagerly so the view is visible before focus.
contextManager.set("coder.agentsEnabled", true);
chatPanelProvider.openChat(pendingChatId);
}
}
} catch (ex) {
if (ex instanceof CertificateError) {
output.warn(ex.detail);
await ex.showNotification("Failed to open workspace", { modal: true });
} else if (isAxiosError(ex)) {
const msg = getErrorMessage(ex, "None");
const detail = getErrorDetail(ex) || "None";
const urlString = axios.getUri(ex.config);
const method = ex.config?.method?.toUpperCase() || "request";
const status = ex.response?.status ?? "None";
const message = `API ${method} to '${urlString}' failed.\nStatus code: ${status}\nMessage: ${msg}\nDetail: ${detail}`;
output.warn(message);
await vscodeProposed.window.showErrorMessage(
"Failed to open workspace",
{
detail: message,
modal: true,
useCustom: true,
},
);
} else {
const message = errToStr(ex, "No error message was provided");
output.warn(message);
await vscodeProposed.window.showErrorMessage(
"Failed to open workspace",
{
detail: message,
modal: true,
useCustom: true,
},
);
}
// Always close remote session when we fail to open a workspace.
await remote.closeRemote();
return;
}
}
// Initialize deployment manager with stored deployment (if any).
// Skip if already set by remote.setup above.
if (deploymentManager.getCurrentDeployment()) {
contextManager.set("coder.loaded", true);
} else if (deployment) {
output.info(`Initializing deployment: ${deployment.url}`);
deploymentManager
.setDeploymentIfValid(deployment)
// Failure is logged internally
.then((success) => {
if (success) {
output.info("Deployment authenticated and set");
}
})
.catch((error: unknown) => {
output.warn("Failed to initialize deployment", error);
const message = toError(error).message;
vscode.window.showErrorMessage(
`Failed to check user authentication: ${message}`,
);
})
.finally(() => {
contextManager.set("coder.loaded", true);
});
} else {
output.info("Not currently logged in");
contextManager.set("coder.loaded", true);
// Handle autologin, if not already logged in.
const cfg = vscode.workspace.getConfiguration();
if (cfg.get("coder.autologin") === true) {
const defaultUrl =
cfg.get<string>("coder.defaultUrl")?.trim() ||
process.env.CODER_URL?.trim();
if (defaultUrl) {
commands.login({ url: defaultUrl, autoLogin: true }).catch((error) => {
output.error("Auto-login failed", error);
});
}
}
}
}
/**
* Migrates old flat storage (sessionToken) to new label-based map storage.
* This is a one-time operation that runs on extension activation.
*/
async function migrateAuthStorage(
serviceContainer: ServiceContainer,
): Promise<void> {
const secretsManager = serviceContainer.getSecretsManager();
const output = serviceContainer.getLogger();
try {
const migratedHostname = await secretsManager.migrateFromLegacyStorage();
if (migratedHostname) {
output.info(
`Successfully migrated auth storage (hostname: ${migratedHostname})`,
);
}
} catch (error: unknown) {
output.error(
`Auth storage migration failed. You may need to log in again.`,
error,
);
}
}
async function showTreeViewSearch(id: string): Promise<void> {
await vscode.commands.executeCommand(`${id}.focus`);
await vscode.commands.executeCommand("list.find");
}