This repository was archived by the owner on May 20, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathcopilotCloudSessionsProvider.ts
More file actions
1644 lines (1462 loc) · 62.6 KB
/
Copy pathcopilotCloudSessionsProvider.ts
File metadata and controls
1644 lines (1462 loc) · 62.6 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 MarkdownIt from 'markdown-it';
import * as pathLib from 'path';
import * as vscode from 'vscode';
import { Uri } from 'vscode';
import { IAuthenticationService } from '../../../platform/authentication/common/authentication';
import { IVSCodeExtensionContext } from '../../../platform/extContext/common/extensionContext';
import { IGitExtensionService } from '../../../platform/git/common/gitExtensionService';
import { IGitService } from '../../../platform/git/common/gitService';
import { PullRequestSearchItem, SessionInfo } from '../../../platform/github/common/githubAPI';
import { IGithubRepositoryService, IOctoKitService, JobInfo, RemoteAgentJobPayload, RemoteAgentJobResponse } from '../../../platform/github/common/githubService';
import { ILogService } from '../../../platform/log/common/logService';
import { ITelemetryService } from '../../../platform/telemetry/common/telemetry';
import { DeferredPromise, retry } from '../../../util/vs/base/common/async';
import { Disposable, toDisposable } from '../../../util/vs/base/common/lifecycle';
import { ResourceMap } from '../../../util/vs/base/common/map';
import { IInstantiationService } from '../../../util/vs/platform/instantiation/common/instantiation';
import { IChatDelegationSummaryService } from '../../agents/copilotcli/common/delegationSummaryService';
import { body_suffix, CONTINUE_TRUNCATION, extractTitle, formatBodyPlaceholder, getAuthorDisplayName, getRepoId, JOBS_API_VERSION, SessionIdForPr, toOpenPullRequestWebviewUri, truncatePrompt } from '../vscode/copilotCodingAgentUtils';
import { CopilotCloudGitOperationsManager } from './copilotCloudGitOperationsManager';
import { ChatSessionContentBuilder } from './copilotCloudSessionContentBuilder';
import { IPullRequestFileChangesService } from './pullRequestFileChangesService';
interface ConfirmationMetadata {
prompt: string;
references?: readonly vscode.ChatPromptReference[];
chatContext: vscode.ChatContext;
}
function validateMetadata(metadata: unknown): asserts metadata is ConfirmationMetadata {
if (typeof metadata !== 'object') {
throw new Error('Invalid confirmation metadata: not an object.');
}
if (metadata === null) {
throw new Error('Invalid confirmation metadata: null value.');
}
if (typeof (metadata as ConfirmationMetadata).prompt !== 'string') {
throw new Error('Invalid confirmation metadata: missing or invalid prompt.');
}
if (typeof (metadata as ConfirmationMetadata).chatContext !== 'object' || (metadata as ConfirmationMetadata).chatContext === null) {
throw new Error('Invalid confirmation metadata: missing or invalid chatContext.');
}
}
const AGENTS_OPTION_GROUP_ID = 'agents';
const DEFAULT_AGENT_ID = '___vscode_default___';
const BACKGROUND_REFRESH_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes
const ACTIVE_SESSION_POLL_INTERVAL_MS = 5 * 1000; // 5 seconds
const SEEN_DELEGATION_PROMPT_KEY = 'seenDelegationPromptBefore';
/**
* Custom renderer for markdown-it that converts markdown to plain text
*/
class PlainTextRenderer {
private md: MarkdownIt;
constructor() {
this.md = new MarkdownIt();
}
/**
* Renders markdown text as plain text by extracting text content from all tokens
*/
render(markdown: string): string {
const tokens = this.md.parse(markdown, {});
return this.renderTokens(tokens).trim();
}
private renderTokens(tokens: MarkdownIt.Token[]): string {
let result = '';
for (const token of tokens) {
// Process child tokens recursively
if (token.children) {
result += this.renderTokens(token.children);
}
// Handle different token types
switch (token.type) {
case 'text':
case 'code_inline':
// Only add content if no children were processed
if (!token.children) {
result += token.content;
}
break;
case 'softbreak':
case 'hardbreak':
result += ' '; // Space instead of newline to match original
break;
case 'paragraph_close':
result += '\n'; // Newline after paragraphs for separation
break;
case 'heading_close':
result += '\n'; // Newline after headings
break;
case 'list_item_close':
result += '\n'; // Newline after list items
break;
case 'fence':
case 'code_block':
case 'hr':
// Skip these entirely
break;
// Don't add default case - only explicitly handle what we want
}
}
return result;
}
}
export class CopilotCloudSessionsProvider extends Disposable implements vscode.ChatSessionContentProvider, vscode.ChatSessionItemProvider {
public static readonly TYPE = 'copilot-cloud-agent';
private readonly _onDidChangeChatSessionItems = this._register(new vscode.EventEmitter<void>());
public readonly onDidChangeChatSessionItems = this._onDidChangeChatSessionItems.event;
private readonly _onDidCommitChatSessionItem = this._register(new vscode.EventEmitter<{ original: vscode.ChatSessionItem; modified: vscode.ChatSessionItem }>());
public readonly onDidCommitChatSessionItem = this._onDidCommitChatSessionItem.event;
private chatSessions: Map<number, PullRequestSearchItem> = new Map();
private chatSessionItemsPromise: Promise<vscode.ChatSessionItem[]> | undefined;
private readonly sessionAgentMap = new ResourceMap<string>();
private readonly sessionReferencesMap = new ResourceMap<readonly vscode.ChatPromptReference[]>();
public chatParticipant = vscode.chat.createChatParticipant(CopilotCloudSessionsProvider.TYPE, async (request, context, stream, token) => {
await this.chatParticipantImpl(request, context, stream, token);
});
private cachedSessionsSize: number = 0;
// Cache for provideChatSessionItems
private cachedSessionItems: (vscode.ChatSessionItem & {
fullDatabaseId: string;
pullRequestDetails: PullRequestSearchItem;
})[] | undefined;
private activeSessionIds: Set<string> = new Set();
private activeSessionPollingInterval: ReturnType<typeof setInterval> | undefined;
private readonly plainTextRenderer = new PlainTextRenderer();
private readonly gitOperationsManager = new CopilotCloudGitOperationsManager(this.logService, this._gitService, this._gitExtensionService);
// Title
private TITLE = vscode.l10n.t('Delegate to cloud agent');
// Buttons (used for matching, be careful changing!)
private readonly AUTHORIZE = vscode.l10n.t('Authorize');
private readonly COMMIT = vscode.l10n.t('Commit Changes');
private readonly PUSH_BRANCH = vscode.l10n.t('Push Branch');
private readonly DELEGATE = vscode.l10n.t('Delegate');
private readonly CANCEL = vscode.l10n.t('Cancel');
// Messages
private readonly BASE_MESSAGE = vscode.l10n.t('Cloud agent works asynchronously to create a pull request with your requested changes. This chat\'s history will be summarized and appended to the pull request as context.');
private readonly AUTHORIZE_MESSAGE = vscode.l10n.t('Cloud agent requires elevated GitHub access to proceed.');
private readonly COMMIT_MESSAGE = vscode.l10n.t('This workspace has uncommitted changes. Should these changes be pushed and included in cloud agent\'s work?');
private readonly PUSH_BRANCH_MESSAGE = (baseRef: string, defaultBranch: string) => vscode.l10n.t('Push your currently checked out branch `{0}`, or start from the default branch `{1}`?', baseRef, defaultBranch);
// Workspace storage keys
private readonly WORKSPACE_CONTEXT_PREFIX = 'copilot.cloudAgent';
constructor(
@IOctoKitService private readonly _octoKitService: IOctoKitService,
@IGitService private readonly _gitService: IGitService,
@ITelemetryService private readonly telemetry: ITelemetryService,
@ILogService private readonly logService: ILogService,
@IGitExtensionService private readonly _gitExtensionService: IGitExtensionService,
@IPullRequestFileChangesService private readonly _prFileChangesService: IPullRequestFileChangesService,
@IAuthenticationService private readonly _authenticationService: IAuthenticationService,
@IVSCodeExtensionContext private readonly _extensionContext: IVSCodeExtensionContext,
@IInstantiationService instantiationService: IInstantiationService,
@IGithubRepositoryService private readonly _githubRepositoryService: IGithubRepositoryService,
@IChatDelegationSummaryService private readonly _chatDelegationSummaryService: IChatDelegationSummaryService,
) {
super();
const interval = setInterval(async () => {
const repoId = await getRepoId(this._gitService);
// TODO: handle no auth token case more gracefully
if (!this._authenticationService.permissiveGitHubSession) {
return;
}
const sessions = await this._octoKitService.getAllOpenSessions(repoId ? `${repoId.org}/${repoId.repo}` : undefined);
if (this.cachedSessionsSize !== sessions.length) {
this.refresh();
}
}, BACKGROUND_REFRESH_INTERVAL_MS);
this._register(toDisposable(() => clearInterval(interval)));
this._register(this._authenticationService.onDidAuthenticationChange(() => {
this.refresh();
}));
}
public refresh(): void {
this.cachedSessionItems = undefined;
this.activeSessionIds.clear();
this.stopActiveSessionPolling();
this._onDidChangeChatSessionItems.fire();
}
private stopActiveSessionPolling(): void {
if (this.activeSessionPollingInterval) {
clearInterval(this.activeSessionPollingInterval);
this.activeSessionPollingInterval = undefined;
}
}
private startActiveSessionPolling(): void {
// Don't start if already polling
if (this.activeSessionPollingInterval) {
return;
}
this.activeSessionPollingInterval = setInterval(async () => {
await this.updateActiveSessionsOnly();
}, ACTIVE_SESSION_POLL_INTERVAL_MS);
// Register for disposal
this._register(toDisposable(() => this.stopActiveSessionPolling()));
}
private async updateActiveSessionsOnly(): Promise<void> {
if (this.activeSessionIds.size === 0) {
this.stopActiveSessionPolling();
return;
}
try {
// Fetch only the active sessions using allSettled to handle individual failures
const sessionResults = await Promise.allSettled(
Array.from(this.activeSessionIds).map(sessionId =>
this._octoKitService.getSessionInfo(sessionId)
)
);
const stillActiveSessions = new Set<string>();
for (const result of sessionResults) {
if (result.status === 'rejected') {
this.logService.warn(`Failed to fetch session info: ${result.reason}`);
continue;
}
const session = result.value;
if (!session) {
continue;
}
this.cachedSessionItems = this.cachedSessionItems?.map(item => {
if (item.fullDatabaseId === session.resource_global_id) {
return {
...item,
status: this.getSessionStatusFromSession(session),
};
}
return item;
});
if (session.state === 'in_progress' || session.state === 'queued') {
stillActiveSessions.add(session.id);
}
}
// Update the active sessions set
this.activeSessionIds = stillActiveSessions;
// If there are changes or no more active sessions, invalidate cache and notify
if (this.activeSessionIds.size === 0) {
this.cachedSessionItems = undefined;
this.stopActiveSessionPolling();
}
this._onDidChangeChatSessionItems.fire();
} catch (error) {
this.logService.error(`Error updating active sessions: ${error}`);
}
}
async provideChatSessionProviderOptions(token: vscode.CancellationToken): Promise<vscode.ChatSessionProviderOptions> {
const repoId = await getRepoId(this._gitService);
if (!repoId) {
return { optionGroups: [] };
}
// TODO: handle no auth token case more gracefully
if (!this._authenticationService.permissiveGitHubSession) {
return { optionGroups: [] };
}
try {
const customAgents = await this._octoKitService.getCustomAgents(repoId.org, repoId.repo, { excludeInvalidConfig: true });
if (customAgents.length === 0) {
return { optionGroups: [] };
}
const agentItems: vscode.ChatSessionProviderOptionItem[] = [
{ id: DEFAULT_AGENT_ID, name: vscode.l10n.t('Agent') },
...customAgents.map(agent => ({
id: agent.name,
name: agent.display_name || agent.name
}))
];
return {
optionGroups: [
{
id: AGENTS_OPTION_GROUP_ID,
name: vscode.l10n.t('Custom Agents'),
description: vscode.l10n.t('Select which agent to use'),
items: agentItems,
}
]
};
} catch (error) {
this.logService.error(`Error fetching custom agents: ${error}`);
return { optionGroups: [] };
}
}
provideHandleOptionsChange(resource: Uri, updates: ReadonlyArray<vscode.ChatSessionOptionUpdate>, token: vscode.CancellationToken): void {
for (const update of updates) {
if (update.optionId === AGENTS_OPTION_GROUP_ID) {
if (update.value) {
this.sessionAgentMap.set(resource, update.value);
this.logService.info(`Agent changed for session ${resource}: ${update.value}`);
} else {
this.sessionAgentMap.delete(resource);
this.logService.info(`Agent cleared for session ${resource}`);
}
}
}
}
async provideChatSessionItems(token: vscode.CancellationToken): Promise<vscode.ChatSessionItem[]> {
// Return cached items if available
if (this.cachedSessionItems) {
return this.cachedSessionItems;
}
if (this.chatSessionItemsPromise) {
return this.chatSessionItemsPromise;
}
this.chatSessionItemsPromise = (async () => {
const repoId = await getRepoId(this._gitService);
// TODO: handle no auth token case more gracefully
if (!this._authenticationService.permissiveGitHubSession) {
return [];
}
const sessions = await this._octoKitService.getAllOpenSessions(repoId ? `${repoId.org}/${repoId.repo}` : undefined);
this.cachedSessionsSize = sessions.length;
// Group sessions by resource_id and keep only the latest per resource_id
const latestSessionsMap = new Map<number, SessionInfo>();
for (const session of sessions) {
const existing = latestSessionsMap.get(session.resource_id);
if (!existing || this.shouldPushSession(session, existing)) {
latestSessionsMap.set(session.resource_id, session);
}
}
// Track active sessions for background polling
const newActiveSessionIds = new Set<string>();
for (const session of latestSessionsMap.values()) {
if (session.state === 'in_progress' || session.state === 'queued') {
newActiveSessionIds.add(session.id);
}
}
// Update active sessions and start polling if needed
this.activeSessionIds = newActiveSessionIds;
if (this.activeSessionIds.size > 0) {
this.startActiveSessionPolling();
} else {
this.stopActiveSessionPolling();
}
// Fetch PRs for all unique resource_global_ids in parallel
const uniqueGlobalIds = new Set(Array.from(latestSessionsMap.values()).map(s => s.resource_global_id));
const prFetches = Array.from(uniqueGlobalIds).map(async globalId => {
const pr = await this._octoKitService.getPullRequestFromGlobalId(globalId);
return { globalId, pr };
});
const prResults = await Promise.all(prFetches);
const prMap = new Map(prResults.filter(r => r.pr).map(r => [r.globalId, r.pr!]));
const validateISOTimestamp = (date: string | undefined): number | undefined => {
try {
if (!date) {
return;
}
const time = new Date(date)?.getTime();
if (time > 0) {
return time;
}
} catch { }
};
const createdAt = sessions.length > 0 ? validateISOTimestamp(sessions[0].created_at) : undefined;
// Create session items from latest sessions
const sessionItems = await Promise.all(Array.from(latestSessionsMap.values()).map(async sessionItem => {
const pr = prMap.get(sessionItem.resource_global_id);
if (!pr) {
return undefined;
}
const multiDiffPart = await this._prFileChangesService.getFileChangesMultiDiffPart(pr);
const changes = multiDiffPart
? multiDiffPart.value.map(change =>
new vscode.ChatSessionChangedFile(change.modifiedUri!, change.added!, change.removed!, change.originalUri))
: {
files: pr.files.totalCount,
insertions: pr.additions,
deletions: pr.deletions
};
const session = {
resource: vscode.Uri.from({ scheme: CopilotCloudSessionsProvider.TYPE, path: '/' + pr.number }),
label: pr.title,
status: this.getSessionStatusFromSession(sessionItem),
badge: this.getPullRequestBadge(pr),
tooltip: this.createPullRequestTooltip(pr),
...(createdAt ? {
timing: {
startTime: createdAt,
endTime: validateISOTimestamp(sessionItem.completed_at),
}
} : {}),
changes,
fullDatabaseId: pr.fullDatabaseId.toString(),
pullRequestDetails: pr,
} satisfies vscode.ChatSessionItem & {
fullDatabaseId: string;
pullRequestDetails: PullRequestSearchItem;
};
this.chatSessions.set(pr.number, pr);
return session;
}));
const filteredSessions = sessionItems
// Remove any undefined sessions
.filter(item => item !== undefined)
// Only keep sessions with attached PRs not CLOSED or MERGED
.filter(item => {
const pr = item.pullRequestDetails;
const state = pr.state.toUpperCase();
return state !== 'CLOSED' && state !== 'MERGED';
});
vscode.commands.executeCommand('setContext', 'github.copilot.chat.cloudSessionsEmpty', filteredSessions.length === 0);
// Cache the results
this.cachedSessionItems = filteredSessions;
return filteredSessions;
})().finally(() => {
this.chatSessionItemsPromise = undefined;
});
return this.chatSessionItemsPromise;
}
private shouldPushSession(sessionItem: SessionInfo, existing: SessionInfo | undefined): boolean {
if (!existing) {
return true;
}
const existingDate = new Date(existing.last_updated_at);
const newDate = new Date(sessionItem.last_updated_at);
return newDate > existingDate;
}
async provideChatSessionContent(resource: Uri, token: vscode.CancellationToken): Promise<vscode.ChatSession> {
const indexedSessionId = SessionIdForPr.parse(resource);
let pullRequestNumber: number | undefined;
if (indexedSessionId) {
pullRequestNumber = indexedSessionId.prNumber;
}
if (typeof pullRequestNumber === 'undefined') {
pullRequestNumber = SessionIdForPr.parsePullRequestNumber(resource);
if (isNaN(pullRequestNumber)) {
this.logService.error(`Invalid pull request number: ${resource}`);
return this.createEmptySession(resource);
}
}
const pr = await this.findPR(pullRequestNumber);
const summaryReference = new DeferredPromise<vscode.ChatPromptReference | undefined>();
const getProblemStatement = async (sessions: SessionInfo[]) => {
if (sessions.length === 0) {
summaryReference.complete(undefined);
return undefined;
}
const repoId = await getRepoId(this._gitService);
if (!repoId) {
summaryReference.complete(undefined);
return undefined;
}
const jobInfo = await this._octoKitService.getJobBySessionId(repoId.org, repoId.repo, sessions[0].id, 'vscode-copilot-chat');
let prompt = jobInfo?.problem_statement || 'Initial Implementation';
// When delegating, we append the summary to the prompt, & that can be very large and doesn't look great.
// Turn the summary into a reference instead.
const info = this._chatDelegationSummaryService.extractPrompt(sessions[0].id, prompt);
if (info) {
summaryReference.complete(info.reference);
prompt = info.prompt;
} else {
summaryReference.complete(undefined);
}
const titleMatch = prompt.match(/TITLE: \s*(.*)/i);
if (titleMatch && titleMatch[1]) {
prompt = titleMatch[1].trim();
} else {
const split = prompt.split('\n');
if (split.length > 0) {
prompt = split[0].trim();
}
}
return prompt.replace(/@copilot\s*/gi, '').trim();
};
if (!pr) {
this.logService.error(`Session not found for ID: ${resource}`);
return this.createEmptySession(resource);
}
const sessions = await this._octoKitService.getCopilotSessionsForPR(pr.fullDatabaseId.toString());
const sortedSessions = sessions
.filter((session, index, array) =>
array.findIndex(s => s.id === session.id) === index
)
.slice().sort((a, b) =>
new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
);
// Get stored references for this session
const storedReferences = summaryReference.p.then(summaryRef => {
return (this.sessionReferencesMap.get(resource) ?? []).concat(summaryRef ? [summaryRef] : []);
});
const sessionContentBuilder = new ChatSessionContentBuilder(CopilotCloudSessionsProvider.TYPE, this._gitService);
const history = await sessionContentBuilder.buildSessionHistory(getProblemStatement(sortedSessions), sortedSessions, pr, (sessionId: string) => this._octoKitService.getSessionLogs(sessionId), storedReferences);
const selectedAgent =
// Local cache of session -> custom agent
this.sessionAgentMap.get(resource)
// Query for the sub-agent that the remote reports for this session
|| undefined; /* TODO: Needs API to support this. */
return {
history,
options: selectedAgent ? { [AGENTS_OPTION_GROUP_ID]: selectedAgent } : undefined,
activeResponseCallback: this.findActiveResponseCallback(sessions, pr),
requestHandler: undefined
};
}
async openSessionsInBrowser(chatSessionItem: vscode.ChatSessionItem): Promise<void> {
const session = SessionIdForPr.parse(chatSessionItem.resource);
let prNumber = session?.prNumber;
if (typeof prNumber === 'undefined' || isNaN(prNumber)) {
prNumber = SessionIdForPr.parsePullRequestNumber(chatSessionItem.resource);
if (isNaN(prNumber)) {
vscode.window.showErrorMessage(vscode.l10n.t('Invalid pull request number: {0}', chatSessionItem.resource));
this.logService.error(`Invalid pull request number: ${chatSessionItem.resource}`);
return;
}
}
const pr = await this.findPR(prNumber);
if (!pr) {
vscode.window.showErrorMessage(vscode.l10n.t('Could not find pull request #{0}', prNumber));
this.logService.error(`Could not find pull request #${prNumber}`);
return;
}
const url = `https://github.com/copilot/tasks/pull/${pr.id}`;
await vscode.env.openExternal(vscode.Uri.parse(url));
}
async openChanges(chatSessionItemResource: vscode.Uri): Promise<void> {
const session = SessionIdForPr.parse(chatSessionItemResource);
let prNumber = session?.prNumber;
if (typeof prNumber === 'undefined' || isNaN(prNumber)) {
prNumber = SessionIdForPr.parsePullRequestNumber(chatSessionItemResource);
if (isNaN(prNumber)) {
vscode.window.showErrorMessage(vscode.l10n.t('Could not parse PR number from session resource'));
this.logService.error(`Could not parse PR number from session resource: ${chatSessionItemResource}`);
return;
}
}
const pr = await this.findPR(prNumber);
if (!pr) {
vscode.window.showErrorMessage(vscode.l10n.t('Could not find pull request #{0}', prNumber));
this.logService.error(`Could not find pull request #${prNumber}`);
return;
}
const multiDiffPart = await this._prFileChangesService.getFileChangesMultiDiffPart(pr);
if (!multiDiffPart) {
vscode.window.showWarningMessage(vscode.l10n.t('No file changes found for pull request #{0}', prNumber));
this.logService.warn(`No file changes found for PR #${prNumber}`);
return;
}
await vscode.commands.executeCommand('_workbench.openMultiDiffEditor', {
multiDiffSourceUri: vscode.Uri.parse(`copilotcloud-pr-changes:/${prNumber}`),
title: vscode.l10n.t('Pull Request #{0}', prNumber),
resources: multiDiffPart.value
});
}
private findActiveResponseCallback(
sessions: SessionInfo[],
pr: PullRequestSearchItem
): ((stream: vscode.ChatResponseStream, token: vscode.CancellationToken) => Thenable<void>) | undefined {
// Only the latest in-progress session gets activeResponseCallback
const pendingSession = sessions
.slice()
.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())
.find(session => session.state === 'in_progress' || session.state === 'queued');
if (pendingSession) {
return this.createActiveResponseCallback(pr, pendingSession.id);
}
return undefined;
}
private createActiveResponseCallback(pr: PullRequestSearchItem, sessionId: string): (stream: vscode.ChatResponseStream, token: vscode.CancellationToken) => Thenable<void> {
return async (stream: vscode.ChatResponseStream, token: vscode.CancellationToken) => {
await this.waitForQueuedToInProgress(sessionId, token);
return this.streamSessionLogs(stream, pr, sessionId, token);
};
}
private createEmptySession(resource: Uri): vscode.ChatSession {
const sessionId = resource ? resource.path.slice(1) : undefined;
return {
history: [],
...(sessionId && sessionId.startsWith('untitled-')
? {
options: {
[AGENTS_OPTION_GROUP_ID]:
this.sessionAgentMap.get(resource)
?? (this.sessionAgentMap.set(resource, DEFAULT_AGENT_ID), DEFAULT_AGENT_ID)
}
}
: {}),
requestHandler: undefined
};
}
private async findPR(prNumber: number, retries: number = 1) {
let pr = this.chatSessions.get(prNumber);
if (pr) {
return pr;
}
const repoId = await getRepoId(this._gitService);
if (!repoId) {
this.logService.warn('Failed to determine GitHub repo from workspace');
return undefined;
}
try {
pr = await retry(async () => {
const pullRequests = await this._octoKitService.getCopilotPullRequestsForUser(repoId.org, repoId.repo);
const found = pullRequests.find(p => p.number === prNumber);
if (!found) {
this.logService.warn(`Pull request ${prNumber} is not visible yet, retrying...`);
throw new Error(`PR ${prNumber} not yet visible`);
}
return found;
}, 1500, retries);
if (pr) {
this.chatSessions.set(pr.number, pr);
}
return pr;
} catch (error) {
this.logService.warn(`Pull request not found for number: ${prNumber}. ${error instanceof Error ? error.message : String(error)}`);
return undefined;
}
}
private getSessionStatusFromSession(session: SessionInfo): vscode.ChatSessionStatus {
// Map session state to ChatSessionStatus
switch (session.state) {
case 'failed':
return vscode.ChatSessionStatus.Failed;
case 'in_progress':
case 'queued':
return vscode.ChatSessionStatus.InProgress;
case 'completed':
return vscode.ChatSessionStatus.Completed;
default:
return vscode.ChatSessionStatus.Completed;
}
}
private getPullRequestBadge(pr: PullRequestSearchItem): vscode.MarkdownString {
let badgeText: string;
switch (pr.state) {
case 'failed':
badgeText = vscode.l10n.t('$(git-pull-request) Failed in {0}', `#${pr.number}`);
break;
case 'in_progress':
badgeText = vscode.l10n.t('$(git-pull-request) Running in {0}', `#${pr.number}`);
break;
case 'queued':
badgeText = vscode.l10n.t('$(git-pull-request) Queued in {0}', `#${pr.number}`);
break;
default:
badgeText = vscode.l10n.t('$(git-pull-request) {0}', `#${pr.number}`);
break;
}
const badge = new vscode.MarkdownString(badgeText);
badge.supportThemeIcons = true;
return badge;
}
private createPullRequestTooltip(pr: PullRequestSearchItem): vscode.MarkdownString {
const markdown = new vscode.MarkdownString(undefined, true);
markdown.supportHtml = true;
// Repository and date
const date = new Date(pr.createdAt);
const ownerName = `${pr.repository.owner.login}/${pr.repository.name}`;
markdown.appendMarkdown(
`[${ownerName}](https://github.com/${ownerName}) on ${date.toLocaleString('default', {
day: 'numeric',
month: 'short',
year: 'numeric',
})} \n`
);
// Icon, title, and PR number
const icon = this.getIconMarkdown(pr);
// Strip markdown from title for plain text display
const title = this.plainTextRenderer.render(pr.title);
markdown.appendMarkdown(
`${icon} **${title}** [#${pr.number}](${pr.url}) \n`
);
// Body/Description (truncated if too long)
markdown.appendMarkdown(' \n');
const maxBodyLength = 200;
let body = this.plainTextRenderer.render(pr.body || '');
// Convert plain text newlines to markdown line breaks (two spaces + newline)
body = body.replace(/\n/g, ' \n');
body = body.length > maxBodyLength ? body.substring(0, maxBodyLength) + '...' : body;
markdown.appendMarkdown(body + ' \n');
return markdown;
}
private getIconMarkdown(pr: PullRequestSearchItem): string {
const state = pr.state.toUpperCase();
return state === 'MERGED' ? '$(git-merge)' : '$(git-pull-request)';
}
private hasHistoryToSummarize(history: readonly (vscode.ChatRequestTurn | vscode.ChatResponseTurn)[]): boolean {
if (!history || history.length === 0) {
return false;
}
const allResponsesEmpty = history.every(turn => {
if (turn instanceof vscode.ChatResponseTurn) {
return turn.response.length === 0;
}
return true;
});
return !allResponsesEmpty;
}
async delegate(
request: vscode.ChatRequest,
stream: vscode.ChatResponseStream,
context: vscode.ChatContext,
token: vscode.CancellationToken,
metadata: ConfirmationMetadata,
base_ref?: string,
head_ref?: string
): Promise<{ uri: vscode.Uri; title: string; description: string; author: string; linkTag: string }> {
let history: string | undefined;
// TODO: Do this async/optimistically before delegation triggered
if (this.hasHistoryToSummarize(context.history)) {
stream.progress(vscode.l10n.t('Analyzing chat history'));
history = await this._chatDelegationSummaryService.summarize(context, token);
}
let customAgentName: string | undefined;
if (metadata.chatContext.chatSessionContext?.chatSessionItem?.resource) {
customAgentName = this.sessionAgentMap.get(metadata.chatContext.chatSessionContext.chatSessionItem.resource);
if (customAgentName) {
this.logService.debug(`Using custom agent '${customAgentName}' for session ${metadata.chatContext.chatSessionContext.chatSessionItem.resource}`);
}
}
const { result, processedReferences } = await this.extractReferences(metadata.references, !!head_ref);
if (!base_ref) {
const repoId = await getRepoId(this._gitService);
if (!repoId) {
throw new Error(vscode.l10n.t('Open a GitHub repository to use the cloud agent.'));
}
const { default_branch } = await this._githubRepositoryService.getRepositoryInfo(repoId.org, repoId.repo);
base_ref = default_branch;
}
const { number, sessionId } = await this.invokeRemoteAgent(
metadata.prompt,
[result, history].filter(Boolean).join('\n\n').trim(),
token,
stream,
base_ref,
customAgentName,
head_ref,
);
if (history) {
void this._chatDelegationSummaryService.trackSummaryUsage(sessionId, history);
}
this.logService.debug(`Delegated to cloud agent for PR #${number} with session ID ${sessionId}`);
// Store references for this session
const sessionUri = vscode.Uri.from({ scheme: CopilotCloudSessionsProvider.TYPE, path: '/' + number });
// Cache the processed references for presentation later
if (processedReferences.length > 0) {
this.sessionReferencesMap.set(sessionUri, processedReferences);
}
stream.progress(vscode.l10n.t('Fetching pull request details'));
const pullRequest = await this.findPR(number, 5);
if (!pullRequest) {
throw new Error(`Failed to find pull request #${number} after delegation.`);
}
const uri = await toOpenPullRequestWebviewUri({ owner: pullRequest.repository.owner.login, repo: pullRequest.repository.name, pullRequestNumber: pullRequest.number });
if (metadata.chatContext.chatSessionContext?.isUntitled) {
// Untitled flow
this._onDidCommitChatSessionItem.fire({
original: metadata.chatContext.chatSessionContext.chatSessionItem,
modified: {
resource: sessionUri,
label: `Pull Request ${number}`
}
});
} else {
// Delegated flow
// NOTE: VS Code will now close the parent/source chat in most cases.
stream.markdown(vscode.l10n.t('A cloud agent has begun working on your request. Follow its progress in the sessions list and associated pull request.'));
}
// Return this for external callers, eg: CLI
return {
uri, // PR uri
title: pullRequest.title,
description: pullRequest.body || '',
author: getAuthorDisplayName(pullRequest.author),
linkTag: `#${pullRequest.number}`
};
}
private async handleConfirmationData(request: vscode.ChatRequest, stream: vscode.ChatResponseStream, context: vscode.ChatContext, token: vscode.CancellationToken) {
if (!request.prompt || request.prompt.indexOf(':') === -1) {
this.logService.error('Invalid confirmation prompt format.');
return {};
}
// Parse out the button selected by the user
const selection = (request.prompt?.split(':')[0] || '').trim().toUpperCase();
const metadata: unknown = request.acceptedConfirmationData?.[0]?.metadata || request.rejectedConfirmationData?.[0]?.metadata;
try {
validateMetadata(metadata);
} catch (error) {
this.logService.error(`Invalid confirmation metadata: ${error}`);
return {};
}
// -- Process each button press in order of precedence
if (!selection || selection === this.CANCEL.toUpperCase() || token.isCancellationRequested) {
stream.markdown(vscode.l10n.t('Cloud agent cancelled'));
return {};
}
if (selection.includes(this.AUTHORIZE.toUpperCase())) {
stream.progress(vscode.l10n.t('Authorizing'));
try {
await this._authenticationService.getGitHubSession('permissive', { createIfNone: true });
if (!this._authenticationService.permissiveGitHubSession) {
throw new Error('Failed to obtain permissive GitHub session');
}
} catch (error) {
this.logService.error(`Authorization failed: ${error}`);
throw new Error(vscode.l10n.t('Authorization failed. Please sign into GitHub and try again.'));
}
}
let head_ref: string | undefined; // If set, this is the branch we pushed pending changes to.
if (selection.includes(this.COMMIT.toUpperCase())) {
try {
stream.progress(vscode.l10n.t('Committing and pushing local changes'));
head_ref = await this.gitOperationsManager.commitAndPushChanges();
stream.markdown(vscode.l10n.t('Local changes pushed to remote branch `{0}`.', head_ref));
} catch (error) {
this.logService.error(`Commit and push failed: ${error}`);
throw vscode.l10n.t('{0}. Commit or stash your changes and try again.', (error instanceof Error ? error.message : String(error)) ?? vscode.l10n.t('Failed to commit and push changes.'));
}
} else if (selection.includes(this.PUSH_BRANCH.toUpperCase())) {
try {
stream.progress(vscode.l10n.t('Pushing base branch to remote'));
const baseBranch = await this.gitOperationsManager.pushBaseRefToRemote();
stream.markdown(vscode.l10n.t('Base branch `{0}` pushed to remote.', baseBranch));
} catch (error) {
this.logService.error(`Push branch failed: ${error}`);
throw vscode.l10n.t('{0}. Push the current branch to remote and try again.', (error instanceof Error ? error.message : String(error)) ?? vscode.l10n.t('Failed to push current branch.'));
}
}
const base_ref: string = await (async () => {
const res = await this.checkBaseBranchPresentOnRemote();
if (!res) {
// Unexpected
throw new Error(vscode.l10n.t('Repo base branch is not detected on remote. Push your branch and try again.'));
}
return (res?.missingOnRemote || !res?.baseRef) ? res.repoDefaultBranch : res?.baseRef;
})();
stream.progress(vscode.l10n.t('Validating branch `{0}` exists on remote', base_ref));
// Now trigger delegation
try {
await this.delegate(request, stream, context, token, metadata, base_ref, head_ref);
} catch (error) {
this.logService.error(`Failure in delegation: ${error}`);
throw new Error(vscode.l10n.t('{0}', (error instanceof Error ? error.message : String(error))));
}
}
private setWorkspaceContext(key: string, value: string) {
this._extensionContext.workspaceState.update(`${this.WORKSPACE_CONTEXT_PREFIX}.${key}`, value);
}
private getWorkspaceContext(key: string): string | undefined {
return this._extensionContext.workspaceState.get<string>(`${this.WORKSPACE_CONTEXT_PREFIX}.${key}`);
}
resetWorkspaceContext() {
const keys =
this._extensionContext.workspaceState.keys()
.filter(key => key.startsWith(this.WORKSPACE_CONTEXT_PREFIX));
for (const key of keys) {
this.logService.debug(`[resetWorkspaceContext] ${key}`);
this._extensionContext.workspaceState.update(key, undefined);
}
}
private async detectedUncommittedChanges(): Promise<boolean> {
const currentRepository = this._gitService.activeRepository?.get();
if (!currentRepository) {
return false;
}
const git = this._gitExtensionService.getExtensionApi();
const repo = git?.getRepository(currentRepository?.rootUri);
if (!repo) {
return false;
}
return repo.state.workingTreeChanges.length > 0 || repo.state.indexChanges.length > 0;
}
/**
* Checks if the current base branch exists on the remote repository.
* Returns branch information including whether it's missing from remote, the base ref name, and the repository's default branch.
*/
private async checkBaseBranchPresentOnRemote(): Promise<{ missingOnRemote: boolean; baseRef: string; repoDefaultBranch: string } | undefined> {
try {
const repoId = await getRepoId(this._gitService);
if (!repoId) {
return undefined;
}
const { baseRef, repository, remoteName } = await this.gitOperationsManager.repoInfo();
const remoteRepoInfo = await this._githubRepositoryService.getRepositoryInfo(repoId.org, repoId.repo);
const remoteHasRef = await this.gitOperationsManager.checkIfRemoteHasRef(repository, remoteName, baseRef);
if (remoteHasRef) {
// Remote HAS the base branch, no action needed.
return { missingOnRemote: false, baseRef, repoDefaultBranch: remoteRepoInfo.default_branch };
}
// Remote is MISSING the base branch
return { missingOnRemote: true, baseRef, repoDefaultBranch: remoteRepoInfo.default_branch };
} catch (error) {
this.logService.debug(`Failed to check default branch: ${error}`);
return undefined;
}
}
/**
* Returns either all the data for a confirmation dialog, or undefined if no confirmation is needed.
* */
private async buildConfirmation(context: vscode.ChatContext): Promise<{ title: string; message: string; buttons: string[] } | undefined> {
const title: string = this.TITLE;
const buttons: string[] = [this.CANCEL];
let message: string = this.BASE_MESSAGE;
const needsPermissiveAuth = !this._authenticationService.permissiveGitHubSession;