-
Notifications
You must be signed in to change notification settings - Fork 38.3k
Expand file tree
/
Copy pathagentSessionsControl.ts
More file actions
500 lines (412 loc) · 19.8 KB
/
agentSessionsControl.ts
File metadata and controls
500 lines (412 loc) · 19.8 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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IContextKey, IContextKeyService } from '../../../../../platform/contextkey/common/contextkey.js';
import { ChatContextKeys } from '../../common/actions/chatContextKeys.js';
import { IContextMenuService } from '../../../../../platform/contextview/browser/contextView.js';
import { IInstantiationService } from '../../../../../platform/instantiation/common/instantiation.js';
import { IOpenEvent, WorkbenchCompressibleAsyncDataTree } from '../../../../../platform/list/browser/listService.js';
import { $, append, EventHelper, addDisposableListener, EventType, hide, setVisibility } from '../../../../../base/browser/dom.js';
import { StandardKeyboardEvent } from '../../../../../base/browser/keyboardEvent.js';
import { KeyCode } from '../../../../../base/common/keyCodes.js';
import { localize } from '../../../../../nls.js';
import { AgentSessionSection, IAgentSession, IAgentSessionSection, IAgentSessionsModel, IMarshalledAgentSessionContext, isAgentSession, isAgentSessionSection } from './agentSessionsModel.js';
import { AgentSessionListItem, AgentSessionRenderer, AgentSessionsAccessibilityProvider, AgentSessionsCompressionDelegate, AgentSessionsDataSource, AgentSessionsDragAndDrop, AgentSessionsIdentityProvider, AgentSessionsKeyboardNavigationLabelProvider, AgentSessionsListDelegate, AgentSessionSectionRenderer, AgentSessionsSorter, IAgentSessionsFilter, IAgentSessionsSorterOptions } from './agentSessionsViewer.js';
import { AgentSessionApprovalModel } from './agentSessionApprovalModel.js';
import { FuzzyScore } from '../../../../../base/common/filters.js';
import { IMenuService, MenuId } from '../../../../../platform/actions/common/actions.js';
import { IChatSessionsService } from '../../common/chatSessionsService.js';
import { ICommandService } from '../../../../../platform/commands/common/commands.js';
import { ACTION_ID_NEW_CHAT } from '../actions/chatActions.js';
import { Emitter, Event } from '../../../../../base/common/event.js';
import { Disposable } from '../../../../../base/common/lifecycle.js';
import { Throttler } from '../../../../../base/common/async.js';
import { ITreeContextMenuEvent } from '../../../../../base/browser/ui/tree/tree.js';
import { MarshalledId } from '../../../../../base/common/marshallingIds.js';
import { Separator } from '../../../../../base/common/actions.js';
import { RenderIndentGuides, TreeFindMode } from '../../../../../base/browser/ui/tree/abstractTree.js';
import { IAgentSessionsService } from './agentSessionsService.js';
import { ITelemetryService } from '../../../../../platform/telemetry/common/telemetry.js';
import { IListStyles } from '../../../../../base/browser/ui/list/listWidget.js';
import { IStyleOverride } from '../../../../../platform/theme/browser/defaultStyles.js';
import { getAgentSessionTime, IAgentSessionsControl } from './agentSessions.js';
import { HoverPosition } from '../../../../../base/browser/ui/hover/hoverWidget.js';
import { URI } from '../../../../../base/common/uri.js';
import { ISessionOpenOptions, openSession } from './agentSessionsOpener.js';
import { IEditorService } from '../../../../services/editor/common/editorService.js';
import { ChatEditorInput } from '../widgetHosts/editor/chatEditorInput.js';
import { IMouseEvent } from '../../../../../base/browser/mouseEvent.js';
import { IChatWidget } from '../chat.js';
export interface IAgentSessionsControlOptions extends IAgentSessionsSorterOptions {
readonly overrideStyles: IStyleOverride<IListStyles>;
readonly filter: IAgentSessionsFilter;
readonly source: string;
readonly disableHover?: boolean;
readonly showIsolationIcon?: boolean;
readonly enableApprovalRow?: boolean;
getHoverPosition(): HoverPosition;
trackActiveEditorSession(): boolean;
collapseOlderSections?(): boolean;
overrideSessionOpenOptions?(openEvent: IOpenEvent<AgentSessionListItem | undefined>): ISessionOpenOptions;
overrideSessionOpen?(resource: URI, openOptions?: ISessionOpenOptions): Promise<void>;
notifySessionOpened?(resource: URI, widget: IChatWidget): void;
}
type AgentSessionOpenedClassification = {
owner: 'bpasero';
providerType: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The provider type of the opened agent session.' };
source: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The source of the opened agent session.' };
comment: 'Event fired when a agent session is opened from the agent sessions control.';
};
type AgentSessionOpenedEvent = {
providerType: string;
source: string;
};
export class AgentSessionsControl extends Disposable implements IAgentSessionsControl {
private sessionsContainer: HTMLElement | undefined;
get element(): HTMLElement | undefined { return this.sessionsContainer; }
private emptyFilterMessage: HTMLElement | undefined;
private sessionsList: WorkbenchCompressibleAsyncDataTree<IAgentSessionsModel, AgentSessionListItem, FuzzyScore> | undefined;
private sessionsListFindIsOpen = false;
private readonly updateSessionsListThrottler = this._register(new Throttler());
private readonly _onDidUpdate = this._register(new Emitter<void>());
readonly onDidUpdate: Event<void> = this._onDidUpdate.event;
private visible: boolean = true;
private focusedAgentSessionArchivedContextKey: IContextKey<boolean>;
private focusedAgentSessionReadContextKey: IContextKey<boolean>;
private focusedAgentSessionTypeContextKey: IContextKey<string>;
private hasMultipleAgentSessionsSelectedContextKey: IContextKey<boolean>;
constructor(
private readonly container: HTMLElement,
private readonly options: IAgentSessionsControlOptions,
@IContextMenuService private readonly contextMenuService: IContextMenuService,
@IContextKeyService private readonly contextKeyService: IContextKeyService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IChatSessionsService private readonly chatSessionsService: IChatSessionsService,
@ICommandService private readonly commandService: ICommandService,
@IMenuService private readonly menuService: IMenuService,
@IAgentSessionsService private readonly agentSessionsService: IAgentSessionsService,
@ITelemetryService private readonly telemetryService: ITelemetryService,
@IEditorService private readonly editorService: IEditorService,
) {
super();
this.focusedAgentSessionArchivedContextKey = ChatContextKeys.isArchivedAgentSession.bindTo(this.contextKeyService);
this.focusedAgentSessionReadContextKey = ChatContextKeys.isReadAgentSession.bindTo(this.contextKeyService);
this.focusedAgentSessionTypeContextKey = ChatContextKeys.agentSessionType.bindTo(this.contextKeyService);
this.hasMultipleAgentSessionsSelectedContextKey = ChatContextKeys.hasMultipleAgentSessionsSelected.bindTo(this.contextKeyService);
this.create(this.container);
this.registerListeners();
}
private registerListeners(): void {
this._register(this.editorService.onDidActiveEditorChange(() => this.revealAndFocusActiveEditorSession()));
}
private revealAndFocusActiveEditorSession(): void {
if (
!this.options.trackActiveEditorSession() ||
!this.visible
) {
return;
}
const input = this.editorService.activeEditor;
const resource = (input instanceof ChatEditorInput) ? input.sessionResource : input?.resource;
if (!resource) {
return;
}
const matchingSession = this.agentSessionsService.model.getSession(resource);
if (matchingSession && this.sessionsList?.hasNode(matchingSession)) {
if (this.sessionsList.getRelativeTop(matchingSession) === null) {
this.sessionsList.reveal(matchingSession, 0.5); // only reveal when not already visible
}
this.sessionsList.setFocus([matchingSession]);
this.sessionsList.setSelection([matchingSession]);
}
}
private create(container: HTMLElement): void {
this.sessionsContainer = append(container, $('.agent-sessions-viewer'));
this.createEmptyFilterMessage(this.sessionsContainer);
this.createList(this.sessionsContainer);
}
private createEmptyFilterMessage(container: HTMLElement): void {
this.emptyFilterMessage = append(container, $('.agent-sessions-empty-filter-message'));
hide(this.emptyFilterMessage);
const span = append(this.emptyFilterMessage, $('span'));
span.textContent = localize('agentSessions.noFilterResults', "No matching sessions.");
const link = append(this.emptyFilterMessage, $('span.reset-filter-link'));
link.textContent = localize('agentSessions.clearFilters', "Clear Filter");
link.tabIndex = 0;
link.setAttribute('role', 'button');
this._register(addDisposableListener(link, EventType.CLICK, () => this.options.filter.reset()));
this._register(addDisposableListener(link, EventType.KEY_DOWN, (e) => {
const event = new StandardKeyboardEvent(e);
if (event.keyCode === KeyCode.Enter || event.keyCode === KeyCode.Space) {
event.preventDefault();
this.options.filter.reset();
}
}));
}
private createList(container: HTMLElement): void {
const collapseByDefault = (element: unknown) => {
if (isAgentSessionSection(element)) {
if (element.section === AgentSessionSection.More && !this.options.filter.getExcludes().read) {
return true; // More section is always collapsed unless only showing unread
}
if (element.section === AgentSessionSection.Archived && this.options.filter.getExcludes().archived) {
return true; // Archived section is collapsed when archived are excluded
}
if (this.options.collapseOlderSections?.()) {
const olderSections = [AgentSessionSection.Week, AgentSessionSection.Older, AgentSessionSection.Archived];
if (olderSections.includes(element.section)) {
return true; // Collapse older time sections if option is enabled
}
if (element.section === AgentSessionSection.Yesterday && this.hasTodaySessions()) {
return true; // Also collapse Yesterday when there are sessions from Today
}
}
}
return false;
};
const sorter = new AgentSessionsSorter(this.options);
const approvalModel = this.options.enableApprovalRow ? this._register(this.instantiationService.createInstance(AgentSessionApprovalModel)) : undefined;
const sessionRenderer = this._register(this.instantiationService.createInstance(AgentSessionRenderer, this.options, approvalModel));
const sessionFilter = this._register(new AgentSessionsDataSource(this.options.filter, sorter));
const list = this.sessionsList = this._register(this.instantiationService.createInstance(WorkbenchCompressibleAsyncDataTree,
'AgentSessionsView',
container,
new AgentSessionsListDelegate(approvalModel),
new AgentSessionsCompressionDelegate(),
[
sessionRenderer,
this.instantiationService.createInstance(AgentSessionSectionRenderer),
],
sessionFilter,
{
accessibilityProvider: new AgentSessionsAccessibilityProvider(),
dnd: this.instantiationService.createInstance(AgentSessionsDragAndDrop),
identityProvider: new AgentSessionsIdentityProvider(),
horizontalScrolling: false,
multipleSelectionSupport: true,
findWidgetEnabled: true,
defaultFindMode: TreeFindMode.Filter,
keyboardNavigationLabelProvider: new AgentSessionsKeyboardNavigationLabelProvider(),
overrideStyles: this.options.overrideStyles,
twistieAdditionalCssClass: () => 'force-no-twistie',
collapseByDefault: (element: unknown) => collapseByDefault(element),
renderIndentGuides: RenderIndentGuides.None,
}
)) as WorkbenchCompressibleAsyncDataTree<IAgentSessionsModel, AgentSessionListItem, FuzzyScore>;
ChatContextKeys.agentSessionsViewerFocused.bindTo(list.contextKeyService);
this._register(sessionRenderer.onDidChangeItemHeight(session => {
if (list.hasNode(session)) {
list.updateElementHeight(session, undefined);
}
}));
this._register(sessionFilter.onDidGetChildren(count => {
this.updateEmptyFilterMessage(count);
}));
const model = this.agentSessionsService.model;
this._register(this.options.filter.onDidChange(async () => {
if (this.visible) {
this.updateSectionCollapseStates();
this.update();
}
}));
this._register(model.onDidChangeSessions(() => {
if (this.visible) {
this.update();
}
}));
list.setInput(model);
this._register(list.onDidOpen(e => this.openAgentSession(e)));
this._register(list.onContextMenu(e => this.showContextMenu(e)));
this._register(list.onMouseDblClick(({ element }) => {
if (element === null) {
this.commandService.executeCommand(ACTION_ID_NEW_CHAT);
}
}));
this._register(Event.any(list.onDidChangeFocus, list.onDidChangeSelection, model.onDidChangeSessions)(() => {
const focused = list.getFocus().at(0);
if (focused && isAgentSession(focused)) {
this.focusedAgentSessionArchivedContextKey.set(focused.isArchived());
this.focusedAgentSessionReadContextKey.set(focused.isRead());
this.focusedAgentSessionTypeContextKey.set(focused.providerType);
} else {
this.focusedAgentSessionArchivedContextKey.reset();
this.focusedAgentSessionReadContextKey.reset();
this.focusedAgentSessionTypeContextKey.reset();
}
const selection = list.getSelection().filter(isAgentSession);
this.hasMultipleAgentSessionsSelectedContextKey.set(selection.length > 1);
}));
this._register(list.onDidChangeFindOpenState(open => {
this.sessionsListFindIsOpen = open;
this.updateSectionCollapseStates();
}));
}
private updateEmptyFilterMessage(visibleChildren: number): void {
if (!this.emptyFilterMessage || !this.sessionsList) {
return;
}
const model = this.agentSessionsService.model;
const hasSessionsInModel = model.sessions.length > 0;
const hasVisibleChildren = visibleChildren > 0;
const isFilterActive = !this.options.filter.isDefault();
const showMessage = hasSessionsInModel && !hasVisibleChildren && isFilterActive;
setVisibility(showMessage, this.emptyFilterMessage);
}
private hasTodaySessions(): boolean {
const startOfToday = new Date().setHours(0, 0, 0, 0);
return this.agentSessionsService.model.sessions.some(session =>
!session.isArchived() &&
getAgentSessionTime(session.timing) >= startOfToday
);
}
private async openAgentSession(e: IOpenEvent<AgentSessionListItem | undefined>): Promise<void> {
const element = e.element;
if (!element || isAgentSessionSection(element)) {
return; // Section headers are not openable
}
this.telemetryService.publicLog2<AgentSessionOpenedEvent, AgentSessionOpenedClassification>('agentSessionOpened', {
providerType: element.providerType,
source: this.options.source
});
const options = this.options.overrideSessionOpenOptions?.(e) ?? e;
if (this.options.overrideSessionOpen) {
await this.options.overrideSessionOpen(element.resource, options);
} else {
const widget = await this.instantiationService.invokeFunction(openSession, element, options);
if (widget) {
this.options.notifySessionOpened?.(element.resource, widget);
}
}
}
private async showContextMenu({ element, anchor, browserEvent }: ITreeContextMenuEvent<AgentSessionListItem>): Promise<void> {
if (!element) {
return;
}
EventHelper.stop(browserEvent, true);
if (isAgentSessionSection(element)) {
this.showAgentSessionSectionContextMenu(element, anchor);
} else {
this.showAgentSessionContextMenu(element, anchor);
}
}
private async showAgentSessionSectionContextMenu(section: IAgentSessionSection, anchor: HTMLElement | IMouseEvent): Promise<void> {
const contextOverlay: Array<[string, boolean | string]> = [];
contextOverlay.push([ChatContextKeys.agentSessionSection.key, section.section]);
const menu = this.menuService.createMenu(MenuId.AgentSessionSectionContext, this.contextKeyService.createOverlay(contextOverlay));
this.contextMenuService.showContextMenu({
getActions: () => Separator.join(...menu.getActions({ arg: section, shouldForwardArgs: true }).map(([, actions]) => actions)),
getAnchor: () => anchor,
getActionsContext: () => section,
});
menu.dispose();
}
private async showAgentSessionContextMenu(session: IAgentSession, anchor: HTMLElement | IMouseEvent): Promise<void> {
this.chatSessionsService.activateChatSessionItemProvider(session.providerType);
const contextOverlay: Array<[string, boolean | string]> = [];
contextOverlay.push([ChatContextKeys.isArchivedAgentSession.key, session.isArchived()]);
contextOverlay.push([ChatContextKeys.isReadAgentSession.key, session.isRead()]);
contextOverlay.push([ChatContextKeys.agentSessionType.key, session.providerType]);
const menu = this.menuService.createMenu(MenuId.AgentSessionsContext, this.contextKeyService.createOverlay(contextOverlay));
const selection = this.sessionsList?.getSelection().filter(isAgentSession) ?? [];
const marshalledContext: IMarshalledAgentSessionContext = {
session,
sessions: selection.length > 1 && selection.includes(session) ? selection : [session],
$mid: MarshalledId.AgentSessionContext
};
this.contextMenuService.showContextMenu({
getActions: () => Separator.join(...menu.getActions({ arg: marshalledContext, shouldForwardArgs: true }).map(([, actions]) => actions)),
getAnchor: () => anchor,
getActionsContext: () => marshalledContext,
});
menu.dispose();
}
openFind(): void {
this.sessionsList?.openFind();
}
private updateSectionCollapseStates(): void {
if (!this.sessionsList) {
return;
}
const model = this.agentSessionsService.model;
for (const child of this.sessionsList.getNode(model).children) {
if (!isAgentSessionSection(child.element)) {
continue;
}
switch (child.element.section) {
case AgentSessionSection.Archived: {
const shouldCollapseArchived =
!this.sessionsListFindIsOpen && // always expand when find is open
this.options.filter.getExcludes().archived; // only collapse when archived are excluded from filter
if (shouldCollapseArchived && !child.collapsed) {
this.sessionsList.collapse(child.element);
} else if (!shouldCollapseArchived && child.collapsed) {
this.sessionsList.expand(child.element);
}
break;
}
case AgentSessionSection.More: {
if (child.collapsed && this.sessionsListFindIsOpen) {
this.sessionsList.expand(child.element); // always expand when find is open
}
break;
}
}
}
}
refresh(): Promise<void> {
return this.agentSessionsService.model.resolve(undefined);
}
async update(): Promise<void> {
return this.updateSessionsListThrottler.queue(async () => {
await this.sessionsList?.updateChildren();
this._onDidUpdate.fire();
});
}
setVisible(visible: boolean): void {
if (this.visible === visible) {
return;
}
this.visible = visible;
if (this.visible) {
this.update();
}
}
layout(height: number, width: number): void {
this.sessionsList?.layout(height, width);
}
focus(): void {
this.sessionsList?.domFocus();
}
clearFocus(): void {
this.sessionsList?.setFocus([]);
this.sessionsList?.setSelection([]);
}
hasFocusOrSelection(): boolean {
return (this.sessionsList?.getFocus().length ?? 0) > 0 || (this.sessionsList?.getSelection().length ?? 0) > 0;
}
scrollToTop(): void {
if (this.sessionsList) {
this.sessionsList.scrollTop = 0;
}
}
getFocus(): IAgentSession[] {
const focused = this.sessionsList?.getFocus() ?? [];
return focused.filter(e => isAgentSession(e));
}
reveal(sessionResource: URI): boolean {
if (!this.sessionsList) {
return false;
}
const session = this.agentSessionsService.model.getSession(sessionResource);
if (!session || !this.sessionsList.hasNode(session)) {
return false;
}
if (this.sessionsList.getRelativeTop(session) === null) {
this.sessionsList.reveal(session, 0.5); // only reveal when not already visible
}
this.sessionsList.setFocus([session]);
this.sessionsList.setSelection([session]);
return true;
}
}