-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathcopilotCLIChatSessionsContribution.ts
More file actions
2773 lines (2453 loc) · 121 KB
/
copilotCLIChatSessionsContribution.ts
File metadata and controls
2773 lines (2453 loc) · 121 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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import type { Attachment, SessionOptions, SweCustomAgent } from '@github/copilot/sdk';
import * as l10n from '@vscode/l10n';
import * as vscode from 'vscode';
import { ChatExtendedRequestHandler, ChatSessionProviderOptionItem, Uri } from 'vscode';
import { IRunCommandExecutionService } from '../../../platform/commands/common/runCommandExecutionService';
import { ConfigKey, IConfigurationService } from '../../../platform/configuration/common/configurationService';
import { INativeEnvService } from '../../../platform/env/common/envService';
import { IVSCodeExtensionContext } from '../../../platform/extContext/common/extensionContext';
import { IFileSystemService } from '../../../platform/filesystem/common/fileSystemService';
import { IGitExtensionService } from '../../../platform/git/common/gitExtensionService';
import { getGitHubRepoInfoFromContext, IGitService, RepoContext } from '../../../platform/git/common/gitService';
import { toGitUri } from '../../../platform/git/common/utils';
import { derivePullRequestState } from '../../../platform/github/common/githubAPI';
import { IOctoKitService } from '../../../platform/github/common/githubService';
import { ILogService } from '../../../platform/log/common/logService';
import { IPromptsService, ParsedPromptFile } from '../../../platform/promptFiles/common/promptsService';
import { ITelemetryService } from '../../../platform/telemetry/common/telemetry';
import { IWorkspaceService } from '../../../platform/workspace/common/workspaceService';
import { isUri } from '../../../util/common/types';
import { DeferredPromise, disposableTimeout, IntervalTimer, SequencerByKey } from '../../../util/vs/base/common/async';
import { CancellationToken } from '../../../util/vs/base/common/cancellation';
import { isCancellationError } from '../../../util/vs/base/common/errors';
import { Emitter, Event } from '../../../util/vs/base/common/event';
import { Disposable, DisposableStore, IDisposable, IReference } from '../../../util/vs/base/common/lifecycle';
import { relative } from '../../../util/vs/base/common/path';
import { basename, dirname, extUri, isEqual } from '../../../util/vs/base/common/resources';
import { StopWatch } from '../../../util/vs/base/common/stopwatch';
import { URI } from '../../../util/vs/base/common/uri';
import { EXTENSION_ID } from '../../common/constants';
import { ChatVariablesCollection, extractDebugTargetSessionIds, isPromptFile } from '../../prompt/common/chatVariablesCollection';
import { IToolsService } from '../../tools/common/toolsService';
import { IChatSessionMetadataStore, RepositoryProperties, StoredModeInstructions } from '../common/chatSessionMetadataStore';
import { IChatSessionWorkspaceFolderService } from '../common/chatSessionWorkspaceFolderService';
import { IChatSessionWorktreeCheckpointService } from '../common/chatSessionWorktreeCheckpointService';
import { IChatSessionWorktreeService } from '../common/chatSessionWorktreeService';
import { FolderRepositoryInfo, FolderRepositoryMRUEntry, IFolderRepositoryManager, IsolationMode } from '../common/folderRepositoryManager';
import { isUntitledSessionId } from '../common/utils';
import { emptyWorkspaceInfo, getWorkingDirectory, isIsolationEnabled, IWorkspaceInfo } from '../common/workspaceInfo';
import { ICustomSessionTitleService } from '../copilotcli/common/customSessionTitleService';
import { IChatDelegationSummaryService } from '../copilotcli/common/delegationSummaryService';
import { getCopilotCLISessionDir } from '../copilotcli/node/cliHelpers';
import { ICopilotCLIAgents, ICopilotCLIModels, ICopilotCLISDK, isWelcomeView } from '../copilotcli/node/copilotCli';
import { CopilotCLIPromptResolver } from '../copilotcli/node/copilotcliPromptResolver';
import { builtinSlashSCommands, CopilotCLICommand, copilotCLICommands, ICopilotCLISession } from '../copilotcli/node/copilotcliSession';
import { ICopilotCLISessionItem, ICopilotCLISessionService } from '../copilotcli/node/copilotcliSessionService';
import { buildMcpServerMappings } from '../copilotcli/node/mcpHandler';
import { ICopilotCLISessionTracker } from '../copilotcli/vscode-node/copilotCLISessionTracker';
import { ICopilotCLIChatSessionItemProvider } from './copilotCLIChatSessions';
import { ICopilotCLIFolderMruService } from './copilotCLIFolderMru';
import { convertReferenceToVariable } from './copilotCLIPromptReferences';
import { ICopilotCLITerminalIntegration, TerminalOpenLocation } from './copilotCLITerminalIntegration';
import { CopilotCloudSessionsProvider } from './copilotCloudSessionsProvider';
const REPOSITORY_OPTION_ID = 'repository';
const _sessionWorktreeIsolationCache = new Map<string, boolean>();
const BRANCH_OPTION_ID = 'branch';
const ISOLATION_OPTION_ID = 'isolation';
const LAST_USED_ISOLATION_OPTION_KEY = 'github.copilot.cli.lastUsedIsolationOption';
const OPEN_REPOSITORY_COMMAND_ID = 'github.copilot.cli.sessions.openRepository';
const OPEN_IN_COPILOT_CLI_COMMAND_ID = 'github.copilot.cli.openInCopilotCLI';
const MAX_MRU_ENTRIES = 10;
const CHECK_FOR_STEERING_DELAY = 100; // ms
// When we start new sessions, we don't have the real session id, we have a temporary untitled id.
// We also need this when we open a session and later run it.
// When opening the session for readonly mode we store it here and when run the session we read from here instead of opening session in readonly mode again.
const _sessionBranch: Map<string, string | undefined> = new Map();
const _sessionIsolation: Map<string, IsolationMode | undefined> = new Map();
const _invalidCopilotCLISessionIdsWithErrorMessage = new Map<string, string>();
namespace SessionIdForCLI {
export function getResource(sessionId: string): vscode.Uri {
return vscode.Uri.from({
scheme: 'copilotcli', path: `/${sessionId}`,
});
}
export function parse(resource: vscode.Uri): string {
return resource.path.slice(1);
}
export function isCLIResource(resource: vscode.Uri): boolean {
return resource.scheme === 'copilotcli';
}
}
/**
* Escape XML special characters
*/
function escapeXml(text: string): string {
return text
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function getIssueRuntimeInfo(): { readonly platform: string; readonly vscodeInfo: string; readonly extensionVersion: string } {
const extensionVersion = vscode.extensions.getExtension(EXTENSION_ID)?.packageJSON?.version;
return {
platform: `${process.platform}-${process.arch}`,
vscodeInfo: `${vscode.env.appName} ${vscode.version}`,
extensionVersion: extensionVersion ?? 'unknown'
};
}
function getSessionLoadFailureIssueInfo(invalidSessionMessage: string): { readonly issueBody: string; readonly issueUrl: string } {
const runtimeInfo = getIssueRuntimeInfo();
const issueTitle = '[Copilot CLI] Failed to load chat session';
const issueBody = `## Description\n\nFailed to load a Copilot CLI chat session.\n\n## Environment\n\n- Platform: ${runtimeInfo.platform}\n- VS Code: ${runtimeInfo.vscodeInfo}\n- Chat Extension Version: ${runtimeInfo.extensionVersion}\n\n## Error\n\n\`\`\`\n${invalidSessionMessage}\n\`\`\``;
const issueUrl = `https://github.com/microsoft/vscode/issues/new?title=${encodeURIComponent(issueTitle)}&body=${encodeURIComponent(issueBody)}`;
return { issueBody, issueUrl };
}
/**
* Resolves candidate session directories for a CLI terminal, ordered by
* terminal affinity.
*
* Sessions whose owning terminal matches `terminal` are returned first so the
* link provider's file-existence probing hits the correct session-state dir
* before unrelated ones. Unrelated sessions are still included at the tail
* because a new session may not have registered its terminal yet (session IDs
* arrive later via MCP?).
*/
export async function resolveSessionDirsForTerminal(
sessionTracker: ICopilotCLISessionTracker,
terminal: vscode.Terminal,
): Promise<Uri[]> {
const activeIds = sessionTracker.getSessionIds();
const matching: Uri[] = [];
const rest: Uri[] = [];
for (const id of activeIds) {
const sessionTerminal = await sessionTracker.getTerminal(id);
const dir = Uri.file(getCopilotCLISessionDir(id));
if (sessionTerminal === terminal) {
matching.push(dir);
} else {
rest.push(dir);
}
}
return [...matching, ...rest];
}
export class CopilotCLIChatSessionItemProvider extends Disposable implements vscode.ChatSessionItemProvider, ICopilotCLIChatSessionItemProvider {
// When we start an untitled CLI session, the id of the session is `untitled:xyz`
// As soon as we create a CLI session we have the real session id, lets say `cli-1234`
// Once the session completes, this untitled session `untitled:xyz` will get swapped with the real session id `cli-1234`
// However if the session items provider is called while the session is still running, we need to return the same old `untitled:xyz` session id back to core.
// There's an issue in core (about holding onto ref of the Chat Model).
// As a temporary solution, return the same untitled session id back to core until the session is completed.
public readonly untitledSessionIdMapping = new Map<string, string>();
/**
* Until the untitled session is properly swappped with the new session, we should keep track of this mapping.
* When VS Code asks for the session, always return the old untitled session Uri.
*/
public readonly sdkToUntitledUriMapping = new Map<string, Uri>();
private readonly _onDidChangeChatSessionItems = this._register(new Emitter<void>());
public readonly onDidChangeChatSessionItems: Event<void> = this._onDidChangeChatSessionItems.event;
private readonly _onDidCommitChatSessionItem = this._register(new Emitter<{ original: vscode.ChatSessionItem; modified: vscode.ChatSessionItem }>());
public readonly onDidCommitChatSessionItem: Event<{ original: vscode.ChatSessionItem; modified: vscode.ChatSessionItem }> = this._onDidCommitChatSessionItem.event;
constructor(
@ICopilotCLISessionService private readonly copilotcliSessionService: ICopilotCLISessionService,
@ICopilotCLISessionTracker private readonly sessionTracker: ICopilotCLISessionTracker,
@ICopilotCLITerminalIntegration private readonly terminalIntegration: ICopilotCLITerminalIntegration,
@IChatSessionMetadataStore private readonly chatSessionMetadataStore: IChatSessionMetadataStore,
@IChatSessionWorktreeService private readonly worktreeManager: IChatSessionWorktreeService,
@IRunCommandExecutionService private readonly commandExecutionService: IRunCommandExecutionService,
@IChatSessionWorkspaceFolderService private readonly workspaceFolderService: IChatSessionWorkspaceFolderService,
@IFolderRepositoryManager private readonly folderRepositoryManager: IFolderRepositoryManager,
@IGitService private readonly gitService: IGitService,
@IOctoKitService private readonly octoKitService: IOctoKitService,
@ILogService private readonly logService: ILogService,
@IConfigurationService configurationService: IConfigurationService,
) {
super();
this._register(this.terminalIntegration);
// Resolve session dirs for terminal links. See resolveSessionDirsForTerminal.
this.terminalIntegration.setSessionDirResolver(terminal =>
resolveSessionDirsForTerminal(this.sessionTracker, terminal)
);
this._register(this.copilotcliSessionService.onDidChangeSessions(() => {
this.notifySessionsChange();
}));
}
/**
* We should remove this or move this to CopilotCLISessionService
*/
public isNewSession(session: string) {
return isUntitledSessionId(session);
}
public notifySessionsChange(): void {
this._onDidChangeChatSessionItems.fire();
}
public async refreshSession(refreshOptions: { reason: 'update'; sessionId: string } | { reason: 'delete'; sessionId: string }): Promise<void> {
this._onDidChangeChatSessionItems.fire();
}
public swap(original: vscode.ChatSessionItem, modified: vscode.ChatSessionItem): void {
this._onDidCommitChatSessionItem.fire({ original, modified });
}
public async provideChatSessionItems(token: vscode.CancellationToken): Promise<vscode.ChatSessionItem[]> {
const sessions = await this.copilotcliSessionService.getAllSessions(token);
const diskSessions = await Promise.all(sessions.map(async session => this.toChatSessionItem(session)));
const count = diskSessions.length;
this.commandExecutionService.executeCommand('setContext', 'github.copilot.chat.cliSessionsEmpty', count === 0);
return diskSessions;
}
private shouldShowBadge(): boolean {
const repositories = this.gitService.repositories
.filter(repository => repository.kind !== 'worktree');
return vscode.workspace.workspaceFolders === undefined || // empty window
vscode.workspace.isAgentSessionsWorkspace || // agent sessions workspace
repositories.length > 1; // multiple repositories
}
public async toChatSessionItem(session: ICopilotCLISessionItem): Promise<vscode.ChatSessionItem> {
const resource = this.sdkToUntitledUriMapping.get(session.id) ?? SessionIdForCLI.getResource(this.untitledSessionIdMapping.get(session.id) ?? session.id);
const worktreeProperties = await this.worktreeManager.getWorktreeProperties(session.id);
const workingDirectory = worktreeProperties?.worktreePath ? vscode.Uri.file(worktreeProperties.worktreePath)
: session.workingDirectory;
const label = session.label;
// Badge
let badge: vscode.MarkdownString | undefined;
if (this.shouldShowBadge()) {
if (worktreeProperties?.repositoryPath) {
// Worktree
const repositoryPathUri = vscode.Uri.file(worktreeProperties.repositoryPath);
const isTrusted = await vscode.workspace.isResourceTrusted(repositoryPathUri);
const badgeIcon = isTrusted ? '$(repo)' : '$(workspace-untrusted)';
badge = new vscode.MarkdownString(`${badgeIcon} ${basename(repositoryPathUri)}`);
badge.supportThemeIcons = true;
} else if (workingDirectory) {
// Workspace
const isTrusted = await vscode.workspace.isResourceTrusted(workingDirectory);
const badgeIcon = isTrusted ? '$(folder)' : '$(workspace-untrusted)';
badge = new vscode.MarkdownString(`${badgeIcon} ${basename(workingDirectory)}`);
badge.supportThemeIcons = true;
}
}
// Statistics (only returned for trusted workspace/worktree folders)
const changes: vscode.ChatSessionChangedFile2[] = [];
if (worktreeProperties?.repositoryPath && await vscode.workspace.isResourceTrusted(vscode.Uri.file(worktreeProperties.repositoryPath))) {
// Worktree
changes.push(...(await this.worktreeManager.getWorktreeChanges(session.id) ?? []));
} else if (workingDirectory && await vscode.workspace.isResourceTrusted(workingDirectory)) {
// Workspace
const workspaceChanges = await this.workspaceFolderService.getWorkspaceChanges(session.id) ?? [];
changes.push(...workspaceChanges.map(change => new vscode.ChatSessionChangedFile2(
vscode.Uri.file(change.filePath),
change.originalFilePath
? toGitUri(vscode.Uri.file(change.originalFilePath), 'HEAD')
: undefined,
change.modifiedFilePath
? vscode.Uri.file(change.modifiedFilePath)
: undefined,
change.statistics.additions,
change.statistics.deletions)));
}
// Status
const status = session.status ?? vscode.ChatSessionStatus.Completed;
// Metadata
let metadata: { readonly [key: string]: unknown };
if (worktreeProperties) {
// Worktree
metadata = {
autoCommit: worktreeProperties.autoCommit !== false,
baseCommit: worktreeProperties?.baseCommit,
baseBranchName: worktreeProperties.version === 2
? worktreeProperties.baseBranchName
: undefined,
baseBranchProtected: worktreeProperties.version === 2
? worktreeProperties.baseBranchProtected === true
: undefined,
branchName: worktreeProperties?.branchName,
isolationMode: IsolationMode.Worktree,
repositoryPath: worktreeProperties?.repositoryPath,
worktreePath: worktreeProperties?.worktreePath,
pullRequestUrl: worktreeProperties.version === 2
? worktreeProperties.pullRequestUrl
: undefined,
pullRequestState: worktreeProperties.version === 2
? worktreeProperties.pullRequestState
: undefined,
firstCheckpointRef: worktreeProperties.version === 2
? worktreeProperties.firstCheckpointRef
: undefined,
baseCheckpointRef: worktreeProperties.version === 2
? worktreeProperties.baseCheckpointRef
: undefined,
lastCheckpointRef: worktreeProperties.version === 2
? worktreeProperties.lastCheckpointRef
: undefined
} satisfies { readonly [key: string]: unknown };
} else {
// Workspace
const sessionRequestDetails = await this.chatSessionMetadataStore.getRequestDetails(session.id);
const repositoryProperties = await this.chatSessionMetadataStore.getRepositoryProperties(session.id);
let lastCheckpointRef: string | undefined;
for (let i = sessionRequestDetails.length - 1; i >= 0; i--) {
const checkpointRef = sessionRequestDetails[i]?.checkpointRef;
if (checkpointRef !== undefined) {
lastCheckpointRef = checkpointRef;
break;
}
}
const firstCheckpointRef = lastCheckpointRef
? `${lastCheckpointRef.slice(0, lastCheckpointRef.lastIndexOf('/'))}/0`
: undefined;
metadata = {
isolationMode: IsolationMode.Workspace,
repositoryPath: repositoryProperties?.repositoryPath,
branchName: repositoryProperties?.branchName,
baseBranchName: repositoryProperties?.baseBranchName,
workingDirectoryPath: workingDirectory?.fsPath,
firstCheckpointRef,
lastCheckpointRef
} satisfies { readonly [key: string]: unknown };
}
return {
resource,
label,
badge,
timing: session.timing,
changes,
status,
metadata,
} satisfies vscode.ChatSessionItem;
}
/**
* Detects a pull request for a session when the user opens it.
* If a PR is found, persists the URL and notifies the UI.
*/
public async detectPullRequestOnSessionOpen(sessionId: string): Promise<void> {
try {
const worktreeProperties = await this.worktreeManager.getWorktreeProperties(sessionId);
if (worktreeProperties?.version !== 2
|| worktreeProperties.pullRequestState === 'merged'
|| !worktreeProperties.branchName
|| !worktreeProperties.repositoryPath) {
this.logService.debug(`[CopilotCLIChatSessionItemProvider] Skipping PR detection on session open for ${sessionId}: version=${worktreeProperties?.version}, prState=${worktreeProperties?.version === 2 ? worktreeProperties.pullRequestState : 'n/a'}, branch=${!!worktreeProperties?.branchName}, repoPath=${!!worktreeProperties?.repositoryPath}`);
return;
}
this.logService.debug(`[CopilotCLIChatSessionItemProvider] Detecting PR on session open for ${sessionId}, branch=${worktreeProperties.branchName}, existingPrUrl=${worktreeProperties.pullRequestUrl ?? 'none'}`);
const prResult = await detectPullRequestFromGitHubAPI(
worktreeProperties.branchName,
worktreeProperties.repositoryPath,
this.gitService,
this.octoKitService,
this.logService,
);
if (prResult) {
const currentProperties = await this.worktreeManager.getWorktreeProperties(sessionId);
if (currentProperties?.version === 2
&& (currentProperties.pullRequestUrl !== prResult.url || currentProperties.pullRequestState !== prResult.state)) {
this.logService.debug(`[CopilotCLIChatSessionItemProvider] Updating PR metadata for ${sessionId}: url=${prResult.url}, state=${prResult.state} (was url=${currentProperties.pullRequestUrl ?? 'none'}, state=${currentProperties.pullRequestState ?? 'none'})`);
await this.worktreeManager.setWorktreeProperties(sessionId, {
...currentProperties,
pullRequestUrl: prResult.url,
pullRequestState: prResult.state,
changes: undefined,
});
this.notifySessionsChange();
} else {
this.logService.debug(`[CopilotCLIChatSessionItemProvider] PR metadata unchanged for ${sessionId}, skipping update`);
}
} else {
this.logService.debug(`[CopilotCLIChatSessionItemProvider] No PR found via GitHub API for ${sessionId}`);
}
} catch (error) {
this.logService.trace(`[CopilotCLIChatSessionItemProvider] Failed to detect pull request on session open for ${sessionId}: ${error instanceof Error ? error.message : String(error)}`);
}
}
public async createCopilotCLITerminal(location: TerminalOpenLocation = 'editor', name?: string, cwd?: string): Promise<void> {
// TODO@rebornix should be set by CLI
const terminalName = name || process.env.COPILOTCLI_TERMINAL_TITLE || l10n.t('Copilot CLI');
await this.terminalIntegration.openTerminal(terminalName, [], cwd, location);
}
public async resumeCopilotCLISessionInTerminal(sessionItem: vscode.ChatSessionItem): Promise<void> {
const id = SessionIdForCLI.parse(sessionItem.resource);
const existingTerminal = await this.sessionTracker.getTerminal(id);
if (existingTerminal) {
existingTerminal.show();
return;
}
const terminalName = sessionItem.label || id;
const cliArgs = ['--resume', id];
const token = new vscode.CancellationTokenSource();
try {
const folderInfo = await this.folderRepositoryManager.getFolderRepository(id, undefined, token.token);
const cwd = folderInfo.worktree ?? folderInfo.repository ?? folderInfo.folder;
const terminal = await this.terminalIntegration.openTerminal(terminalName, cliArgs, cwd?.fsPath);
if (terminal) {
this.sessionTracker.setSessionTerminal(id, terminal);
this.terminalIntegration.setTerminalSessionDir(terminal, Uri.file(getCopilotCLISessionDir(id)));
}
} finally {
token.dispose();
}
}
}
function isBranchOptionFeatureEnabled(configurationService: IConfigurationService): boolean {
return configurationService.getConfig(ConfigKey.Advanced.CLIBranchSupport);
}
function isIsolationOptionFeatureEnabled(configurationService: IConfigurationService): boolean {
return configurationService.getConfig(ConfigKey.Advanced.CLIIsolationOption);
}
export class CopilotCLIChatSessionContentProvider extends Disposable implements vscode.ChatSessionContentProvider {
private readonly _onDidChangeChatSessionOptions = this._register(new Emitter<vscode.ChatSessionOptionChangeEvent>());
readonly onDidChangeChatSessionOptions = this._onDidChangeChatSessionOptions.event;
private readonly _onDidChangeChatSessionProviderOptions = this._register(new Emitter<void>());
readonly onDidChangeChatSessionProviderOptions = this._onDidChangeChatSessionProviderOptions.event;
private _currentSessionId: string | undefined;
private _selectedRepoForBranches: { repoUri: URI; headBranchName: string | undefined } | undefined;
private _displayedOptionIds = new Set<string>();
/**
* ID of the last used folder in an untitled workspace (for defaulting selection).
*/
private _lastUsedFolderIdInUntitledWorkspace: string | undefined;
constructor(
private readonly sessionItemProvider: CopilotCLIChatSessionItemProvider,
@ICopilotCLIAgents private readonly copilotCLIAgents: ICopilotCLIAgents,
@ICopilotCLISessionService private readonly sessionService: ICopilotCLISessionService,
@IChatSessionWorktreeService private readonly copilotCLIWorktreeManagerService: IChatSessionWorktreeService,
@IWorkspaceService private readonly workspaceService: IWorkspaceService,
@IFileSystemService private readonly fileSystem: IFileSystemService,
@IGitService private readonly gitService: IGitService,
@IFolderRepositoryManager private readonly folderRepositoryManager: IFolderRepositoryManager,
@IConfigurationService private readonly configurationService: IConfigurationService,
@ICustomSessionTitleService private readonly customSessionTitleService: ICustomSessionTitleService,
@IVSCodeExtensionContext private readonly context: IVSCodeExtensionContext,
@ILogService private readonly logService: ILogService,
@ICopilotCLIFolderMruService private readonly folderMruService: ICopilotCLIFolderMruService,
) {
super();
const originalRepos = this.getRepositoryOptionItems().length;
this._register(this.gitService.onDidFinishInitialization(() => {
if (originalRepos !== this.getRepositoryOptionItems().length) {
this._onDidChangeChatSessionProviderOptions.fire();
}
}));
this._register(this.gitService.onDidOpenRepository(() => {
if (originalRepos !== this.getRepositoryOptionItems().length) {
this._onDidChangeChatSessionProviderOptions.fire();
}
}));
this._register(this.workspaceService.onDidChangeWorkspaceFolders(() => {
this._onDidChangeChatSessionProviderOptions.fire();
}));
this._register(this.copilotCLIAgents.onDidChangeAgents(() => {
this._onDidChangeChatSessionProviderOptions.fire();
}));
}
public notifySessionOptionsChange(resource: vscode.Uri, updates: ReadonlyArray<{ optionId: string; value: string | vscode.ChatSessionProviderOptionItem }>): void {
this._onDidChangeChatSessionOptions.fire({ resource, updates });
}
public notifyProviderOptionsChange(): void {
this._onDidChangeChatSessionProviderOptions.fire();
}
private async getDefaultUntitledSessionRepositoryOption(copilotcliSessionId: string | undefined, token: vscode.CancellationToken) {
const repositories = this.isUntitledWorkspace() ? folderMRUToChatProviderOptions(await this.folderMruService.getRecentlyUsedFolders(token)) : this.getRepositoryOptionItems();
// Use FolderRepositoryManager to get folder/repository info (no trust check needed for UI population)
const folderInfo = copilotcliSessionId ? await this.folderRepositoryManager.getFolderRepository(copilotcliSessionId, undefined, token) : undefined;
const uri = folderInfo?.repository ?? folderInfo?.folder;
if (uri) {
return uri;
} else if (repositories.length) {
// No folder selected yet for this untitled session - use MRU or first available
const lastUsedFolderId = this._lastUsedFolderIdInUntitledWorkspace;
const firstRepo = (lastUsedFolderId && repositories.find(repo => repo.id === lastUsedFolderId)?.id) ?? repositories[0].id;
return Uri.file(firstRepo);
}
return undefined;
}
async provideChatSessionContent(resource: Uri, token: vscode.CancellationToken): Promise<vscode.ChatSession> {
const stopwatch = new StopWatch();
try {
const copilotcliSessionId = SessionIdForCLI.parse(resource);
const isUntitled = this.sessionItemProvider.isNewSession(copilotcliSessionId);
if (isUntitled) {
return await this.provideChatSessionContentForUntitledSession(resource, token);
} else {
return await this.provideChatSessionContentForExistingSession(resource, token);
}
} finally {
this.logService.info(`[CopilotCLIChatSessionContentProvider] provideChatSessionContent for ${resource.toString()} took ${stopwatch.elapsed()}ms`);
}
}
public trackLastUsedFolderInWelcomeView(folderUri: vscode.Uri): void {
// Update MRU tracking for untitled workspaces
if (isWelcomeView(this.workspaceService)) {
this._lastUsedFolderIdInUntitledWorkspace = folderUri.fsPath;
}
}
async provideChatSessionContentForUntitledSession(resource: Uri, token: vscode.CancellationToken): Promise<vscode.ChatSession> {
const copilotcliSessionId = SessionIdForCLI.parse(resource);
this._currentSessionId = copilotcliSessionId;
const folderRepo = await this.folderRepositoryManager.getFolderRepository(copilotcliSessionId, undefined, token);
const isUntitled = this.sessionItemProvider.isNewSession(copilotcliSessionId);
const [history, title] = await Promise.all([
isUntitled ? Promise.resolve([]) : this.getSessionHistory(copilotcliSessionId, folderRepo, token),
this.customSessionTitleService.getCustomSessionTitle(copilotcliSessionId),
]);
const options: Record<string, string | vscode.ChatSessionProviderOptionItem> = {};
// Use FolderRepositoryManager to get folder/repository info (no trust check needed for UI population)
const defaultRepo = await this.getDefaultUntitledSessionRepositoryOption(copilotcliSessionId, token);
if (defaultRepo) {
// Determine upfront whether the default repository/folder is trusted. We need to do
// this since the user should not be presented with a resource trust dialog in case the
// default repository/folder is not trusted.
const defaultRepoIsTrusted = await vscode.workspace.isResourceTrusted(defaultRepo);
if (defaultRepoIsTrusted) {
options[REPOSITORY_OPTION_ID] = defaultRepo.fsPath;
// Use the manager to track the selection for untitled sessions
this.trackLastUsedFolderInWelcomeView(defaultRepo);
this.folderRepositoryManager.setNewSessionFolder(copilotcliSessionId, defaultRepo);
// Check if the default folder is a git repo so the branch dropdown appears immediately
const repoInfo = await this.folderRepositoryManager.getRepositoryInfo(defaultRepo, token);
if (repoInfo.repository) {
this._selectedRepoForBranches = { repoUri: repoInfo.repository, headBranchName: repoInfo.headBranchName };
} else {
this._selectedRepoForBranches = undefined;
}
if (repoInfo.repository && isIsolationOptionFeatureEnabled(this.configurationService)) {
if (!_sessionIsolation.has(copilotcliSessionId)) {
const lastUsed = this.context.globalState.get<IsolationMode>(LAST_USED_ISOLATION_OPTION_KEY, IsolationMode.Workspace);
_sessionIsolation.set(copilotcliSessionId, lastUsed);
}
const isolationMode = _sessionIsolation.get(copilotcliSessionId)!;
options[ISOLATION_OPTION_ID] = {
id: isolationMode,
name: isolationMode === IsolationMode.Worktree ? l10n.t('Worktree') : l10n.t('Workspace'),
icon: new vscode.ThemeIcon(isolationMode === IsolationMode.Worktree ? 'worktree' : 'folder')
};
}
const shouldShowBranch = !isIsolationOptionFeatureEnabled(this.configurationService) || _sessionIsolation.get(copilotcliSessionId) === IsolationMode.Worktree;
const branchItems = await this.getBranchOptionItems();
if (branchItems.length > 0 && shouldShowBranch) {
_sessionBranch.set(copilotcliSessionId, branchItems[0].id);
options[BRANCH_OPTION_ID] = {
id: branchItems[0].id,
name: branchItems[0].name,
icon: new vscode.ThemeIcon('git-branch')
};
}
} else {
options[REPOSITORY_OPTION_ID] = '';
}
this.notifyProviderOptionsChange();
}
return {
title,
history,
activeResponseCallback: undefined,
requestHandler: undefined,
options: options
};
}
async provideChatSessionContentForExistingSession(resource: Uri, token: vscode.CancellationToken): Promise<vscode.ChatSession> {
const copilotcliSessionId = SessionIdForCLI.parse(resource);
this._currentSessionId = copilotcliSessionId;
// Fire-and-forget: detect PR when the user opens a session
void this.sessionItemProvider.detectPullRequestOnSessionOpen(copilotcliSessionId);
const folderRepo = await this.folderRepositoryManager.getFolderRepository(copilotcliSessionId, undefined, token);
const [history, title, folderInfo, worktreeProperties] = await Promise.all([
this.getSessionHistory(copilotcliSessionId, folderRepo, token),
this.customSessionTitleService.getCustomSessionTitle(copilotcliSessionId),
this.folderRepositoryManager.getFolderRepository(copilotcliSessionId, undefined, token),
this.copilotCLIWorktreeManagerService.getWorktreeProperties(copilotcliSessionId)
]);
const options: Record<string, string | vscode.ChatSessionProviderOptionItem> = {};
if (folderInfo.repository) {
options[REPOSITORY_OPTION_ID] = {
...toRepositoryOptionItem(folderInfo.repository),
locked: true
};
} else if (folderInfo.folder) {
const folderName = this.workspaceService.getWorkspaceFolderName(folderInfo.folder) || basename(folderInfo.folder);
options[REPOSITORY_OPTION_ID] = {
...toWorkspaceFolderOptionItem(folderInfo.folder, folderName),
locked: true
};
} else {
// Existing session with no folder info - show unknown
let folderName = l10n.t('Unknown');
if (this.workspaceService.getWorkspaceFolders().length === 1) {
folderName = this.workspaceService.getWorkspaceFolderName(this.workspaceService.getWorkspaceFolders()[0]) || folderName;
}
options[REPOSITORY_OPTION_ID] = {
id: '',
name: folderName,
icon: new vscode.ThemeIcon('folder'),
locked: true
};
}
if (worktreeProperties?.repositoryPath) {
const branchName = worktreeProperties.branchName;
const repoUri = vscode.Uri.file(worktreeProperties.repositoryPath);
this._selectedRepoForBranches = { repoUri, headBranchName: branchName };
options[BRANCH_OPTION_ID] = {
id: branchName,
name: branchName,
icon: new vscode.ThemeIcon('git-branch'),
locked: true
};
}
if (isIsolationOptionFeatureEnabled(this.configurationService)) {
const isWorktree = !!worktreeProperties;
options[ISOLATION_OPTION_ID] = {
id: isWorktree ? IsolationMode.Worktree : IsolationMode.Workspace,
name: isWorktree ? l10n.t('Worktree') : l10n.t('Workspace'),
icon: new vscode.ThemeIcon(isWorktree ? 'worktree' : 'folder'),
locked: true
};
}
// Ensure the branch option group is shown when we have a branch value but it's not displayed.
if (options[BRANCH_OPTION_ID] && !this._displayedOptionIds.has(BRANCH_OPTION_ID)) {
this.notifyProviderOptionsChange();
}
if (this.configurationService.getConfig(ConfigKey.Advanced.CLIForkSessionsEnabled)) {
return {
title,
history,
activeResponseCallback: undefined,
requestHandler: undefined,
options: options,
forkHandler: async (sessionResource, requestTurn, token) => {
const sessionId = SessionIdForCLI.parse(sessionResource);
return this.forkSession(sessionId, requestTurn?.id, token);
},
};
} else {
return {
title,
history,
activeResponseCallback: undefined,
requestHandler: undefined,
options: options,
};
}
}
private async forkSession(sessionId: string, requestId: string | undefined, token: CancellationToken): Promise<vscode.ChatSessionItem> {
const folderInfo = await this.folderRepositoryManager.getFolderRepository(sessionId, undefined, token);
const forkedSessionId = await this.sessionService.forkSession({ sessionId, requestId, workspace: folderInfo }, token);
const items = await this.sessionItemProvider.provideChatSessionItems(token);
const forkedSessionUri = SessionIdForCLI.getResource(forkedSessionId);
const item = items.find(i => isEqual(i.resource, forkedSessionUri));
if (!item) {
throw new Error(`Failed to find session item for forked session ${forkedSessionId}`);
}
return item;
}
private async getSessionHistory(sessionId: string, workspaceInfo: IWorkspaceInfo, token: vscode.CancellationToken) {
try {
_invalidCopilotCLISessionIdsWithErrorMessage.delete(sessionId);
const history = await this.sessionService.getChatHistory({ sessionId, workspace: workspaceInfo }, token);
return history;
} catch (error) {
if (!isUnknownEventTypeError(error)) {
throw error;
}
const partialHistory = await this.sessionService.tryGetPartialSesionHistory(sessionId);
if (partialHistory) {
_invalidCopilotCLISessionIdsWithErrorMessage.set(sessionId, error.message || String(error));
return partialHistory;
}
throw error;
}
}
async provideChatSessionProviderOptions(): Promise<vscode.ChatSessionProviderOptions> {
const optionGroups: vscode.ChatSessionProviderOptionGroup[] = [];
if (this._selectedRepoForBranches && isIsolationOptionFeatureEnabled(this.configurationService)) {
optionGroups.push({
id: ISOLATION_OPTION_ID,
name: l10n.t('Isolation'),
description: l10n.t('Pick Isolation Mode'),
items: [
{ id: IsolationMode.Workspace, name: l10n.t('Workspace'), icon: new vscode.ThemeIcon('folder') },
{ id: IsolationMode.Worktree, name: l10n.t('Worktree'), icon: new vscode.ThemeIcon('worktree') },
]
});
}
// Handle repository options based on workspace type
if (this.isUntitledWorkspace()) {
// For untitled workspaces, show last used repositories and "Open Repository..." command
const repositories = await this.folderMruService.getRecentlyUsedFolders(CancellationToken.None);
const items = folderMRUToChatProviderOptions(repositories);
items.splice(MAX_MRU_ENTRIES); // Limit to max entries
if (this._lastUsedFolderIdInUntitledWorkspace && !items.some(repo => repo.id === this._lastUsedFolderIdInUntitledWorkspace)) {
const uri = Uri.file(this._lastUsedFolderIdInUntitledWorkspace);
items.unshift(toWorkspaceFolderOptionItem(uri, basename(uri)));
}
const commands: vscode.Command[] = [];
commands.push({
command: OPEN_REPOSITORY_COMMAND_ID,
title: l10n.t('Browse folders...')
});
optionGroups.push({
id: REPOSITORY_OPTION_ID,
name: l10n.t('Folder'),
description: l10n.t('Pick Folder'),
items,
commands
});
} else {
const repositories = this.getRepositoryOptionItems();
if (repositories.length > 1) {
optionGroups.push({
id: REPOSITORY_OPTION_ID,
name: l10n.t('Folder'),
description: l10n.t('Pick Folder'),
items: repositories
});
}
}
if (this._selectedRepoForBranches && (isBranchOptionFeatureEnabled(this.configurationService) || (await this.isWorktreeIsolationSelected()))) {
const branchItems = await this.getBranchOptionItems(true);
if (branchItems.length > 0) {
optionGroups.push({
id: BRANCH_OPTION_ID,
name: l10n.t('Branch'),
description: l10n.t('Pick Branch'),
items: branchItems,
// icon: new vscode.ThemeIcon('git-branch')
});
}
}
this._displayedOptionIds.clear();
optionGroups.forEach(group => {
this._displayedOptionIds.add(group.id);
});
return { optionGroups };
}
private _branchRepositoryOptions?: { repoUri: Uri; items: Promise<vscode.ChatSessionProviderOptionItem[]> };
private async getBranchOptionItems(overrideListBranches = false): Promise<vscode.ChatSessionProviderOptionItem[]> {
if (!this._selectedRepoForBranches) {
return [];
}
if (!overrideListBranches && !isBranchOptionFeatureEnabled(this.configurationService)) {
return [];
}
const { repoUri, headBranchName } = this._selectedRepoForBranches;
if (!this._branchRepositoryOptions || !isEqual(repoUri, this._branchRepositoryOptions.repoUri)) {
this._branchRepositoryOptions = {
repoUri,
items: this.getBranchOptionItemsForRepository(repoUri, headBranchName)
};
}
return this._branchRepositoryOptions.items;
}
private readonly _getBranchOptionItemsForRepositorySequencer = new SequencerByKey<string>();
private async getBranchOptionItemsForRepository(repoUri: Uri, headBranchName: string | undefined): Promise<vscode.ChatSessionProviderOptionItem[]> {
const key = `${repoUri.toString()}${headBranchName}`;
return this._getBranchOptionItemsForRepositorySequencer.queue(key, async () => {
const refs = await this.gitService.getRefs(repoUri, { sort: 'committerdate' });
// Filter to local branches only (RefType.Head === 0)
const localBranches = refs.filter(ref => ref.type === 0 /* RefType.Head */ && ref.name);
// Build items with HEAD branch first
const items: vscode.ChatSessionProviderOptionItem[] = [];
let headItem: vscode.ChatSessionProviderOptionItem | undefined;
for (const ref of localBranches) {
const isHead = ref.name === headBranchName;
const item: vscode.ChatSessionProviderOptionItem = {
id: ref.name!,
name: ref.name!,
icon: new vscode.ThemeIcon('git-branch'),
// default: isHead
};
if (isHead) {
headItem = item;
} else {
items.push(item);
}
}
if (headItem) {
items.unshift(headItem);
}
return items;
});
}
/**
* Check if the current workspace is untitled (has no workspace folders).
*/
private isUntitledWorkspace(): boolean {
return this.workspaceService.getWorkspaceFolders().length === 0;
}
/**
* Check if the current session has worktree isolation selected.
* Used to determine whether the branch picker should be shown.
*/
private async isWorktreeIsolationSelected(): Promise<boolean> {
if (!isIsolationOptionFeatureEnabled(this.configurationService)) {
return true;
}
if (!this._currentSessionId) {
return false;
}
const sessionId = this._currentSessionId;
const cached = _sessionWorktreeIsolationCache.get(sessionId);
if (typeof cached === 'boolean') {
return cached;
}
if (isUntitledSessionId(sessionId)) {
const isWorktree = _sessionIsolation.get(sessionId) === IsolationMode.Worktree;
_sessionWorktreeIsolationCache.set(sessionId, isWorktree);
return isWorktree;
}
if (_sessionIsolation.get(sessionId) === IsolationMode.Worktree) {
_sessionWorktreeIsolationCache.set(sessionId, true);
return true;
}
const folderInfo = await this.folderRepositoryManager.getFolderRepository(sessionId, undefined, CancellationToken.None);
const isWorktree = !!folderInfo.worktreeProperties;
_sessionWorktreeIsolationCache.set(sessionId, isWorktree);
return isWorktree;
}
private getRepositoryOptionItems() {
// Exclude worktrees from the repository list
const repositories = this.gitService.repositories
.filter(repository => repository.kind !== 'worktree')
.filter(repository => {
if (this.isUntitledWorkspace()) {
return true;
}
// Only include repositories that belong to one of the workspace folders
return this.workspaceService.getWorkspaceFolder(repository.rootUri) !== undefined;
});
const repoItems = repositories
.map(repository => toRepositoryOptionItem(repository));
// In multi-root workspaces, also include workspace folders that don't have any git repos
const workspaceFolders = this.workspaceService.getWorkspaceFolders();
if (workspaceFolders.length) {
// Find workspace folders that contain git repos
const foldersWithRepos = new Set<string>();
for (const repo of repositories) {
const folder = this.workspaceService.getWorkspaceFolder(repo.rootUri);
if (folder) {
foldersWithRepos.add(folder.fsPath);
}
}
// Add workspace folders that don't have any git repos
for (const folder of workspaceFolders) {
if (!foldersWithRepos.has(folder.fsPath)) {
const folderName = this.workspaceService.getWorkspaceFolderName(folder);
repoItems.push(toWorkspaceFolderOptionItem(folder, folderName));
}
}
}
return repoItems.sort((a, b) => a.name.localeCompare(b.name));
}
// Handle option changes for a session (store current state in a map)
async provideHandleOptionsChange(resource: Uri, updates: ReadonlyArray<vscode.ChatSessionOptionUpdate>, token: vscode.CancellationToken): Promise<void> {
const sessionId = SessionIdForCLI.parse(resource);
this._currentSessionId = sessionId;
const wasBranchOptionShow = !!this._selectedRepoForBranches;
let triggerProviderOptionsChange = false;
for (const update of updates) {
if (update.optionId === REPOSITORY_OPTION_ID && typeof update.value === 'string' && this.sessionItemProvider.isNewSession(sessionId)) {
const folder = vscode.Uri.file(update.value);
if (isEqual(folder, this._selectedRepoForBranches?.repoUri)) {
continue;
}
_sessionBranch.delete(sessionId);
if ((await checkPathExists(folder, this.fileSystem))) {
this.trackLastUsedFolderInWelcomeView(folder);
this.folderRepositoryManager.setNewSessionFolder(sessionId, folder);
// Check if the selected folder is a git repo to show/hide branch dropdown
const repoInfo = await this.folderRepositoryManager.getRepositoryInfo(folder, token);
this._selectedRepoForBranches = repoInfo.repository
? { repoUri: repoInfo.repository, headBranchName: repoInfo.headBranchName }
: undefined;
// When switching to a new repository, we need to update the branch selection for the session. Push an
// update to the session to select the first branch in the new repo and then we will fire an event so
// that the branches from the new repository are loaded in the dropdown.
if (this._selectedRepoForBranches && updates.length === 1) {
const sessionChanges: { optionId: string; value: string | vscode.ChatSessionProviderOptionItem }[] = [];
const branchItems = await this.getBranchOptionItems();
if (branchItems.length > 0) {
const branchItem = branchItems[0];
_sessionBranch.set(sessionId, branchItem.id);
sessionChanges.push({
optionId: BRANCH_OPTION_ID,
value: {
id: branchItem.id,
name: branchItem.name,
icon: new vscode.ThemeIcon('git-branch')
}
});
}
if (sessionChanges.length > 0) {
this.notifySessionOptionsChange(resource, sessionChanges);
}