-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathcopilotCLIChatSessions.ts
More file actions
2514 lines (2234 loc) · 111 KB
/
copilotCLIChatSessions.ts
File metadata and controls
2514 lines (2234 loc) · 111 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, ChatRequestTurn2, 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 { 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, 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 { ResourceMap } from '../../../util/vs/base/common/map';
import { relative } from '../../../util/vs/base/common/path';
import { basename, dirname, extUri } 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 { GitBranchNameGenerator } from '../../prompt/node/gitBranch';
import { IAgentSessionsWorkspace } from '../common/agentSessionsWorkspace';
import { IChatSessionMetadataStore, 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 { 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 { ICopilotCLIFolderMruService } from './copilotCLIFolderMru';
import { convertReferenceToVariable } from './copilotCLIPromptReferences';
import { ICopilotCLITerminalIntegration, TerminalOpenLocation } from './copilotCLITerminalIntegration';
import { CopilotCloudSessionsProvider } from './copilotCloudSessionsProvider';
const COPILOT_WORKTREE_PATTERN = 'copilot-worktree-';
/**
* ODO:
* 1. We cannot use setNewSessionFolder hence we need a way to track what is the folder we need to use when creating new sessions.
* 2. When we invoke initializeFolderRepository we should pass the folder thats been selected by the user.
* 3. Verify all command handlers do the exact same thing
* 4. Remove this._currentSessionId
* 5. Remove isWorktreeIsolationSelected and update to account for dropdown.
* 6. Is chatSessionContext?.initialSessionOptions still valid with new API
* 7. Validated selected MRU item
*
* Cases to cover:
* 1. Hook up the dropdowns for empty workspace folders as well
* 2. In mult-root workspace we need to display workspace/worktree dropdown along with the repo dropdown
* 3. Temporarily lock/unlock dropdowns while creating session
* 4. Lock dropdowns when opening an existing session
* 5. Browse folders command in empty workspaces
* 6. Branch dropdown should only be displayed when we select a folder/repo thats a git repo.
*
* Test:
* 1. All of the above
* 2. Forking sessions
* 3. Steering messages
* 4. Queued messages
* 5. Selecting a new folder in browse folders command should end up with that folder in the dropdown.
* 6. Delegate from CLI to Cloud
* 7. Delegate from Local to CLI
*/
export interface ICopilotCLIChatSessionItemProvider extends IDisposable {
refreshSession(refreshOptions: { reason: 'update'; sessionId: string } | { reason: 'delete'; sessionId: string }): Promise<void>;
}
const REPOSITORY_OPTION_ID = 'repository';
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];
}
function isBranchOptionFeatureEnabled(configurationService: IConfigurationService): boolean {
return configurationService.getConfig(ConfigKey.Advanced.CLIBranchSupport);
}
function isIsolationOptionFeatureEnabled(configurationService: IConfigurationService): boolean {
return configurationService.getConfig(ConfigKey.Advanced.CLIIsolationOption);
}
function toRepositoryOptionItem(repository: RepoContext | Uri, isDefault: boolean = false): ChatSessionProviderOptionItem {
const repositoryUri = isUri(repository) ? repository : repository.rootUri;
const repositoryIcon = isUri(repository) ? 'repo' : repository.kind === 'repository' ? 'repo' : 'archive';
const repositoryName = repositoryUri.path.split('/').pop() ?? repositoryUri.toString();
return {
id: repositoryUri.fsPath,
name: repositoryName,
icon: new vscode.ThemeIcon(repositoryIcon),
default: isDefault
} satisfies vscode.ChatSessionProviderOptionItem;
}
function toWorkspaceFolderOptionItem(workspaceFolderUri: URI, name: string): ChatSessionProviderOptionItem {
return {
id: workspaceFolderUri.fsPath,
name: name,
icon: new vscode.ThemeIcon('folder'),
} satisfies vscode.ChatSessionProviderOptionItem;
}
export class CopilotCLIChatSessionContentProvider extends Disposable implements vscode.ChatSessionContentProvider, ICopilotCLIChatSessionItemProvider {
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;
private readonly controller: vscode.ChatSessionItemController;
private readonly newSessions = new ResourceMap<vscode.ChatSessionItem>();
/**
* ID of the last used folder in an untitled workspace (for defaulting selection).
*/
private _lastUsedFolderIdInUntitledWorkspace?: { kind: 'folder' | 'repo'; uri: vscode.Uri; lastAccessed: number };
constructor(
@ICopilotCLISessionService private readonly sessionService: ICopilotCLISessionService,
@IChatSessionMetadataStore private readonly chatSessionMetadataStore: IChatSessionMetadataStore,
@IChatSessionWorktreeService private readonly copilotCLIWorktreeManagerService: IChatSessionWorktreeService,
@IWorkspaceService private readonly workspaceService: IWorkspaceService,
@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,
@ICopilotCLISessionTracker private readonly sessionTracker: ICopilotCLISessionTracker,
@ICopilotCLITerminalIntegration private readonly terminalIntegration: ICopilotCLITerminalIntegration,
@IRunCommandExecutionService private readonly commandExecutionService: IRunCommandExecutionService,
@IChatSessionWorkspaceFolderService private readonly workspaceFolderService: IChatSessionWorkspaceFolderService,
@IOctoKitService private readonly octoKitService: IOctoKitService,
@ILogService private readonly logService: ILogService,
@IAgentSessionsWorkspace private readonly _agentSessionsWorkspace: IAgentSessionsWorkspace,
@ICopilotCLIFolderMruService private readonly copilotCLIFolderMruService: ICopilotCLIFolderMruService,
) {
super();
this._register(this.terminalIntegration);
// Resolve session dirs for terminal links. See resolveSessionDirsForTerminal.
this.terminalIntegration.setSessionDirResolver(terminal =>
resolveSessionDirsForTerminal(this.sessionTracker, terminal)
);
let isRefreshing = false;
const controller = this.controller = this._register(vscode.chat.createChatSessionItemController(
'copilotcli',
async () => {
if (isRefreshing) {
return;
}
isRefreshing = true;
try {
const sessions = await this.sessionService.getAllSessions(CancellationToken.None);
const items = await Promise.all(sessions.map(async session => this.toChatSessionItem(session)));
const count = items.length;
void this.commandExecutionService.executeCommand('setContext', 'github.copilot.chat.cliSessionsEmpty', count === 0);
controller.items.replace(items);
} finally {
isRefreshing = false;
}
}
));
controller.newChatSessionItemHandler = async (context) => {
const sessionId = this.sessionService.createNewSessionId();
const resource = SessionIdForCLI.getResource(sessionId);
const session = controller.createChatSessionItem(resource, context.request.prompt ?? context.request.command ?? '');
this.customSessionTitleService.generateSessionTitle(sessionId, context.request, CancellationToken.None)
.then(() => {
// Given we're done generating a title, refresh the contents of this session so that the new title is picked up.
if (this.controller.items.get(resource)) {
this.refreshSession({ reason: 'update', sessionId }).catch(() => { /* expected if session was deleted */ });
}
})
.catch(ex => this.logService.error(ex, 'Failed to generate custom session title'));
controller.items.add(session);
this.newSessions.set(resource, session);
return session;
};
if (this.configurationService.getConfig(ConfigKey.Advanced.CLIForkSessionsEnabled)) {
controller.forkHandler = async (sessionResource: Uri, request: ChatRequestTurn2 | undefined, token: vscode.CancellationToken) => {
const sessionId = SessionIdForCLI.parse(sessionResource);
const folderInfo = await this.folderRepositoryManager.getFolderRepository(sessionId, undefined, token);
const forkedSessionId = await this.sessionService.forkSession({ sessionId, requestId: request?.id, workspace: folderInfo }, token);
const item = await this.sessionService.getSessionItem(forkedSessionId, token);
if (!item) {
throw new Error(`Failed to get session item for forked session ${forkedSessionId}`);
}
return this.toChatSessionItem(item);
};
}
this._register(this.sessionService.onDidDeleteSession(async (e) => {
controller.items.delete(SessionIdForCLI.getResource(e));
}));
this._register(this.sessionService.onDidChangeSession(async (e) => {
const item = await this.toChatSessionItem(e);
controller.items.add(item);
}));
this._register(this.sessionService.onDidCreateSession(async (e) => {
const resource = SessionIdForCLI.getResource(e.id);
if (controller.items.get(resource)) {
return;
}
const item = await this.toChatSessionItem(e);
controller.items.add(item);
}));
// Handle worktree cleanup/recreation when archive state changes
if (controller.onDidChangeChatSessionItemState) {
this._register(controller.onDidChangeChatSessionItemState(async (item) => {
const sessionId = SessionIdForCLI.parse(item.resource);
if (item.archived) {
try {
const result = await this.copilotCLIWorktreeManagerService.cleanupWorktreeOnArchive(sessionId);
this.logService.trace(`[CopilotCLI] Worktree cleanup for session ${sessionId}: ${result.cleaned ? 'cleaned' : result.reason}`);
} catch (error) {
this.logService.error(`[CopilotCLI] Failed to cleanup worktree for archived session ${sessionId}:`, error);
}
} else {
try {
const result = await this.copilotCLIWorktreeManagerService.recreateWorktreeOnUnarchive(sessionId);
this.logService.trace(`[CopilotCLI] Worktree recreation for session ${sessionId}: ${result.recreated ? 'recreated' : result.reason}`);
} catch (error) {
this.logService.error(`[CopilotCLI] Failed to recreate worktree for unarchived session ${sessionId}:`, error);
}
}
}));
}
controller.getChatSessionInputState = async (sessionResource, context, token) => {
const groups = sessionResource ? await this.buildExistingSessionInputStateGroups(sessionResource, token) : await this.provideChatSessionProviderOptionGroups(context.previousInputState);
return controller.createChatSessionInputState(groups);
};
}
public async refreshSession(refreshOptions: { reason: 'update'; sessionId: string } | { reason: 'delete'; sessionId: string }): Promise<void> {
if (refreshOptions.reason === 'delete') {
const uri = SessionIdForCLI.getResource(refreshOptions.sessionId);
this.controller.items.delete(uri);
} else {
const item = await this.sessionService.getSessionItem(refreshOptions.sessionId, CancellationToken.None);
if (item) {
const chatSessionItem = await this.toChatSessionItem(item);
this.controller.items.add(chatSessionItem);
}
}
}
public async provideChatSessionItems(token: vscode.CancellationToken): Promise<vscode.ChatSessionItem[]> {
const sessions = await this.sessionService.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 = SessionIdForCLI.getResource(session.id);
const worktreeProperties = await this.copilotCLIWorktreeManagerService.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.copilotCLIWorktreeManagerService.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
? toGitUri(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 };
}
const item = this.controller.createChatSessionItem(resource, label);
item.badge = badge;
item.timing = session.timing;
item.changes = changes;
item.status = status;
item.metadata = metadata;
return item;
}
/**
* 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.copilotCLIWorktreeManagerService.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.copilotCLIWorktreeManagerService.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.copilotCLIWorktreeManagerService.setWorktreeProperties(sessionId, {
...currentProperties,
pullRequestUrl: prResult.url,
pullRequestState: prResult.state,
changes: undefined,
});
await this.refreshSession({ reason: 'update', sessionId });
} 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)}`);
}
}
async provideChatSessionContent(resource: Uri, token: vscode.CancellationToken, _context?: { readonly inputState: vscode.ChatSessionInputState; readonly sessionOptions: ReadonlyArray<{ optionId: string; value: string | vscode.ChatSessionProviderOptionItem }> }): Promise<vscode.ChatSession> {
const stopwatch = new StopWatch();
try {
const copilotcliSessionId = SessionIdForCLI.parse(resource);
if (copilotcliSessionId.startsWith('untitled:') || copilotcliSessionId.startsWith('untitled-')) {
return {
history: [],
requestHandler: undefined,
};
}
if (this.sessionService.isNewSessionId(copilotcliSessionId)) {
const session = this.newSessions.get(resource);
if (!session) {
throw new Error('Session not found');
}
return {
history: [],
requestHandler: undefined,
title: session.label,
activeResponseCallback: undefined,
options: {},
};
} else {
return await this.provideChatSessionContentForExistingSession(resource, token);
}
} finally {
this.logService.info(`[CopilotCLIChatSessionContentProvider] provideChatSessionContent for ${resource.toString()} took ${stopwatch.elapsed()}ms`);
}
}
async provideChatSessionContentForExistingSession(resource: Uri, token: vscode.CancellationToken): Promise<vscode.ChatSession> {
const copilotcliSessionId = SessionIdForCLI.parse(resource);
// Fire-and-forget: detect PR when the user opens a session.
void this.detectPullRequestOnSessionOpen(copilotcliSessionId);
const folderRepo = await this.folderRepositoryManager.getFolderRepository(copilotcliSessionId, undefined, token);
const [history, title] = await Promise.all([
this.getSessionHistory(copilotcliSessionId, folderRepo, token),
this.customSessionTitleService.getCustomSessionTitle(copilotcliSessionId),
]);
return {
title,
history,
activeResponseCallback: undefined,
requestHandler: undefined,
};
}
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 provideChatSessionProviderOptionGroups(previousInputState: vscode.ChatSessionInputState | undefined): Promise<vscode.ChatSessionProviderOptionGroup[]> {
const optionGroups: vscode.ChatSessionProviderOptionGroup[] = [];
const previouslySelectedIsolationOption = previousInputState?.groups.find(g => g.id === ISOLATION_OPTION_ID)?.selected;
if (isIsolationOptionFeatureEnabled(this.configurationService)) {
const lastUsed = this.context.globalState.get<IsolationMode>(LAST_USED_ISOLATION_OPTION_KEY, IsolationMode.Workspace);
const defaultSelection = lastUsed === IsolationMode.Workspace ?
{ id: IsolationMode.Workspace, name: l10n.t('Workspace'), icon: new vscode.ThemeIcon('folder') } :
{ id: IsolationMode.Worktree, name: l10n.t('Worktree'), icon: new vscode.ThemeIcon('worktree') };
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') },
],
selected: previouslySelectedIsolationOption ?? defaultSelection
});
}
// Handle repository options based on workspace type
let defaultRepoUri = !isWelcomeView(this.workspaceService) && !this._agentSessionsWorkspace.isAgentSessionsWorkspace && this.workspaceService.getWorkspaceFolders()?.length === 1 ? this.workspaceService.getWorkspaceFolders()![0] : undefined;
if (isWelcomeView(this.workspaceService)) {
const commands: vscode.Command[] = [];
const previouslySelected = previousInputState?.groups.find(g => g.id === REPOSITORY_OPTION_ID)?.selected;
let items: vscode.ChatSessionProviderOptionItem[] = [];
// For untitled workspaces, show last used repositories and "Open Repository..." command
const repositories = await this.copilotCLIFolderMruService.getRecentlyUsedFolders(CancellationToken.None);
items = folderMRUToChatProviderOptions(repositories);
items.splice(MAX_MRU_ENTRIES); // Limit to max entries
if (this._lastUsedFolderIdInUntitledWorkspace) {
const folder = this._lastUsedFolderIdInUntitledWorkspace.uri;
const isRepo = this._lastUsedFolderIdInUntitledWorkspace.kind === 'repo';
const lastAccessed = this._lastUsedFolderIdInUntitledWorkspace.lastAccessed;
const id = folder.fsPath;
if (!items.find(item => item.id === id)) {
const lastUsedEntry = folderMRUToChatProviderOptions([{
folder,
repository: isRepo ? folder : undefined,
lastAccessed
}])[0];
items.unshift(lastUsedEntry);
}
}
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,
selected: previouslySelected,
commands
});
} else {
const repositories = this.getRepositoryOptionItems();
if (repositories.length > 1) {
const previouslySelected = previousInputState?.groups.find(g => g.id === REPOSITORY_OPTION_ID)?.selected ?? repositories[0];
defaultRepoUri = previouslySelected?.id ? vscode.Uri.file(previouslySelected.id) : defaultRepoUri;
optionGroups.push({
id: REPOSITORY_OPTION_ID,
name: l10n.t('Folder'),
description: l10n.t('Pick Folder'),
items: repositories,
selected: previouslySelected ?? repositories[0]
});
} else if (repositories.length === 1) {
defaultRepoUri = vscode.Uri.file(repositories[0].id);
}
}
if ((isBranchOptionFeatureEnabled(this.configurationService))) {
// If we have a selected branch and it belongs to this repo, then use that as the default branch selection,
// //Else fall back to the repo's head branch, and if that doesn't exist use no default selection.
const repo = defaultRepoUri ? await this.gitService.getRepository(defaultRepoUri) : undefined;
const branches = repo ? await this.getBranchOptionItemsForRepository(repo.rootUri, repo.headBranchName) : [];
const previouslySelectedBranchItem = previousInputState?.groups.find(g => g.id === BRANCH_OPTION_ID)?.selected;
const activeBranch = repo?.headBranchName ? branches.find(branch => branch.id === repo.headBranchName) : undefined;
const selectedBranch = previouslySelectedBranchItem?.id || activeBranch?.id;
const selectedItem = (selectedBranch ? branches.find(branch => branch.id === selectedBranch) : undefined) ?? previouslySelectedBranchItem;
if (branches.length > 0) {
optionGroups.push({
id: BRANCH_OPTION_ID,
name: l10n.t('Branch'),
description: l10n.t('Pick Branch'),
items: branches,
selected: selectedItem,
when: `chatSessionOption.${ISOLATION_OPTION_ID} == '${IsolationMode.Worktree}'`
});
}
}
return optionGroups;
}
private async buildExistingSessionInputStateGroups(resource: vscode.Uri, token: vscode.CancellationToken): Promise<vscode.ChatSessionProviderOptionGroup[]> {
const copilotcliSessionId = SessionIdForCLI.parse(resource);
const optionGroups: vscode.ChatSessionProviderOptionGroup[] = [];
const folderInfo = await this.folderRepositoryManager.getFolderRepository(copilotcliSessionId, undefined, token);
const repositories = isWelcomeView(this.workspaceService) ? folderMRUToChatProviderOptions(await this.copilotCLIFolderMruService.getRecentlyUsedFolders(token)) : this.getRepositoryOptionItems();
const folderOrRepoId = folderInfo.repository?.fsPath ?? folderInfo.folder?.fsPath;
const existingItem = folderOrRepoId ? repositories.find(repo => repo.id === folderOrRepoId) : undefined;
const worktreeProperties = await this.copilotCLIWorktreeManagerService.getWorktreeProperties(copilotcliSessionId);
let repoSelected: vscode.ChatSessionProviderOptionItem;
if (existingItem) {
repoSelected = { ...existingItem, locked: true };
} else if (folderInfo.repository) {
repoSelected = { ...toRepositoryOptionItem(folderInfo.repository), locked: true };
} else if (folderInfo.folder) {
const folderName = this.workspaceService.getWorkspaceFolderName(folderInfo.folder) || basename(folderInfo.folder);
repoSelected = { ...toWorkspaceFolderOptionItem(folderInfo.folder, folderName), locked: true };
} else {
let folderName = l10n.t('Unknown');
if (this.workspaceService.getWorkspaceFolders().length === 1) {
folderName = this.workspaceService.getWorkspaceFolderName(this.workspaceService.getWorkspaceFolders()[0]) || folderName;
}
repoSelected = { id: '', name: folderName, icon: new vscode.ThemeIcon('folder'), locked: true };
}
if (isIsolationOptionFeatureEnabled(this.configurationService)) {
const isWorktree = !!worktreeProperties;
const isolationSelected = {
id: isWorktree ? IsolationMode.Worktree : IsolationMode.Workspace,
name: isWorktree ? l10n.t('Worktree') : l10n.t('Workspace'),
icon: new vscode.ThemeIcon(isWorktree ? 'worktree' : 'folder'),
locked: true
};
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') },
],
selected: isolationSelected
});
}
optionGroups.push({
id: REPOSITORY_OPTION_ID,
name: l10n.t('Folder'),
description: l10n.t('Pick Folder'),
items: [repoSelected],
selected: repoSelected,
commands: []
});
const branchName = worktreeProperties?.branchName;
const branchSelected = branchName ? { id: branchName, name: branchName, icon: new vscode.ThemeIcon('git-branch'), locked: true } : undefined;
optionGroups.push({
id: BRANCH_OPTION_ID,
name: l10n.t('Branch'),
description: l10n.t('Pick Branch'),
items: branchSelected ? [branchSelected] : [],
selected: branchSelected,
when: `chatSessionOption.${ISOLATION_OPTION_ID} == '${IsolationMode.Worktree}'`
});
return optionGroups;
}
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;
let mainOrheadBranch: vscode.ChatSessionProviderOptionItem | undefined;
for (const ref of localBranches) {
if (!ref.name) {
continue;
}
if (ref.name.includes(COPILOT_WORKTREE_PATTERN)) {
continue;
}
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 if (ref.name === 'main' || ref.name === 'master') {
mainOrheadBranch = item;
} else {
items.push(item);
}
}
if (mainOrheadBranch) {
items.unshift(mainOrheadBranch);
}
if (headItem) {
items.unshift(headItem);
}
return items;
});
}
private getRepositoryOptionItems() {
// Exclude worktrees from the repository list
const repositories = this.gitService.repositories
.filter(repository => repository.kind !== 'worktree')
.filter(repository => {
if (isWelcomeView(this.workspaceService)) {
// In the welcome view, include all repositories from the MRU list
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));
}
public async trackLastUsedFolderInWelcomeView(folderUri: vscode.Uri) {
// Update MRU tracking for untitled workspaces
if (isWelcomeView(this.workspaceService)) {
const repository = await this.gitService.getRepository(folderUri);
if (repository) {
this._lastUsedFolderIdInUntitledWorkspace = { kind: 'repo', uri: repository.rootUri, lastAccessed: Date.now() };
} else {
this._lastUsedFolderIdInUntitledWorkspace = { kind: 'folder', uri: folderUri, lastAccessed: Date.now() };
}
}
}
}
export class CopilotCLIChatSessionParticipant extends Disposable {
constructor(
private readonly contentProvider: CopilotCLIChatSessionContentProvider,
private readonly promptResolver: CopilotCLIPromptResolver,
private readonly cloudSessionProvider: CopilotCloudSessionsProvider | undefined,
private readonly branchNameGenerator: GitBranchNameGenerator | undefined,
@IGitService private readonly gitService: IGitService,
@ICopilotCLIModels private readonly copilotCLIModels: ICopilotCLIModels,
@ICopilotCLIAgents private readonly copilotCLIAgents: ICopilotCLIAgents,
@ICopilotCLISessionService private readonly sessionService: ICopilotCLISessionService,
@IChatSessionWorktreeService private readonly copilotCLIWorktreeManagerService: IChatSessionWorktreeService,
@IChatSessionWorktreeCheckpointService private readonly copilotCLIWorktreeCheckpointService: IChatSessionWorktreeCheckpointService,
@IChatSessionWorkspaceFolderService private readonly workspaceFolderService: IChatSessionWorkspaceFolderService,
@ITelemetryService private readonly telemetryService: ITelemetryService,
@ILogService private readonly logService: ILogService,
@IPromptsService private readonly promptsService: IPromptsService,
@IChatDelegationSummaryService private readonly chatDelegationSummaryService: IChatDelegationSummaryService,
@IFolderRepositoryManager private readonly folderRepositoryManager: IFolderRepositoryManager,
@IConfigurationService private readonly configurationService: IConfigurationService,
@ICopilotCLISDK private readonly copilotCLISDK: ICopilotCLISDK,
@IChatSessionMetadataStore private readonly chatSessionMetadataStore: IChatSessionMetadataStore,
@IOctoKitService private readonly octoKitService: IOctoKitService,
@IWorkspaceService private readonly workspaceService: IWorkspaceService,
) {
super();
}
createHandler(): ChatExtendedRequestHandler {
return this.handleRequest.bind(this);
}
private readonly contextForRequest = new Map<string, { prompt: string; attachments: Attachment[] }>();
/**
* Tracks in-flight requests per session so we can coordinate worktree
* commit / PR handling and cleanup.
*
* We generally cannot have parallel requests for the same session, but when
* steering is involved there can be multiple requests in flight for a
* single session (the original request continues running while steering
* requests are processed). This map records all active requests for each
* session so that any worktree-related actions are deferred until the last
* in-flight request for that session has completed.
*/
private readonly pendingRequestBySession = new Map<string, Set<vscode.ChatRequest>>();
/**
* Outer request handler that supports *yielding* for session steering.
*
* ## How steering works end-to-end
*
* 1. The user sends a message while the session is already processing a
* previous request (status is `InProgress` or `NeedsInput`).
* 2. VS Code signals this by setting `context.yieldRequested = true` on the
* *previous* request's context object.
* 3. This handler polls `context.yieldRequested` every 100 ms. Once detected
* the outer `Promise.race` resolves, returning control to VS Code so it
* can dispatch the new (steering) request.
* 4. Crucially, the inner `handleRequestImpl` promise is **not** cancelled
* or disposed – the original SDK session continues running in the
* background.
* 5. When the new request arrives, `handleRequest` on the underlying
* {@link CopilotCLISession} detects the session is still busy and routes
* through `_handleRequestSteering`, which sends the new prompt with
* `mode: 'immediate'` and waits for both the steering send and the
* original request to complete.
*/
private async handleRequest(request: vscode.ChatRequest, context: vscode.ChatContext, stream: vscode.ChatResponseStream, token: vscode.CancellationToken): Promise<vscode.ChatResult | void> {
const disposables = new DisposableStore();
try {
const handled = this.handleRequestImpl(request, context, stream, token);
const interval = disposables.add(new IntervalTimer());
const yielded = new DeferredPromise<void>();
interval.cancelAndSet(() => {
if (context.yieldRequested) {
yielded.complete();
}
}, CHECK_FOR_STEERING_DELAY);
return await Promise.race([yielded.p, handled]);
} finally {
disposables.dispose();
}
}
private sendTelemetryForHandleRequest(request: vscode.ChatRequest, context: vscode.ChatContext): void {
const { chatSessionContext } = context;
const hasChatSessionItem = String(!!chatSessionContext?.chatSessionItem);
const sessionId = chatSessionContext ? SessionIdForCLI.parse(chatSessionContext.chatSessionItem.resource) : undefined;
const isUntitled = sessionId ? String(this.sessionService.isNewSessionId(sessionId)) : 'false';
const hasDelegatePrompt = String(request.command === 'delegate');
/* __GDPR__
"copilotcli.chat.invoke" : {
"owner": "joshspicer",
"comment": "Event sent when a CopilotCLI chat request is made.",
"chatRequestId": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "The unique chat request ID." },
"hasChatSessionItem": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "Invoked with a chat session item." },
"isUntitled": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "Indicates if the chat session is untitled." },
"hasDelegatePrompt": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "Indicates if the prompt is a /delegate command." }
}
*/
this.telemetryService.sendMSFTTelemetryEvent('copilotcli.chat.invoke', {
chatRequestId: request.id,
hasChatSessionItem,
isUntitled,
hasDelegatePrompt
});
}
private async handleRequestImpl(request: vscode.ChatRequest, context: vscode.ChatContext, stream: vscode.ChatResponseStream, token: vscode.CancellationToken): Promise<vscode.ChatResult | void> {