-
Notifications
You must be signed in to change notification settings - Fork 39.3k
Expand file tree
/
Copy pathchangesViewModel.ts
More file actions
512 lines (429 loc) · 20.4 KB
/
changesViewModel.ts
File metadata and controls
512 lines (429 loc) · 20.4 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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Codicon } from '../../../../base/common/codicons.js';
import { arrayEqualsC, structuralEquals } from '../../../../base/common/equals.js';
import { Iterable } from '../../../../base/common/iterator.js';
import { Disposable } from '../../../../base/common/lifecycle.js';
import { derived, derivedOpts, IObservable, IObservableWithChange, ISettableObservable, runOnChange, observableValue, observableSignalFromEvent, constObservable, ObservablePromise, derivedObservableWithCache } from '../../../../base/common/observable.js';
import { isEqual } from '../../../../base/common/resources.js';
import { URI } from '../../../../base/common/uri.js';
import { IStorageService, StorageScope, StorageTarget } from '../../../../platform/storage/common/storage.js';
import { IAgentSessionsService } from '../../../../workbench/contrib/chat/browser/agentSessions/agentSessionsService.js';
import { IChatSessionFileChange, IChatSessionFileChange2 } from '../../../../workbench/contrib/chat/common/chatSessionsService.js';
import { GitDiffChange, IGitService } from '../../../../workbench/contrib/git/common/gitService.js';
import { COPILOT_CLOUD_SESSION_TYPE, IChat } from '../../../services/sessions/common/session.js';
import { ISessionsManagementService } from '../../../services/sessions/common/sessionsManagement.js';
import { IAgentFeedbackService } from '../../agentFeedback/browser/agentFeedbackService.js';
import { CodeReviewStateKind, getCodeReviewFilesFromSessionChanges, getCodeReviewVersion, ICodeReviewService, PRReviewStateKind } from '../../codeReview/browser/codeReviewService.js';
import { IGitHubService } from '../../github/browser/githubService.js';
import { toPRContentUri } from '../../github/common/utils.js';
import { ChangesVersionMode, ChangesViewMode, IsolationMode } from '../common/changes.js';
function toIChatSessionFileChange2(changes: GitDiffChange[], originalRef: string | undefined, modifiedRef: string | undefined): IChatSessionFileChange2[] {
return changes.map(change => ({
uri: change.uri,
originalUri: change.originalUri
? originalRef
? change.originalUri.with({ scheme: 'git', query: JSON.stringify({ path: change.originalUri.fsPath, ref: originalRef }) })
: change.originalUri
: undefined,
modifiedUri: change.modifiedUri
? modifiedRef
? change.modifiedUri.with({ scheme: 'git', query: JSON.stringify({ path: change.modifiedUri.fsPath, ref: modifiedRef }) })
: change.modifiedUri
: undefined,
insertions: change.insertions,
deletions: change.deletions,
} satisfies IChatSessionFileChange2));
}
function sortChatByLastTurnEndDesc(chatA: IChat, chatB: IChat): number {
const chatALastTurnEnd = chatA.lastTurnEnd.get();
const chatBLastTurnEnd = chatB.lastTurnEnd.get();
if (!chatALastTurnEnd && !chatBLastTurnEnd) {
return 0;
}
if (!chatALastTurnEnd) {
return 1;
}
if (!chatBLastTurnEnd) {
return -1;
}
return chatBLastTurnEnd.getTime() - chatALastTurnEnd.getTime();
}
export interface ActiveSessionState {
readonly isolationMode: IsolationMode;
readonly hasGitRepository: boolean;
readonly branchName: string | undefined;
readonly baseBranchName: string | undefined;
readonly upstreamBranchName: string | undefined;
readonly isMergeBaseBranchProtected: boolean | undefined;
readonly incomingChanges: number | undefined;
readonly outgoingChanges: number | undefined;
readonly uncommittedChanges: number | undefined;
readonly hasGitHubRemote: boolean | undefined;
readonly hasPullRequest: boolean | undefined;
readonly hasOpenPullRequest: boolean | undefined;
}
export class ChangesViewModel extends Disposable {
readonly activeSessionResourceObs: IObservable<URI | undefined>;
readonly activeSessionTypeObs: IObservable<string | undefined>;
readonly activeSessionChangesObs: IObservable<readonly (IChatSessionFileChange | IChatSessionFileChange2)[]>;
readonly activeSessionHasGitRepositoryObs: IObservable<boolean>;
readonly activeSessionFirstCheckpointRefObs: IObservable<string | undefined>;
readonly activeSessionLastCheckpointRefObs: IObservable<string | undefined>;
readonly activeSessionReviewCommentCountByFileObs: IObservable<Map<string, number>>;
readonly activeSessionAgentFeedbackCountByFileObs: IObservable<Map<string, number>>;
readonly activeSessionStateObs: IObservable<ActiveSessionState | undefined>;
readonly activeSessionIsLoadingObs: IObservable<boolean>;
private _activeSessionMetadataObs!: IObservable<{ readonly [key: string]: unknown } | undefined>;
private _activeSessionAllChangesPromiseObs!: IObservableWithChange<IObservable<IChatSessionFileChange2[] | undefined>>;
private _activeSessionLastTurnChangesPromiseObs!: IObservableWithChange<IObservable<IChatSessionFileChange2[] | undefined>>;
readonly versionModeObs: ISettableObservable<ChangesVersionMode>;
setVersionMode(mode: ChangesVersionMode): void {
if (this.versionModeObs.get() === mode) {
return;
}
this.versionModeObs.set(mode, undefined);
}
readonly viewModeObs: ISettableObservable<ChangesViewMode>;
setViewMode(mode: ChangesViewMode): void {
if (this.viewModeObs.get() === mode) {
return;
}
this.viewModeObs.set(mode, undefined);
this.storageService.store('changesView.viewMode', mode, StorageScope.WORKSPACE, StorageTarget.USER);
}
constructor(
@IAgentFeedbackService private readonly agentFeedbackService: IAgentFeedbackService,
@IAgentSessionsService private readonly agentSessionsService: IAgentSessionsService,
@ICodeReviewService private readonly codeReviewService: ICodeReviewService,
@IGitHubService private readonly gitHubService: IGitHubService,
@IGitService private readonly gitService: IGitService,
@ISessionsManagementService private readonly sessionManagementService: ISessionsManagementService,
@IStorageService private readonly storageService: IStorageService,
) {
super();
// Active session resource
this.activeSessionResourceObs = derivedOpts({ equalsFn: isEqual }, reader => {
const activeSession = this.sessionManagementService.activeSession.read(reader);
return activeSession?.resource;
});
// Active session type
this.activeSessionTypeObs = derived(reader => {
const activeSession = this.sessionManagementService.activeSession.read(reader);
return activeSession?.sessionType;
});
// Active session metadata
this._activeSessionMetadataObs = this._getActiveSessionMetadata();
// Active session has git repository
this.activeSessionHasGitRepositoryObs = derived(reader => {
const sessionType = this.activeSessionTypeObs.read(reader);
const metadata = this._activeSessionMetadataObs.read(reader);
return sessionType === COPILOT_CLOUD_SESSION_TYPE || metadata?.repositoryPath !== undefined;
});
// Active session first checkpoint ref
this.activeSessionFirstCheckpointRefObs = derived(reader => {
const metadata = this._activeSessionMetadataObs.read(reader);
return metadata?.firstCheckpointRef as string | undefined;
});
// Active session last checkpoint ref
this.activeSessionLastCheckpointRefObs = derived(reader => {
const activeSessionChats = this.sessionManagementService.activeSession.read(reader)?.chats.read(reader);
if (!activeSessionChats || activeSessionChats.length === 0) {
return undefined;
}
// Session has only one chat
if (activeSessionChats.length === 1) {
const metadata = this._activeSessionMetadataObs.read(reader);
return metadata?.lastCheckpointRef as string | undefined;
}
// Session has multiple chats - find the last chat that completed
const chatsSortedByLastTurnEnd = activeSessionChats.toSorted(sortChatByLastTurnEndDesc);
const model = this.agentSessionsService.getSession(chatsSortedByLastTurnEnd[0].resource);
return model?.metadata?.lastCheckpointRef as string | undefined;
});
// Active session state
const { isLoading, state } = this._getActiveSessionState();
this.activeSessionIsLoadingObs = isLoading;
this.activeSessionStateObs = state;
// Active session changes
this.activeSessionChangesObs = this._getActiveSessionChanges();
// Active session review comment count by file
this.activeSessionReviewCommentCountByFileObs = this._getActiveSessionReviewComments();
// Active session agent feedback count by file
this.activeSessionAgentFeedbackCountByFileObs = this._getActiveSessionAgentFeedback();
// Version mode
this.versionModeObs = observableValue<ChangesVersionMode>(this, ChangesVersionMode.BranchChanges);
this._register(runOnChange(this.activeSessionResourceObs, () => {
this.setVersionMode(ChangesVersionMode.BranchChanges);
}));
// View mode
const storedMode = this.storageService.get('changesView.viewMode', StorageScope.WORKSPACE);
const initialMode = storedMode === ChangesViewMode.Tree ? ChangesViewMode.Tree : ChangesViewMode.List;
this.viewModeObs = observableValue<ChangesViewMode>(this, initialMode);
}
private _getActiveSessionMetadata(): IObservable<{ readonly [key: string]: unknown } | undefined> {
const sessionsChangedSignal = observableSignalFromEvent(this,
this.sessionManagementService.onDidChangeSessions);
const sessionMetadata = derivedObservableWithCache<{ readonly [key: string]: unknown } | undefined>(this, (reader, lastValue) => {
const sessionResource = this.activeSessionResourceObs.read(reader);
if (!sessionResource) {
return undefined;
}
sessionsChangedSignal.read(reader);
const model = this.agentSessionsService.getSession(sessionResource);
if (model === undefined) {
// This occurs when the untitled session is committed. In order
// to avoid flickering of the toolbar, we keep the old metadata
// until the new metadata is available.
return lastValue;
}
return model.metadata;
});
return derivedOpts<{ readonly [key: string]: unknown } | undefined>({ equalsFn: structuralEquals }, reader => {
return sessionMetadata.read(reader);
});
}
private _getActiveSessionChanges(): IObservable<readonly (IChatSessionFileChange | IChatSessionFileChange2)[]> {
// Changes
const activeSessionChangesObs = derived(reader => {
const activeSession = this.sessionManagementService.activeSession.read(reader);
if (!activeSession) {
return Iterable.empty();
}
return activeSession.changes.read(reader);
});
const activeSessionRepositoryPathObs = derived(reader => {
const metadata = this._activeSessionMetadataObs.read(reader);
const repositoryPath = metadata?.repositoryPath as string | undefined;
const worktreePath = metadata?.worktreePath as string | undefined;
return worktreePath ?? repositoryPath;
});
// All changes
this._activeSessionAllChangesPromiseObs = derived(reader => {
const sessionType = this.activeSessionTypeObs.read(reader);
if (sessionType === COPILOT_CLOUD_SESSION_TYPE) {
// Cloud session
const metadata = this._activeSessionMetadataObs.read(reader);
const firstCheckpointRef = metadata?.baseRefOid as string | undefined;
const lastCheckpointRef = metadata?.headRefOid as string | undefined;
if (!firstCheckpointRef || !lastCheckpointRef) {
return constObservable([]);
}
const diffPromise = this._getPullRequestChanges(firstCheckpointRef, lastCheckpointRef);
return new ObservablePromise(diffPromise).resolvedValue;
}
// Local session
const repositoryPath = activeSessionRepositoryPathObs.read(reader);
const firstCheckpointRef = this.activeSessionFirstCheckpointRefObs.read(reader);
const lastCheckpointRef = this.activeSessionLastCheckpointRefObs.read(reader);
if (!repositoryPath || !firstCheckpointRef || !lastCheckpointRef) {
return constObservable([]);
}
const diffPromise = this._getRepositoryChanges(repositoryPath, firstCheckpointRef, lastCheckpointRef);
return new ObservablePromise(diffPromise).resolvedValue;
});
// Last turn changes
this._activeSessionLastTurnChangesPromiseObs = derived(reader => {
const sessionType = this.activeSessionTypeObs.read(reader);
if (sessionType === COPILOT_CLOUD_SESSION_TYPE) {
// Cloud session
const metadata = this._activeSessionMetadataObs.read(reader);
const lastCheckpointRef = metadata?.headRefOid as string | undefined;
if (!lastCheckpointRef) {
return constObservable([]);
}
const diffPromise = this._getPullRequestChanges(`${lastCheckpointRef}^`, lastCheckpointRef);
return new ObservablePromise(diffPromise).resolvedValue;
}
// Local session
const repositoryPath = activeSessionRepositoryPathObs.read(reader);
const lastCheckpointRef = this.activeSessionLastCheckpointRefObs.read(reader);
if (!repositoryPath || !lastCheckpointRef) {
return constObservable([]);
}
const diffPromise = this._getRepositoryChanges(repositoryPath, `${lastCheckpointRef}^`, lastCheckpointRef);
return new ObservablePromise(diffPromise).resolvedValue;
});
return derivedOpts({
equalsFn: arrayEqualsC<IChatSessionFileChange | IChatSessionFileChange2>()
}, reader => {
const hasGitRepository = this.activeSessionHasGitRepositoryObs.read(reader);
if (!hasGitRepository) {
return [];
}
const versionMode = this.versionModeObs.read(reader);
if (versionMode === ChangesVersionMode.BranchChanges) {
return activeSessionChangesObs.read(reader);
} else if (versionMode === ChangesVersionMode.AllChanges) {
return this._activeSessionAllChangesPromiseObs.read(reader).read(reader) ?? [];
} else if (versionMode === ChangesVersionMode.LastTurn) {
return this._activeSessionLastTurnChangesPromiseObs.read(reader).read(reader) ?? [];
}
return [];
});
}
private _getActiveSessionState(): { isLoading: IObservable<boolean>; state: IObservable<ActiveSessionState | undefined> } {
const isLoadingObs = derived(reader => {
// Branch changes
const versionMode = this.versionModeObs.read(reader);
if (versionMode === ChangesVersionMode.BranchChanges) {
return false;
}
// All changes
if (versionMode === ChangesVersionMode.AllChanges) {
const allChangesResult = this._activeSessionAllChangesPromiseObs.read(reader).read(reader);
return allChangesResult === undefined;
}
// Last turn changes
if (versionMode === ChangesVersionMode.LastTurn) {
const lastTurnChangesResult = this._activeSessionLastTurnChangesPromiseObs.read(reader).read(reader);
return lastTurnChangesResult === undefined;
}
return false;
});
const activeSessionStateObs = derivedObservableWithCache<ActiveSessionState | undefined>(this, (reader, lastValue) => {
const isLoading = isLoadingObs.read(reader);
if (isLoading) {
return lastValue;
}
const sessionMetadata = this._activeSessionMetadataObs.read(reader);
const activeSession = this.sessionManagementService.activeSession.read(reader);
const workspace = activeSession?.workspace.read(reader);
// Session state
const workspaceRepository = workspace?.repositories[0];
const hasGitRepository = this.activeSessionHasGitRepositoryObs.read(reader);
const branchName = (sessionMetadata?.branchName ?? sessionMetadata?.branch) as string | undefined;
const baseBranchName = (sessionMetadata?.baseBranchName ?? sessionMetadata?.baseBranch) as string | undefined;
const isMergeBaseBranchProtected = workspaceRepository?.baseBranchProtected;
const isolationMode = workspaceRepository?.workingDirectory === undefined
? IsolationMode.Workspace
: IsolationMode.Worktree;
// Pull request state
const gitHubInfo = activeSession?.gitHubInfo.read(reader);
const hasPullRequest = gitHubInfo?.pullRequest?.uri !== undefined;
const hasOpenPullRequest = hasPullRequest &&
(gitHubInfo.pullRequest.icon?.id === Codicon.gitPullRequestDraft.id ||
gitHubInfo.pullRequest.icon?.id === Codicon.gitPullRequest.id);
// Repository state
const hasGitHubRemote = (sessionMetadata?.hasGitHubRemote as boolean | undefined) === true;
const upstreamBranchName = sessionMetadata?.upstreamBranchName as string | undefined;
const incomingChanges = (sessionMetadata?.incomingChanges as number | undefined) ?? 0;
const outgoingChanges = (sessionMetadata?.outgoingChanges as number | undefined) ?? 0;
const uncommittedChanges = (sessionMetadata?.uncommittedChanges as number | undefined) ?? 0;
return {
isolationMode,
hasGitRepository,
branchName,
baseBranchName,
isMergeBaseBranchProtected,
upstreamBranchName,
incomingChanges,
outgoingChanges,
uncommittedChanges,
hasGitHubRemote,
hasPullRequest,
hasOpenPullRequest
} satisfies ActiveSessionState;
});
return {
isLoading: isLoadingObs,
state: derivedOpts({ equalsFn: structuralEquals },
reader => activeSessionStateObs.read(reader))
};
}
private _getActiveSessionReviewComments(): IObservable<Map<string, number>> {
return derived(reader => {
const sessionResource = this.activeSessionResourceObs.read(reader);
const changes = [...this.activeSessionChangesObs.read(reader)];
if (!sessionResource) {
return new Map<string, number>();
}
const result = new Map<string, number>();
const prReviewState = this.codeReviewService.getPRReviewState(sessionResource).read(reader);
if (prReviewState.kind === PRReviewStateKind.Loaded) {
for (const comment of prReviewState.comments) {
const uriKey = comment.uri.fsPath;
result.set(uriKey, (result.get(uriKey) ?? 0) + 1);
}
}
if (changes.length === 0) {
return result;
}
const reviewFiles = getCodeReviewFilesFromSessionChanges(changes);
const reviewVersion = getCodeReviewVersion(reviewFiles);
const reviewState = this.codeReviewService.getReviewState(sessionResource).read(reader);
if (reviewState.kind !== CodeReviewStateKind.Result || reviewState.version !== reviewVersion) {
return result;
}
for (const comment of reviewState.comments) {
const uriKey = comment.uri.fsPath;
result.set(uriKey, (result.get(uriKey) ?? 0) + 1);
}
return result;
});
}
private _getActiveSessionAgentFeedback(): IObservable<Map<string, number>> {
return derived(reader => {
const sessionResource = this.activeSessionResourceObs.read(reader);
if (!sessionResource) {
return new Map<string, number>();
}
observableSignalFromEvent(this, this.agentFeedbackService.onDidChangeFeedback).read(reader);
const feedbackItems = this.agentFeedbackService.getFeedback(sessionResource);
const result = new Map<string, number>();
for (const item of feedbackItems) {
if (!item.sourcePRReviewCommentId) {
const uriKey = item.resourceUri.fsPath;
result.set(uriKey, (result.get(uriKey) ?? 0) + 1);
}
}
return result;
});
}
private async _getRepositoryChanges(repositoryPath: string, firstCheckpointRef: string, lastCheckpointRef: string): Promise<IChatSessionFileChange2[] | undefined> {
const repository = await this.gitService.openRepository(URI.file(repositoryPath));
const changes = await repository?.diffBetweenWithStats2(`${firstCheckpointRef}..${lastCheckpointRef}`) ?? [];
return toIChatSessionFileChange2(changes, firstCheckpointRef, lastCheckpointRef);
}
private async _getPullRequestChanges(firstCheckpointRef: string, lastCheckpointRef: string): Promise<IChatSessionFileChange2[] | undefined> {
const gitHubInfo = this.sessionManagementService.activeSession.get()?.gitHubInfo.get();
if (!gitHubInfo?.owner || !gitHubInfo?.repo || !gitHubInfo?.pullRequest?.number) {
return [];
}
const params = {
owner: gitHubInfo.owner,
repo: gitHubInfo.repo,
prNumber: gitHubInfo.pullRequest.number,
} as const;
const changes = await this.gitHubService.getChangedFiles(params.owner, params.repo, firstCheckpointRef, lastCheckpointRef);
return changes.map(change => {
const uri = toPRContentUri(change.filename, {
...params,
commitSha: lastCheckpointRef,
status: change.status,
isBase: false
});
const originalUri = change.status !== 'added'
? toPRContentUri(change.previous_filename || change.filename, {
...params,
commitSha: firstCheckpointRef,
previousFileName: change.previous_filename,
status: change.status,
isBase: true
})
: undefined;
const modifiedUri = change.status !== 'removed'
? uri
: undefined;
return {
uri,
originalUri,
modifiedUri,
insertions: change.additions,
deletions: change.deletions
} satisfies IChatSessionFileChange2;
});
}
}