Repository navigation
Expand file tree
/
Copy pathcommands.ts
More file actions
1890 lines (1756 loc) · 56.3 KB
/
Copy pathcommands.ts
File metadata and controls
1890 lines (1756 loc) · 56.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
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
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as fs from "node:fs/promises";
import * as os from "node:os";
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";
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";
import { type CliFeatureSet, cliFeatureSet } from "./featureSet";
import {
AuthTelemetry,
type AuthLoginOutcome,
type AuthLogoutOutcome,
} from "./instrumentation/auth";
import {
DiagnosticTelemetry,
type DiagnosticTrace,
} from "./instrumentation/diagnostics";
import { WorkspaceOperationTelemetry } from "./instrumentation/workspace";
import {
type DevContainerMode,
type WorkspaceOpenSource,
WorkspaceOpenTelemetry,
type WorkspaceOpenTrace,
type WorkspacePickerErrorCategory,
type WorkspacePickerResult,
type WorkspacePickerSource,
} from "./instrumentation/workspaceOpen";
import {
LegacyEditorId,
currentEditorId,
hostEditorId,
isRemoteAuthorityCompatible,
parseRemoteAuthority,
sshHostOf,
toLegacyAuthority,
toRemoteAuthority,
} from "./remote/authority";
import {
applySettingOverrides,
getRecommendedSshSettings,
} from "./remote/sshOverrides";
import { isKeyringEnabled, resolveCliAuth } from "./settings/cli";
import { appendVsCodeLogs } from "./supportBundle/appendVsCodeLogs";
import {
getRemoteServerDataPath,
toRemoteLogGlobs,
} from "./supportBundle/remoteServerDataPath";
import { runExportTelemetryCommand } from "./telemetry/export/command";
import {
reportElapsedProgress,
withCancellableProgress,
withProgress,
} from "./ui/progress";
import { maybeAskAgent, maybeAskUrl } from "./ui/prompts";
import { vscodeProposed } from "./vscode/proposed";
import { parseNetcheckReport } from "./webviews/netcheck/types";
import { parseSpeedtestResult } from "./webviews/speedtest/types";
import {
AgentTreeItem,
type OpenableTreeItem,
WorkspaceTreeItem,
} from "./workspace/workspacesProvider";
import type {
Workspace,
WorkspaceAgent,
} from "coder/site/src/api/typesGenerated";
import type { CoderApi } from "./api/coderApi";
import type { CliManager } from "./cli/cliManager";
import type { ServiceContainer } from "./container";
import type { DeploymentManager } from "./deployment/deploymentManager";
import type { Logger } from "./logging/logger";
import type { LoginCoordinator, LoginMethod } from "./login/loginCoordinator";
import type { MementoManager } from "./storage/mementoManager";
import type { PathResolver } from "./storage/pathResolver";
import type { SecretsManager, SessionAuth } from "./storage/secretsManager";
import type { TelemetryService } from "./telemetry/service";
import type { NetcheckPanelFactory } from "./webviews/netcheck/netcheckPanelFactory";
import type { SpeedtestPanelFactory } from "./webviews/speedtest/speedtestPanelFactory";
import type {
DuplicateWorkspaceIpc,
PongMessage,
} from "./workspace/duplicateWorkspaceIpc";
/** One entry from the private `_workbench.getRecentlyOpened` command. */
interface RecentlyOpened {
folderUri?: vscode.Uri;
workspace?: { configPath?: vscode.Uri };
}
const NO_SSH_CONFIG_MESSAGE =
"No SSH config has been generated yet. It is written when you connect to a workspace.";
interface OpenOptions {
workspaceOwner?: string;
workspaceName?: string;
agentName?: string;
folderPath?: string;
openRecent?: boolean;
source?: WorkspaceOpenSource;
/** When false, an absent folderPath opens a bare remote window instead of
* falling back to the agent's expanded_directory. Defaults to true. */
useDefaultDirectory?: boolean;
}
interface LoginArgs {
readonly url?: string;
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";
readonly agentName?: string;
readonly client: CoderApi;
readonly workspaceId: string;
/** Authority for the workspace, live or reconstructed from metadata. */
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<WorkspaceResolution, { status: "selected" }>;
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<Record<AgentDiagnostic, string>> = {
ping: "ping",
speedTest: "run a speed test on",
supportBundle: "create a support bundle for",
};
const DASHBOARD_PATHS: Readonly<Record<DashboardPage, string>> = {
workspace: "",
settings: "/settings",
sharing: "/settings/sharing",
};
const openDefaults = {
openRecent: false,
useDefaultDirectory: true,
} as const satisfies Partial<OpenOptions>;
/** `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;
private readonly mementoManager: MementoManager;
private readonly secretsManager: SecretsManager;
private readonly cliManager: CliManager;
private readonly loginCoordinator: LoginCoordinator;
private readonly duplicateWorkspaceIpc: DuplicateWorkspaceIpc;
private readonly speedtestPanelFactory: SpeedtestPanelFactory;
private readonly netcheckPanelFactory: NetcheckPanelFactory;
private readonly telemetryService: TelemetryService;
private readonly authTelemetry: AuthTelemetry;
private readonly diagnosticTelemetry: DiagnosticTelemetry;
private readonly workspaceOpenTelemetry: WorkspaceOpenTelemetry;
// 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 agent?: WorkspaceAgent;
public workspaceLogPath?: string;
public remoteWorkspaceClient?: CoderApi;
public constructor(
serviceContainer: ServiceContainer,
private readonly extensionClient: CoderApi,
private readonly deploymentManager: DeploymentManager,
) {
this.telemetryService = serviceContainer.getTelemetryService();
this.authTelemetry = new AuthTelemetry(this.telemetryService);
this.diagnosticTelemetry = new DiagnosticTelemetry(this.telemetryService);
this.workspaceOpenTelemetry = new WorkspaceOpenTelemetry(
this.telemetryService,
);
this.logger = serviceContainer.getLogger();
this.pathResolver = serviceContainer.getPathResolver();
this.mementoManager = serviceContainer.getMementoManager();
this.secretsManager = serviceContainer.getSecretsManager();
this.cliManager = serviceContainer.getCliManager();
this.loginCoordinator = serviceContainer.getLoginCoordinator();
this.duplicateWorkspaceIpc = serviceContainer.getDuplicateWorkspaceIpc();
this.speedtestPanelFactory = serviceContainer.getSpeedtestPanelFactory();
this.netcheckPanelFactory = serviceContainer.getNetcheckPanelFactory();
}
/**
* 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;
}
/**
* Get the remote workspace deployment URL, throwing if not connected.
*/
private requireRemoteBaseUrl(): string {
const url = this.remoteWorkspaceClient?.getAxiosInstance().defaults.baseURL;
if (!url) {
throw new Error("No remote workspace connection");
}
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?: LoginArgs): Promise<void> {
if (this.deploymentManager.isAuthenticated()) {
return;
}
await this.authTelemetry.traceLogin(
args?.autoLogin ? "auto_login" : "command",
(trace) => this.performLogin(args, trace.setMethod),
);
}
private async performLogin(
args: LoginArgs | undefined,
setMethod: (method: LoginMethod) => void,
): Promise<AuthLoginOutcome> {
this.logger.debug("Logging in");
const currentDeployment = await this.secretsManager.getCurrentDeployment();
const url = await maybeAskUrl(
this.mementoManager,
args?.url,
currentDeployment?.url,
);
if (!url) {
return { success: false, reason: "no_url_provided" };
}
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 result;
}
// Record the method eagerly so it is captured even if persistence throws.
setMethod(result.method);
await this.deploymentManager.setDeployment({
url,
safeHostname,
token: result.token,
user: result.user,
});
this.showWelcomeMessage(result.user.username);
this.logger.debug("Login complete to deployment:", url);
return { success: true, method: result.method };
}
private showWelcomeMessage(username: string): void {
vscode.window
.showInformationMessage(
`Welcome to Coder, ${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");
}
});
}
/**
* 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(target?: WorkspaceTarget): Promise<void> {
await this.diagnosticTelemetry.trace("speed_test", (telemetry) =>
this.runSpeedTest(target, telemetry),
);
}
private async runSpeedTest(
target: WorkspaceTarget | undefined,
telemetry: DiagnosticTrace,
): Promise<void> {
const resolved = await this.resolveDiagnosticWorkspace(
target,
"speedTest",
telemetry,
);
if (!resolved) {
return;
}
const { client } = resolved;
const agentId = toAgentIdentifier(resolved);
const input = await vscode.window.showInputBox({
title: "Speed Test Duration",
prompt: "Duration in seconds",
value: "5",
validateInput: (value) => {
const n = Number(value.trim());
if (!value.trim() || !Number.isFinite(n) || n <= 0) {
return "Please enter a positive number";
}
return undefined;
},
});
if (input === undefined) {
telemetry.abort("input");
return;
}
const seconds = Number(input.trim());
telemetry.setRequestedDuration(seconds);
await runDiagnosticCli({
telemetry,
logger: this.logger,
name: "Speed test",
progressTitle: `Running speed test for ${agentId}`,
exec: async ({ signal, progress }) => {
progress.report({ message: "Connecting..." });
const env = await this.resolveCliEnv(client);
const stopProgress = reportElapsedProgress({
progress,
totalMs: seconds * 1000,
format: (pct, elapsedMs) =>
pct >= 100
? "Collecting results..."
: `${Math.floor(elapsedMs / 1000)}s / ${seconds}s`,
});
try {
return await cliExec.speedtest(env, agentId, `${seconds}s`, signal);
} finally {
stopProgress();
}
},
parseAndDisplay: (rawJson) => {
const parsed = parseSpeedtestResult(rawJson);
this.speedtestPanelFactory.show({
result: parsed,
rawJson,
workspaceId: agentId,
});
// Record success after the panel shows, so a display failure is an
// error rather than a contradictory success span.
telemetry.succeedSpeedtest(parsed);
},
});
}
/**
* Run a network check against the current deployment and display the
* report in a webview panel. Can be triggered from the sidebar or command
* palette.
*/
public async netcheck(): Promise<void> {
await this.diagnosticTelemetry.trace("netcheck", (telemetry) =>
this.runNetcheck(telemetry),
);
}
private async runNetcheck(telemetry: DiagnosticTrace): Promise<void> {
// Netcheck reports on the deployment as a whole, so unlike the other
// diagnostics there is no workspace to resolve; prefer the deployment
// the current remote workspace belongs to.
const client = this.remoteWorkspaceClient ?? this.extensionClient;
const baseUrl = client.getAxiosInstance().defaults.baseURL;
if (!baseUrl) {
telemetry.error();
vscode.window.showErrorMessage("You are not logged in");
return;
}
const host = toSafeHost(baseUrl);
await runDiagnosticCli({
telemetry,
logger: this.logger,
name: "Network check",
progressTitle: `Running network check for ${host}`,
exec: async ({ signal, progress }) => {
progress.report({ message: "Resolving CLI..." });
const env = await this.resolveCliEnv(client);
progress.report({
message: "Gathering network report. This may take a few seconds...",
});
return await cliExec.netcheck(env, signal);
},
parseAndDisplay: (rawJson) => {
const report = parseNetcheckReport(rawJson);
this.netcheckPanelFactory.show({ host, report }, rawJson);
// Record success after the panel shows, so a display failure is an
// error rather than a contradictory success span.
telemetry.succeedNetcheck(report);
},
});
}
public async supportBundle(target?: WorkspaceTarget): Promise<void> {
await this.diagnosticTelemetry.trace("support_bundle", (telemetry) =>
this.runSupportBundle(target, telemetry),
);
}
private async runSupportBundle(
target: WorkspaceTarget | undefined,
telemetry: DiagnosticTrace,
): Promise<void> {
const resolved = await this.resolveDiagnosticWorkspace(
target,
"supportBundle",
telemetry,
);
if (!resolved) {
return;
}
const { agentName, client, workspaceId, remoteAuthority } = resolved;
if (!(await this.confirmSupportBundleCollection())) {
telemetry.abort("prompt");
return;
}
const outputUri = await this.promptSupportBundlePath();
if (!outputUri) {
telemetry.abort("save_dialog");
return;
}
const result = await withCancellableProgress(
async ({ signal, progress }) => {
progress.report({ message: "Resolving CLI..." });
// Independent of the CLI and never rejects, so resolve the globs
// concurrently and discard them when the CLI lacks support.
const remoteLogGlobs = getRemoteServerDataPath({
appRoot: vscode.env.appRoot,
remoteAuthority,
logger: this.logger,
}).then(toRemoteLogGlobs);
const env = await this.resolveCliEnv(client);
// The resolution APIs take no signal, so race to keep cancel honest.
const workspaceFiles = env.featureSet.supportBundleWorkspaceFiles
? await raceWithAbort(remoteLogGlobs, signal)
: [];
progress.report({ message: "Collecting diagnostics..." });
// Flush buffered below-level connection logs before the CLI runs so
// the channel has time to write them to disk; retain the ring so a
// later failure flush still replays them. Best-effort: the channel
// writes on its own schedule, so the tail may not land in this bundle.
this.logger.flush("support_bundle", { retain: true });
await cliExec.supportBundle(env, workspaceId, {
outputPath: outputUri.fsPath,
agentName,
workspaceFiles,
signal,
});
progress.report({ message: "Adding VS Code logs..." });
await appendVsCodeLogs(
outputUri.fsPath,
{
activeProxyLogPath: this.workspaceLogPath,
proxyLogDir: this.pathResolver.getProxyLogPath(),
extensionLogDir: this.pathResolver.getCodeLogDir(),
telemetryDir: this.pathResolver.getTelemetryPath(),
},
this.logger,
);
return outputUri;
},
{
location: vscode.ProgressLocation.Notification,
title: `Creating support bundle for ${workspaceId}`,
cancellable: true,
},
);
if (!result.ok) {
if (result.cancelled) {
telemetry.abort("progress");
return;
}
telemetry.error();
this.logger.error("Support bundle failed", result.error);
vscode.window.showErrorMessage(
escapeNotificationLinks(
`Support bundle failed: ${toError(result.error).message}`,
),
);
return;
}
const action = await vscode.window.showInformationMessage(
`Support bundle saved to ${result.value.fsPath}`,
"Reveal in File Explorer",
);
if (action === "Reveal in File Explorer") {
await vscode.commands.executeCommand("revealFileInOS", result.value);
}
}
private promptSupportBundlePath(): Thenable<vscode.Uri | undefined> {
const defaultName = `coder-support-${Math.floor(Date.now() / 1000)}.zip`;
return vscode.window.showSaveDialog({
defaultUri: vscode.Uri.file(path.join(os.homedir(), defaultName)),
filters: { "Zip files": ["zip"] },
title: "Save Support Bundle",
});
}
/** Modal disclosure of what a support bundle collects; the CLI's own prompt is suppressed. */
private async confirmSupportBundleCollection(): Promise<boolean> {
const detail = [
"A support bundle may contain sensitive information. It collects:",
"",
"\u2022 Deployment and workspace diagnostics",
"\u2022 Coder extension and connection logs from recent VS Code windows",
"\u2022 Remote SSH extension logs",
"\u2022 Locally recorded telemetry",
"\u2022 Coder extension settings",
"",
"Review the bundle before sharing it.",
].join("\n");
const choice = await vscode.window.showInformationMessage(
"Create a support bundle?",
{ modal: true, detail },
"Continue",
);
return choice === "Continue";
}
public async exportTelemetry(): Promise<void> {
await this.diagnosticTelemetry.trace("export_telemetry", (telemetry) =>
this.runExportTelemetry(telemetry),
);
}
private async runExportTelemetry(telemetry: DiagnosticTrace): Promise<void> {
await runExportTelemetryCommand(
this.pathResolver.getTelemetryPath(),
this.logger,
() => this.telemetryService.flush(),
this.telemetryService.getContext(),
telemetry,
);
}
/** Open the generated SSH config, picking a file when several exist. */
public async openSshConfig(): Promise<void> {
const configPath =
this.connectedSshConfigPath() ?? (await this.pickSshConfigPath());
if (!configPath) {
return;
}
try {
await openFile(configPath);
} catch {
vscode.window.showInformationMessage(NO_SSH_CONFIG_MESSAGE);
return;
}
// The file is rewritten on every connection, so edits would be lost.
await vscode.commands.executeCommand(
"workbench.action.files.setActiveEditorReadonlyInSession",
);
}
/** The file serving this window's connection, if it has one. */
private connectedSshConfigPath(): string | undefined {
try {
// remoteAuthority is a proposed API; our own vscode module may not read it.
const authority = vscodeProposed.env.remoteAuthority;
const parts = authority ? parseRemoteAuthority(authority) : null;
return parts
? this.pathResolver.getSshConfigPath(
parts.safeHostname,
hostEditorId(parts.sshHost),
)
: undefined;
} catch {
// Malformed Coder authority or unavailable API; fall back to the picker.
return undefined;
}
}
/** Ask which config to open, of this editor's prefixes and the legacy one. */
private async pickSshConfigPath(): Promise<string | undefined> {
const files = await readdirOrEmpty(this.pathResolver.getSshConfigDir());
const items = [...new Set([currentEditorId(), LegacyEditorId])].flatMap(
(editorId) =>
files
.map((file) => this.pathResolver.parseSshConfigFile(file, editorId))
.filter((safeHostname) => safeHostname !== undefined)
.map((safeHostname) => ({
label: safeHostname,
// Which hosts it serves; two files can share a deployment.
description: `coder-${editorId}.${safeHostname}--*`,
path: this.pathResolver.getSshConfigPath(safeHostname, editorId),
})),
);
if (items.length === 0) {
vscode.window.showInformationMessage(NO_SSH_CONFIG_MESSAGE);
return undefined;
}
if (items.length === 1) {
return items[0].path;
}
const picked = await vscode.window.showQuickPick(items, {
title: "Open generated SSH configuration",
placeHolder: "Select a deployment",
});
return picked?.path;
}
/**
* 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> {
await this.authTelemetry.traceLogout(() => this.performLogout());
}
private async performLogout(): Promise<AuthLogoutOutcome> {
const deployment = this.deploymentManager.getCurrentDeployment();
if (!this.deploymentManager.isAuthenticated() || !deployment) {
return { success: false, reason: "not_authenticated" };
}
const auth = await this.secretsManager.getSessionAuthForUrl(deployment.url);
const signOutCli = await this.askSignOutCli(auth);
if (signOutCli === undefined) {
return { success: false, reason: "user_dismissed" };
}
// Another window may have switched deployments while the prompt was open.
if (this.deploymentManager.getCurrentDeployment()?.url !== deployment.url) {
return { success: false, reason: "not_authenticated" };
}
this.logger.debug("Logging out");
await this.deploymentManager.clearDeployment("logout");
const cleared = await this.cliManager.clearCredentials(deployment.url, {
signOutCli,
});
await this.secretsManager.clearAllAuthData(deployment.safeHostname);
if (!cleared) {
vscode.window
.showWarningMessage(
'You\'ve been logged out of Coder, but some credentials could not be removed. Log out again to retry, or run "coder logout" in a terminal.',
"Show Output",
)
.then((action) => {
if (action === "Show Output") {
this.logger.show();
}
});
return { success: false, reason: "cleanup_incomplete" };
}
this.showLogoutMessage();
this.logger.debug("Logout complete");
return { success: true };
}
private showLogoutMessage(): void {
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);
});
}
});
}
/** Whether to sign the CLI out too. Asks when it holds this session's token; undefined when dismissed. */
private async askSignOutCli(
auth: SessionAuth | undefined,
): Promise<boolean | undefined> {
if (!auth || !(await this.cliManager.holdsToken(auth.url, auth.token))) {
return false;
}
// The CLI cannot refresh an OAuth token and logout revokes it, so there is nothing to keep.
if (auth.oauth) {
return true;
}
const action = await vscodeProposed.window.showWarningMessage(
"Sign out of the Coder CLI too?",
{
useCustom: true,
modal: true,
detail: `${auth.url}\n\nThe Coder CLI is signed in with this session. Signing it out also signs out other tools that rely on it.`,
},
"Sign Out",
"Keep Signed In",
);
if (action === undefined) {
return undefined;
}
return action === "Sign Out";
}
/**
* 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.authTelemetry.traceLogin("switch_deployment", (trace) =>
this.performLogin(undefined, trace.setMethod),
);
}
/**
* 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) {
const signOutCli = await this.askSignOutCli(auth);
if (signOutCli === undefined) {
return;
}
await this.cliManager.clearCredentials(auth.url, { signOutCli });
}
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.${isKeyringEnabled(vscode.workspace.getConfiguration()) ? " This also signs the Coder CLI out where it shares a session." : ""}`,
},
"Remove All",
);
if (confirm === "Remove All") {
// One at a time: `coder logout` rewrites the whole keyring entry.
for (const h of selected.hostnames) {
const auth = await this.secretsManager.getSessionAuth(h);
if (auth?.url) {
await this.cliManager.clearCredentials(auth.url, {
signOutCli: await this.cliManager.holdsToken(
auth.url,
auth.token,
),
});
}
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(
getRecommendedSshSettings(vscode.workspace.getConfiguration()),
);
if (entries.length === 0) {
vscode.window.showInformationMessage(
"No recommended SSH settings are supported by the installed Remote SSH extension.",
);
return;
}
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> {
await openInBrowser(this.requireExtensionBaseUrl(), "/templates");
}
/**
* 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) {
await this.openWorkspaceInDashboard(item.workspace, "workspace");
} else if (this.workspace && this.remoteWorkspaceClient) {
await openInBrowser(
this.requireRemoteBaseUrl(),
`/@${createWorkspaceIdentifier(this.workspace)}`,
);
} 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