forked from microsoft/copilot-for-eclipse
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathActionBar.java
More file actions
1137 lines (1025 loc) · 46.1 KB
/
Copy pathActionBar.java
File metadata and controls
1137 lines (1025 loc) · 46.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
package com.microsoft.copilot.eclipse.ui.chat;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.e4.core.services.events.IEventBroker;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceDialog;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextListener;
import org.eclipse.jface.text.TextEvent;
import org.eclipse.jface.text.contentassist.ContentAssistEvent;
import org.eclipse.jface.text.contentassist.ContentAssistant;
import org.eclipse.jface.text.contentassist.ICompletionListener;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.jface.text.contentassist.IContentAssistant;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.PreferencesUtil;
import org.osgi.service.event.EventHandler;
import com.microsoft.copilot.eclipse.core.Constants;
import com.microsoft.copilot.eclipse.core.CopilotCore;
import com.microsoft.copilot.eclipse.core.chat.BuiltInChatMode;
import com.microsoft.copilot.eclipse.core.chat.BuiltInChatModeManager;
import com.microsoft.copilot.eclipse.core.chat.CustomChatMode;
import com.microsoft.copilot.eclipse.core.chat.CustomChatModeManager;
import com.microsoft.copilot.eclipse.core.events.CopilotEventConstants;
import com.microsoft.copilot.eclipse.core.lsp.protocol.ChatMode;
import com.microsoft.copilot.eclipse.core.lsp.protocol.quota.CopilotPlan;
import com.microsoft.copilot.eclipse.core.utils.ChatMessageUtils;
import com.microsoft.copilot.eclipse.core.utils.FileUtils;
import com.microsoft.copilot.eclipse.core.utils.PlatformUtils;
import com.microsoft.copilot.eclipse.core.utils.WorkspaceUtils;
import com.microsoft.copilot.eclipse.ui.CopilotUi;
import com.microsoft.copilot.eclipse.ui.UiConstants;
import com.microsoft.copilot.eclipse.ui.chat.contextwindow.ContextSizeDonut;
import com.microsoft.copilot.eclipse.ui.chat.services.ChatServiceManager;
import com.microsoft.copilot.eclipse.ui.chat.services.ModelService;
import com.microsoft.copilot.eclipse.ui.chat.services.ReferencedFileService;
import com.microsoft.copilot.eclipse.ui.chat.services.UserPreferenceService;
import com.microsoft.copilot.eclipse.ui.chat.tools.JavaDebuggerToolAdapter;
import com.microsoft.copilot.eclipse.ui.dialogs.jobs.GitHubCodingAgentDialog;
import com.microsoft.copilot.eclipse.ui.dialogs.jobs.ProjectSelectionDialog;
import com.microsoft.copilot.eclipse.ui.i18n.Messages;
import com.microsoft.copilot.eclipse.ui.preferences.McpPreferencePage;
import com.microsoft.copilot.eclipse.ui.swt.CssConstants;
import com.microsoft.copilot.eclipse.ui.swt.DropdownButton;
import com.microsoft.copilot.eclipse.ui.utils.AccessibilityUtils;
import com.microsoft.copilot.eclipse.ui.utils.PreferencesUtils;
import com.microsoft.copilot.eclipse.ui.utils.SwtUtils;
import com.microsoft.copilot.eclipse.ui.utils.UiUtils;
/**
* A custom widget that displays a turn.
*/
public class ActionBar extends Composite implements NewConversationListener {
private Button btnMsgToggle;
private DropdownButton modelPickerButton;
private DropdownButton modePickerButton;
private ChatInputTextViewer inputTextViewer;
private Composite cmpFileRef;
private Composite cmpActionArea;
private Composite bottomRightButtonsComposite;
private CurrentReferencedFile currentFileRef;
private ContentAssistant ca;
private Image sendImage;
private Image sendDisabledImage;
private boolean isSendButton = true;
private LinkedHashSet<MessageListener> messageListeners = new LinkedHashSet<>();
private Button mcpToolButton;
private Image mcpToolImage;
private Image mcpToolDisabledImage;
private Image mcpToolDetectedImage;
private Image redNoticeImage;
private Button sendToJobButton;
private Image sendToJobImage;
private Image sendToJobDisabledImage;
private Button autoBreakpointButton;
private Image autoBreakpointImage;
private Image autoBreakpointDisabledImage;
private ContextSizeDonut contextSizeDonut;
private StaticBanner staticBanner;
private Composite inputArea;
private ChatServiceManager chatServiceManager;
IEventBroker eventBroker;
EventHandler updateSendButtonToCancelButtonHandler;
EventHandler featureFlagsChangedEventHandler;
EventHandler updateMcpToolButtonAndPlaceHolderHandler;
private static enum SendOrCancelButtonStates {
SEND_ENABLED, SEND_DISABLED, CANCEL_ENABLED;
}
/**
* Creates a new InputArea.
*/
public ActionBar(Composite parent, int style, ChatServiceManager chatServiceManager) {
super(parent, SWT.NONE);
GridLayout glContainer = new GridLayout(1, false);
glContainer.marginWidth = 10;
glContainer.marginHeight = 0;
glContainer.verticalSpacing = 0;
this.setLayout(glContainer);
this.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
this.setData(CssConstants.CSS_ID_KEY, "chat-action-bar-wrapper");
this.chatServiceManager = chatServiceManager;
this.updateSendButtonToCancelButtonHandler = event -> {
updateButtonState(SendOrCancelButtonStates.CANCEL_ENABLED);
};
this.eventBroker = PlatformUI.getWorkbench().getService(IEventBroker.class);
this.eventBroker.subscribe(CopilotEventConstants.TOPIC_CHAT_ON_SEND, updateSendButtonToCancelButtonHandler);
this.updateMcpToolButtonAndPlaceHolderHandler = event -> {
updateMcpToolButtonVisibility();
updateAutoBreakpointButtonVisibility();
refreshPlaceholder();
};
this.eventBroker.subscribe(CopilotEventConstants.TOPIC_CHAT_MODE_CHANGED, updateMcpToolButtonAndPlaceHolderHandler);
this.featureFlagsChangedEventHandler = event -> {
// Update buttons layout when feature flags change
SwtUtils.invokeOnDisplayThreadAsync(() -> {
updateButtonsLayout();
}, this);
};
this.eventBroker.subscribe(CopilotEventConstants.TOPIC_CHAT_DID_CHANGE_FEATURE_FLAGS,
featureFlagsChangedEventHandler);
// Transparent wrapper for the optional TodoListBar / WorkingSetBar and the bordered input below.
// StaticBanner is created as a sibling of inputArea so it stays structurally above the whole stack.
this.inputArea = new Composite(this, SWT.NONE);
GridLayout glInputArea = new GridLayout(1, false);
glInputArea.marginWidth = 0;
glInputArea.marginHeight = 0;
glInputArea.marginLeft = 0;
glInputArea.marginRight = 0;
glInputArea.marginTop = 0;
glInputArea.marginBottom = 0;
glInputArea.horizontalSpacing = 0;
glInputArea.verticalSpacing = 0;
this.inputArea.setLayout(glInputArea);
this.inputArea.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
Composite borderedActionBar = new Composite(this.inputArea, style | SWT.BORDER);
GridLayout gl = new GridLayout(1, false);
gl.marginHeight = 5;
gl.verticalSpacing = 0;
borderedActionBar.setLayout(gl);
borderedActionBar.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
borderedActionBar.setData(CssConstants.CSS_ID_KEY, "chat-action-bar");
RowLayout rowLayout = new RowLayout();
rowLayout.wrap = true;
rowLayout.pack = true;
rowLayout.justify = false;
rowLayout.type = SWT.HORIZONTAL;
// marginWidth/marginHeight will not overwrite marginLeft/Right marginTop/Bottom
// both of them are used to compute size in row layout, so set them separately
rowLayout.marginWidth = 0;
rowLayout.marginHeight = 0;
rowLayout.marginRight = 0;
rowLayout.marginLeft = 0;
rowLayout.marginTop = 0;
rowLayout.marginBottom = 10;
rowLayout.center = true;
this.cmpFileRef = new Composite(borderedActionBar, SWT.NONE);
this.cmpFileRef.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
this.cmpFileRef.setLayout(rowLayout);
new AddContextButton(this.cmpFileRef);
this.currentFileRef = new CurrentReferencedFile(this.cmpFileRef);
ReferencedFileService referencedFileService = chatServiceManager.getReferencedFileService();
referencedFileService.bindCurrentFileWidget(currentFileRef);
referencedFileService.bindReferencedFilesWidget(this);
ModelService modelService = chatServiceManager.getModelService();
modelService.bindActionBarForSupportVisionChange(this);
ChatInputTextViewer tv = new ChatInputTextViewer(borderedActionBar, chatServiceManager);
tv.setEditable(true);
// Relayout the chat view container so the new ActionBar preferred height is honored when the input grows or
// shrinks (e.g., recalling a long history entry with Up arrow, wrapping a long line, or clearing the input).
// Avoids a brittle fixed-depth parent traversal inside ChatInputTextViewer (see issue #215).
tv.setLayoutRefreshCallback(() -> {
if (ActionBar.this.isDisposed()) {
return;
}
Composite layoutTarget = ActionBar.this.getParent();
if (layoutTarget != null && !layoutTarget.isDisposed()) {
// TODO: An very interesting bug here, if we call layout(true, true), even no changes,
// The width of welcome view will become shorter and shorter, may investigate it later
layoutTarget.layout(true, false);
}
});
tv.addTextListener(new ITextListener() {
@Override
public void textChanged(TextEvent event) {
if (!isSendButton) {
return;
}
if (tv.getDocument().get().equals(StringUtils.EMPTY)) {
updateButtonState(SendOrCancelButtonStates.SEND_DISABLED);
} else {
updateButtonState(SendOrCancelButtonStates.SEND_ENABLED);
}
}
});
tv.setSendMessageHandler((message) -> {
if (isSendButton) {
handleSendMessage();
}
});
this.inputTextViewer = tv;
AccessibilityUtils.addAccessibilityNameForUiComponent(tv.getTextWidget(), "ask copilot input text area");
ca = new ContentAssistant();
ca.enableAutoActivateCompletionOnType(true);
ca.enableCompletionProposalTriggerChars(true);
ca.enableAutoActivation(true);
ca.setContentAssistProcessor(new ChatAssistProcessor(tv, chatServiceManager), IDocument.DEFAULT_CONTENT_TYPE);
ca.setProposalPopupOrientation(IContentAssistant.PROPOSAL_STACKED);
ca.enableColoredLabels(true);
ca.setAutoActivationDelay(0);
ca.addCompletionListener(new ICompletionListener() {
private static final int MAX_VISIBLE_ITEMS = 10; // follow the same behavior of CompletionProposalPopup
private Map<Table, Listener> tableListeners = new HashMap<>();
@Override
public void assistSessionStarted(ContentAssistEvent event) {
}
@Override
public void assistSessionEnded(ContentAssistEvent event) {
}
@Override
public void selectionChanged(ICompletionProposal proposal, boolean smartToggle) {
Object proposalPopup = PlatformUtils.getPropertyWithReflection(ca, "fProposalPopup");
Object popupTable = PlatformUtils.getPropertyWithReflection(proposalPopup, "fProposalTable");
// get ca.fProposalPopup.fProposalTable using reflection
if (popupTable != null && popupTable instanceof Table table && table.getLayoutData() instanceof GridData) {
updateTableLayout(table);
// when selection changed, table did not fill data in mac, which will make the size incorrect
// use listener to track the set data event, and update layout when data is filled
Listener listener = tableListeners.computeIfAbsent(table, t -> e -> updateTableLayout(t));
table.addListener(SWT.SetData, listener);
}
}
private void updateTableLayout(Table table) {
Point size = table.computeSize(SWT.DEFAULT, SWT.DEFAULT);
int heightHint = Math.min(size.y, table.getItemHeight() * MAX_VISIBLE_ITEMS);
int widthHint = Math.min(size.x, tv.getControl().getSize().x);
// If horizontal scrollbar is needed, add its height to the table height
// Otherwise, the last raw may not be fully visible
if (size.x > widthHint) {
heightHint += table.getHorizontalBar().getSize().y;
}
table.getShell().setSize(widthHint, heightHint);
}
});
ca.install(tv);
tv.setContentAssistProcessor(ca);
GridLayout glActionArea = new GridLayout(2, false);
// Same as RowLayout above, need to set marginWidth/Height and marginLeft/Right/Top/Bottom separately in GridLayout
glActionArea.marginWidth = 0;
glActionArea.marginHeight = 0;
glActionArea.marginRight = 0;
glActionArea.marginLeft = 0;
glActionArea.marginTop = 5;
glActionArea.marginBottom = -5;
this.cmpActionArea = new Composite(borderedActionBar, SWT.NONE);
this.cmpActionArea.setLayout(glActionArea);
this.cmpActionArea.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
Composite cmpControlBar = new Composite(this.cmpActionArea, SWT.NONE);
GridLayout glControlBar = new GridLayout(5, false);
glControlBar.marginWidth = 0;
glControlBar.marginLeft = 0;
cmpControlBar.setLayout(glControlBar);
cmpControlBar.setLayoutData(new GridData(SWT.LEFT, SWT.BOTTOM, true, false));
setUpChatModePicker(cmpControlBar);
setUpModelPicker(cmpControlBar);
setUpAutoBreakpointButtonInControlBar(cmpControlBar);
setUpMcpToolButtonInControlBar(cmpControlBar);
setUpContextSizeDonutInControlBar(cmpControlBar);
// Create a composite for the bottom-right side buttons
GridLayout buttonsLayout = new GridLayout(2, false);
buttonsLayout.marginWidth = 0;
buttonsLayout.marginHeight = 0;
this.bottomRightButtonsComposite = new Composite(this.cmpActionArea, SWT.NONE);
this.bottomRightButtonsComposite.setLayout(buttonsLayout);
this.bottomRightButtonsComposite.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
// Update send to job button and send button together
updateButtonsLayout();
this.addDisposeListener(e -> {
if (mcpToolImage != null && !mcpToolImage.isDisposed()) {
mcpToolImage.dispose();
}
if (mcpToolDisabledImage != null && !mcpToolDisabledImage.isDisposed()) {
mcpToolDisabledImage.dispose();
}
if (mcpToolDetectedImage != null && !mcpToolDetectedImage.isDisposed()) {
mcpToolDetectedImage.dispose();
}
if (redNoticeImage != null && !redNoticeImage.isDisposed()) {
redNoticeImage.dispose();
}
});
}
/**
* Update the referenced file widgets when supportVision changes.
*
* @param supportVision true if the current model supports vision, false otherwise
*/
public void updateReferencedWidgetsWithSupportVision(boolean supportVision) {
SwtUtils.invokeOnDisplayThreadAsync(() -> {
List<IResource> referencedFiles = chatServiceManager.getReferencedFileService().getReferencedFiles();
updateReferencedFilesInternal(referencedFiles, supportVision);
}, this);
}
/**
* Update the referenced file widgets when the file set changes.
*
* @param files the list of files to update
*/
public void updateReferencedWidgetsWithFiles(List<IResource> files) {
SwtUtils.invokeOnDisplayThreadAsync(() -> {
boolean supportVision = chatServiceManager.getModelService().isVisionSupported();
updateReferencedFilesInternal(files, supportVision);
}, this);
}
/**
* Update the referenced file widgets with the given files and supportVision flag.
*/
private void updateReferencedFilesInternal(List<IResource> files, boolean supportVision) {
if (files == null) {
return;
}
if (this.cmpFileRef == null || this.cmpFileRef.isDisposed()) {
return;
}
// Get parent composite and disable redraw to avoid flickering when references files are updated
Composite actionBarParent = this.getParent();
actionBarParent.setRedraw(false);
try {
for (Control child : cmpFileRef.getChildren()) {
if (child instanceof ReferencedFile && !(child instanceof CurrentReferencedFile)) {
child.dispose();
}
}
for (IResource file : files) {
if (file instanceof IFile) {
boolean isUnSupportedFile = !supportVision && ChatMessageUtils.isImageFile((IFile) file);
new ReferencedFile(this.cmpFileRef, file, isUnSupportedFile);
} else if (file instanceof IFolder) {
new ReferencedFile(this.cmpFileRef, file, false);
}
}
} finally {
actionBarParent.setRedraw(true);
refreshLayout();
}
}
/**
* Refresh the layout of both sendToJob button and send button together to ensure proper coordination.
*/
public void updateButtonsLayout() {
if (sendToJobButton != null && !sendToJobButton.isDisposed()) {
sendToJobButton.dispose();
sendToJobButton = null;
}
if (btnMsgToggle != null && !btnMsgToggle.isDisposed()) {
btnMsgToggle.dispose();
btnMsgToggle = null;
}
// Check if client preview features are enabled
boolean clientPreviewFeaturesEnabled = CopilotCore.getPlugin().getFeatureFlags().isClientPreviewFeatureEnabled();
// Bottom right buttons composite: 2 columns if sendToJob is visible, 1 column otherwise
GridLayout buttonsLayout = (GridLayout) this.bottomRightButtonsComposite.getLayout();
buttonsLayout.numColumns = clientPreviewFeaturesEnabled ? 2 : 1;
// Add sendToJob button - only visible if clientPreviewFeaturesEnabled
if (clientPreviewFeaturesEnabled) {
if (sendToJobImage == null || sendToJobImage.isDisposed()) {
sendToJobImage = UiUtils.buildImageFromPngPath("/icons/chat/send_to_job.png");
}
if (sendToJobDisabledImage == null || sendToJobDisabledImage.isDisposed()) {
sendToJobDisabledImage = UiUtils.buildImageFromPngPath("/icons/chat/send_to_job_disabled.png");
}
this.sendToJobButton = UiUtils.createIconButton(this.bottomRightButtonsComposite, SWT.PUSH | SWT.FLAT);
boolean hasText = !StringUtils.isBlank(this.inputTextViewer.getContent());
this.sendToJobButton.setEnabled(hasText);
this.sendToJobButton.setImage(hasText ? sendToJobImage : sendToJobDisabledImage);
this.sendToJobButton.setToolTipText(Messages.chat_actionBar_sendToJobButton_Tooltip);
GridData sendToJobGd = new GridData(SWT.LEFT, SWT.CENTER, false, false);
sendToJobGd.widthHint = sendToJobImage.getImageData().width + 2 * UiConstants.BTN_PADDING;
sendToJobGd.heightHint = sendToJobImage.getImageData().height + 2 * UiConstants.BTN_PADDING;
this.sendToJobButton.setLayoutData(sendToJobGd);
this.sendToJobButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
handleSendToJob();
setFocusToInputTextViewer();
}
});
}
// Add toggle button for all modes if it has not been created
if (btnMsgToggle == null || btnMsgToggle.isDisposed()) {
this.sendImage = UiUtils.buildImageFromPngPath("/icons/chat/send.png");
this.sendDisabledImage = UiUtils.buildImageFromPngPath("/icons/chat/send_disabled.png");
this.btnMsgToggle = UiUtils.createIconButton(bottomRightButtonsComposite, SWT.PUSH | SWT.FLAT);
boolean isEnabled = !StringUtils.isBlank(this.inputTextViewer.getContent());
this.btnMsgToggle.setEnabled(isEnabled);
this.btnMsgToggle.setImage(isEnabled ? this.sendImage : this.sendDisabledImage);
this.btnMsgToggle.setToolTipText(Messages.chat_actionBar_sendButton_Tooltip);
GridData sendGd = new GridData(SWT.RIGHT, SWT.CENTER, false, false);
sendGd.widthHint = this.sendImage.getImageData().width + 2 * UiConstants.BTN_PADDING;
sendGd.heightHint = this.sendImage.getImageData().height + 2 * UiConstants.BTN_PADDING;
this.btnMsgToggle.setLayoutData(sendGd);
this.btnMsgToggle.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
if (isSendButton) {
handleSendMessage();
} else {
handleCancelMessage();
}
}
});
this.btnMsgToggle.addDisposeListener(e -> {
if (sendImage != null && !sendImage.isDisposed()) {
sendImage.dispose();
}
if (sendDisabledImage != null && !sendDisabledImage.isDisposed()) {
sendDisabledImage.dispose();
}
});
AccessibilityUtils.addAccessibilityNameForUiComponent(this.btnMsgToggle,
Messages.chat_actionBar_sendButton_Tooltip);
}
// Refresh the layout
this.bottomRightButtonsComposite.requestLayout();
}
/**
* Refresh the chat input text viewer.
*/
public void refreshChatInputTextViewer() {
if (this.inputTextViewer != null) {
this.inputTextViewer.refresh();
}
}
private void setUpModelPicker(Composite parent) {
this.modelPickerButton = new DropdownButton(parent, SWT.NONE);
this.modelPickerButton.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, true, false));
ModelService modelService = chatServiceManager.getModelService();
modelService.bindModelPicker(modelPickerButton);
}
private void setUpChatModePicker(Composite parent) {
this.modePickerButton = new DropdownButton(parent, SWT.NONE);
this.modePickerButton.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, false, false));
this.modePickerButton.setToolTipText(Messages.chat_actionBar_modePicker_Tooltip);
this.modePickerButton.setAccessibilityName("chat mode picker");
UserPreferenceService userPreferenceService = chatServiceManager.getUserPreferenceService();
userPreferenceService.bindChatModePicker(this.modePickerButton);
// Add a listener to reload modes when dropdown is about to be shown
this.modePickerButton.addListener(SWT.MouseDown, event -> {
userPreferenceService.reloadChatModes();
});
this.modePickerButton.setSelectionListener(id -> {
userPreferenceService.setActiveChatMode(id);
updateMcpToolButtonVisibility();
});
}
private void setUpMcpToolButtonInControlBar(Composite parent) {
if (mcpToolImage == null || mcpToolImage.isDisposed()) {
mcpToolImage = UiUtils.buildImageFromPngPath("/icons/chat/tools.png");
}
if (mcpToolDisabledImage == null || mcpToolDisabledImage.isDisposed()) {
mcpToolDisabledImage = UiUtils.buildImageFromPngPath("/icons/chat/tools_disabled.png");
}
if (mcpToolDetectedImage == null || mcpToolDetectedImage.isDisposed()) {
mcpToolDetectedImage = UiUtils.buildImageFromPngPath("/icons/chat/tools_detected.png");
}
this.mcpToolButton = UiUtils.createIconButton(parent, SWT.PUSH | SWT.FLAT);
this.chatServiceManager.getMcpConfigService().bindWithMcpToolButton(mcpToolButton, mcpToolImage,
mcpToolDisabledImage, mcpToolDetectedImage);
GridData mcpToolGd = new GridData(SWT.LEFT, SWT.CENTER, false, false);
mcpToolGd.widthHint = mcpToolImage.getImageData().width + 2 * UiConstants.BTN_PADDING;
mcpToolGd.heightHint = mcpToolImage.getImageData().height + 2 * UiConstants.BTN_PADDING;
this.mcpToolButton.setLayoutData(mcpToolGd);
this.mcpToolButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (!CopilotCore.getPlugin().getFeatureFlags().isMcpEnabled()) {
return;
}
// Check if new MCP registrations are found
if (chatServiceManager.getMcpConfigService().isNewExtMcpRegFound()) {
showMcpToolContextMenu();
} else {
// Default behavior - open preference page directly
openMcpPreferences();
}
// set focus back to input text viewer after handling MCP button click
setFocusToInputTextViewer();
}
});
// Set initial visibility based on chat mode
updateMcpToolButtonVisibility();
}
private void setUpContextSizeDonutInControlBar(Composite parent) {
this.contextSizeDonut = new ContextSizeDonut(parent, chatServiceManager.getContextWindowService());
}
private void setUpAutoBreakpointButtonInControlBar(Composite parent) {
if (autoBreakpointImage == null || autoBreakpointImage.isDisposed()) {
autoBreakpointImage = UiUtils.buildImageFromPngPath("/icons/chat/breakpoint_auto.png");
}
if (autoBreakpointDisabledImage == null || autoBreakpointDisabledImage.isDisposed()) {
autoBreakpointDisabledImage = UiUtils.buildImageFromPngPath("/icons/chat/breakpoint_auto_disabled.png");
}
this.autoBreakpointButton = UiUtils.createIconButton(parent, SWT.CHECK | SWT.FLAT);
GridData autoBreakpointGd = new GridData(SWT.LEFT, SWT.CENTER, false, false);
autoBreakpointGd.widthHint = autoBreakpointImage.getImageData().width + 2 * UiConstants.BTN_PADDING;
autoBreakpointGd.heightHint = autoBreakpointImage.getImageData().height + 2 * UiConstants.BTN_PADDING;
this.autoBreakpointButton.setLayoutData(autoBreakpointGd);
// Get initial state from preferences
IPreferenceStore preferenceStore = CopilotUi.getPlugin().getPreferenceStore();
boolean autoResponseEnabled = preferenceStore.getBoolean(Constants.AUTO_BREAKPOINT_RESPONSE);
this.autoBreakpointButton.setSelection(autoResponseEnabled);
// Update image and tooltip based on selection state
this.autoBreakpointButton.setImage(autoResponseEnabled ? autoBreakpointImage : autoBreakpointDisabledImage);
this.autoBreakpointButton
.setToolTipText(autoResponseEnabled ? Messages.chat_actionBar_autoBreakpointButton_enabled_Tooltip
: Messages.chat_actionBar_autoBreakpointButton_disabled_Tooltip);
this.autoBreakpointButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
boolean selected = autoBreakpointButton.getSelection();
preferenceStore.setValue(Constants.AUTO_BREAKPOINT_RESPONSE, selected);
autoBreakpointButton.setImage(selected ? autoBreakpointImage : autoBreakpointDisabledImage);
autoBreakpointButton.setToolTipText(selected ? Messages.chat_actionBar_autoBreakpointButton_enabled_Tooltip
: Messages.chat_actionBar_autoBreakpointButton_disabled_Tooltip);
// Notify ChatView to enable/disable the handler
Map<String, Object> data = new HashMap<>();
data.put("enabled", selected);
eventBroker.post(CopilotEventConstants.TOPIC_CHAT_AUTO_BREAKPOINT_TOGGLE, data);
}
});
AccessibilityUtils.addAccessibilityNameForUiComponent(this.autoBreakpointButton,
Messages.chat_actionBar_autoBreakpointButton_accessibilityName);
// Set initial visibility based on java_debugger tool availability
updateAutoBreakpointButtonVisibility();
}
//@formatter:off
/**
* Update MCP tool button visibility based on whether the current mode allows tool configuration.
* Shows the tool button only when the mode allows tool configuration:
* - Agent mode: Shows tool button
* - Plan mode: Hides tool button (Plan uses Agent UI but no tools)
* - Ask mode: Hides tool button
* - Custom modes: Shows tool button (all custom modes allow tools)
*/
//@formatter:on
public void updateMcpToolButtonVisibility() {
if (mcpToolButton == null || mcpToolButton.isDisposed()) {
return;
}
boolean allowsToolConfiguration = false;
// Get the active mode name or ID from UserPreferenceService
String activeModeNameOrId = chatServiceManager.getUserPreferenceService().getActiveModeNameOrId();
if (activeModeNameOrId != null) {
// First check if it's a built-in mode
BuiltInChatMode builtInMode = BuiltInChatModeManager.INSTANCE.getBuiltInModeByDisplayName(activeModeNameOrId);
if (builtInMode != null) {
// Use the allowsToolConfiguration() method from the built-in mode
allowsToolConfiguration = builtInMode.allowsToolConfiguration();
} else {
// Check if it's a custom mode
CustomChatMode customMode = CustomChatModeManager.INSTANCE.getCustomModeById(activeModeNameOrId);
if (customMode != null) {
// Custom modes always allow tool configuration
allowsToolConfiguration = customMode.allowsToolConfiguration();
} else {
// Fallback: Check if current ChatMode enum equals Agent (backward compatibility)
ChatMode activeChatMode = chatServiceManager.getUserPreferenceService().getActiveChatMode();
allowsToolConfiguration = ChatMode.Agent.equals(activeChatMode);
}
}
} else {
// Fallback when activeModeNameOrId is null
ChatMode activeChatMode = chatServiceManager.getUserPreferenceService().getActiveChatMode();
allowsToolConfiguration = ChatMode.Agent.equals(activeChatMode);
}
mcpToolButton.setVisible(allowsToolConfiguration);
((GridData) mcpToolButton.getLayoutData()).exclude = !allowsToolConfiguration;
mcpToolButton.requestLayout();
}
/**
* Update auto-breakpoint button visibility based on whether java_debugger tool is enabled for the current mode.
*/
public void updateAutoBreakpointButtonVisibility() {
if (autoBreakpointButton == null || autoBreakpointButton.isDisposed()) {
return;
}
// Check if java_debugger tool is enabled for the current mode
boolean isJavaDebuggerEnabled = isJavaDebuggerToolEnabledForCurrentMode();
autoBreakpointButton.setVisible(isJavaDebuggerEnabled);
((GridData) autoBreakpointButton.getLayoutData()).exclude = !isJavaDebuggerEnabled;
autoBreakpointButton.requestLayout();
}
/**
* Check if java_debugger tool is enabled for the current mode.
*
* @return true if java_debugger tool is enabled for the current mode, false otherwise
*/
private boolean isJavaDebuggerToolEnabledForCurrentMode() {
// First check if the tool exists in the service
if (chatServiceManager.getAgentToolService().getTool(JavaDebuggerToolAdapter.TOOL_NAME) == null) {
return false;
}
// Get the active mode and check if java_debugger is in its tools list from CLS
String activeModeId = chatServiceManager.getUserPreferenceService().getActiveModeNameOrId();
if (activeModeId == null) {
return false;
}
// Check built-in modes
BuiltInChatMode builtInMode = BuiltInChatModeManager.INSTANCE.getBuiltInModeByDisplayName(activeModeId);
if (builtInMode != null) {
return builtInMode.getTools().contains(JavaDebuggerToolAdapter.TOOL_NAME);
}
// Check custom modes
CustomChatMode customMode = CustomChatModeManager.INSTANCE.getCustomModeById(activeModeId);
if (customMode != null) {
return customMode.getTools().contains(JavaDebuggerToolAdapter.TOOL_NAME);
}
return false;
}
@Override
public void onNewConversation() {
resetSendButton();
disposeStaticBanner();
}
/**
* Handles the cancel message event.
*/
public void resetSendButton() {
if (this.inputTextViewer.getContent().isEmpty()) {
updateButtonState(SendOrCancelButtonStates.SEND_DISABLED);
} else {
updateButtonState(SendOrCancelButtonStates.SEND_ENABLED);
}
this.chatServiceManager.getFileToolService().setWorkingSetBarButtonStatus(true);
}
/**
* Sets the focus to the chat input text viewer.
*
* @return true if the focus was set, false otherwise
*/
public boolean setFocusToInputTextViewer() {
if (inputTextViewer == null) {
return false;
}
StyledText textWidget = inputTextViewer.getTextWidget();
if (textWidget != null && !textWidget.isDisposed()) {
textWidget.setSelection(inputTextViewer.getContent().length());
return textWidget.setFocus();
}
return false;
}
/**
* Set the content of the input text viewer.
*
* @param content the content to set
*/
public void setInputTextViewerContent(String content) {
if (inputTextViewer != null && content != null) {
inputTextViewer.setContent(content);
}
}
/**
* Handles the send message event.
*/
public void handleSendMessage() {
updateButtonState(SendOrCancelButtonStates.CANCEL_ENABLED);
String message = this.inputTextViewer.getContent();
String workDoneToken = UUID.randomUUID().toString();
this.inputTextViewer.setContent(StringUtils.EMPTY);
notifySend(workDoneToken, message);
}
/**
* Handles the send to job button click event. Shows a dialog to inform user about git repository requirement.
*/
private void handleSendToJob() {
ChatServiceManager chatServiceManager = (ChatServiceManager) CopilotCore.getPlugin().getChatServiceManager();
if (chatServiceManager != null) {
UserPreferenceService userPreferenceService = chatServiceManager.getUserPreferenceService();
if (userPreferenceService != null) {
String selectedProjectPath = null;
Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
// Only proceed if a project was selected when multiple projects are present or user confirmed the Copilot agent
// job when single project
List<IProject> topLevelGitProjects = WorkspaceUtils.listTopLevelProjectsWithGitRepository();
if (topLevelGitProjects.isEmpty()) {
MessageDialog.openInformation(shell,
com.microsoft.copilot.eclipse.ui.dialogs.Messages.githubCodingAgentDialog_title,
Messages.chat_actionBar_sendToJob_noProject);
} else if (topLevelGitProjects.size() > 1) {
selectedProjectPath = ProjectSelectionDialog.open(shell);
} else if (userPreferenceService.isSkipGitHubJobConfirmDialog() || GitHubCodingAgentDialog.open(shell)) {
selectedProjectPath = FileUtils.getResourceUri(topLevelGitProjects.get(0));
}
// Only proceed if a project path was selected (dialog was not cancelled)
if (selectedProjectPath != null) {
updateButtonState(SendOrCancelButtonStates.CANCEL_ENABLED);
String message = this.inputTextViewer.getContent();
String workDoneToken = UUID.randomUUID().toString();
this.inputTextViewer.setContent(StringUtils.EMPTY);
notifySendWithSlug(workDoneToken, message, UiConstants.GITHUB_COPILOT_CODING_AGENT_SLUG, selectedProjectPath);
} else {
// Dialog was cancelled, reset button state based on current input content
if (this.inputTextViewer.getContent().isEmpty()) {
updateButtonState(SendOrCancelButtonStates.SEND_DISABLED);
} else {
updateButtonState(SendOrCancelButtonStates.SEND_ENABLED);
}
}
}
}
}
private void handleCancelMessage() {
resetSendButton();
notifyCancel();
IEventBroker eventBroker = PlatformUI.getWorkbench().getService(IEventBroker.class);
eventBroker.post(CopilotEventConstants.TOPIC_CHAT_MESSAGE_CANCELLED, null);
}
private void notifyCancel() {
for (MessageListener listener : messageListeners) {
listener.onCancel();
}
}
/**
* Registers a send message listener.
*
* @param listener the listener
*/
public void registerMessageListener(MessageListener listener) {
this.messageListeners.add(listener);
}
/**
* Unregisters a send message listener.
*
* @param listener the listener
*/
public void unregisterMessageListener(MessageListener listener) {
this.messageListeners.remove(listener);
}
/**
* Returns the current action bar conversation state. Return true if the conversation is stand by or cancelled, false
* otherwise
*/
public boolean isSendButton() {
return isSendButton;
}
private void updateButtonState(SendOrCancelButtonStates state) {
switch (state) {
case SEND_ENABLED:
isSendButton = true;
updateSendOrCancelMsgBtn(true, sendImage, Messages.chat_actionBar_sendButton_Tooltip);
updateSendToJobBtn(true);
break;
case SEND_DISABLED:
isSendButton = true;
updateSendOrCancelMsgBtn(false, sendDisabledImage, Messages.chat_actionBar_sendButton_Tooltip);
updateSendToJobBtn(false);
break;
case CANCEL_ENABLED:
isSendButton = false;
Image cancelImage = PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_ELCL_STOP);
updateSendOrCancelMsgBtn(true, cancelImage, Messages.chat_actionBar_cancelButton_Tooltip);
updateSendToJobBtn(false);
break;
default:
break;
}
}
/**
* Refreshes the placeholder text in the chat input text viewer.
*/
public void refreshPlaceholder() {
if (inputTextViewer != null && !inputTextViewer.getTextWidget().isDisposed()) {
inputTextViewer.getTextWidget().redraw();
}
}
/**
* Notifies the send message listeners.
*
* @param workDoneToken the work done token
* @param message the message
*/
public void notifySend(String workDoneToken, String message) {
Map<String, Object> properties = Map.of("workDoneToken", workDoneToken, "message", message, "createNewTurn", true);
this.eventBroker.post(CopilotEventConstants.TOPIC_CHAT_MESSAGE_SEND, properties);
}
/**
* Notifies the send message listeners with a specific agent slug.
*
* @param workDoneToken the work done token
* @param message the message
* @param agentSlug the agent slug to use for this turn
* @param agentJobWorkspaceFolder the workspace folder for the agent job
*/
public void notifySendWithSlug(String workDoneToken, String message, String agentSlug,
String agentJobWorkspaceFolder) {
Map<String, Object> properties = Map.of("workDoneToken", workDoneToken, "message", message, "agentSlug", agentSlug,
"agentJobWorkspaceFolder", agentJobWorkspaceFolder, "createNewTurn", true);
this.eventBroker.post(CopilotEventConstants.TOPIC_CHAT_MESSAGE_SEND, properties);
}
private void updateSendOrCancelMsgBtn(boolean enable, Image image, String tooltip) {
if (btnMsgToggle == null || btnMsgToggle.isDisposed()) {
return;
}
SwtUtils.invokeOnDisplayThread(() -> {
btnMsgToggle.setEnabled(enable);
btnMsgToggle.setImage(image);
btnMsgToggle.setToolTipText(tooltip);
}, btnMsgToggle);
}
private void updateSendToJobBtn(boolean enable) {
if (sendToJobButton == null || sendToJobButton.isDisposed()) {
return;
}
SwtUtils.invokeOnDisplayThread(() -> {
sendToJobButton.setEnabled(enable);
sendToJobButton.setImage(enable ? sendToJobImage : sendToJobDisabledImage);
}, sendToJobButton);
}
/**
* Popup a file picker dialog to select files. It's guaranteed that the selected files are unique.
*/
@NonNull
private List<IFile> selectFile() {
Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IContainer container = root.getContainerForLocation(root.getLocation());
AttachFileSelectionDialog dialog = new AttachFileSelectionDialog(shell, true, container);
dialog.setTitle(Messages.chat_filePicker_title);
dialog.setMessage(Messages.chat_filePicker_message);
List<IFile> result = new ArrayList<>();
if (dialog.open() == Window.OK) {
Object[] selectedFiles = dialog.getResult();
Set<String> selectedFileUris = new HashSet<>();
for (Object selectedFile : selectedFiles) {
if (selectedFile instanceof IFile file) {
URI fileUri = file.getLocationURI();
if (fileUri != null && selectedFileUris.add(fileUri.toASCIIString())) {
result.add(file);
}
}
}
return result;
}
return result;
}
/**
* Show the rate-limit static banner above the input area, with a single "Get more info" action link.
*
* @param message the message to display
* @param warning {@code true} for the warning icon; {@code false} for the info icon
*/
public void createRateLimitBanner(String message, boolean warning) {
List<BannerAction> actions = List.of(
new BannerAction(Messages.chat_rateLimitBanner_getMoreInfo, UiConstants.COPILOT_RATE_LIMIT_INFO_URL));
showStaticBanner(message, actions, warning);
}
/**
* Show the quota-warning static banner above the input area. Action links are sourced from
* {@link QuotaActions#forPlan(CopilotPlan, boolean, Boolean)} so they stay in sync with the inline
* {@link WarnWidget}.
*
* @param message the message to display
* @param plan the user's Copilot plan, or {@code null} for no action links
* @param overageEnabled whether additional paid usage is already enabled for the user; switches the
* "Enable Additional Usage" label to "Increase Budget"