@gitlab/duo-ui 10.23.1 → 11.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,891 @@
1
+ <script>
2
+ import throttle from 'lodash/throttle';
3
+
4
+ import {
5
+ GlButton,
6
+ GlDropdownItem,
7
+ GlCard,
8
+ GlFormTextarea,
9
+ GlForm,
10
+ GlSafeHtmlDirective as SafeHtml,
11
+ } from '@gitlab/ui';
12
+
13
+ import { translate } from '../../utils/i18n';
14
+
15
+ import {
16
+ badgeTypes,
17
+ badgeTypeValidator,
18
+ CHAT_RESET_MESSAGE,
19
+ CHAT_CLEAR_MESSAGE,
20
+ CHAT_NEW_MESSAGE,
21
+ CHAT_INCLUDE_MESSAGE,
22
+ MESSAGE_MODEL_ROLES,
23
+ MAX_PROMPT_LENGTH,
24
+ PROMPT_LENGTH_WARNING,
25
+ } from './constants';
26
+ import { VIEW_TYPES } from './components/duo_chat_header/constants';
27
+ import DuoChatLoader from './components/duo_chat_loader/duo_chat_loader.vue';
28
+ import DuoChatPredefinedPrompts from './components/duo_chat_predefined_prompts/duo_chat_predefined_prompts.vue';
29
+ import DuoChatConversation from './components/duo_chat_conversation/duo_chat_conversation.vue';
30
+ import WebDuoChatHeader from './components/duo_chat_header/web_duo_chat_header.vue';
31
+ import DuoChatThreads from './components/duo_chat_threads/duo_chat_threads.vue';
32
+
33
+ export const i18n = {
34
+ CHAT_DEFAULT_TITLE: translate('WebDuoChat.chatDefaultTitle', 'GitLab Duo Chat'),
35
+ CHAT_HISTORY_TITLE: translate('WebDuoChat.chatHistoryTitle', 'Chat history'),
36
+ CHAT_DISCLAMER: translate(
37
+ 'WebDuoChat.chatDisclamer',
38
+ 'Responses may be inaccurate. Verify before use.'
39
+ ),
40
+ CHAT_EMPTY_STATE_TITLE: translate(
41
+ 'WebDuoChat.chatEmptyStateTitle',
42
+ '👋 I am GitLab Duo Chat, your personal AI-powered assistant. How can I help you today?'
43
+ ),
44
+ CHAT_PROMPT_PLACEHOLDER_DEFAULT: translate(
45
+ 'WebDuoChat.chatPromptPlaceholderDefault',
46
+ "Let's work through this together..."
47
+ ),
48
+ CHAT_PROMPT_PLACEHOLDER_WITH_COMMANDS: translate(
49
+ 'WebDuoChat.chatPromptPlaceholderWithCommands',
50
+ 'Type /help to learn more'
51
+ ),
52
+ CHAT_SUBMIT_LABEL: translate('WebDuoChat.chatSubmitLabel', 'Send chat message.'),
53
+ CHAT_CANCEL_LABEL: translate('WebDuoChat.chatCancelLabel', 'Cancel'),
54
+ CHAT_MODEL_PLACEHOLDER: translate('WebDuoChat.chatModelPlaceholder', 'GitLab Duo Chat'),
55
+ CHAT_DEFAULT_PREDEFINED_PROMPTS: [
56
+ translate(
57
+ 'WebDuoChat.chatDefaultPredefinedPromptsChangePassword',
58
+ 'How do I change my password in GitLab?'
59
+ ),
60
+ translate('WebDuoChat.chatDefaultPredefinedPromptsForkProject', 'How do I fork a project?'),
61
+ translate(
62
+ 'WebDuoChat.chatDefaultPredefinedPromptsCloneRepository',
63
+ 'How do I clone a repository?'
64
+ ),
65
+ translate(
66
+ 'WebDuoChat.chatDefaultPredefinedPromptsCreateTemplate',
67
+ 'How do I create a template?'
68
+ ),
69
+ ],
70
+ };
71
+
72
+ const isMessage = (item) => Boolean(item) && item?.role;
73
+ const isSlashCommand = (command) => Boolean(command) && command?.name && command.description;
74
+
75
+ // eslint-disable-next-line unicorn/no-array-callback-reference
76
+ const itemsValidator = (items) => items.every(isMessage);
77
+ // eslint-disable-next-line unicorn/no-array-callback-reference
78
+ const slashCommandsValidator = (commands) => commands.every(isSlashCommand);
79
+
80
+ const isThread = (thread) =>
81
+ typeof thread === 'object' &&
82
+ typeof thread.id === 'string' &&
83
+ typeof thread.lastUpdatedAt === 'string' &&
84
+ typeof thread.createdAt === 'string' &&
85
+ typeof thread.conversationType === 'string' &&
86
+ (thread.title === null || typeof thread.title === 'string');
87
+
88
+ // eslint-disable-next-line unicorn/no-array-callback-reference
89
+ const threadListValidator = (threads) => threads.every(isThread);
90
+
91
+ const localeValidator = (value) => {
92
+ try {
93
+ Intl.getCanonicalLocales(value);
94
+ return true;
95
+ } catch {
96
+ return false;
97
+ }
98
+ };
99
+
100
+ export default {
101
+ name: 'DuoChat',
102
+ components: {
103
+ GlButton,
104
+ GlFormTextarea,
105
+ GlForm,
106
+ DuoChatLoader,
107
+ DuoChatPredefinedPrompts,
108
+ DuoChatConversation,
109
+ WebDuoChatHeader,
110
+ DuoChatThreads,
111
+ GlCard,
112
+ GlDropdownItem,
113
+ },
114
+ directives: {
115
+ SafeHtml,
116
+ },
117
+ props: {
118
+ /**
119
+ * The title of the chat/feature.
120
+ */
121
+ title: {
122
+ type: String,
123
+ required: false,
124
+ default: i18n.CHAT_DEFAULT_TITLE,
125
+ },
126
+ /**
127
+ * Array of messages to display in the chat.
128
+ */
129
+ messages: {
130
+ type: Array,
131
+ required: false,
132
+ default: () => [],
133
+ validator: itemsValidator,
134
+ },
135
+ /**
136
+ * The ID of the active thread (if any).
137
+ */
138
+ activeThreadId: {
139
+ type: String,
140
+ required: false,
141
+ default: () => '',
142
+ },
143
+ /**
144
+ * The chat page that should be shown.
145
+ */
146
+ multiThreadedView: {
147
+ type: String,
148
+ required: false,
149
+ default: VIEW_TYPES.LIST,
150
+ validator: (value) => [VIEW_TYPES.LIST, VIEW_TYPES.CHAT].includes(value),
151
+ },
152
+ /**
153
+ * Array of RequestIds that have been canceled.
154
+ */
155
+ canceledRequestIds: {
156
+ type: Array,
157
+ required: false,
158
+ default: () => [],
159
+ },
160
+ /**
161
+ * A non-recoverable error message to display in the chat.
162
+ */
163
+ error: {
164
+ type: String,
165
+ required: false,
166
+ default: '',
167
+ },
168
+ /**
169
+ * Array of messages to display in the chat.
170
+ */
171
+ threadList: {
172
+ type: Array,
173
+ required: false,
174
+ default: () => [],
175
+ validator: threadListValidator,
176
+ },
177
+
178
+ /**
179
+ * Whether the chat is currently fetching a response from AI.
180
+ */
181
+ isLoading: {
182
+ type: Boolean,
183
+ required: false,
184
+ default: false,
185
+ },
186
+ /**
187
+ * Whether the conversational interfaces should be enabled.
188
+ */
189
+ isChatAvailable: {
190
+ type: Boolean,
191
+ required: false,
192
+ default: true,
193
+ },
194
+ /**
195
+ * Whether the insertCode feature should be available.
196
+ */
197
+ enableCodeInsertion: {
198
+ type: Boolean,
199
+ required: false,
200
+ default: false,
201
+ },
202
+ /**
203
+ * Array of predefined prompts to display in the chat to start a conversation.
204
+ */
205
+ predefinedPrompts: {
206
+ type: Array,
207
+ required: false,
208
+ default: () => i18n.CHAT_DEFAULT_PREDEFINED_PROMPTS,
209
+ },
210
+ /**
211
+ * The type of the badge. This is passed down to the `GlExperimentBadge` component. Refer that component for more information.
212
+ */
213
+ badgeType: {
214
+ type: String || null,
215
+ required: false,
216
+ default: badgeTypes[0],
217
+ validator: badgeTypeValidator,
218
+ },
219
+ /**
220
+ * The current tool's name to display in the loading message while waiting for a response from AI. Refer the `DuoChatLoader` component for more information.
221
+ */
222
+ toolName: {
223
+ type: String,
224
+ required: false,
225
+ default: i18n.CHAT_DEFAULT_TITLE,
226
+ },
227
+ /**
228
+ * Array of slash commands to display in the chat.
229
+ */
230
+ slashCommands: {
231
+ type: Array,
232
+ required: false,
233
+ default: () => [],
234
+ validator: slashCommandsValidator,
235
+ },
236
+ /**
237
+ * Whether the header should be displayed.
238
+ */
239
+ showHeader: {
240
+ type: Boolean,
241
+ required: false,
242
+ default: true,
243
+ },
244
+ /**
245
+ * Override the default empty state title text.
246
+ */
247
+ emptyStateTitle: {
248
+ type: String,
249
+ required: false,
250
+ default: i18n.CHAT_EMPTY_STATE_TITLE,
251
+ },
252
+ /**
253
+ * Override the default chat prompt placeholder text.
254
+ */
255
+ chatPromptPlaceholder: {
256
+ type: String,
257
+ required: false,
258
+ default: '',
259
+ },
260
+ /**
261
+ * Whether the chat is running in multi-threaded mode
262
+ */
263
+ isMultithreaded: {
264
+ type: Boolean,
265
+ required: false,
266
+ default: false,
267
+ },
268
+ /**
269
+ * Base URL of the GitLab instance.
270
+ */
271
+ trustedUrls: {
272
+ type: Array,
273
+ required: false,
274
+ default: () => [],
275
+ },
276
+ /*
277
+ * The preferred locale for the chat interface.
278
+ * Follows BCP 47 language tag format (e.g., 'en-US', 'fr-FR', 'es-ES').
279
+ */
280
+ preferredLocale: {
281
+ type: Array,
282
+ required: false,
283
+ default: () => ['en-US', 'en'],
284
+ validator: localeValidator,
285
+ },
286
+ shouldRenderResizable: {
287
+ type: Boolean,
288
+ required: false,
289
+ default: false,
290
+ },
291
+ },
292
+ data() {
293
+ return {
294
+ prompt: '',
295
+ scrolledToBottom: true,
296
+ activeCommandIndex: 0,
297
+ displaySubmitButton: true,
298
+ compositionJustEnded: false,
299
+ contextItemsMenuIsOpen: false,
300
+ contextItemMenuRef: null,
301
+ currentView: this.multiThreadedView,
302
+ maxPromptLength: MAX_PROMPT_LENGTH,
303
+ maxPromptLengthWarning: PROMPT_LENGTH_WARNING,
304
+ promptLengthWarningCount: MAX_PROMPT_LENGTH - PROMPT_LENGTH_WARNING,
305
+ };
306
+ },
307
+ computed: {
308
+ shouldShowThreadList() {
309
+ return this.isMultithreaded && this.currentView === VIEW_TYPES.LIST;
310
+ },
311
+ withSlashCommands() {
312
+ return this.slashCommands.length > 0;
313
+ },
314
+ hasMessages() {
315
+ return this.messages?.length > 0;
316
+ },
317
+ conversations() {
318
+ if (!this.hasMessages) return [];
319
+
320
+ return this.messages.reduce(
321
+ (acc, message) => {
322
+ if (message.content === CHAT_RESET_MESSAGE) {
323
+ acc.push([]);
324
+ } else {
325
+ acc[acc.length - 1].push(message);
326
+ }
327
+ return acc;
328
+ },
329
+ [[]]
330
+ );
331
+ },
332
+ lastMessage() {
333
+ return this.messages?.[this.messages.length - 1];
334
+ },
335
+ caseInsensitivePrompt() {
336
+ return this.prompt.toLowerCase().trim();
337
+ },
338
+ isPromptEmpty() {
339
+ return this.caseInsensitivePrompt.length === 0;
340
+ },
341
+ isStreaming() {
342
+ if (this.canceledRequestIds.includes(this.lastMessage?.requestId)) {
343
+ return false;
344
+ }
345
+ return Boolean(
346
+ (this.lastMessage?.chunks?.length > 0 && !this.lastMessage?.content) ||
347
+ typeof this.lastMessage?.chunkId === 'number'
348
+ );
349
+ },
350
+ filteredSlashCommands() {
351
+ return this.slashCommands
352
+ .filter((c) => c.name.toLowerCase().startsWith(this.caseInsensitivePrompt))
353
+ .filter((c) => {
354
+ if (c.name === CHAT_INCLUDE_MESSAGE) {
355
+ return this.hasContextItemSelectionMenu;
356
+ }
357
+ return true;
358
+ });
359
+ },
360
+ shouldShowSlashCommands() {
361
+ if (!this.withSlashCommands || this.contextItemsMenuIsOpen) return false;
362
+ const startsWithSlash = this.caseInsensitivePrompt.startsWith('/');
363
+ const startsWithSlashCommand = this.slashCommands.some((c) =>
364
+ this.caseInsensitivePrompt.startsWith(c.name)
365
+ );
366
+ return startsWithSlash && this.filteredSlashCommands.length && !startsWithSlashCommand;
367
+ },
368
+ shouldShowContextItemSelectionMenu() {
369
+ if (!this.hasContextItemSelectionMenu) {
370
+ return false;
371
+ }
372
+
373
+ const isSlash = this.caseInsensitivePrompt === '/';
374
+ if (!this.caseInsensitivePrompt || isSlash) {
375
+ // if user has removed entire command (or whole command except for '/') we should close context item menu and allow slash command menu to show again
376
+ return false;
377
+ }
378
+
379
+ return CHAT_INCLUDE_MESSAGE.startsWith(this.caseInsensitivePrompt);
380
+ },
381
+ inputPlaceholder() {
382
+ if (this.chatPromptPlaceholder) {
383
+ return this.chatPromptPlaceholder;
384
+ }
385
+
386
+ return this.withSlashCommands
387
+ ? i18n.CHAT_PROMPT_PLACEHOLDER_WITH_COMMANDS
388
+ : i18n.CHAT_PROMPT_PLACEHOLDER_DEFAULT;
389
+ },
390
+ hasContextItemSelectionMenu() {
391
+ return Boolean(this.contextItemMenuRef);
392
+ },
393
+ activeThread() {
394
+ return this.activeThreadId
395
+ ? this.threadList.find((thread) => thread.id === this.activeThreadId)
396
+ : null;
397
+ },
398
+ activeThreadTitle() {
399
+ return this.activeThread?.title;
400
+ },
401
+ activeThreadTitleForView() {
402
+ return (this.currentView === VIEW_TYPES.CHAT && this.activeThreadTitle) || '';
403
+ },
404
+ },
405
+ watch: {
406
+ multiThreadedView(newView) {
407
+ this.currentView = newView;
408
+ },
409
+ isLoading(newVal) {
410
+ if (!newVal && !this.isStreaming) {
411
+ this.displaySubmitButton = true; // Re-enable submit button when loading stops
412
+ }
413
+ },
414
+ isStreaming(newVal) {
415
+ if (!newVal && !this.isLoading) {
416
+ this.displaySubmitButton = true; // Re-enable submit button when streaming stops
417
+ }
418
+ },
419
+ lastMessage(newMessage) {
420
+ if (this.scrolledToBottom || newMessage?.role.toLowerCase() === MESSAGE_MODEL_ROLES.user) {
421
+ // only scroll to bottom on new message if the user hasn't explicitly scrolled up to view an earlier message
422
+ // or if the user has just submitted a new message
423
+ this.scrollToBottom();
424
+ }
425
+ },
426
+ shouldShowSlashCommands(shouldShow) {
427
+ if (shouldShow) {
428
+ this.onShowSlashCommands();
429
+ }
430
+ },
431
+ },
432
+ created() {
433
+ this.handleScrollingThrottled = throttle(this.handleScrolling, 200); // Assume a 200ms throttle for example
434
+ },
435
+ mounted() {
436
+ this.scrollToBottom();
437
+ },
438
+
439
+ methods: {
440
+ onGoBack() {
441
+ this.$emit('back-to-list');
442
+ },
443
+ onGoBackToChat() {
444
+ this.$emit('back-to-chat');
445
+ },
446
+ onNewChat() {
447
+ this.$emit('new-chat');
448
+
449
+ this.$nextTick(() => {
450
+ this.focusChatInput();
451
+ });
452
+ },
453
+ compositionEnd() {
454
+ this.compositionJustEnded = true;
455
+ },
456
+ hideChat() {
457
+ /**
458
+ * Emitted when clicking the cross in the title and the chat gets closed.
459
+ */
460
+ this.$emit('chat-hidden');
461
+ },
462
+ cancelPrompt() {
463
+ /**
464
+ * Emitted when user clicks the stop button in the textarea
465
+ */
466
+
467
+ this.displaySubmitButton = true;
468
+ this.$emit('chat-cancel');
469
+ this.setPromptAndFocus();
470
+ },
471
+ sendChatPrompt() {
472
+ if (!this.displaySubmitButton || this.contextItemsMenuIsOpen) {
473
+ return;
474
+ }
475
+ if (this.prompt) {
476
+ if (
477
+ this.caseInsensitivePrompt.startsWith(CHAT_INCLUDE_MESSAGE) &&
478
+ this.hasContextItemSelectionMenu
479
+ ) {
480
+ this.contextItemsMenuIsOpen = true;
481
+ return;
482
+ }
483
+
484
+ if (
485
+ ![CHAT_RESET_MESSAGE, CHAT_CLEAR_MESSAGE, CHAT_NEW_MESSAGE].includes(
486
+ this.caseInsensitivePrompt
487
+ )
488
+ ) {
489
+ this.displaySubmitButton = false;
490
+ }
491
+
492
+ /**
493
+ * Emitted when a new user prompt should be sent out.
494
+ *
495
+ * @param {String} prompt The user prompt to send.
496
+ */
497
+ this.$emit('send-chat-prompt', this.prompt.trim());
498
+
499
+ this.setPromptAndFocus();
500
+ }
501
+ },
502
+ sendPredefinedPrompt(prompt) {
503
+ this.contextItemsMenuIsOpen = false;
504
+ this.prompt = prompt;
505
+ this.sendChatPrompt();
506
+ },
507
+ handleScrolling(event) {
508
+ const { scrollTop, offsetHeight, scrollHeight } = event.target;
509
+ this.scrolledToBottom = scrollTop + offsetHeight >= scrollHeight;
510
+ },
511
+ async scrollToBottom() {
512
+ await this.$nextTick();
513
+
514
+ this.$refs.anchor?.scrollIntoView?.();
515
+ },
516
+ focusChatInput() {
517
+ // This method is also called directly by consumers of this component
518
+ // https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/blob/dae2d4669ab4da327921492a2962beae8a05c290/webviews/vue2/gitlab_duo_chat/src/App.vue#L109
519
+ this.$refs.prompt?.$el?.querySelector?.('textarea')?.focus();
520
+ },
521
+ onTrackFeedback(event) {
522
+ /**
523
+ * Notify listeners about the feedback form submission on a response message.
524
+ * @param {*} event An event, containing the feedback choices and the extended feedback text.
525
+ */
526
+ this.$emit('track-feedback', event);
527
+ },
528
+ onShowSlashCommands() {
529
+ /**
530
+ * Emitted when user opens the slash commands menu
531
+ */
532
+ this.$emit('chat-slash');
533
+ },
534
+ sendChatPromptOnEnter(e) {
535
+ const { metaKey, ctrlKey, altKey, shiftKey, isComposing } = e;
536
+ const isModifierKey = metaKey || ctrlKey || altKey || shiftKey;
537
+
538
+ return !(isModifierKey || isComposing || this.compositionJustEnded);
539
+ },
540
+ onInputKeyup(e) {
541
+ const { key } = e;
542
+
543
+ if (this.contextItemsMenuIsOpen) {
544
+ if (!this.shouldShowContextItemSelectionMenu) {
545
+ this.contextItemsMenuIsOpen = false;
546
+ }
547
+ this.contextItemMenuRef?.handleKeyUp(e);
548
+ return;
549
+ }
550
+ if (this.caseInsensitivePrompt === CHAT_INCLUDE_MESSAGE) {
551
+ this.contextItemsMenuIsOpen = true;
552
+ return;
553
+ }
554
+
555
+ if (this.shouldShowSlashCommands) {
556
+ e.preventDefault();
557
+
558
+ if (key === 'Enter') {
559
+ this.selectSlashCommand(this.activeCommandIndex);
560
+ } else if (key === 'ArrowUp') {
561
+ this.prevCommand();
562
+ } else if (key === 'ArrowDown') {
563
+ this.nextCommand();
564
+ } else {
565
+ this.activeCommandIndex = 0;
566
+ }
567
+ } else if (key === 'Enter' && this.sendChatPromptOnEnter(e)) {
568
+ e.preventDefault();
569
+
570
+ this.sendChatPrompt();
571
+ }
572
+
573
+ this.compositionJustEnded = false;
574
+ },
575
+ prevCommand() {
576
+ this.activeCommandIndex -= 1;
577
+ this.wrapCommandIndex();
578
+ },
579
+ nextCommand() {
580
+ this.activeCommandIndex += 1;
581
+ this.wrapCommandIndex();
582
+ },
583
+ wrapCommandIndex() {
584
+ if (this.activeCommandIndex < 0) {
585
+ this.activeCommandIndex = this.filteredSlashCommands.length - 1;
586
+ } else if (this.activeCommandIndex >= this.filteredSlashCommands.length) {
587
+ this.activeCommandIndex = 0;
588
+ }
589
+ },
590
+ async setPromptAndFocus(prompt = '') {
591
+ this.prompt = prompt;
592
+ await this.$nextTick();
593
+ this.focusChatInput();
594
+ },
595
+ selectSlashCommand(index) {
596
+ const command = this.filteredSlashCommands[index];
597
+ if (command.shouldSubmit) {
598
+ this.prompt = command.name;
599
+ this.sendChatPrompt();
600
+ } else {
601
+ this.setPromptAndFocus(`${command.name} `);
602
+
603
+ if (command.name === CHAT_INCLUDE_MESSAGE && this.hasContextItemSelectionMenu) {
604
+ this.contextItemsMenuIsOpen = true;
605
+ }
606
+ }
607
+ },
608
+ onInsertCodeSnippet(e) {
609
+ /**
610
+ * Emit insert-code-snippet event that clients can use to interact with a suggested code.
611
+ * @param {*} event An event containing code string in the "detail.code" field.
612
+ */
613
+ this.$emit('insert-code-snippet', e);
614
+ },
615
+ onCopyCodeSnippet(e) {
616
+ /**
617
+ * Emit copy-code-snippet event that clients can use to interact with a suggested code.
618
+ * @param {*} event An event containing code string in the "detail.code" field.
619
+ */
620
+ this.$emit('copy-code-snippet', e);
621
+ },
622
+ onCopyMessage(e) {
623
+ /**
624
+ * Emit copy-message event that clients can use to copy chat message content.
625
+ * @param {*} event An event containing code string in the "detail.message" field.
626
+ */
627
+ this.$emit('copy-message', e);
628
+ },
629
+ onGetContextItemContent(event) {
630
+ /**
631
+ * Emit get-context-item-content event that tells clients to load the full file content for a selected context item.
632
+ * The fully hydrated context item should be updated in the chat message context item.
633
+ * @param {*} event An event containing the message ID and context item to hydrate
634
+ */
635
+ this.$emit('get-context-item-content', event);
636
+ },
637
+ closeContextItemsMenuOpen() {
638
+ this.contextItemsMenuIsOpen = false;
639
+ this.setPromptAndFocus();
640
+ },
641
+ setContextItemsMenuRef(ref) {
642
+ this.contextItemMenuRef = ref;
643
+ },
644
+ onSelectThread(thread) {
645
+ /**
646
+ * Emitted when a thread is selected from the history.
647
+ * @param {Object} thread The selected thread object
648
+ */
649
+ this.$emit('thread-selected', thread);
650
+ },
651
+ onDeleteThread(threadId) {
652
+ /**
653
+ * Emitted when a thread is deleted from the history.
654
+ * @param {String} threadId The ID of the thread to delete
655
+ */
656
+ this.$emit('delete-thread', threadId);
657
+ },
658
+ onOpenFilePath(filePath) {
659
+ /**
660
+ * Emitted when a file path link is clicked in a chat message.
661
+ * @param {String} filePath The file path to open
662
+ */
663
+ this.$emit('open-file-path', filePath);
664
+ },
665
+ handleUndo(event) {
666
+ event.preventDefault();
667
+ document.execCommand('undo');
668
+ },
669
+ handleRedo(event) {
670
+ event.preventDefault();
671
+ document.execCommand('redo');
672
+ },
673
+ remainingCharacterCountMessage(count) {
674
+ return `${count} characters remaining`;
675
+ },
676
+ overLimitCharacterCountMessage(count) {
677
+ return `${Math.abs(count)} characters over limit`;
678
+ },
679
+ },
680
+ i18n,
681
+ };
682
+ </script>
683
+ <template>
684
+ <div
685
+ id="chat-component"
686
+ class="markdown-code-block duo-chat gl-bottom-0 gl-flex gl-max-h-full gl-flex-col"
687
+ role="complementary"
688
+ data-testid="chat-component"
689
+ >
690
+ <web-duo-chat-header
691
+ v-if="showHeader"
692
+ ref="header"
693
+ :active-thread-id="activeThreadId"
694
+ :title="isMultithreaded && currentView === 'list' ? $options.i18n.CHAT_HISTORY_TITLE : title"
695
+ :subtitle="activeThreadTitleForView"
696
+ :is-multithreaded="isMultithreaded"
697
+ :current-view="currentView"
698
+ :should-render-resizable="shouldRenderResizable"
699
+ :badge-type="isMultithreaded ? null : badgeType"
700
+ @go-back="onGoBack"
701
+ @go-back-to-chat="onGoBackToChat"
702
+ @new-chat="onNewChat"
703
+ @close="hideChat"
704
+ >
705
+ <template #subheader>
706
+ <slot name="subheader"></slot>
707
+ </template>
708
+ </web-duo-chat-header>
709
+
710
+ <div
711
+ class="gl-flex gl-flex-1 gl-flex-grow gl-flex-col gl-overflow-y-auto gl-overscroll-contain gl-bg-inherit"
712
+ data-testid="chat-history"
713
+ @scroll="handleScrollingThrottled"
714
+ >
715
+ <duo-chat-threads
716
+ v-if="shouldShowThreadList"
717
+ :threads="threadList"
718
+ :preferred-locale="preferredLocale"
719
+ @new-chat="onNewChat"
720
+ @select-thread="onSelectThread"
721
+ @delete-thread="onDeleteThread"
722
+ @close="hideChat"
723
+ />
724
+ <transition-group
725
+ v-else
726
+ mode="out-in"
727
+ tag="section"
728
+ name="message"
729
+ class="duo-chat-history gl-mt-auto gl-p-5"
730
+ >
731
+ <duo-chat-conversation
732
+ v-for="(conversation, index) in conversations"
733
+ :key="`conversation-${index}`"
734
+ :enable-code-insertion="enableCodeInsertion"
735
+ :messages="conversation"
736
+ :canceled-request-ids="canceledRequestIds"
737
+ :show-delimiter="index > 0"
738
+ :trusted-urls="trustedUrls"
739
+ @track-feedback="onTrackFeedback"
740
+ @insert-code-snippet="onInsertCodeSnippet"
741
+ @copy-code-snippet="onCopyCodeSnippet"
742
+ @copy-message="onCopyMessage"
743
+ @get-context-item-content="onGetContextItemContent"
744
+ @open-file-path="onOpenFilePath"
745
+ />
746
+ <template v-if="!hasMessages && !isLoading">
747
+ <div
748
+ key="empty-state-message"
749
+ class="duo-chat-message gl-rounded-bl-none gl-p-4 gl-leading-20 gl-text-gray-900 gl-break-anywhere"
750
+ data-testid="gl-duo-chat-empty-state"
751
+ >
752
+ <p v-if="emptyStateTitle" data-testid="gl-duo-chat-empty-state-title" class="gl-m-0">
753
+ {{ emptyStateTitle }}
754
+ </p>
755
+ <duo-chat-predefined-prompts
756
+ key="predefined-prompts"
757
+ :prompts="predefinedPrompts"
758
+ @click="sendPredefinedPrompt"
759
+ />
760
+ </div>
761
+ </template>
762
+ <duo-chat-loader v-if="isLoading" key="loader" :tool-name="toolName" />
763
+ <div key="anchor" ref="anchor" class="scroll-anchor"></div>
764
+ </transition-group>
765
+ </div>
766
+ <footer
767
+ v-if="isChatAvailable && !shouldShowThreadList"
768
+ data-testid="chat-footer"
769
+ class="duo-chat-drawer-footer gl-relative gl-z-2 gl-shrink-0 gl-border-0 gl-bg-default gl-pb-3"
770
+ :class="{ 'duo-chat-drawer-body-scrim-on-footer': !scrolledToBottom }"
771
+ >
772
+ <gl-form data-testid="chat-prompt-form" @submit.stop.prevent="sendChatPrompt">
773
+ <div class="gl-relative gl-max-w-full">
774
+ <!--
775
+ @slot For integrating `<gl-context-items-menu>` component if pinned-context should be available. The following scopedSlot properties are provided: `isOpen`, `onClose`, `setRef`, `focusPrompt`, which should be passed to the `<gl-context-items-menu>` component when rendering, e.g. `<template #context-items-menu="{ isOpen, onClose, setRef, focusPrompt }">` `<duo-chat-context-item-menu :ref="setRef" :open="isOpen" @close="onClose" @focus-prompt="focusPrompt" ...`
776
+ -->
777
+ <slot
778
+ name="context-items-menu"
779
+ :is-open="contextItemsMenuIsOpen"
780
+ :on-close="closeContextItemsMenuOpen"
781
+ :set-ref="setContextItemsMenuRef"
782
+ :focus-prompt="focusChatInput"
783
+ ></slot>
784
+ </div>
785
+
786
+ <div
787
+ class="duo-chat-input gl-min-h-8 gl-max-w-full gl-grow gl-flex-col gl-rounded-bl-[12px] gl-rounded-br-[18px] gl-rounded-tl-[12px] gl-rounded-tr-[12px] gl-align-top"
788
+ >
789
+ <div
790
+ class="gl-flex gl-justify-between gl-border-0 gl-border-b-1 gl-border-solid gl-border-strong gl-px-4 gl-py-4"
791
+ >
792
+ <div>{{ $options.i18n.CHAT_MODEL_PLACEHOLDER }}</div>
793
+ <div><slot name="agentic-switch"></slot></div>
794
+ </div>
795
+ <div class="gl-h-[40px] gl-grow" :data-value="prompt">
796
+ <gl-card
797
+ v-if="shouldShowSlashCommands"
798
+ ref="commands"
799
+ class="slash-commands !gl-absolute gl-w-full -gl-translate-y-full gl-list-none gl-pl-0 gl-shadow-md"
800
+ body-class="!gl-p-2"
801
+ >
802
+ <gl-dropdown-item
803
+ v-for="(command, index) in filteredSlashCommands"
804
+ :key="command.name"
805
+ :class="{ 'active-command': index === activeCommandIndex }"
806
+ @mouseenter.native="activeCommandIndex = index"
807
+ @click="selectSlashCommand(index)"
808
+ >
809
+ <span class="gl-flex gl-justify-between">
810
+ <span class="gl-block">{{ command.name }}</span>
811
+ <small class="gl-pl-3 gl-text-right gl-italic gl-text-subtle">{{
812
+ command.description
813
+ }}</small>
814
+ </span>
815
+ </gl-dropdown-item>
816
+ </gl-card>
817
+
818
+ <gl-form-textarea
819
+ ref="prompt"
820
+ v-model="prompt"
821
+ data-testid="chat-prompt-input"
822
+ :textarea-classes="[
823
+ '!gl-h-full',
824
+ '!gl-bg-transparent',
825
+ '!gl-py-4',
826
+ '!gl-shadow-none',
827
+ 'form-control',
828
+ 'gl-form-input',
829
+ 'gl-form-textarea',
830
+ { 'gl-truncate': !prompt },
831
+ ]"
832
+ :placeholder="inputPlaceholder"
833
+ :character-count-limit="maxPromptLength"
834
+ autofocus
835
+ @keydown.enter.exact.native.prevent
836
+ @keydown.ctrl.z.exact="handleUndo"
837
+ @keydown.meta.z.exact="handleUndo"
838
+ @keydown.ctrl.shift.z="handleRedo"
839
+ @keydown.meta.shift.z="handleRedo"
840
+ @keydown.ctrl.y="handleRedo"
841
+ @keydown.meta.y="handleRedo"
842
+ @keyup.native="onInputKeyup"
843
+ @compositionend="compositionEnd"
844
+ >
845
+ <template #remaining-character-count-text="{ count }">
846
+ <span
847
+ v-if="count <= promptLengthWarningCount"
848
+ class="gl-absolute gl-bottom-[-25px] gl-right-px gl-pr-3"
849
+ >
850
+ {{ remainingCharacterCountMessage(count) }}
851
+ </span>
852
+ </template>
853
+ <template #character-count-over-limit-text="{ count }">
854
+ <span class="gl-absolute gl-bottom-[-25px] gl-right-px gl-pr-3">{{
855
+ overLimitCharacterCountMessage(count)
856
+ }}</span>
857
+ </template>
858
+ </gl-form-textarea>
859
+ </div>
860
+ <div class="gl-flex gl-justify-end gl-px-3 gl-pb-3">
861
+ <gl-button
862
+ v-if="displaySubmitButton"
863
+ icon="paper-airplane"
864
+ category="primary"
865
+ variant="confirm"
866
+ class="gl-bottom-2 gl-right-2 gl-ml-auto !gl-rounded-full"
867
+ type="submit"
868
+ data-testid="chat-prompt-submit-button"
869
+ :disabled="isPromptEmpty"
870
+ :aria-label="$options.i18n.CHAT_SUBMIT_LABEL"
871
+ />
872
+ <gl-button
873
+ v-else
874
+ icon="stop"
875
+ category="primary"
876
+ variant="default"
877
+ class="gl-bottom-2 gl-right-2 gl-ml-auto !gl-rounded-full"
878
+ data-testid="chat-prompt-cancel-button"
879
+ :aria-label="$options.i18n.CHAT_CANCEL_LABEL"
880
+ @click="cancelPrompt"
881
+ />
882
+ </div>
883
+ </div>
884
+ </gl-form>
885
+ <slot name="footer-controls"></slot>
886
+ <p class="gl-mb-0 gl-mt-3 gl-px-4 gl-text-sm gl-text-secondary">
887
+ {{ $options.i18n.CHAT_DISCLAMER }}
888
+ </p>
889
+ </footer>
890
+ </div>
891
+ </template>