Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/src/vs/workbench/contrib/chat/browser/attachments/chatAttachmentWidgets.ts
4780 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
6
import * as dom from '../../../../../base/browser/dom.js';
7
import { $ } from '../../../../../base/browser/dom.js';
8
import { StandardKeyboardEvent } from '../../../../../base/browser/keyboardEvent.js';
9
import { StandardMouseEvent } from '../../../../../base/browser/mouseEvent.js';
10
import { Button } from '../../../../../base/browser/ui/button/button.js';
11
import { HoverStyle, IDelayedHoverOptions, type IHoverLifecycleOptions, type IHoverOptions } from '../../../../../base/browser/ui/hover/hover.js';
12
import { createInstantHoverDelegate } from '../../../../../base/browser/ui/hover/hoverDelegateFactory.js';
13
import { HoverPosition } from '../../../../../base/browser/ui/hover/hoverWidget.js';
14
import { Codicon } from '../../../../../base/common/codicons.js';
15
import * as event from '../../../../../base/common/event.js';
16
import { MarkdownString } from '../../../../../base/common/htmlContent.js';
17
import { Iterable } from '../../../../../base/common/iterator.js';
18
import { KeyCode } from '../../../../../base/common/keyCodes.js';
19
import { Disposable, DisposableStore, IDisposable } from '../../../../../base/common/lifecycle.js';
20
import { Schemas } from '../../../../../base/common/network.js';
21
import { basename, dirname } from '../../../../../base/common/path.js';
22
import { ThemeIcon } from '../../../../../base/common/themables.js';
23
import { URI } from '../../../../../base/common/uri.js';
24
import { IRange } from '../../../../../editor/common/core/range.js';
25
import { EditorContextKeys } from '../../../../../editor/common/editorContextKeys.js';
26
import { LanguageFeatureRegistry } from '../../../../../editor/common/languageFeatureRegistry.js';
27
import { Location, SymbolKind } from '../../../../../editor/common/languages.js';
28
import { ILanguageService } from '../../../../../editor/common/languages/language.js';
29
import { ILanguageFeaturesService } from '../../../../../editor/common/services/languageFeatures.js';
30
import { IModelService } from '../../../../../editor/common/services/model.js';
31
import { ITextModelService } from '../../../../../editor/common/services/resolverService.js';
32
import { localize } from '../../../../../nls.js';
33
import { getFlatContextMenuActions } from '../../../../../platform/actions/browser/menuEntryActionViewItem.js';
34
import { IMenuService, MenuId } from '../../../../../platform/actions/common/actions.js';
35
import { ICommandService } from '../../../../../platform/commands/common/commands.js';
36
import { IContextKey, IContextKeyService, IScopedContextKeyService, RawContextKey } from '../../../../../platform/contextkey/common/contextkey.js';
37
import { IContextMenuService } from '../../../../../platform/contextview/browser/contextView.js';
38
import { fillInSymbolsDragData } from '../../../../../platform/dnd/browser/dnd.js';
39
import { IOpenEditorOptions, registerOpenEditorListeners } from '../../../../../platform/editor/browser/editor.js';
40
import { ITextEditorOptions } from '../../../../../platform/editor/common/editor.js';
41
import { FileKind, IFileService } from '../../../../../platform/files/common/files.js';
42
import { IHoverService } from '../../../../../platform/hover/browser/hover.js';
43
import { IInstantiationService, ServicesAccessor } from '../../../../../platform/instantiation/common/instantiation.js';
44
import { ILabelService } from '../../../../../platform/label/common/label.js';
45
import { IMarkdownRendererService } from '../../../../../platform/markdown/browser/markdownRenderer.js';
46
import { IOpenerService, OpenInternalOptions } from '../../../../../platform/opener/common/opener.js';
47
import { FolderThemeIcon, IThemeService } from '../../../../../platform/theme/common/themeService.js';
48
import { fillEditorsDragData } from '../../../../browser/dnd.js';
49
import { IFileLabelOptions, IResourceLabel, ResourceLabels } from '../../../../browser/labels.js';
50
import { ResourceContextKey } from '../../../../common/contextkeys.js';
51
import { IEditorService, SIDE_GROUP } from '../../../../services/editor/common/editorService.js';
52
import { IPreferencesService } from '../../../../services/preferences/common/preferences.js';
53
import { revealInSideBarCommand } from '../../../files/browser/fileActions.contribution.js';
54
import { CellUri } from '../../../notebook/common/notebookCommon.js';
55
import { INotebookService } from '../../../notebook/common/notebookService.js';
56
import { toHistoryItemHoverContent } from '../../../scm/browser/scmHistory.js';
57
import { getHistoryItemEditorTitle } from '../../../scm/browser/util.js';
58
import { ITerminalService } from '../../../terminal/browser/terminal.js';
59
import { IChatContentReference } from '../../common/chatService/chatService.js';
60
import { IChatRequestPasteVariableEntry, IChatRequestVariableEntry, IElementVariableEntry, INotebookOutputVariableEntry, IPromptFileVariableEntry, IPromptTextVariableEntry, ISCMHistoryItemVariableEntry, OmittedState, PromptFileVariableKind, ChatRequestToolReferenceEntry, ISCMHistoryItemChangeVariableEntry, ISCMHistoryItemChangeRangeVariableEntry, ITerminalVariableEntry } from '../../common/attachments/chatVariableEntries.js';
61
import { ILanguageModelChatMetadataAndIdentifier, ILanguageModelsService } from '../../common/languageModels.js';
62
import { ILanguageModelToolsService, ToolSet } from '../../common/tools/languageModelToolsService.js';
63
import { getCleanPromptName } from '../../common/promptSyntax/config/promptFileLocations.js';
64
65
const commonHoverOptions: Partial<IHoverOptions> = {
66
style: HoverStyle.Pointer,
67
position: {
68
hoverPosition: HoverPosition.BELOW
69
},
70
trapFocus: true,
71
};
72
const commonHoverLifecycleOptions: IHoverLifecycleOptions = {
73
groupId: 'chat-attachments',
74
};
75
76
abstract class AbstractChatAttachmentWidget extends Disposable {
77
public readonly element: HTMLElement;
78
public readonly label: IResourceLabel;
79
80
private readonly _onDidDelete: event.Emitter<Event> = this._register(new event.Emitter<Event>());
81
get onDidDelete(): event.Event<Event> {
82
return this._onDidDelete.event;
83
}
84
85
private readonly _onDidOpen: event.Emitter<void> = this._register(new event.Emitter<void>());
86
get onDidOpen(): event.Event<void> {
87
return this._onDidOpen.event;
88
}
89
90
constructor(
91
protected readonly attachment: IChatRequestVariableEntry,
92
private readonly options: { shouldFocusClearButton: boolean; supportsDeletion: boolean },
93
container: HTMLElement,
94
contextResourceLabels: ResourceLabels,
95
protected readonly currentLanguageModel: ILanguageModelChatMetadataAndIdentifier | undefined,
96
@ICommandService protected readonly commandService: ICommandService,
97
@IOpenerService protected readonly openerService: IOpenerService,
98
@ITerminalService protected readonly terminalService?: ITerminalService,
99
) {
100
super();
101
this.element = dom.append(container, $('.chat-attached-context-attachment.show-file-icons'));
102
this.attachClearButton();
103
this.label = contextResourceLabels.create(this.element, { supportIcons: true, hoverTargetOverride: this.element });
104
this._register(this.label);
105
this.element.tabIndex = 0;
106
this.element.role = 'button';
107
108
// Add middle-click support for removal
109
this._register(dom.addDisposableListener(this.element, dom.EventType.AUXCLICK, (e: MouseEvent) => {
110
if (e.button === 1 /* Middle Button */ && this.options.supportsDeletion && !this.attachment.range) {
111
e.preventDefault();
112
e.stopPropagation();
113
this._onDidDelete.fire(e);
114
}
115
}));
116
}
117
118
protected modelSupportsVision() {
119
return modelSupportsVision(this.currentLanguageModel);
120
}
121
122
protected attachClearButton() {
123
124
if (this.attachment.range || !this.options.supportsDeletion) {
125
// no clear button for attachments with ranges because range means
126
// referenced from prompt
127
return;
128
}
129
130
const clearButton = new Button(this.element, {
131
supportIcons: true,
132
hoverDelegate: createInstantHoverDelegate(),
133
title: localize('chat.attachment.clearButton', "Remove from context")
134
});
135
clearButton.element.tabIndex = -1;
136
clearButton.icon = Codicon.close;
137
this._register(clearButton);
138
this._register(event.Event.once(clearButton.onDidClick)((e) => {
139
this._onDidDelete.fire(e);
140
}));
141
this._register(dom.addStandardDisposableListener(this.element, dom.EventType.KEY_DOWN, e => {
142
if (e.keyCode === KeyCode.Backspace || e.keyCode === KeyCode.Delete) {
143
this._onDidDelete.fire(e.browserEvent);
144
}
145
}));
146
}
147
148
protected addResourceOpenHandlers(resource: URI, range: IRange | undefined): void {
149
this.element.style.cursor = 'pointer';
150
151
this._register(registerOpenEditorListeners(this.element, async options => {
152
if (this.attachment.kind === 'directory') {
153
await this.openResource(resource, options, true);
154
} else {
155
await this.openResource(resource, options, false, range);
156
}
157
}));
158
}
159
160
protected async openResource(resource: URI, options: Partial<IOpenEditorOptions>, isDirectory: true): Promise<void>;
161
protected async openResource(resource: URI, options: Partial<IOpenEditorOptions>, isDirectory: false, range: IRange | undefined): Promise<void>;
162
protected async openResource(resource: URI, openOptions: Partial<IOpenEditorOptions>, isDirectory?: boolean, range?: IRange): Promise<void> {
163
if (isDirectory) {
164
// Reveal Directory in explorer
165
this.commandService.executeCommand(revealInSideBarCommand.id, resource);
166
return;
167
}
168
169
if (resource.scheme === Schemas.vscodeTerminal) {
170
this.terminalService?.openResource(resource);
171
return;
172
}
173
174
// Open file in editor
175
const openTextEditorOptions: ITextEditorOptions | undefined = range ? { selection: range } : undefined;
176
const options: OpenInternalOptions = {
177
fromUserGesture: true,
178
openToSide: openOptions.openToSide,
179
editorOptions: {
180
...openTextEditorOptions,
181
...openOptions.editorOptions
182
},
183
};
184
185
await this.openerService.open(resource, options);
186
this._onDidOpen.fire();
187
this.element.focus();
188
}
189
}
190
191
function modelSupportsVision(currentLanguageModel: ILanguageModelChatMetadataAndIdentifier | undefined) {
192
return currentLanguageModel?.metadata.capabilities?.vision ?? false;
193
}
194
195
export class FileAttachmentWidget extends AbstractChatAttachmentWidget {
196
197
constructor(
198
resource: URI,
199
range: IRange | undefined,
200
attachment: IChatRequestVariableEntry,
201
correspondingContentReference: IChatContentReference | undefined,
202
currentLanguageModel: ILanguageModelChatMetadataAndIdentifier | undefined,
203
options: { shouldFocusClearButton: boolean; supportsDeletion: boolean },
204
container: HTMLElement,
205
contextResourceLabels: ResourceLabels,
206
@ICommandService commandService: ICommandService,
207
@IOpenerService openerService: IOpenerService,
208
@IThemeService private readonly themeService: IThemeService,
209
@IHoverService private readonly hoverService: IHoverService,
210
@ILanguageModelsService private readonly languageModelsService: ILanguageModelsService,
211
@IInstantiationService private readonly instantiationService: IInstantiationService,
212
) {
213
super(attachment, options, container, contextResourceLabels, currentLanguageModel, commandService, openerService);
214
215
const fileBasename = basename(resource.path);
216
const fileDirname = dirname(resource.path);
217
const friendlyName = `${fileBasename} ${fileDirname}`;
218
let ariaLabel = range ? localize('chat.fileAttachmentWithRange', "Attached file, {0}, line {1} to line {2}", friendlyName, range.startLineNumber, range.endLineNumber) : localize('chat.fileAttachment', "Attached file, {0}", friendlyName);
219
220
if (attachment.omittedState === OmittedState.Full) {
221
ariaLabel = localize('chat.omittedFileAttachment', "Omitted this file: {0}", attachment.name);
222
this.renderOmittedWarning(friendlyName, ariaLabel);
223
} else {
224
const fileOptions: IFileLabelOptions = { hidePath: true, title: correspondingContentReference?.options?.status?.description };
225
this.label.setFile(resource, attachment.kind === 'file' ? {
226
...fileOptions,
227
fileKind: FileKind.FILE,
228
range,
229
} : {
230
...fileOptions,
231
fileKind: FileKind.FOLDER,
232
icon: !this.themeService.getFileIconTheme().hasFolderIcons ? FolderThemeIcon : undefined
233
});
234
}
235
236
this.element.ariaLabel = ariaLabel;
237
238
this.instantiationService.invokeFunction(accessor => {
239
this._register(hookUpResourceAttachmentDragAndContextMenu(accessor, this.element, resource));
240
});
241
this.addResourceOpenHandlers(resource, range);
242
}
243
244
private renderOmittedWarning(friendlyName: string, ariaLabel: string) {
245
const pillIcon = dom.$('div.chat-attached-context-pill', {}, dom.$('span.codicon.codicon-warning'));
246
const textLabel = dom.$('span.chat-attached-context-custom-text', {}, friendlyName);
247
this.element.appendChild(pillIcon);
248
this.element.appendChild(textLabel);
249
250
const hoverElement = dom.$('div.chat-attached-context-hover');
251
hoverElement.setAttribute('aria-label', ariaLabel);
252
this.element.classList.add('warning');
253
254
hoverElement.textContent = localize('chat.fileAttachmentHover', "{0} does not support this file type.", this.currentLanguageModel ? this.languageModelsService.lookupLanguageModel(this.currentLanguageModel.identifier)?.name : this.currentLanguageModel ?? 'This model');
255
this._register(this.hoverService.setupDelayedHover(this.element, {
256
...commonHoverOptions,
257
content: hoverElement,
258
}, commonHoverLifecycleOptions));
259
}
260
}
261
262
263
export class TerminalCommandAttachmentWidget extends AbstractChatAttachmentWidget {
264
265
constructor(
266
attachment: ITerminalVariableEntry,
267
currentLanguageModel: ILanguageModelChatMetadataAndIdentifier | undefined,
268
options: { shouldFocusClearButton: boolean; supportsDeletion: boolean },
269
container: HTMLElement,
270
contextResourceLabels: ResourceLabels,
271
@ICommandService commandService: ICommandService,
272
@IOpenerService openerService: IOpenerService,
273
@IHoverService private readonly hoverService: IHoverService,
274
@ITerminalService protected override readonly terminalService: ITerminalService,
275
) {
276
super(attachment, options, container, contextResourceLabels, currentLanguageModel, commandService, openerService, terminalService);
277
278
const ariaLabel = localize('chat.terminalCommand', "Terminal command, {0}", attachment.command);
279
const clickHandler = () => this.openResource(attachment.resource, { editorOptions: { preserveFocus: true } }, false, undefined);
280
281
this._register(createTerminalCommandElements(this.element, attachment, ariaLabel, this.hoverService, clickHandler));
282
283
this._register(dom.addDisposableListener(this.element, dom.EventType.KEY_DOWN, async (e: KeyboardEvent) => {
284
const event = new StandardKeyboardEvent(e);
285
if (event.equals(KeyCode.Enter) || event.equals(KeyCode.Space)) {
286
dom.EventHelper.stop(e, true);
287
await clickHandler();
288
}
289
}));
290
}
291
}
292
293
const enum TerminalConstants {
294
MaxAttachmentOutputLineCount = 5,
295
MaxAttachmentOutputLineLength = 80,
296
}
297
298
function createTerminalCommandElements(
299
element: HTMLElement,
300
attachment: ITerminalVariableEntry,
301
ariaLabel: string,
302
hoverService: IHoverService,
303
clickHandler: () => Promise<void>
304
): IDisposable {
305
const disposable = new DisposableStore();
306
element.ariaLabel = ariaLabel;
307
element.style.cursor = 'pointer';
308
309
const terminalIconSpan = dom.$('span');
310
terminalIconSpan.classList.add(...ThemeIcon.asClassNameArray(Codicon.terminal));
311
const pillIcon = dom.$('div.chat-attached-context-pill', {}, terminalIconSpan);
312
const textLabel = dom.$('span.chat-attached-context-custom-text', {}, attachment.command);
313
element.appendChild(pillIcon);
314
element.appendChild(textLabel);
315
316
disposable.add(dom.addDisposableListener(element, dom.EventType.CLICK, e => {
317
e.preventDefault();
318
e.stopPropagation();
319
clickHandler();
320
}));
321
322
disposable.add(hoverService.setupDelayedHover(element, () => getHoverContent(ariaLabel, attachment), commonHoverLifecycleOptions));
323
return disposable;
324
}
325
326
function getHoverContent(ariaLabel: string, attachment: ITerminalVariableEntry): IDelayedHoverOptions {
327
{
328
const hoverElement = dom.$('div.chat-attached-context-hover');
329
hoverElement.setAttribute('aria-label', ariaLabel);
330
331
const commandTitle = dom.$('div', {}, typeof attachment.exitCode === 'number'
332
? localize('chat.terminalCommandHoverCommandTitleExit', "Command: {0}, exit code: {1}", attachment.command, attachment.exitCode)
333
: localize('chat.terminalCommandHoverCommandTitle', "Command"));
334
commandTitle.classList.add('attachment-additional-info');
335
const commandBlock = dom.$('pre.chat-terminal-command-block');
336
hoverElement.append(commandTitle, commandBlock);
337
338
if (attachment.output && attachment.output.trim().length > 0) {
339
const outputTitle = dom.$('div', {}, localize('chat.terminalCommandHoverOutputTitle', "Output:"));
340
outputTitle.classList.add('attachment-additional-info');
341
const outputBlock = dom.$('pre.chat-terminal-command-output');
342
const fullOutputLines = attachment.output.split('\n');
343
const hoverOutputLines = [];
344
for (const line of fullOutputLines) {
345
if (hoverOutputLines.length >= TerminalConstants.MaxAttachmentOutputLineCount) {
346
hoverOutputLines.push('...');
347
break;
348
}
349
const trimmed = line.trim();
350
if (trimmed.length === 0) {
351
continue;
352
}
353
if (trimmed.length > TerminalConstants.MaxAttachmentOutputLineLength) {
354
hoverOutputLines.push(`${trimmed.slice(0, TerminalConstants.MaxAttachmentOutputLineLength)}...`);
355
} else {
356
hoverOutputLines.push(trimmed);
357
}
358
}
359
outputBlock.textContent = hoverOutputLines.join('\n');
360
hoverElement.append(outputTitle, outputBlock);
361
}
362
363
return {
364
...commonHoverOptions,
365
content: hoverElement,
366
};
367
}
368
}
369
370
export class ImageAttachmentWidget extends AbstractChatAttachmentWidget {
371
372
constructor(
373
resource: URI | undefined,
374
attachment: IChatRequestVariableEntry,
375
currentLanguageModel: ILanguageModelChatMetadataAndIdentifier | undefined,
376
options: { shouldFocusClearButton: boolean; supportsDeletion: boolean },
377
container: HTMLElement,
378
contextResourceLabels: ResourceLabels,
379
@ICommandService commandService: ICommandService,
380
@IOpenerService openerService: IOpenerService,
381
@IHoverService private readonly hoverService: IHoverService,
382
@ILanguageModelsService private readonly languageModelsService: ILanguageModelsService,
383
@IInstantiationService instantiationService: IInstantiationService,
384
@ILabelService private readonly labelService: ILabelService,
385
) {
386
super(attachment, options, container, contextResourceLabels, currentLanguageModel, commandService, openerService);
387
388
let ariaLabel: string;
389
if (attachment.omittedState === OmittedState.Full) {
390
ariaLabel = localize('chat.omittedImageAttachment', "Omitted this image: {0}", attachment.name);
391
} else if (attachment.omittedState === OmittedState.Partial) {
392
ariaLabel = localize('chat.partiallyOmittedImageAttachment', "Partially omitted this image: {0}", attachment.name);
393
} else {
394
ariaLabel = localize('chat.imageAttachment', "Attached image, {0}", attachment.name);
395
}
396
397
const ref = attachment.references?.[0]?.reference;
398
resource = ref && URI.isUri(ref) ? ref : undefined;
399
const clickHandler = async () => {
400
if (resource) {
401
await this.openResource(resource, { editorOptions: { preserveFocus: true } }, false, undefined);
402
}
403
};
404
405
const currentLanguageModelName = this.currentLanguageModel ? this.languageModelsService.lookupLanguageModel(this.currentLanguageModel.identifier)?.name ?? this.currentLanguageModel.identifier : 'Current model';
406
407
const fullName = resource ? this.labelService.getUriLabel(resource) : (attachment.fullName || attachment.name);
408
this._register(createImageElements(resource, attachment.name, fullName, this.element, attachment.value as Uint8Array, this.hoverService, ariaLabel, currentLanguageModelName, clickHandler, this.currentLanguageModel, attachment.omittedState));
409
410
if (resource) {
411
this.addResourceOpenHandlers(resource, undefined);
412
instantiationService.invokeFunction(accessor => {
413
this._register(hookUpResourceAttachmentDragAndContextMenu(accessor, this.element, resource));
414
});
415
}
416
}
417
}
418
419
function createImageElements(resource: URI | undefined, name: string, fullName: string,
420
element: HTMLElement,
421
buffer: ArrayBuffer | Uint8Array,
422
hoverService: IHoverService, ariaLabel: string,
423
currentLanguageModelName: string | undefined,
424
clickHandler: () => void,
425
currentLanguageModel?: ILanguageModelChatMetadataAndIdentifier,
426
omittedState?: OmittedState): IDisposable {
427
428
const disposable = new DisposableStore();
429
if (omittedState === OmittedState.Partial) {
430
element.classList.add('partial-warning');
431
}
432
433
element.ariaLabel = ariaLabel;
434
element.style.position = 'relative';
435
436
if (resource) {
437
element.style.cursor = 'pointer';
438
disposable.add(dom.addDisposableListener(element, 'click', clickHandler));
439
}
440
const supportsVision = modelSupportsVision(currentLanguageModel);
441
const pillIcon = dom.$('div.chat-attached-context-pill', {}, dom.$(supportsVision ? 'span.codicon.codicon-file-media' : 'span.codicon.codicon-warning'));
442
const textLabel = dom.$('span.chat-attached-context-custom-text', {}, name);
443
element.appendChild(pillIcon);
444
element.appendChild(textLabel);
445
446
const hoverElement = dom.$('div.chat-attached-context-hover');
447
hoverElement.setAttribute('aria-label', ariaLabel);
448
449
if ((!supportsVision && currentLanguageModel) || omittedState === OmittedState.Full) {
450
element.classList.add('warning');
451
hoverElement.textContent = localize('chat.imageAttachmentHover', "{0} does not support images.", currentLanguageModelName ?? 'This model');
452
disposable.add(hoverService.setupDelayedHover(element, {
453
content: hoverElement,
454
style: HoverStyle.Pointer,
455
}));
456
} else {
457
disposable.add(hoverService.setupDelayedHover(element, {
458
content: hoverElement,
459
style: HoverStyle.Pointer,
460
}));
461
462
const blob = new Blob([buffer as Uint8Array<ArrayBuffer>], { type: 'image/png' });
463
const url = URL.createObjectURL(blob);
464
const pillImg = dom.$('img.chat-attached-context-pill-image', { src: url, alt: '' });
465
const pill = dom.$('div.chat-attached-context-pill', {}, pillImg);
466
467
// eslint-disable-next-line no-restricted-syntax
468
const existingPill = element.querySelector('.chat-attached-context-pill');
469
if (existingPill) {
470
existingPill.replaceWith(pill);
471
}
472
473
const hoverImage = dom.$('img.chat-attached-context-image', { src: url, alt: '' });
474
const imageContainer = dom.$('div.chat-attached-context-image-container', {}, hoverImage);
475
hoverElement.appendChild(imageContainer);
476
477
if (resource) {
478
const urlContainer = dom.$('a.chat-attached-context-url', {}, omittedState === OmittedState.Partial ? localize('chat.imageAttachmentWarning', "This GIF was partially omitted - current frame will be sent.") : fullName);
479
const separator = dom.$('div.chat-attached-context-url-separator');
480
disposable.add(dom.addDisposableListener(urlContainer, 'click', () => clickHandler()));
481
hoverElement.append(separator, urlContainer);
482
}
483
484
hoverImage.onload = () => { URL.revokeObjectURL(url); };
485
hoverImage.onerror = () => {
486
// reset to original icon on error or invalid image
487
const pillIcon = dom.$('div.chat-attached-context-pill', {}, dom.$('span.codicon.codicon-file-media'));
488
const pill = dom.$('div.chat-attached-context-pill', {}, pillIcon);
489
// eslint-disable-next-line no-restricted-syntax
490
const existingPill = element.querySelector('.chat-attached-context-pill');
491
if (existingPill) {
492
existingPill.replaceWith(pill);
493
}
494
};
495
}
496
return disposable;
497
}
498
499
export class PasteAttachmentWidget extends AbstractChatAttachmentWidget {
500
501
constructor(
502
attachment: IChatRequestPasteVariableEntry,
503
currentLanguageModel: ILanguageModelChatMetadataAndIdentifier | undefined,
504
options: { shouldFocusClearButton: boolean; supportsDeletion: boolean },
505
container: HTMLElement,
506
contextResourceLabels: ResourceLabels,
507
@ICommandService commandService: ICommandService,
508
@IOpenerService openerService: IOpenerService,
509
@IHoverService private readonly hoverService: IHoverService,
510
@IInstantiationService private readonly instantiationService: IInstantiationService,
511
) {
512
super(attachment, options, container, contextResourceLabels, currentLanguageModel, commandService, openerService);
513
514
const ariaLabel = localize('chat.attachment', "Attached context, {0}", attachment.name);
515
this.element.ariaLabel = ariaLabel;
516
517
const classNames = ['file-icon', `${attachment.language}-lang-file-icon`];
518
let resource: URI | undefined;
519
let range: IRange | undefined;
520
521
if (attachment.copiedFrom) {
522
resource = attachment.copiedFrom.uri;
523
range = attachment.copiedFrom.range;
524
const filename = basename(resource.path);
525
this.label.setLabel(filename, undefined, { extraClasses: classNames });
526
} else {
527
this.label.setLabel(attachment.fileName, undefined, { extraClasses: classNames });
528
}
529
this.element.appendChild(dom.$('span.attachment-additional-info', {}, `Pasted ${attachment.pastedLines}`));
530
531
this.element.style.position = 'relative';
532
533
const sourceUri = attachment.copiedFrom?.uri;
534
const hoverContent = new MarkdownString(`${sourceUri ? this.instantiationService.invokeFunction(accessor => accessor.get(ILabelService).getUriLabel(sourceUri, { relative: true })) : attachment.fileName}\n\n---\n\n\`\`\`${attachment.language}\n\n${attachment.code}\n\`\`\``);
535
this._register(this.hoverService.setupDelayedHover(this.element, {
536
...commonHoverOptions,
537
content: hoverContent,
538
}, commonHoverLifecycleOptions));
539
540
const copiedFromResource = attachment.copiedFrom?.uri;
541
if (copiedFromResource) {
542
this._register(this.instantiationService.invokeFunction(hookUpResourceAttachmentDragAndContextMenu, this.element, copiedFromResource));
543
this.addResourceOpenHandlers(copiedFromResource, range);
544
}
545
}
546
}
547
548
export class DefaultChatAttachmentWidget extends AbstractChatAttachmentWidget {
549
constructor(
550
resource: URI | undefined,
551
range: IRange | undefined,
552
attachment: IChatRequestVariableEntry,
553
correspondingContentReference: IChatContentReference | undefined,
554
currentLanguageModel: ILanguageModelChatMetadataAndIdentifier | undefined,
555
options: { shouldFocusClearButton: boolean; supportsDeletion: boolean },
556
container: HTMLElement,
557
contextResourceLabels: ResourceLabels,
558
@ICommandService commandService: ICommandService,
559
@IOpenerService openerService: IOpenerService,
560
@IContextKeyService private readonly contextKeyService: IContextKeyService,
561
@IInstantiationService private readonly instantiationService: IInstantiationService,
562
) {
563
super(attachment, options, container, contextResourceLabels, currentLanguageModel, commandService, openerService);
564
565
const attachmentLabel = attachment.fullName ?? attachment.name;
566
const withIcon = attachment.icon?.id ? `$(${attachment.icon.id})\u00A0${attachmentLabel}` : attachmentLabel;
567
this.label.setLabel(withIcon, correspondingContentReference?.options?.status?.description);
568
this.element.ariaLabel = localize('chat.attachment', "Attached context, {0}", attachment.name);
569
570
if (attachment.kind === 'diagnostic') {
571
if (attachment.filterUri) {
572
resource = attachment.filterUri ? URI.revive(attachment.filterUri) : undefined;
573
range = attachment.filterRange;
574
} else {
575
this.element.style.cursor = 'pointer';
576
this._register(dom.addDisposableListener(this.element, dom.EventType.CLICK, () => {
577
this.commandService.executeCommand('workbench.panel.markers.view.focus');
578
}));
579
}
580
}
581
582
if (attachment.kind === 'symbol') {
583
const scopedContextKeyService = this._register(this.contextKeyService.createScoped(this.element));
584
this._register(this.instantiationService.invokeFunction(hookUpSymbolAttachmentDragAndContextMenu, this.element, scopedContextKeyService, { ...attachment, kind: attachment.symbolKind }, MenuId.ChatInputSymbolAttachmentContext));
585
}
586
587
if (resource) {
588
this.addResourceOpenHandlers(resource, range);
589
}
590
}
591
}
592
593
export class PromptFileAttachmentWidget extends AbstractChatAttachmentWidget {
594
595
private hintElement: HTMLElement;
596
597
constructor(
598
attachment: IPromptFileVariableEntry,
599
currentLanguageModel: ILanguageModelChatMetadataAndIdentifier | undefined,
600
options: { shouldFocusClearButton: boolean; supportsDeletion: boolean },
601
container: HTMLElement,
602
contextResourceLabels: ResourceLabels,
603
@ICommandService commandService: ICommandService,
604
@IOpenerService openerService: IOpenerService,
605
@ILabelService private readonly labelService: ILabelService,
606
@IInstantiationService private readonly instantiationService: IInstantiationService,
607
) {
608
super(attachment, options, container, contextResourceLabels, currentLanguageModel, commandService, openerService);
609
610
611
this.hintElement = dom.append(this.element, dom.$('span.prompt-type'));
612
613
this.updateLabel(attachment);
614
615
this.instantiationService.invokeFunction(accessor => {
616
this._register(hookUpResourceAttachmentDragAndContextMenu(accessor, this.element, attachment.value));
617
});
618
this.addResourceOpenHandlers(attachment.value, undefined);
619
}
620
621
private updateLabel(attachment: IPromptFileVariableEntry) {
622
const resource = attachment.value;
623
const fileBasename = basename(resource.path);
624
const fileDirname = dirname(resource.path);
625
const friendlyName = `${fileBasename} ${fileDirname}`;
626
const isPrompt = attachment.id.startsWith(PromptFileVariableKind.PromptFile);
627
const ariaLabel = isPrompt
628
? localize('chat.promptAttachment', "Prompt file, {0}", friendlyName)
629
: localize('chat.instructionsAttachment', "Instructions attachment, {0}", friendlyName);
630
const typeLabel = isPrompt
631
? localize('prompt', "Prompt")
632
: localize('instructions', "Instructions");
633
634
const title = this.labelService.getUriLabel(resource) + (attachment.originLabel ? `\n${attachment.originLabel}` : '');
635
636
//const { topError } = this.promptFile;
637
this.element.classList.remove('warning', 'error');
638
639
// if there are some errors/warning during the process of resolving
640
// attachment references (including all the nested child references),
641
// add the issue details in the hover title for the attachment, one
642
// error/warning at a time because there is a limited space available
643
// if (topError) {
644
// const { errorSubject: subject } = topError;
645
// const isError = (subject === 'root');
646
// this.element.classList.add((isError) ? 'error' : 'warning');
647
648
// const severity = (isError)
649
// ? localize('error', "Error")
650
// : localize('warning', "Warning");
651
652
// title += `\n[${severity}]: ${topError.localizedMessage}`;
653
// }
654
655
const fileWithoutExtension = getCleanPromptName(resource);
656
this.label.setFile(URI.file(fileWithoutExtension), {
657
fileKind: FileKind.FILE,
658
hidePath: true,
659
range: undefined,
660
title,
661
icon: ThemeIcon.fromId(Codicon.bookmark.id),
662
extraClasses: [],
663
});
664
665
this.hintElement.innerText = typeLabel;
666
667
668
this.element.ariaLabel = ariaLabel;
669
}
670
}
671
672
export class PromptTextAttachmentWidget extends AbstractChatAttachmentWidget {
673
674
constructor(
675
attachment: IPromptTextVariableEntry,
676
currentLanguageModel: ILanguageModelChatMetadataAndIdentifier | undefined,
677
options: { shouldFocusClearButton: boolean; supportsDeletion: boolean },
678
container: HTMLElement,
679
contextResourceLabels: ResourceLabels,
680
@ICommandService commandService: ICommandService,
681
@IOpenerService openerService: IOpenerService,
682
@IPreferencesService preferencesService: IPreferencesService,
683
@IHoverService hoverService: IHoverService
684
) {
685
super(attachment, options, container, contextResourceLabels, currentLanguageModel, commandService, openerService);
686
687
if (attachment.settingId) {
688
const openSettings = () => preferencesService.openSettings({ jsonEditor: false, query: `@id:${attachment.settingId}` });
689
690
this.element.style.cursor = 'pointer';
691
this._register(dom.addDisposableListener(this.element, dom.EventType.CLICK, async (e: MouseEvent) => {
692
dom.EventHelper.stop(e, true);
693
openSettings();
694
}));
695
696
this._register(dom.addDisposableListener(this.element, dom.EventType.KEY_DOWN, async (e: KeyboardEvent) => {
697
const event = new StandardKeyboardEvent(e);
698
if (event.equals(KeyCode.Enter) || event.equals(KeyCode.Space)) {
699
dom.EventHelper.stop(e, true);
700
openSettings();
701
}
702
}));
703
}
704
this.label.setLabel(localize('instructions.label', 'Additional Instructions'), undefined, undefined);
705
706
this._register(hoverService.setupDelayedHover(this.element, {
707
...commonHoverOptions,
708
content: attachment.value,
709
}, commonHoverLifecycleOptions));
710
}
711
}
712
713
714
export class ToolSetOrToolItemAttachmentWidget extends AbstractChatAttachmentWidget {
715
constructor(
716
attachment: ChatRequestToolReferenceEntry,
717
currentLanguageModel: ILanguageModelChatMetadataAndIdentifier | undefined,
718
options: { shouldFocusClearButton: boolean; supportsDeletion: boolean },
719
container: HTMLElement,
720
contextResourceLabels: ResourceLabels,
721
@ILanguageModelToolsService toolsService: ILanguageModelToolsService,
722
@ICommandService commandService: ICommandService,
723
@IOpenerService openerService: IOpenerService,
724
@IHoverService hoverService: IHoverService
725
) {
726
super(attachment, options, container, contextResourceLabels, currentLanguageModel, commandService, openerService);
727
728
729
const toolOrToolSet = Iterable.find(toolsService.getTools(), tool => tool.id === attachment.id) ?? Iterable.find(toolsService.toolSets.get(), toolSet => toolSet.id === attachment.id);
730
731
let name = attachment.name;
732
const icon = attachment.icon ?? Codicon.tools;
733
734
if (toolOrToolSet instanceof ToolSet) {
735
name = toolOrToolSet.referenceName;
736
} else if (toolOrToolSet) {
737
name = toolOrToolSet.toolReferenceName ?? name;
738
}
739
740
this.label.setLabel(`$(${icon.id})\u00A0${name}`, undefined);
741
742
this.element.style.cursor = 'pointer';
743
this.element.ariaLabel = localize('chat.attachment', "Attached context, {0}", name);
744
745
let hoverContent: string | undefined;
746
747
if (toolOrToolSet instanceof ToolSet) {
748
hoverContent = localize('toolset', "{0} - {1}", toolOrToolSet.description ?? toolOrToolSet.referenceName, toolOrToolSet.source.label);
749
} else if (toolOrToolSet) {
750
hoverContent = localize('tool', "{0} - {1}", toolOrToolSet.userDescription ?? toolOrToolSet.modelDescription, toolOrToolSet.source.label);
751
}
752
753
if (hoverContent) {
754
this._register(hoverService.setupDelayedHover(this.element, {
755
...commonHoverOptions,
756
content: hoverContent,
757
}, commonHoverLifecycleOptions));
758
}
759
}
760
761
762
}
763
764
export class NotebookCellOutputChatAttachmentWidget extends AbstractChatAttachmentWidget {
765
constructor(
766
resource: URI,
767
attachment: INotebookOutputVariableEntry,
768
currentLanguageModel: ILanguageModelChatMetadataAndIdentifier | undefined,
769
options: { shouldFocusClearButton: boolean; supportsDeletion: boolean },
770
container: HTMLElement,
771
contextResourceLabels: ResourceLabels,
772
@ICommandService commandService: ICommandService,
773
@IOpenerService openerService: IOpenerService,
774
@IHoverService private readonly hoverService: IHoverService,
775
@ILanguageModelsService private readonly languageModelsService: ILanguageModelsService,
776
@INotebookService private readonly notebookService: INotebookService,
777
@IInstantiationService private readonly instantiationService: IInstantiationService,
778
) {
779
super(attachment, options, container, contextResourceLabels, currentLanguageModel, commandService, openerService);
780
781
switch (attachment.mimeType) {
782
case 'application/vnd.code.notebook.error': {
783
this.renderErrorOutput(resource, attachment);
784
break;
785
}
786
case 'image/png':
787
case 'image/jpeg':
788
case 'image/svg': {
789
this.renderImageOutput(resource, attachment);
790
break;
791
}
792
default: {
793
this.renderGenericOutput(resource, attachment);
794
}
795
}
796
797
this.instantiationService.invokeFunction(accessor => {
798
this._register(hookUpResourceAttachmentDragAndContextMenu(accessor, this.element, resource));
799
});
800
this.addResourceOpenHandlers(resource, undefined);
801
}
802
getAriaLabel(attachment: INotebookOutputVariableEntry): string {
803
return localize('chat.NotebookImageAttachment', "Attached Notebook output, {0}", attachment.name);
804
}
805
private renderErrorOutput(resource: URI, attachment: INotebookOutputVariableEntry) {
806
const attachmentLabel = attachment.name;
807
const withIcon = attachment.icon?.id ? `$(${attachment.icon.id})\u00A0${attachmentLabel}` : attachmentLabel;
808
const buffer = this.getOutputItem(resource, attachment)?.data.buffer ?? new Uint8Array();
809
let title: string | undefined = undefined;
810
try {
811
const error = JSON.parse(new TextDecoder().decode(buffer)) as Error;
812
if (error.name && error.message) {
813
title = `${error.name}: ${error.message}`;
814
}
815
} catch {
816
//
817
}
818
this.label.setLabel(withIcon, undefined, { title });
819
this.element.ariaLabel = this.getAriaLabel(attachment);
820
}
821
private renderGenericOutput(resource: URI, attachment: INotebookOutputVariableEntry) {
822
this.element.ariaLabel = this.getAriaLabel(attachment);
823
this.label.setFile(resource, { hidePath: true, icon: ThemeIcon.fromId('output') });
824
}
825
private renderImageOutput(resource: URI, attachment: INotebookOutputVariableEntry) {
826
let ariaLabel: string;
827
if (attachment.omittedState === OmittedState.Full) {
828
ariaLabel = localize('chat.omittedNotebookImageAttachment', "Omitted this Notebook ouput: {0}", attachment.name);
829
} else if (attachment.omittedState === OmittedState.Partial) {
830
ariaLabel = localize('chat.partiallyOmittedNotebookImageAttachment', "Partially omitted this Notebook output: {0}", attachment.name);
831
} else {
832
ariaLabel = this.getAriaLabel(attachment);
833
}
834
835
const clickHandler = async () => await this.openResource(resource, { editorOptions: { preserveFocus: true } }, false, undefined);
836
const currentLanguageModelName = this.currentLanguageModel ? this.languageModelsService.lookupLanguageModel(this.currentLanguageModel.identifier)?.name ?? this.currentLanguageModel.identifier : undefined;
837
const buffer = this.getOutputItem(resource, attachment)?.data.buffer ?? new Uint8Array();
838
this._register(createImageElements(resource, attachment.name, attachment.name, this.element, buffer, this.hoverService, ariaLabel, currentLanguageModelName, clickHandler, this.currentLanguageModel, attachment.omittedState));
839
}
840
841
private getOutputItem(resource: URI, attachment: INotebookOutputVariableEntry) {
842
const parsedInfo = CellUri.parseCellOutputUri(resource);
843
if (!parsedInfo || typeof parsedInfo.cellHandle !== 'number' || typeof parsedInfo.outputIndex !== 'number') {
844
return undefined;
845
}
846
const notebook = this.notebookService.getNotebookTextModel(parsedInfo.notebook);
847
if (!notebook) {
848
return undefined;
849
}
850
const cell = notebook.cells.find(c => c.handle === parsedInfo.cellHandle);
851
if (!cell) {
852
return undefined;
853
}
854
const output = cell.outputs.length > parsedInfo.outputIndex ? cell.outputs[parsedInfo.outputIndex] : undefined;
855
return output?.outputs.find(o => o.mime === attachment.mimeType);
856
}
857
858
}
859
860
export class ElementChatAttachmentWidget extends AbstractChatAttachmentWidget {
861
constructor(
862
attachment: IElementVariableEntry,
863
currentLanguageModel: ILanguageModelChatMetadataAndIdentifier | undefined,
864
options: { shouldFocusClearButton: boolean; supportsDeletion: boolean },
865
container: HTMLElement,
866
contextResourceLabels: ResourceLabels,
867
@ICommandService commandService: ICommandService,
868
@IOpenerService openerService: IOpenerService,
869
@IEditorService editorService: IEditorService,
870
) {
871
super(attachment, options, container, contextResourceLabels, currentLanguageModel, commandService, openerService);
872
873
const ariaLabel = localize('chat.elementAttachment', "Attached element, {0}", attachment.name);
874
this.element.ariaLabel = ariaLabel;
875
876
this.element.style.position = 'relative';
877
this.element.style.cursor = 'pointer';
878
const attachmentLabel = attachment.name;
879
const withIcon = attachment.icon?.id ? `$(${attachment.icon.id})\u00A0${attachmentLabel}` : attachmentLabel;
880
this.label.setLabel(withIcon, undefined, { title: localize('chat.clickToViewContents', "Click to view the contents of: {0}", attachmentLabel) });
881
882
this._register(dom.addDisposableListener(this.element, dom.EventType.CLICK, async () => {
883
const content = attachment.value?.toString() || '';
884
await editorService.openEditor({
885
resource: undefined,
886
contents: content,
887
options: {
888
pinned: true
889
}
890
});
891
}));
892
}
893
}
894
895
export class SCMHistoryItemAttachmentWidget extends AbstractChatAttachmentWidget {
896
constructor(
897
attachment: ISCMHistoryItemVariableEntry,
898
currentLanguageModel: ILanguageModelChatMetadataAndIdentifier | undefined,
899
options: { shouldFocusClearButton: boolean; supportsDeletion: boolean },
900
container: HTMLElement,
901
contextResourceLabels: ResourceLabels,
902
@ICommandService commandService: ICommandService,
903
@IMarkdownRendererService markdownRendererService: IMarkdownRendererService,
904
@IHoverService hoverService: IHoverService,
905
@IOpenerService openerService: IOpenerService,
906
@IThemeService themeService: IThemeService
907
) {
908
super(attachment, options, container, contextResourceLabels, currentLanguageModel, commandService, openerService);
909
910
this.label.setLabel(attachment.name, undefined);
911
912
this.element.style.cursor = 'pointer';
913
this.element.ariaLabel = localize('chat.attachment', "Attached context, {0}", attachment.name);
914
915
const { content, disposables } = toHistoryItemHoverContent(markdownRendererService, attachment.historyItem, false);
916
this._store.add(hoverService.setupDelayedHover(this.element, {
917
...commonHoverOptions,
918
content,
919
}, commonHoverLifecycleOptions));
920
this._store.add(disposables);
921
922
this._store.add(dom.addDisposableListener(this.element, dom.EventType.CLICK, (e: MouseEvent) => {
923
dom.EventHelper.stop(e, true);
924
this._openAttachment(attachment);
925
}));
926
927
this._store.add(dom.addDisposableListener(this.element, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => {
928
const event = new StandardKeyboardEvent(e);
929
if (event.equals(KeyCode.Enter) || event.equals(KeyCode.Space)) {
930
dom.EventHelper.stop(e, true);
931
this._openAttachment(attachment);
932
}
933
}));
934
}
935
936
private async _openAttachment(attachment: ISCMHistoryItemVariableEntry): Promise<void> {
937
await this.commandService.executeCommand('_workbench.openMultiDiffEditor', {
938
title: getHistoryItemEditorTitle(attachment.historyItem), multiDiffSourceUri: attachment.value
939
});
940
}
941
}
942
943
export class SCMHistoryItemChangeAttachmentWidget extends AbstractChatAttachmentWidget {
944
constructor(
945
attachment: ISCMHistoryItemChangeVariableEntry,
946
currentLanguageModel: ILanguageModelChatMetadataAndIdentifier | undefined,
947
options: { shouldFocusClearButton: boolean; supportsDeletion: boolean },
948
container: HTMLElement,
949
contextResourceLabels: ResourceLabels,
950
@ICommandService commandService: ICommandService,
951
@IHoverService hoverService: IHoverService,
952
@IMarkdownRendererService markdownRendererService: IMarkdownRendererService,
953
@IOpenerService openerService: IOpenerService,
954
@IThemeService themeService: IThemeService,
955
@IEditorService private readonly editorService: IEditorService,
956
) {
957
super(attachment, options, container, contextResourceLabels, currentLanguageModel, commandService, openerService);
958
959
const nameSuffix = `\u00A0$(${Codicon.gitCommit.id})${attachment.historyItem.displayId ?? attachment.historyItem.id}`;
960
this.label.setFile(attachment.value, { fileKind: FileKind.FILE, hidePath: true, nameSuffix });
961
962
this.element.ariaLabel = localize('chat.attachment', "Attached context, {0}", attachment.name);
963
964
const { content, disposables } = toHistoryItemHoverContent(markdownRendererService, attachment.historyItem, false);
965
this._store.add(hoverService.setupDelayedHover(this.element, {
966
...commonHoverOptions, content,
967
}, commonHoverLifecycleOptions));
968
this._store.add(disposables);
969
970
this.addResourceOpenHandlers(attachment.value, undefined);
971
}
972
973
protected override async openResource(resource: URI, options: IOpenEditorOptions, isDirectory: true): Promise<void>;
974
protected override async openResource(resource: URI, options: IOpenEditorOptions, isDirectory: false, range: IRange | undefined): Promise<void>;
975
protected override async openResource(resource: URI, options: IOpenEditorOptions, isDirectory?: boolean, range?: IRange): Promise<void> {
976
const attachment = this.attachment as ISCMHistoryItemChangeVariableEntry;
977
const historyItem = attachment.historyItem;
978
979
await this.editorService.openEditor({
980
resource,
981
label: `${basename(resource.path)} (${historyItem.displayId ?? historyItem.id})`,
982
options: { ...options.editorOptions }
983
}, options.openToSide ? SIDE_GROUP : undefined);
984
}
985
}
986
987
export class SCMHistoryItemChangeRangeAttachmentWidget extends AbstractChatAttachmentWidget {
988
constructor(
989
attachment: ISCMHistoryItemChangeRangeVariableEntry,
990
currentLanguageModel: ILanguageModelChatMetadataAndIdentifier | undefined,
991
options: { shouldFocusClearButton: boolean; supportsDeletion: boolean },
992
container: HTMLElement,
993
contextResourceLabels: ResourceLabels,
994
@ICommandService commandService: ICommandService,
995
@IOpenerService openerService: IOpenerService,
996
@IEditorService private readonly editorService: IEditorService,
997
) {
998
super(attachment, options, container, contextResourceLabels, currentLanguageModel, commandService, openerService);
999
1000
const historyItemStartId = attachment.historyItemChangeStart.historyItem.displayId ?? attachment.historyItemChangeStart.historyItem.id;
1001
const historyItemEndId = attachment.historyItemChangeEnd.historyItem.displayId ?? attachment.historyItemChangeEnd.historyItem.id;
1002
1003
const nameSuffix = `\u00A0$(${Codicon.gitCommit.id})${historyItemStartId}..${historyItemEndId}`;
1004
this.label.setFile(attachment.value, { fileKind: FileKind.FILE, hidePath: true, nameSuffix });
1005
1006
this.element.ariaLabel = localize('chat.attachment', "Attached context, {0}", attachment.name);
1007
1008
this.addResourceOpenHandlers(attachment.value, undefined);
1009
}
1010
1011
protected override async openResource(resource: URI, options: IOpenEditorOptions, isDirectory: true): Promise<void>;
1012
protected override async openResource(resource: URI, options: IOpenEditorOptions, isDirectory: false, range: IRange | undefined): Promise<void>;
1013
protected override async openResource(resource: URI, options: IOpenEditorOptions, isDirectory?: boolean, range?: IRange): Promise<void> {
1014
const attachment = this.attachment as ISCMHistoryItemChangeRangeVariableEntry;
1015
const historyItemChangeStart = attachment.historyItemChangeStart;
1016
const historyItemChangeEnd = attachment.historyItemChangeEnd;
1017
1018
const originalUriTitle = `${basename(historyItemChangeStart.uri.fsPath)} (${historyItemChangeStart.historyItem.displayId ?? historyItemChangeStart.historyItem.id})`;
1019
const modifiedUriTitle = `${basename(historyItemChangeEnd.uri.fsPath)} (${historyItemChangeEnd.historyItem.displayId ?? historyItemChangeEnd.historyItem.id})`;
1020
1021
await this.editorService.openEditor({
1022
original: { resource: historyItemChangeStart.uri },
1023
modified: { resource: historyItemChangeEnd.uri },
1024
label: `${originalUriTitle} ↔ ${modifiedUriTitle}`,
1025
options: { ...options.editorOptions }
1026
}, options.openToSide ? SIDE_GROUP : undefined);
1027
}
1028
}
1029
1030
export function hookUpResourceAttachmentDragAndContextMenu(accessor: ServicesAccessor, widget: HTMLElement, resource: URI): IDisposable {
1031
const contextKeyService = accessor.get(IContextKeyService);
1032
const instantiationService = accessor.get(IInstantiationService);
1033
1034
const store = new DisposableStore();
1035
1036
// Context
1037
const scopedContextKeyService = store.add(contextKeyService.createScoped(widget));
1038
store.add(setResourceContext(accessor, scopedContextKeyService, resource));
1039
1040
// Drag and drop
1041
widget.draggable = true;
1042
store.add(dom.addDisposableListener(widget, 'dragstart', e => {
1043
instantiationService.invokeFunction(accessor => fillEditorsDragData(accessor, [resource], e));
1044
e.dataTransfer?.setDragImage(widget, 0, 0);
1045
}));
1046
1047
// Context menu
1048
store.add(addBasicContextMenu(accessor, widget, scopedContextKeyService, MenuId.ChatInputResourceAttachmentContext, resource));
1049
1050
return store;
1051
}
1052
1053
export function hookUpSymbolAttachmentDragAndContextMenu(accessor: ServicesAccessor, widget: HTMLElement, scopedContextKeyService: IScopedContextKeyService, attachment: { name: string; value: Location; kind: SymbolKind }, contextMenuId: MenuId): IDisposable {
1054
const instantiationService = accessor.get(IInstantiationService);
1055
const languageFeaturesService = accessor.get(ILanguageFeaturesService);
1056
const textModelService = accessor.get(ITextModelService);
1057
1058
const store = new DisposableStore();
1059
1060
// Context
1061
store.add(setResourceContext(accessor, scopedContextKeyService, attachment.value.uri));
1062
1063
const chatResourceContext = chatAttachmentResourceContextKey.bindTo(scopedContextKeyService);
1064
chatResourceContext.set(attachment.value.uri.toString());
1065
1066
// Drag and drop
1067
widget.draggable = true;
1068
store.add(dom.addDisposableListener(widget, 'dragstart', e => {
1069
instantiationService.invokeFunction(accessor => fillEditorsDragData(accessor, [{ resource: attachment.value.uri, selection: attachment.value.range }], e));
1070
1071
fillInSymbolsDragData([{
1072
fsPath: attachment.value.uri.fsPath,
1073
range: attachment.value.range,
1074
name: attachment.name,
1075
kind: attachment.kind,
1076
}], e);
1077
1078
e.dataTransfer?.setDragImage(widget, 0, 0);
1079
}));
1080
1081
// Context menu
1082
const providerContexts: ReadonlyArray<[IContextKey<boolean>, LanguageFeatureRegistry<unknown>]> = [
1083
[EditorContextKeys.hasDefinitionProvider.bindTo(scopedContextKeyService), languageFeaturesService.definitionProvider],
1084
[EditorContextKeys.hasReferenceProvider.bindTo(scopedContextKeyService), languageFeaturesService.referenceProvider],
1085
[EditorContextKeys.hasImplementationProvider.bindTo(scopedContextKeyService), languageFeaturesService.implementationProvider],
1086
[EditorContextKeys.hasTypeDefinitionProvider.bindTo(scopedContextKeyService), languageFeaturesService.typeDefinitionProvider],
1087
];
1088
1089
const updateContextKeys = async () => {
1090
const modelRef = await textModelService.createModelReference(attachment.value.uri);
1091
try {
1092
const model = modelRef.object.textEditorModel;
1093
for (const [contextKey, registry] of providerContexts) {
1094
contextKey.set(registry.has(model));
1095
}
1096
} finally {
1097
modelRef.dispose();
1098
}
1099
};
1100
store.add(addBasicContextMenu(accessor, widget, scopedContextKeyService, contextMenuId, attachment.value, updateContextKeys));
1101
1102
return store;
1103
}
1104
1105
function setResourceContext(accessor: ServicesAccessor, scopedContextKeyService: IScopedContextKeyService, resource: URI) {
1106
const fileService = accessor.get(IFileService);
1107
const languageService = accessor.get(ILanguageService);
1108
const modelService = accessor.get(IModelService);
1109
1110
const resourceContextKey = new ResourceContextKey(scopedContextKeyService, fileService, languageService, modelService);
1111
resourceContextKey.set(resource);
1112
return resourceContextKey;
1113
}
1114
1115
function addBasicContextMenu(accessor: ServicesAccessor, widget: HTMLElement, scopedContextKeyService: IScopedContextKeyService, menuId: MenuId, arg: unknown, updateContextKeys?: () => Promise<void>): IDisposable {
1116
const contextMenuService = accessor.get(IContextMenuService);
1117
const menuService = accessor.get(IMenuService);
1118
1119
return dom.addDisposableListener(widget, dom.EventType.CONTEXT_MENU, async domEvent => {
1120
const event = new StandardMouseEvent(dom.getWindow(domEvent), domEvent);
1121
dom.EventHelper.stop(domEvent, true);
1122
1123
try {
1124
await updateContextKeys?.();
1125
} catch (e) {
1126
console.error(e);
1127
}
1128
1129
contextMenuService.showContextMenu({
1130
contextKeyService: scopedContextKeyService,
1131
getAnchor: () => event,
1132
getActions: () => {
1133
const menu = menuService.getMenuActions(menuId, scopedContextKeyService, { arg });
1134
return getFlatContextMenuActions(menu);
1135
},
1136
});
1137
});
1138
}
1139
1140
export const chatAttachmentResourceContextKey = new RawContextKey<string>('chatAttachmentResource', undefined, { type: 'URI', description: localize('resource', "The full value of the chat attachment resource, including scheme and path") });
1141
1142