-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathcommands.ts
More file actions
844 lines (779 loc) · 24.9 KB
/
commands.ts
File metadata and controls
844 lines (779 loc) · 24.9 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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
import {
type Workspace,
type WorkspaceAgent,
} from "coder/site/src/api/typesGenerated";
import * as fs from "node:fs/promises";
import * as path from "node:path";
import * as semver from "semver";
import * as vscode from "vscode";
import { createWorkspaceIdentifier, extractAgents } from "./api/api-helper";
import { type CoderApi } from "./api/coderApi";
import { type CliManager } from "./core/cliManager";
import * as cliUtils from "./core/cliUtils";
import { type ServiceContainer } from "./core/container";
import { type MementoManager } from "./core/mementoManager";
import { type PathResolver } from "./core/pathResolver";
import { type SecretsManager } from "./core/secretsManager";
import { type DeploymentManager } from "./deployment/deploymentManager";
import { CertificateError } from "./error/certificateError";
import { toError } from "./error/errorUtils";
import { featureSetForVersion } from "./featureSet";
import { type Logger } from "./logging/logger";
import { type LoginCoordinator } from "./login/loginCoordinator";
import { withProgress } from "./progress";
import { maybeAskAgent, maybeAskUrl } from "./promptUtils";
import {
RECOMMENDED_SSH_SETTINGS,
applySettingOverrides,
} from "./remote/sshOverrides";
import { getGlobalFlags, resolveCliAuth } from "./settings/cli";
import { escapeCommandArg, toRemoteAuthority, toSafeHost } from "./util";
import { vscodeProposed } from "./vscodeProposed";
import {
AgentTreeItem,
type OpenableTreeItem,
WorkspaceTreeItem,
} from "./workspace/workspacesProvider";
export class Commands {
private readonly logger: Logger;
private readonly pathResolver: PathResolver;
private readonly mementoManager: MementoManager;
private readonly secretsManager: SecretsManager;
private readonly cliManager: CliManager;
private readonly loginCoordinator: LoginCoordinator;
// These will only be populated when actively connected to a workspace and are
// used in commands. Because commands can be executed by the user, it is not
// possible to pass in arguments, so we have to store the current workspace
// and its client somewhere, separately from the current globally logged-in
// client, since you can connect to workspaces not belonging to whatever you
// are logged into (for convenience; otherwise the recents menu can be a pain
// if you use multiple deployments).
public workspace?: Workspace;
public workspaceLogPath?: string;
public remoteWorkspaceClient?: CoderApi;
public constructor(
serviceContainer: ServiceContainer,
private readonly extensionClient: CoderApi,
private readonly deploymentManager: DeploymentManager,
) {
this.logger = serviceContainer.getLogger();
this.pathResolver = serviceContainer.getPathResolver();
this.mementoManager = serviceContainer.getMementoManager();
this.secretsManager = serviceContainer.getSecretsManager();
this.cliManager = serviceContainer.getCliManager();
this.loginCoordinator = serviceContainer.getLoginCoordinator();
}
/**
* Get the current deployment, throwing if not logged in.
*/
private requireExtensionBaseUrl(): string {
const url = this.extensionClient.getAxiosInstance().defaults.baseURL;
if (!url) {
throw new Error("You are not logged in");
}
return url;
}
/**
* Log into a deployment. If already authenticated, this is a no-op.
* If no URL is provided, shows a menu of recent URLs plus defaults.
*/
public async login(args?: {
url?: string;
autoLogin?: boolean;
}): Promise<void> {
if (this.deploymentManager.isAuthenticated()) {
return;
}
await this.performLogin(args);
}
private async performLogin(args?: {
url?: string;
autoLogin?: boolean;
}): Promise<void> {
this.logger.debug("Logging in");
const currentDeployment = await this.secretsManager.getCurrentDeployment();
const url = await maybeAskUrl(
this.mementoManager,
args?.url,
currentDeployment?.url,
);
if (!url) {
return; // The user aborted.
}
const safeHostname = toSafeHost(url);
this.logger.debug("Using hostname", safeHostname);
const result = await this.loginCoordinator.ensureLoggedIn({
safeHostname,
url,
autoLogin: args?.autoLogin,
});
if (!result.success) {
return;
}
await this.deploymentManager.setDeployment({
url,
safeHostname,
token: result.token,
user: result.user,
});
vscode.window
.showInformationMessage(
`Welcome to Coder, ${result.user.username}!`,
{
detail:
"You can now use the Coder extension to manage your Coder instance.",
},
"Open Workspace",
)
.then((action) => {
if (action === "Open Workspace") {
vscode.commands.executeCommand("coder.open");
}
});
this.logger.debug("Login complete to deployment:", url);
}
/**
* View the logs for the currently connected workspace.
*/
public async viewLogs(): Promise<void> {
if (this.workspaceLogPath) {
// Return the connected deployment's log file.
return openFile(this.workspaceLogPath);
}
const logDir = this.pathResolver.getProxyLogPath();
try {
const files = await readdirOrEmpty(logDir);
// Sort explicitly since fs.readdir order is platform-dependent
const logFiles = files
.filter((f) => f.endsWith(".log"))
.sort((a, b) => a.localeCompare(b))
.reverse();
if (logFiles.length === 0) {
vscode.window.showInformationMessage(
"No log files found in the log directory.",
);
return;
}
const selected = await vscode.window.showQuickPick(logFiles, {
title: "Select a log file to view",
});
if (selected) {
await openFile(path.join(logDir, selected));
}
} catch (error) {
vscode.window.showErrorMessage(
`Failed to read log directory: ${error instanceof Error ? error.message : String(error)}`,
);
}
}
/**
* Log out and clear stored credentials, requiring re-authentication on next login.
*/
public async logout(): Promise<void> {
if (!this.deploymentManager.isAuthenticated()) {
return;
}
this.logger.debug("Logging out");
const deployment = this.deploymentManager.getCurrentDeployment();
await this.deploymentManager.clearDeployment();
if (deployment) {
await this.cliManager.clearCredentials(deployment.url);
await this.secretsManager.clearAllAuthData(deployment.safeHostname);
}
vscode.window
.showInformationMessage("You've been logged out of Coder!", "Login")
.then((action) => {
if (action === "Login") {
this.login().catch((error) => {
this.logger.error("Login failed", error);
});
}
});
this.logger.debug("Logout complete");
}
/**
* Switch to a different deployment without clearing credentials.
* If login fails or user cancels, stays on current deployment.
*/
public async switchDeployment(): Promise<void> {
this.logger.debug("Switching deployment");
await this.performLogin();
}
/**
* Manage stored credentials for all deployments.
* Shows a list of deployments with options to remove individual or all credentials.
*/
public async manageCredentials(): Promise<void> {
try {
const hostnames = await this.secretsManager.getKnownSafeHostnames();
if (hostnames.length === 0) {
vscode.window.showInformationMessage("No stored credentials.");
return;
}
const items: Array<{
label: string;
description: string;
hostnames: string[];
}> = hostnames.map((hostname) => ({
label: `$(key) ${hostname}`,
description: "Remove stored credentials",
hostnames: [hostname],
}));
// Only show "Remove All" when there are multiple deployments
if (hostnames.length > 1) {
items.push({
label: "$(trash) Remove All",
description: `Remove credentials for all ${hostnames.length} deployments`,
hostnames,
});
}
const selected = await vscode.window.showQuickPick(items, {
title: "Manage Stored Credentials",
placeHolder: "Select a deployment to remove",
});
if (!selected) {
return;
}
if (selected.hostnames.length === 1) {
const selectedHostname = selected.hostnames[0];
const auth = await this.secretsManager.getSessionAuth(selectedHostname);
if (auth?.url) {
await this.cliManager.clearCredentials(auth.url);
}
await this.secretsManager.clearAllAuthData(selectedHostname);
this.logger.info("Removed credentials for", selectedHostname);
vscode.window.showInformationMessage(
`Removed credentials for ${selectedHostname}`,
);
} else {
const confirm = await vscodeProposed.window.showWarningMessage(
`Remove ${selected.hostnames.length} Credentials`,
{
useCustom: true,
modal: true,
detail: `This will remove credentials for: ${selected.hostnames.join(", ")}\n\nYou'll need to log in again to access them.`,
},
"Remove All",
);
if (confirm === "Remove All") {
await Promise.all(
selected.hostnames.map(async (h) => {
const auth = await this.secretsManager.getSessionAuth(h);
if (auth?.url) {
await this.cliManager.clearCredentials(auth.url);
}
await this.secretsManager.clearAllAuthData(h);
}),
);
this.logger.info(
"Removed credentials for all deployments:",
selected.hostnames.join(", "),
);
vscode.window.showInformationMessage(
"Removed credentials for all deployments",
);
}
}
} catch (error: unknown) {
this.logger.error("Failed to manage stored credentials", error);
vscode.window.showErrorMessage(
`Failed to manage stored credentials: ${toError(error).message}`,
);
}
}
/**
* Apply recommended SSH settings for reliable Coder workspace connections.
*/
public async applyRecommendedSettings(): Promise<void> {
const entries = Object.entries(RECOMMENDED_SSH_SETTINGS);
const summary = entries.map(([, s]) => s.label).join("\n");
const confirm = await vscodeProposed.window.showWarningMessage(
"Apply Recommended SSH Settings",
{
useCustom: true,
modal: true,
detail: summary,
},
"Apply",
);
if (confirm !== "Apply") {
return;
}
const overrides = entries.map(([key, setting]) => ({
key,
value: setting.value,
}));
const ok = await applySettingOverrides(
this.pathResolver.getUserSettingsPath(),
overrides,
this.logger,
);
if (!ok) {
const action = await vscode.window.showErrorMessage(
"Failed to write SSH settings. Check the Coder output for details.",
"Show Output",
);
if (action === "Show Output") {
this.logger.show();
}
} else if (this.remoteWorkspaceClient) {
const action = await vscode.window.showInformationMessage(
"Applied recommended SSH settings. Reload the window for changes to take effect.",
"Reload Window",
);
if (action === "Reload Window") {
await vscode.commands.executeCommand("workbench.action.reloadWindow");
}
} else {
vscode.window.showInformationMessage("Applied recommended SSH settings.");
}
}
/**
* Create a new workspace for the currently logged-in deployment.
*
* Must only be called if currently logged in.
*/
public async createWorkspace(): Promise<void> {
const baseUrl = this.requireExtensionBaseUrl();
const uri = baseUrl + "/templates";
await vscode.commands.executeCommand("vscode.open", uri);
}
/**
* Open a link to the workspace in the Coder dashboard.
*
* If passing in a workspace, it must belong to the currently logged-in
* deployment.
*
* Otherwise, the currently connected workspace is used (if any).
*/
public async navigateToWorkspace(item?: OpenableTreeItem) {
if (item) {
const baseUrl = this.requireExtensionBaseUrl();
const workspaceId = createWorkspaceIdentifier(item.workspace);
const uri = baseUrl + `/@${workspaceId}`;
await vscode.commands.executeCommand("vscode.open", uri);
} else if (this.workspace && this.remoteWorkspaceClient) {
const baseUrl =
this.remoteWorkspaceClient.getAxiosInstance().defaults.baseURL;
const uri = `${baseUrl}/@${createWorkspaceIdentifier(this.workspace)}`;
await vscode.commands.executeCommand("vscode.open", uri);
} else {
vscode.window.showInformationMessage("No workspace found.");
}
}
/**
* Open a link to the workspace settings in the Coder dashboard.
*
* If passing in a workspace, it must belong to the currently logged-in
* deployment.
*
* Otherwise, the currently connected workspace is used (if any).
*/
public async navigateToWorkspaceSettings(item?: OpenableTreeItem) {
if (item) {
const baseUrl = this.requireExtensionBaseUrl();
const workspaceId = createWorkspaceIdentifier(item.workspace);
const uri = baseUrl + `/@${workspaceId}/settings`;
await vscode.commands.executeCommand("vscode.open", uri);
} else if (this.workspace && this.remoteWorkspaceClient) {
const baseUrl =
this.remoteWorkspaceClient.getAxiosInstance().defaults.baseURL;
const uri = `${baseUrl}/@${createWorkspaceIdentifier(this.workspace)}/settings`;
await vscode.commands.executeCommand("vscode.open", uri);
} else {
vscode.window.showInformationMessage("No workspace found.");
}
}
/**
* Open a workspace or agent that is showing in the sidebar.
*
* This builds the host name and passes it to the VS Code Remote SSH
* extension.
* Throw if not logged into a deployment.
*/
public async openFromSidebar(item: OpenableTreeItem): Promise<void> {
if (item) {
const baseUrl = this.extensionClient.getAxiosInstance().defaults.baseURL;
if (!baseUrl) {
throw new Error("You are not logged in");
}
if (item instanceof AgentTreeItem) {
await this.openWorkspace(
baseUrl,
item.workspace,
item.agent,
undefined,
true,
);
} else if (item instanceof WorkspaceTreeItem) {
const agents = await this.extractAgentsWithFallback(item.workspace);
const agent = await maybeAskAgent(agents);
if (!agent) {
// User declined to pick an agent.
return;
}
await this.openWorkspace(
baseUrl,
item.workspace,
agent,
undefined,
true,
);
} else {
throw new TypeError("Unable to open unknown sidebar item");
}
} else {
// If there is no tree item, then the user manually ran this command.
// Default to the regular open instead.
await this.open();
}
}
public async openAppStatus(app: {
name?: string;
url?: string;
agent_name?: string;
command?: string;
workspace_name: string;
}): Promise<void> {
// Launch and run command in terminal if command is provided
if (app.command) {
return withProgress(
{
location: vscode.ProgressLocation.Notification,
title: `Connecting to AI Agent...`,
},
async () => {
const terminal = vscode.window.createTerminal(app.name);
// If workspace_name is provided, run coder ssh before the command
const baseUrl = this.requireExtensionBaseUrl();
const safeHost = toSafeHost(baseUrl);
const binary = await this.cliManager.fetchBinary(
this.extensionClient,
);
const version = semver.parse(await cliUtils.version(binary));
const featureSet = featureSetForVersion(version);
const configDir = this.pathResolver.getGlobalConfigDir(safeHost);
const configs = vscode.workspace.getConfiguration();
const auth = resolveCliAuth(configs, featureSet, baseUrl, configDir);
const globalFlags = getGlobalFlags(configs, auth);
terminal.sendText(
`${escapeCommandArg(binary)} ${globalFlags.join(" ")} ssh ${app.workspace_name}`,
);
await new Promise((resolve) => setTimeout(resolve, 5000));
terminal.sendText(app.command ?? "");
terminal.show(false);
},
);
}
// If no URL or command, show information about the app status
vscode.window.showInformationMessage(`${app.name}`, {
detail: `Agent: ${app.agent_name || "Unknown"}`,
});
}
/**
* Open a workspace belonging to the currently logged-in deployment.
*
* If no workspace is provided, ask the user for one. If no agent is
* provided, use the first or ask the user if there are multiple.
*
* Throw if not logged into a deployment or if a matching workspace or agent
* cannot be found.
*/
public async open(
workspaceOwner?: string,
workspaceName?: string,
agentName?: string,
folderPath?: string,
openRecent?: boolean,
): Promise<boolean> {
const baseUrl = this.extensionClient.getAxiosInstance().defaults.baseURL;
if (!baseUrl) {
throw new Error("You are not logged in");
}
let workspace: Workspace | undefined;
if (workspaceOwner && workspaceName) {
workspace = await this.extensionClient.getWorkspaceByOwnerAndName(
workspaceOwner,
workspaceName,
);
} else {
workspace = await this.pickWorkspace();
if (!workspace) {
// User declined to pick a workspace.
return false;
}
}
const agents = await this.extractAgentsWithFallback(workspace);
const agent = await maybeAskAgent(agents, agentName);
if (!agent) {
// User declined to pick an agent.
return false;
}
return this.openWorkspace(
baseUrl,
workspace,
agent,
folderPath,
openRecent,
);
}
/**
* Open a devcontainer from a workspace belonging to the currently logged-in deployment.
*
* Throw if not logged into a deployment.
*/
public async openDevContainer(
workspaceOwner: string,
workspaceName: string,
workspaceAgent: string,
devContainerName: string,
devContainerFolder: string,
localWorkspaceFolder = "",
localConfigFile = "",
): Promise<void> {
const baseUrl = this.extensionClient.getAxiosInstance().defaults.baseURL;
if (!baseUrl) {
throw new Error("You are not logged in");
}
const remoteAuthority = toRemoteAuthority(
baseUrl,
workspaceOwner,
workspaceName,
workspaceAgent,
);
const hostPath = localWorkspaceFolder || undefined;
const configFile =
hostPath && localConfigFile
? {
path: localConfigFile,
scheme: "vscode-fileHost",
}
: undefined;
const devContainer = Buffer.from(
JSON.stringify({
containerName: devContainerName,
hostPath,
configFile,
localDocker: false,
}),
"utf-8",
).toString("hex");
const type = localWorkspaceFolder ? "dev-container" : "attached-container";
const devContainerAuthority = `${type}+${devContainer}@${remoteAuthority}`;
let newWindow = true;
if (!vscode.workspace.workspaceFolders?.length) {
newWindow = false;
}
// Only set the memento when opening a new folder
await this.mementoManager.setFirstConnect();
await vscode.commands.executeCommand(
"vscode.openFolder",
vscode.Uri.from({
scheme: "vscode-remote",
authority: devContainerAuthority,
path: devContainerFolder,
}),
newWindow,
);
}
/**
* Update the current workspace. If there is no active workspace connection,
* this is a no-op.
*/
public async updateWorkspace(): Promise<void> {
if (!this.workspace || !this.remoteWorkspaceClient) {
return;
}
const action = await vscodeProposed.window.showWarningMessage(
"Update Workspace",
{
useCustom: true,
modal: true,
detail: `Update ${createWorkspaceIdentifier(this.workspace)} to the latest version?\n\nUpdating will restart your workspace which stops any running processes and may result in the loss of unsaved work.`,
},
"Update and Restart",
);
if (action === "Update and Restart") {
await this.remoteWorkspaceClient.updateWorkspaceVersion(this.workspace);
}
}
/**
* Ask the user to select a workspace. Return undefined if canceled.
*/
private async pickWorkspace(): Promise<Workspace | undefined> {
const quickPick = vscode.window.createQuickPick();
quickPick.value = "owner:me ";
quickPick.placeholder = "owner:me template:go";
quickPick.title = `Connect to a workspace`;
let lastWorkspaces: readonly Workspace[];
quickPick.onDidChangeValue((value) => {
quickPick.busy = true;
this.extensionClient
.getWorkspaces({
q: value,
})
.then((workspaces) => {
lastWorkspaces = workspaces.workspaces;
const items: vscode.QuickPickItem[] = workspaces.workspaces.map(
(workspace) => {
let icon = "$(debug-start)";
if (workspace.latest_build.status !== "running") {
icon = "$(debug-stop)";
}
const status =
workspace.latest_build.status.substring(0, 1).toUpperCase() +
workspace.latest_build.status.substring(1);
return {
alwaysShow: true,
label: `${icon} ${workspace.owner_name} / ${workspace.name}`,
detail: `Template: ${workspace.template_display_name || workspace.template_name} • Status: ${status}`,
};
},
);
quickPick.items = items;
})
.catch((ex) => {
this.logger.error("Failed to fetch workspaces", ex);
if (ex instanceof CertificateError) {
void ex.showNotification();
}
})
.finally(() => {
quickPick.busy = false;
});
});
quickPick.show();
return new Promise<Workspace | undefined>((resolve) => {
quickPick.onDidHide(() => {
resolve(undefined);
});
quickPick.onDidChangeSelection((selected) => {
if (selected.length < 1) {
return resolve(undefined);
}
const workspace = lastWorkspaces[quickPick.items.indexOf(selected[0])];
resolve(workspace);
});
});
}
/**
* Return agents from the workspace.
*
* This function can return agents even if the workspace is off. Use this to
* ensure we have an agent so we get a stable host name, because Coder will
* happily connect to the same agent with or without it in the URL (if it is
* the first) but VS Code will treat these as different sessions.
*/
private async extractAgentsWithFallback(
workspace: Workspace,
): Promise<WorkspaceAgent[]> {
const agents = extractAgents(workspace.latest_build.resources);
if (workspace.latest_build.status !== "running" && agents.length === 0) {
// If we have no agents, the workspace may not be running, in which case
// we need to fetch the agents through the resources API, as the
// workspaces query does not include agents when off.
this.logger.info("Fetching agents from template version");
const resources = await this.extensionClient.getTemplateVersionResources(
workspace.latest_build.template_version_id,
);
return extractAgents(resources);
}
return agents;
}
/**
* Given a workspace and agent, build the host name, find a directory to open,
* and pass both to the Remote SSH plugin in the form of a remote authority
* URI.
*
* If provided, folderPath is always used, otherwise expanded_directory from
* the agent is used.
*/
async openWorkspace(
baseUrl: string,
workspace: Workspace,
agent: WorkspaceAgent,
folderPath: string | undefined,
openRecent = false,
): Promise<boolean> {
const remoteAuthority = toRemoteAuthority(
baseUrl,
workspace.owner_name,
workspace.name,
agent.name,
);
let newWindow = true;
// Open in the existing window if no workspaces are open.
if (!vscode.workspace.workspaceFolders?.length) {
newWindow = false;
}
if (!folderPath) {
folderPath = agent.expanded_directory;
}
// If the agent had no folder or we have been asked to open the most recent,
// we can try to open a recently opened folder/workspace.
if (!folderPath || openRecent) {
const output: {
workspaces: Array<{ folderUri: vscode.Uri; remoteAuthority: string }>;
} = await vscode.commands.executeCommand("_workbench.getRecentlyOpened");
const opened = output.workspaces.filter(
// Remove recents that do not belong to this connection. The remote
// authority maps to a workspace/agent combination (using the SSH host
// name). There may also be some legacy connections that still may
// reference a workspace without an agent name, which will be missed.
(opened) => opened.folderUri?.authority === remoteAuthority,
);
// openRecent will always use the most recent. Otherwise, if there are
// multiple we ask the user which to use.
if (opened.length === 1 || (opened.length > 1 && openRecent)) {
folderPath = opened[0].folderUri.path;
} else if (opened.length > 1) {
const items = opened.map((f) => f.folderUri.path);
folderPath = await vscode.window.showQuickPick(items, {
title: "Select a recently opened folder",
});
if (!folderPath) {
// User aborted.
return false;
}
}
}
// Only set the memento when opening a new folder/window
await this.mementoManager.setFirstConnect();
if (folderPath) {
await vscode.commands.executeCommand(
"vscode.openFolder",
vscode.Uri.from({
scheme: "vscode-remote",
authority: remoteAuthority,
path: folderPath,
}),
// Open this in a new window!
newWindow,
);
return true;
}
// This opens the workspace without an active folder opened.
await vscode.commands.executeCommand("vscode.newWindow", {
remoteAuthority: remoteAuthority,
reuseWindow: !newWindow,
});
return true;
}
}
async function openFile(filePath: string): Promise<void> {
const uri = vscode.Uri.file(filePath);
await vscode.window.showTextDocument(uri);
}
/**
* Read a directory's entries, returning an empty array if it does not exist.
*/
async function readdirOrEmpty(dirPath: string): Promise<string[]> {
try {
return await fs.readdir(dirPath);
} catch (err) {
if (err instanceof Error && "code" in err && err.code === "ENOENT") {
return [];
}
throw err;
}
}