-
Notifications
You must be signed in to change notification settings - Fork 28.9k
/
voiceChatActions.ts
1368 lines (1146 loc) · 50.7 KB
/
voiceChatActions.ts
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. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'vs/css!./media/voiceChatActions';
import { RunOnceScheduler, disposableTimeout, raceCancellation } from 'vs/base/common/async';
import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation';
import { Codicon } from 'vs/base/common/codicons';
import { Color } from 'vs/base/common/color';
import { Event } from 'vs/base/common/event';
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import { Disposable, DisposableStore, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { isNumber } from 'vs/base/common/types';
import { getCodeEditor } from 'vs/editor/browser/editorBrowser';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { localize, localize2 } from 'vs/nls';
import { Action2, IAction2Options, MenuId } from 'vs/platform/actions/common/actions';
import { CommandsRegistry, ICommandService } from 'vs/platform/commands/common/commands';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { Extensions, IConfigurationRegistry } from 'vs/platform/configuration/common/configurationRegistry';
import { ContextKeyExpr, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey';
import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { ProgressLocation } from 'vs/platform/progress/common/progress';
import { Registry } from 'vs/platform/registry/common/platform';
import { contrastBorder, focusBorder } from 'vs/platform/theme/common/colorRegistry';
import { spinningLoading, syncing } from 'vs/platform/theme/common/iconRegistry';
import { ColorScheme } from 'vs/platform/theme/common/theme';
import { registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { ActiveEditorContext } from 'vs/workbench/common/contextkeys';
import { IWorkbenchContribution } from 'vs/workbench/common/contributions';
import { ACTIVITY_BAR_BADGE_BACKGROUND } from 'vs/workbench/common/theme';
import { AccessibilityVoiceSettingId, SpeechTimeoutDefault, accessibilityConfigurationNodeBase } from 'vs/workbench/contrib/accessibility/browser/accessibilityConfiguration';
import { CHAT_CATEGORY } from 'vs/workbench/contrib/chat/browser/actions/chatActions';
import { IChatExecuteActionContext } from 'vs/workbench/contrib/chat/browser/actions/chatExecuteActions';
import { IChatWidget, IChatWidgetService, IQuickChatService, showChatView } from 'vs/workbench/contrib/chat/browser/chat';
import { ChatAgentLocation, IChatAgentService } from 'vs/workbench/contrib/chat/common/chatAgents';
import { CONTEXT_CHAT_REQUEST_IN_PROGRESS, CONTEXT_IN_CHAT_INPUT, CONTEXT_CHAT_ENABLED, CONTEXT_RESPONSE, CONTEXT_RESPONSE_FILTERED } from 'vs/workbench/contrib/chat/common/chatContextKeys';
import { KEYWORD_ACTIVIATION_SETTING_ID } from 'vs/workbench/contrib/chat/common/chatService';
import { isResponseVM } from 'vs/workbench/contrib/chat/common/chatViewModel';
import { IVoiceChatService, VoiceChatInProgress as GlobalVoiceChatInProgress } from 'vs/workbench/contrib/chat/common/voiceChatService';
import { IExtensionsWorkbenchService } from 'vs/workbench/contrib/extensions/common/extensions';
import { InlineChatController } from 'vs/workbench/contrib/inlineChat/browser/inlineChatController';
import { CTX_INLINE_CHAT_FOCUSED } from 'vs/workbench/contrib/inlineChat/common/inlineChat';
import { NOTEBOOK_EDITOR_FOCUSED } from 'vs/workbench/contrib/notebook/common/notebookContextKeys';
import { HasSpeechProvider, ISpeechService, KeywordRecognitionStatus, SpeechToTextInProgress, SpeechToTextStatus, TextToSpeechStatus, TextToSpeechInProgress as GlobalTextToSpeechInProgress } from 'vs/workbench/contrib/speech/common/speechService';
import { ITerminalService } from 'vs/workbench/contrib/terminal/browser/terminal';
import { TerminalChatContextKeys, TerminalChatController } from 'vs/workbench/contrib/terminal/browser/terminalContribExports';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IHostService } from 'vs/workbench/services/host/browser/host';
import { IWorkbenchLayoutService, Parts } from 'vs/workbench/services/layout/browser/layoutService';
import { IStatusbarEntry, IStatusbarEntryAccessor, IStatusbarService, StatusbarAlignment } from 'vs/workbench/services/statusbar/browser/statusbar';
import { IViewsService } from 'vs/workbench/services/views/common/viewsService';
import { IChatResponseModel } from 'vs/workbench/contrib/chat/common/chatModel';
import { IAccessibilityService } from 'vs/platform/accessibility/common/accessibility';
import { renderStringAsPlaintext } from 'vs/base/browser/markdownRenderer';
//#region Speech to Text
type VoiceChatSessionContext = 'view' | 'inline' | 'terminal' | 'quick' | 'editor';
const VoiceChatSessionContexts: VoiceChatSessionContext[] = ['view', 'inline', 'terminal', 'quick', 'editor'];
const TerminalChatExecute = MenuId.for('terminalChatInput'); // unfortunately, terminal decided to go with their own menu (https://github.com/microsoft/vscode/issues/208789)
// Global Context Keys (set on global context key service)
const CanVoiceChat = ContextKeyExpr.and(CONTEXT_CHAT_ENABLED, HasSpeechProvider);
const FocusInChatInput = ContextKeyExpr.or(CTX_INLINE_CHAT_FOCUSED, CONTEXT_IN_CHAT_INPUT);
const AnyChatRequestInProgress = ContextKeyExpr.or(CONTEXT_CHAT_REQUEST_IN_PROGRESS, TerminalChatContextKeys.requestActive);
// Scoped Context Keys (set on per-chat-context scoped context key service)
const ScopedVoiceChatGettingReady = new RawContextKey<boolean>('scopedVoiceChatGettingReady', false, { type: 'boolean', description: localize('scopedVoiceChatGettingReady', "True when getting ready for receiving voice input from the microphone for voice chat. This key is only defined scoped, per chat context.") });
const ScopedVoiceChatInProgress = new RawContextKey<VoiceChatSessionContext | undefined>('scopedVoiceChatInProgress', undefined, { type: 'string', description: localize('scopedVoiceChatInProgress', "Defined as a location where voice recording from microphone is in progress for voice chat. This key is only defined scoped, per chat context.") });
const AnyScopedVoiceChatInProgress = ContextKeyExpr.or(...VoiceChatSessionContexts.map(context => ScopedVoiceChatInProgress.isEqualTo(context)));
enum VoiceChatSessionState {
Stopped = 1,
GettingReady,
Started
}
interface IVoiceChatSessionController {
readonly onDidAcceptInput: Event<unknown>;
readonly onDidHideInput: Event<unknown>;
readonly context: VoiceChatSessionContext;
readonly scopedContextKeyService: IContextKeyService;
updateState(state: VoiceChatSessionState): void;
focusInput(): void;
acceptInput(): Promise<IChatResponseModel | undefined>;
updateInput(text: string): void;
getInput(): string;
setInputPlaceholder(text: string): void;
clearInputPlaceholder(): void;
}
class VoiceChatSessionControllerFactory {
static async create(accessor: ServicesAccessor, context: 'view' | 'inline' | 'quick' | 'focused'): Promise<IVoiceChatSessionController | undefined> {
const chatWidgetService = accessor.get(IChatWidgetService);
const quickChatService = accessor.get(IQuickChatService);
const layoutService = accessor.get(IWorkbenchLayoutService);
const editorService = accessor.get(IEditorService);
const terminalService = accessor.get(ITerminalService);
const viewsService = accessor.get(IViewsService);
switch (context) {
case 'focused': {
const controller = VoiceChatSessionControllerFactory.doCreateForFocusedChat(terminalService, chatWidgetService, layoutService);
return controller ?? VoiceChatSessionControllerFactory.create(accessor, 'view'); // fallback to 'view'
}
case 'view': {
const chatWidget = await showChatView(viewsService);
if (chatWidget) {
return VoiceChatSessionControllerFactory.doCreateForChatWidget('view', chatWidget);
}
break;
}
case 'inline': {
const activeCodeEditor = getCodeEditor(editorService.activeTextEditorControl);
if (activeCodeEditor) {
const inlineChat = InlineChatController.get(activeCodeEditor);
if (inlineChat) {
if (!inlineChat.joinCurrentRun()) {
inlineChat.run();
}
return VoiceChatSessionControllerFactory.doCreateForChatWidget('inline', inlineChat.chatWidget);
}
}
break;
}
case 'quick': {
quickChatService.open(); // this will populate focused chat widget in the chat widget service
return VoiceChatSessionControllerFactory.create(accessor, 'focused');
}
}
return undefined;
}
private static doCreateForFocusedChat(terminalService: ITerminalService, chatWidgetService: IChatWidgetService, layoutService: IWorkbenchLayoutService): IVoiceChatSessionController | undefined {
// 1.) probe terminal chat which is not part of chat widget service
const activeInstance = terminalService.activeInstance;
if (activeInstance) {
const terminalChat = TerminalChatController.activeChatWidget || TerminalChatController.get(activeInstance);
if (terminalChat?.hasFocus()) {
return VoiceChatSessionControllerFactory.doCreateForTerminalChat(terminalChat);
}
}
// 2.) otherwise go via chat widget service
const chatWidget = chatWidgetService.lastFocusedWidget;
if (chatWidget?.hasInputFocus()) {
// Figure out the context of the chat widget by asking
// layout service for the part that has focus. Unfortunately
// there is no better way because the widget does not know
// its location.
let context: VoiceChatSessionContext;
if (layoutService.hasFocus(Parts.EDITOR_PART)) {
context = chatWidget.location === ChatAgentLocation.Panel ? 'editor' : 'inline';
} else if (
[Parts.SIDEBAR_PART, Parts.PANEL_PART, Parts.AUXILIARYBAR_PART, Parts.TITLEBAR_PART, Parts.STATUSBAR_PART, Parts.BANNER_PART, Parts.ACTIVITYBAR_PART].some(part => layoutService.hasFocus(part))
) {
context = 'view';
} else {
context = 'quick';
}
return VoiceChatSessionControllerFactory.doCreateForChatWidget(context, chatWidget);
}
return undefined;
}
private static createChatContextKeyController(contextKeyService: IContextKeyService, context: VoiceChatSessionContext): (state: VoiceChatSessionState) => void {
const contextVoiceChatGettingReady = ScopedVoiceChatGettingReady.bindTo(contextKeyService);
const contextVoiceChatInProgress = ScopedVoiceChatInProgress.bindTo(contextKeyService);
return (state: VoiceChatSessionState) => {
switch (state) {
case VoiceChatSessionState.GettingReady:
contextVoiceChatGettingReady.set(true);
contextVoiceChatInProgress.reset();
break;
case VoiceChatSessionState.Started:
contextVoiceChatGettingReady.reset();
contextVoiceChatInProgress.set(context);
break;
case VoiceChatSessionState.Stopped:
contextVoiceChatGettingReady.reset();
contextVoiceChatInProgress.reset();
break;
}
};
}
private static doCreateForChatWidget(context: VoiceChatSessionContext, chatWidget: IChatWidget): IVoiceChatSessionController {
return {
context,
scopedContextKeyService: chatWidget.scopedContextKeyService,
onDidAcceptInput: chatWidget.onDidAcceptInput,
onDidHideInput: chatWidget.onDidHide,
focusInput: () => chatWidget.focusInput(),
acceptInput: () => chatWidget.acceptInput(),
updateInput: text => chatWidget.setInput(text),
getInput: () => chatWidget.getInput(),
setInputPlaceholder: text => chatWidget.setInputPlaceholder(text),
clearInputPlaceholder: () => chatWidget.resetInputPlaceholder(),
updateState: VoiceChatSessionControllerFactory.createChatContextKeyController(chatWidget.scopedContextKeyService, context)
};
}
private static doCreateForTerminalChat(terminalChat: TerminalChatController): IVoiceChatSessionController {
const context = 'terminal';
return {
context,
scopedContextKeyService: terminalChat.scopedContextKeyService,
onDidAcceptInput: terminalChat.onDidAcceptInput,
onDidHideInput: terminalChat.onDidHide,
focusInput: () => terminalChat.focus(),
acceptInput: () => terminalChat.acceptInput(),
updateInput: text => terminalChat.updateInput(text, false),
getInput: () => terminalChat.getInput(),
setInputPlaceholder: text => terminalChat.setPlaceholder(text),
clearInputPlaceholder: () => terminalChat.resetPlaceholder(),
updateState: VoiceChatSessionControllerFactory.createChatContextKeyController(terminalChat.scopedContextKeyService, context)
};
}
}
interface IVoiceChatSession {
setTimeoutDisabled(disabled: boolean): void;
accept(): void;
stop(): void;
}
interface IActiveVoiceChatSession extends IVoiceChatSession {
readonly id: number;
readonly controller: IVoiceChatSessionController;
readonly disposables: DisposableStore;
}
class VoiceChatSessions {
private static instance: VoiceChatSessions | undefined = undefined;
static getInstance(instantiationService: IInstantiationService): VoiceChatSessions {
if (!VoiceChatSessions.instance) {
VoiceChatSessions.instance = instantiationService.createInstance(VoiceChatSessions);
}
return VoiceChatSessions.instance;
}
private currentVoiceChatSession: IActiveVoiceChatSession | undefined = undefined;
private voiceChatSessionIds = 0;
constructor(
@IVoiceChatService private readonly voiceChatService: IVoiceChatService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IAccessibilityService private readonly accessibilityService: IAccessibilityService
) { }
async start(controller: IVoiceChatSessionController, context?: IChatExecuteActionContext): Promise<IVoiceChatSession> {
// Stop running text-to-speech or speech-to-text sessions in chats
this.stop();
ChatSynthesizerSessions.getInstance(this.instantiationService).stop();
let disableTimeout = false;
const sessionId = ++this.voiceChatSessionIds;
const session: IActiveVoiceChatSession = this.currentVoiceChatSession = {
id: sessionId,
controller,
disposables: new DisposableStore(),
setTimeoutDisabled: (disabled: boolean) => { disableTimeout = disabled; },
accept: () => this.accept(sessionId),
stop: () => this.stop(sessionId, controller.context)
};
const cts = new CancellationTokenSource();
session.disposables.add(toDisposable(() => cts.dispose(true)));
session.disposables.add(controller.onDidAcceptInput(() => this.stop(sessionId, controller.context)));
session.disposables.add(controller.onDidHideInput(() => this.stop(sessionId, controller.context)));
controller.focusInput();
controller.updateState(VoiceChatSessionState.GettingReady);
const voiceChatSession = await this.voiceChatService.createVoiceChatSession(cts.token, { usesAgents: controller.context !== 'inline', model: context?.widget?.viewModel?.model });
let inputValue = controller.getInput();
let voiceChatTimeout = this.configurationService.getValue<number>(AccessibilityVoiceSettingId.SpeechTimeout);
if (!isNumber(voiceChatTimeout) || voiceChatTimeout < 0) {
voiceChatTimeout = SpeechTimeoutDefault;
}
const acceptTranscriptionScheduler = session.disposables.add(new RunOnceScheduler(() => this.accept(sessionId), voiceChatTimeout));
session.disposables.add(voiceChatSession.onDidChange(({ status, text, waitingForInput }) => {
if (cts.token.isCancellationRequested) {
return;
}
switch (status) {
case SpeechToTextStatus.Started:
this.onDidSpeechToTextSessionStart(controller, session.disposables);
break;
case SpeechToTextStatus.Recognizing:
if (text) {
session.controller.updateInput(inputValue ? [inputValue, text].join(' ') : text);
if (voiceChatTimeout > 0 && context?.voice?.disableTimeout !== true && !disableTimeout) {
acceptTranscriptionScheduler.cancel();
}
}
break;
case SpeechToTextStatus.Recognized:
if (text) {
inputValue = inputValue ? [inputValue, text].join(' ') : text;
session.controller.updateInput(inputValue);
if (voiceChatTimeout > 0 && context?.voice?.disableTimeout !== true && !waitingForInput && !disableTimeout) {
acceptTranscriptionScheduler.schedule();
}
}
break;
case SpeechToTextStatus.Stopped:
this.stop(session.id, controller.context);
break;
}
}));
return session;
}
private onDidSpeechToTextSessionStart(controller: IVoiceChatSessionController, disposables: DisposableStore): void {
controller.updateState(VoiceChatSessionState.Started);
let dotCount = 0;
const updatePlaceholder = () => {
dotCount = (dotCount + 1) % 4;
controller.setInputPlaceholder(`${localize('listening', "I'm listening")}${'.'.repeat(dotCount)}`);
placeholderScheduler.schedule();
};
const placeholderScheduler = disposables.add(new RunOnceScheduler(updatePlaceholder, 500));
updatePlaceholder();
}
stop(voiceChatSessionId = this.voiceChatSessionIds, context?: VoiceChatSessionContext): void {
if (
!this.currentVoiceChatSession ||
this.voiceChatSessionIds !== voiceChatSessionId ||
(context && this.currentVoiceChatSession.controller.context !== context)
) {
return;
}
this.currentVoiceChatSession.controller.clearInputPlaceholder();
this.currentVoiceChatSession.controller.updateState(VoiceChatSessionState.Stopped);
this.currentVoiceChatSession.disposables.dispose();
this.currentVoiceChatSession = undefined;
}
async accept(voiceChatSessionId = this.voiceChatSessionIds): Promise<void> {
if (
!this.currentVoiceChatSession ||
this.voiceChatSessionIds !== voiceChatSessionId
) {
return;
}
const controller = this.currentVoiceChatSession.controller;
const response = await controller.acceptInput();
if (!response) {
return;
}
if (
!this.accessibilityService.isScreenReaderOptimized() && // do not auto synthesize when screen reader is active
this.configurationService.getValue<boolean>(AccessibilityVoiceSettingId.AutoSynthesize) === true
) {
let context: IVoiceChatSessionController | 'focused';
if (controller.context === 'inline') {
// TODO@bpasero this is ugly, but the lightweight inline chat turns into
// a different widget as soon as a response comes in, so we fallback to
// picking up from the focused chat widget
context = 'focused';
} else {
context = controller;
}
ChatSynthesizerSessions.getInstance(this.instantiationService).start(this.instantiationService.invokeFunction(accessor => ChatSynthesizerSessionController.create(accessor, context, response)));
}
}
}
export const VOICE_KEY_HOLD_THRESHOLD = 500;
async function startVoiceChatWithHoldMode(id: string, accessor: ServicesAccessor, target: 'view' | 'inline' | 'quick' | 'focused', context?: IChatExecuteActionContext): Promise<void> {
const instantiationService = accessor.get(IInstantiationService);
const keybindingService = accessor.get(IKeybindingService);
const holdMode = keybindingService.enableKeybindingHoldMode(id);
const controller = await VoiceChatSessionControllerFactory.create(accessor, target);
if (!controller) {
return;
}
const session = await VoiceChatSessions.getInstance(instantiationService).start(controller, context);
let acceptVoice = false;
const handle = disposableTimeout(() => {
acceptVoice = true;
session?.setTimeoutDisabled(true); // disable accept on timeout when hold mode runs for VOICE_KEY_HOLD_THRESHOLD
}, VOICE_KEY_HOLD_THRESHOLD);
await holdMode;
handle.dispose();
if (acceptVoice) {
session.accept();
}
}
class VoiceChatWithHoldModeAction extends Action2 {
constructor(desc: Readonly<IAction2Options>, private readonly target: 'view' | 'inline' | 'quick') {
super(desc);
}
run(accessor: ServicesAccessor, context?: IChatExecuteActionContext): Promise<void> {
return startVoiceChatWithHoldMode(this.desc.id, accessor, this.target, context);
}
}
export class VoiceChatInChatViewAction extends VoiceChatWithHoldModeAction {
static readonly ID = 'workbench.action.chat.voiceChatInChatView';
constructor() {
super({
id: VoiceChatInChatViewAction.ID,
title: localize2('workbench.action.chat.voiceChatInView.label', "Voice Chat in Chat View"),
category: CHAT_CATEGORY,
precondition: ContextKeyExpr.and(
CanVoiceChat,
CONTEXT_CHAT_REQUEST_IN_PROGRESS.negate() // disable when a chat request is in progress
),
f1: true
}, 'view');
}
}
export class HoldToVoiceChatInChatViewAction extends Action2 {
static readonly ID = 'workbench.action.chat.holdToVoiceChatInChatView';
constructor() {
super({
id: HoldToVoiceChatInChatViewAction.ID,
title: localize2('workbench.action.chat.holdToVoiceChatInChatView.label', "Hold to Voice Chat in Chat View"),
keybinding: {
weight: KeybindingWeight.WorkbenchContrib,
when: ContextKeyExpr.and(
CanVoiceChat,
CONTEXT_CHAT_REQUEST_IN_PROGRESS.negate(), // disable when a chat request is in progress
FocusInChatInput?.negate(), // when already in chat input, disable this action and prefer to start voice chat directly
EditorContextKeys.focus.negate(), // do not steal the inline-chat keybinding
NOTEBOOK_EDITOR_FOCUSED.negate() // do not steal the notebook keybinding
),
primary: KeyMod.CtrlCmd | KeyCode.KeyI
}
});
}
override async run(accessor: ServicesAccessor, context?: IChatExecuteActionContext): Promise<void> {
// The intent of this action is to provide 2 modes to align with what `Ctrlcmd+I` in inline chat:
// - if the user press and holds, we start voice chat in the chat view
// - if the user press and releases quickly enough, we just open the chat view without voice chat
const instantiationService = accessor.get(IInstantiationService);
const keybindingService = accessor.get(IKeybindingService);
const viewsService = accessor.get(IViewsService);
const holdMode = keybindingService.enableKeybindingHoldMode(HoldToVoiceChatInChatViewAction.ID);
let session: IVoiceChatSession | undefined;
const handle = disposableTimeout(async () => {
const controller = await VoiceChatSessionControllerFactory.create(accessor, 'view');
if (controller) {
session = await VoiceChatSessions.getInstance(instantiationService).start(controller, context);
session.setTimeoutDisabled(true);
}
}, VOICE_KEY_HOLD_THRESHOLD);
(await showChatView(viewsService))?.focusInput();
await holdMode;
handle.dispose();
if (session) {
session.accept();
}
}
}
export class InlineVoiceChatAction extends VoiceChatWithHoldModeAction {
static readonly ID = 'workbench.action.chat.inlineVoiceChat';
constructor() {
super({
id: InlineVoiceChatAction.ID,
title: localize2('workbench.action.chat.inlineVoiceChat', "Inline Voice Chat"),
category: CHAT_CATEGORY,
precondition: ContextKeyExpr.and(
CanVoiceChat,
ActiveEditorContext,
CONTEXT_CHAT_REQUEST_IN_PROGRESS.negate() // disable when a chat request is in progress
),
f1: true
}, 'inline');
}
}
export class QuickVoiceChatAction extends VoiceChatWithHoldModeAction {
static readonly ID = 'workbench.action.chat.quickVoiceChat';
constructor() {
super({
id: QuickVoiceChatAction.ID,
title: localize2('workbench.action.chat.quickVoiceChat.label', "Quick Voice Chat"),
category: CHAT_CATEGORY,
precondition: ContextKeyExpr.and(
CanVoiceChat,
CONTEXT_CHAT_REQUEST_IN_PROGRESS.negate() // disable when a chat request is in progress
),
f1: true
}, 'quick');
}
}
export class StartVoiceChatAction extends Action2 {
static readonly ID = 'workbench.action.chat.startVoiceChat';
constructor() {
super({
id: StartVoiceChatAction.ID,
title: localize2('workbench.action.chat.startVoiceChat.label', "Start Voice Chat"),
category: CHAT_CATEGORY,
f1: true,
keybinding: {
weight: KeybindingWeight.WorkbenchContrib,
when: ContextKeyExpr.and(
FocusInChatInput, // scope this action to chat input fields only
EditorContextKeys.focus.negate(), // do not steal the editor inline-chat keybinding
NOTEBOOK_EDITOR_FOCUSED.negate() // do not steal the notebook inline-chat keybinding
),
primary: KeyMod.CtrlCmd | KeyCode.KeyI
},
icon: Codicon.mic,
precondition: ContextKeyExpr.and(
CanVoiceChat,
ScopedVoiceChatGettingReady.negate(), // disable when voice chat is getting ready
AnyChatRequestInProgress?.negate(), // disable when any chat request is in progress
SpeechToTextInProgress.negate() // disable when speech to text is in progress
),
menu: [{
id: MenuId.ChatExecute,
when: ContextKeyExpr.and(
HasSpeechProvider,
ScopedChatSynthesisInProgress.negate(), // hide when text to speech is in progress
AnyScopedVoiceChatInProgress?.negate(), // hide when voice chat is in progress
),
group: 'navigation',
order: -1
}, {
id: TerminalChatExecute,
when: ContextKeyExpr.and(
HasSpeechProvider,
ScopedChatSynthesisInProgress.negate(), // hide when text to speech is in progress
AnyScopedVoiceChatInProgress?.negate(), // hide when voice chat is in progress
),
group: 'navigation',
order: -1
}]
});
}
async run(accessor: ServicesAccessor, context?: IChatExecuteActionContext): Promise<void> {
const widget = context?.widget;
if (widget) {
// if we already get a context when the action is executed
// from a toolbar within the chat widget, then make sure
// to move focus into the input field so that the controller
// is properly retrieved
widget.focusInput();
}
return startVoiceChatWithHoldMode(this.desc.id, accessor, 'focused', context);
}
}
export class StopListeningAction extends Action2 {
static readonly ID = 'workbench.action.chat.stopListening';
constructor() {
super({
id: StopListeningAction.ID,
title: localize2('workbench.action.chat.stopListening.label', "Stop Listening"),
category: CHAT_CATEGORY,
f1: true,
keybinding: {
weight: KeybindingWeight.WorkbenchContrib + 100,
primary: KeyCode.Escape,
when: AnyScopedVoiceChatInProgress
},
icon: spinningLoading,
precondition: GlobalVoiceChatInProgress, // need global context here because of `f1: true`
menu: [{
id: MenuId.ChatExecute,
when: AnyScopedVoiceChatInProgress,
group: 'navigation',
order: -1
}, {
id: TerminalChatExecute,
when: AnyScopedVoiceChatInProgress,
group: 'navigation',
order: -1
}]
});
}
async run(accessor: ServicesAccessor): Promise<void> {
VoiceChatSessions.getInstance(accessor.get(IInstantiationService)).stop();
}
}
export class StopListeningAndSubmitAction extends Action2 {
static readonly ID = 'workbench.action.chat.stopListeningAndSubmit';
constructor() {
super({
id: StopListeningAndSubmitAction.ID,
title: localize2('workbench.action.chat.stopListeningAndSubmit.label', "Stop Listening and Submit"),
category: CHAT_CATEGORY,
f1: true,
keybinding: {
weight: KeybindingWeight.WorkbenchContrib,
when: ContextKeyExpr.and(
FocusInChatInput,
AnyScopedVoiceChatInProgress
),
primary: KeyMod.CtrlCmd | KeyCode.KeyI
},
precondition: GlobalVoiceChatInProgress // need global context here because of `f1: true`
});
}
run(accessor: ServicesAccessor): void {
VoiceChatSessions.getInstance(accessor.get(IInstantiationService)).accept();
}
}
//#endregion
//#region Text to Speech
const ScopedChatSynthesisInProgress = new RawContextKey<boolean>('scopedChatSynthesisInProgress', false, { type: 'boolean', description: localize('scopedChatSynthesisInProgress', "Defined as a location where voice recording from microphone is in progress for voice chat. This key is only defined scoped, per chat context.") });
interface IChatSynthesizerSessionController {
readonly onDidHideChat: Event<unknown>;
readonly contextKeyService: IContextKeyService;
readonly response: IChatResponseModel;
}
class ChatSynthesizerSessionController {
static create(accessor: ServicesAccessor, context: IVoiceChatSessionController | 'focused', response: IChatResponseModel): IChatSynthesizerSessionController {
if (context === 'focused') {
return ChatSynthesizerSessionController.doCreateForFocusedChat(accessor, response);
} else {
return {
onDidHideChat: context.onDidHideInput,
contextKeyService: context.scopedContextKeyService,
response
};
}
}
private static doCreateForFocusedChat(accessor: ServicesAccessor, response: IChatResponseModel): IChatSynthesizerSessionController {
const chatWidgetService = accessor.get(IChatWidgetService);
const contextKeyService = accessor.get(IContextKeyService);
const terminalService = accessor.get(ITerminalService);
// 1.) probe terminal chat which is not part of chat widget service
const activeInstance = terminalService.activeInstance;
if (activeInstance) {
const terminalChat = TerminalChatController.activeChatWidget || TerminalChatController.get(activeInstance);
if (terminalChat?.hasFocus()) {
return {
onDidHideChat: terminalChat.onDidHide,
contextKeyService: terminalChat.scopedContextKeyService,
response
};
}
}
// 2.) otherwise go via chat widget service
let chatWidget = chatWidgetService.getWidgetBySessionId(response.session.sessionId);
if (chatWidget?.location === ChatAgentLocation.Editor) {
// TODO@bpasero workaround for https://github.com/microsoft/vscode/issues/212785
chatWidget = chatWidgetService.lastFocusedWidget;
}
return {
onDidHideChat: chatWidget?.onDidHide ?? Event.None,
contextKeyService: chatWidget?.scopedContextKeyService ?? contextKeyService,
response
};
}
}
class ChatSynthesizerSessions {
private static instance: ChatSynthesizerSessions | undefined = undefined;
static getInstance(instantiationService: IInstantiationService): ChatSynthesizerSessions {
if (!ChatSynthesizerSessions.instance) {
ChatSynthesizerSessions.instance = instantiationService.createInstance(ChatSynthesizerSessions);
}
return ChatSynthesizerSessions.instance;
}
private activeSession: CancellationTokenSource | undefined = undefined;
constructor(
@ISpeechService private readonly speechService: ISpeechService,
@IInstantiationService private readonly instantiationService: IInstantiationService
) { }
async start(controller: IChatSynthesizerSessionController): Promise<void> {
// Stop running text-to-speech or speech-to-text sessions in chats
this.stop();
VoiceChatSessions.getInstance(this.instantiationService).stop();
const activeSession = this.activeSession = new CancellationTokenSource();
const disposables = new DisposableStore();
activeSession.token.onCancellationRequested(() => disposables.dispose());
const session = await this.speechService.createTextToSpeechSession(activeSession.token, 'chat');
if (activeSession.token.isCancellationRequested) {
return;
}
disposables.add(controller.onDidHideChat(() => this.stop()));
const scopedChatToSpeechInProgress = ScopedChatSynthesisInProgress.bindTo(controller.contextKeyService);
disposables.add(toDisposable(() => scopedChatToSpeechInProgress.reset()));
disposables.add(session.onDidChange(e => {
switch (e.status) {
case TextToSpeechStatus.Started:
scopedChatToSpeechInProgress.set(true);
break;
case TextToSpeechStatus.Stopped:
scopedChatToSpeechInProgress.reset();
break;
}
}));
for await (const chunk of this.nextChatResponseChunk(controller.response, activeSession.token)) {
if (activeSession.token.isCancellationRequested) {
return;
}
await raceCancellation(session.synthesize(chunk), activeSession.token);
}
}
private async *nextChatResponseChunk(response: IChatResponseModel, token: CancellationToken): AsyncIterable<string> {
let totalOffset = 0;
let complete = false;
do {
const responseLength = response.response.asString().length;
const { chunk, offset } = this.parseNextChatResponseChunk(response, totalOffset);
totalOffset = offset;
complete = response.isComplete;
if (chunk) {
yield chunk;
}
if (token.isCancellationRequested) {
return;
}
if (!complete && responseLength === response.response.asString().length) {
await raceCancellation(Event.toPromise(response.onDidChange), token); // wait for the response to change
}
} while (!token.isCancellationRequested && !complete);
}
private parseNextChatResponseChunk(response: IChatResponseModel, offset: number): { readonly chunk: string | undefined; readonly offset: number } {
let chunk: string | undefined = undefined;
const text = response.response.asString();
if (response.isComplete) {
chunk = text.substring(offset);
offset = text.length + 1;
} else {
const res = parseNextChatResponseChunk(text, offset);
chunk = res.chunk;
offset = res.offset;
}
return {
chunk: chunk ? renderStringAsPlaintext({ value: chunk }) : chunk, // convert markdown to plain text
offset
};
}
stop(): void {
this.activeSession?.dispose(true);
this.activeSession = undefined;
}
}
const sentenceDelimiter = ['.', '!', '?', ':'];
const lineDelimiter = '\n';
const wordDelimiter = ' ';
export function parseNextChatResponseChunk(text: string, offset: number): { readonly chunk: string | undefined; readonly offset: number } {
let chunk: string | undefined = undefined;
for (let i = text.length - 1; i >= offset; i--) { // going from end to start to produce largest chunks
const cur = text[i];
const next = text[i + 1];
if (
sentenceDelimiter.includes(cur) && next === wordDelimiter || // end of sentence
lineDelimiter === cur // end of line
) {
chunk = text.substring(offset, i + 1).trim();
offset = i + 1;
break;
}
}
return { chunk, offset };
}
export class ReadChatResponseAloud extends Action2 {
constructor() {
super({
id: 'workbench.action.chat.readChatResponseAloud',
title: localize2('workbench.action.chat.readChatResponseAloud', "Read Aloud"),
icon: Codicon.unmute,
precondition: CanVoiceChat,
menu: {
id: MenuId.ChatMessageTitle,
when: ContextKeyExpr.and(
CanVoiceChat,
CONTEXT_RESPONSE, // only for responses
ScopedChatSynthesisInProgress.negate(), // but not when already in progress
CONTEXT_RESPONSE_FILTERED.negate() // and not when response is filtered
),
group: 'navigation'
}
});
}
run(accessor: ServicesAccessor, ...args: any[]) {
const instantiationService = accessor.get(IInstantiationService);
const response = args[0];
if (!isResponseVM(response)) {
return;
}
const controller = ChatSynthesizerSessionController.create(accessor, 'focused', response.model);
ChatSynthesizerSessions.getInstance(instantiationService).start(controller);
}
}
export class StopReadAloud extends Action2 {
static readonly ID = 'workbench.action.speech.stopReadAloud';
constructor() {
super({
id: StopReadAloud.ID,
icon: syncing,
title: localize2('workbench.action.speech.stopReadAloud', "Stop Reading Aloud"),
f1: true,
category: CHAT_CATEGORY,
precondition: GlobalTextToSpeechInProgress, // need global context here because of `f1: true`
keybinding: {
weight: KeybindingWeight.WorkbenchContrib + 100,
primary: KeyCode.Escape,
when: ScopedChatSynthesisInProgress
},
menu: [
{
id: MenuId.ChatExecute,
when: ScopedChatSynthesisInProgress,
group: 'navigation',
order: -1
},
{
id: TerminalChatExecute,
when: ScopedChatSynthesisInProgress,
group: 'navigation',
order: -1
}
]
});
}
async run(accessor: ServicesAccessor) {
ChatSynthesizerSessions.getInstance(accessor.get(IInstantiationService)).stop();
}
}
export class StopReadChatItemAloud extends Action2 {
static readonly ID = 'workbench.action.chat.stopReadChatItemAloud';
constructor() {
super({
id: StopReadChatItemAloud.ID,
icon: Codicon.mute,
title: localize2('workbench.action.chat.stopReadChatItemAloud', "Stop Reading Aloud"),
precondition: ScopedChatSynthesisInProgress,
keybinding: {
weight: KeybindingWeight.WorkbenchContrib + 100,
primary: KeyCode.Escape,
},
menu: [
{
id: MenuId.ChatMessageTitle,
when: ContextKeyExpr.and(
ScopedChatSynthesisInProgress, // only when in progress
CONTEXT_RESPONSE, // only for responses
CONTEXT_RESPONSE_FILTERED.negate() // but not when response is filtered
),
group: 'navigation'
}
]
});
}
async run(accessor: ServicesAccessor, ...args: any[]) {
ChatSynthesizerSessions.getInstance(accessor.get(IInstantiationService)).stop();
}
}
//#endregion
//#region Keyword Recognition
function supportsKeywordActivation(configurationService: IConfigurationService, speechService: ISpeechService, chatAgentService: IChatAgentService): boolean {
if (!speechService.hasSpeechProvider || !chatAgentService.getDefaultAgent(ChatAgentLocation.Panel)) {
return false;
}
const value = configurationService.getValue(KEYWORD_ACTIVIATION_SETTING_ID);
return typeof value === 'string' && value !== KeywordActivationContribution.SETTINGS_VALUE.OFF;
}
export class KeywordActivationContribution extends Disposable implements IWorkbenchContribution {
static readonly ID = 'workbench.contrib.keywordActivation';
static SETTINGS_VALUE = {
OFF: 'off',