diff --git a/src/vs/sessions/contrib/chat/browser/voiceBridge.contribution.ts b/src/vs/sessions/contrib/chat/browser/voiceBridge.contribution.ts index ef8d3a1eee416d..46374a36e61055 100644 --- a/src/vs/sessions/contrib/chat/browser/voiceBridge.contribution.ts +++ b/src/vs/sessions/contrib/chat/browser/voiceBridge.contribution.ts @@ -20,6 +20,7 @@ import { SessionStatus } from '../../../services/sessions/common/session.js'; import { IActiveSession, inheritableSessionTarget, ISendRequestOptions, ISessionsManagementService } from '../../../services/sessions/common/sessionsManagement.js'; import { INewChatVoiceComposer, INewChatVoiceTargetService, NEW_CHAT_VOICE_SENTINEL } from './newChatVoice.js'; import { INewSessionComposerService } from './newSessionComposerService.js'; +import { ChatRequestQueueKind } from '../../../../workbench/contrib/chat/common/chatService/chatService.js'; export async function prepareNewVoiceSession( text: string, @@ -133,17 +134,21 @@ export class SessionsVoiceBridgeContribution extends Disposable implements IWork const widget = expectedSessionId ? this.chatWidgetService.getWidgetBySessionResource(URI.parse(expectedSessionId)) : this._activeSessionWidget() ?? this.chatWidgetService.lastFocusedWidget; - if (expectedSessionId && widget?.viewModel?.sessionResource.toString() !== expectedSessionId) { + const viewModel = widget?.viewModel; + if (expectedSessionId && viewModel?.sessionResource.toString() !== expectedSessionId) { return false; } - if (widget?.viewModel) { - if (widget.viewModel.editing) { + if (widget && viewModel) { + if (viewModel.editing) { // Let the user review edited input before submitting. widget.input.setValue(text, false); return false; } else { // Preserve any text the user already typed in the input. - return widget.acceptInput(combineVoiceInput(widget.getInput(), text), { preserveFocus: true }); + return widget.acceptInput(combineVoiceInput(widget.getInput(), text), { + preserveFocus: true, + ...(viewModel.model?.requestInProgress?.get() === true ? { queue: ChatRequestQueueKind.Steering } : {}), + }); } } return false; diff --git a/src/vs/sessions/contrib/chat/test/browser/voiceBridge.test.ts b/src/vs/sessions/contrib/chat/test/browser/voiceBridge.test.ts index 78f594d792cea7..986ca215391f84 100644 --- a/src/vs/sessions/contrib/chat/test/browser/voiceBridge.test.ts +++ b/src/vs/sessions/contrib/chat/test/browser/voiceBridge.test.ts @@ -15,7 +15,8 @@ import { CommandsRegistry } from '../../../../../platform/commands/common/comman import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; import { ServicesAccessor } from '../../../../../platform/instantiation/common/instantiation.js'; import { IChatWidget, IChatWidgetService } from '../../../../../workbench/contrib/chat/browser/chat.js'; -import { IChatResponseModel } from '../../../../../workbench/contrib/chat/common/model/chatModel.js'; +import { IChatModel, IChatResponseModel } from '../../../../../workbench/contrib/chat/common/model/chatModel.js'; +import { ChatRequestQueueKind } from '../../../../../workbench/contrib/chat/common/chatService/chatService.js'; import { IChatViewModel } from '../../../../../workbench/contrib/chat/common/model/chatViewModel.js'; import { IVoiceSessionController } from '../../../../../workbench/contrib/chat/browser/voiceClient/voiceSessionController.js'; import { IChat, ISession, ISessionWorkspace, SessionStatus } from '../../../../services/sessions/common/session.js'; @@ -61,7 +62,12 @@ suite('SessionsVoiceBridgeContribution - input ownership', () => { let resource = URI.parse('chat-session:/a'); const inputs: string[] = []; const widget = new class extends mock() { - override get viewModel() { return upcastPartial({ sessionResource: resource }); } + override get viewModel() { + return upcastPartial({ + sessionResource: resource, + model: upcastPartial({ requestInProgress: constObservable(false) }), + }); + } override getInput() { return 'Already typed'; } override async acceptInput(text?: string) { inputs.push(text ?? ''); @@ -77,6 +83,57 @@ suite('SessionsVoiceBridgeContribution - input ownership', () => { }); }); + for (const inProgress of [false, true]) { + test(`voice bridge ${inProgress ? 'steers ongoing work' : 'sends normally when idle'}`, async () => { + const resource = URI.parse('chat-session:/a'); + const inputs: { text: string | undefined; options: Parameters[1] }[] = []; + const widget = new class extends mock() { + override readonly viewModel = upcastPartial({ + sessionResource: resource, + model: upcastPartial({ requestInProgress: constObservable(inProgress) }), + }); + override getInput() { return 'Typed draft'; } + override async acceptInput(text?: string, options?: Parameters[1]) { + inputs.push({ text, options }); + return undefined; + } + }(); + await registerBridge(widget, undefined)('Voice request', resource.toString()); + assert.deepStrictEqual(inputs, [{ + text: 'Typed draft Voice request', + options: { preserveFocus: true, ...(inProgress ? { queue: ChatRequestQueueKind.Steering } : {}) }, + }]); + }); + } + + for (const hasModel of [false, true]) { + test(`voice bridge submits normally when ${hasModel ? 'request progress' : 'the model'} is unavailable`, async () => { + const resource = URI.parse('chat-session:/a'); + const inputs: { text: string | undefined; options: Parameters[1] }[] = []; + const widget = new class extends mock() { + override readonly viewModel = upcastPartial({ + sessionResource: resource, + ...(hasModel ? { model: upcastPartial({}) } : {}), + }); + override getInput() { return 'Typed draft'; } + override async acceptInput(text?: string, options?: Parameters[1]) { + inputs.push({ text, options }); + return undefined; + } + }(); + await registerBridge(widget, undefined)('Voice request', resource.toString()); + assert.deepStrictEqual(inputs, [{ + text: 'Typed draft Voice request', + options: { preserveFocus: true }, + }]); + }); + } + + test('voice bridge rejects input when the widget has no view model', async () => { + const widget = new class extends mock() { }(); + assert.strictEqual(await registerBridge(widget, undefined)('Voice request', 'chat-session:/a'), false); + }); + test('does not redirect an existing session turn to a new composer and reports a busy composer honestly', async () => { const sent: string[] = []; const composer = upcastPartial({ diff --git a/src/vs/workbench/contrib/chat/browser/actions/chatAccessibilityHelp.ts b/src/vs/workbench/contrib/chat/browser/actions/chatAccessibilityHelp.ts index 6eb4df7667ac59..87c4de8686ee0f 100644 --- a/src/vs/workbench/contrib/chat/browser/actions/chatAccessibilityHelp.ts +++ b/src/vs/workbench/contrib/chat/browser/actions/chatAccessibilityHelp.ts @@ -198,6 +198,8 @@ export function getAccessibilityHelpText(type: 'panelChat' | 'inlineChat' | 'qui content.push(localize('chat.voiceInputMode.segmented', 'When the segmented voice input control is enabled, the input toolbar offers Dictation and Voice Mode. A connected hands-free session also offers Mute or Unmute Microphone; manual Voice Mode instead offers Start or Stop Listening, where stopping sends the completed turn. Each button can be focused and activated with Enter or Space.')); content.push(localize('chat.voiceInputMode.holdToTalk', 'In manual Voice Mode, the Start or Stop Listening button toggles listening when tapped, or you can press and hold it to talk and release to send. You can also hold the Voice Mode: Hold to Talk keybinding{0} to talk and release to send; this interrupts the assistant to barge in.', '')); content.push(localize('chat.voiceMode.byokSession', "When using configured OpenAI BYOK Voice Mode, only the bound chat input's prompts and responses are read. Voice Mode belongs to the input where you start it, including chat editor tabs and the chat sidebar. Switching the bound input or discarding a recording stops Voice Mode to prevent buffered audio from acting on another session. Start Voice Mode again in the intended input; creating the session from the same draft does not require a restart.")); + content.push(localize('chat.voiceMode.steering', "When Voice Mode sends a new request while the coding agent is working, it is sent as steering rather than queued for after the current task. Voice-only exchanges during ongoing work are not retained as context for later requests. Answers to pending questions and approvals continue to respond to those prompts.")); + content.push(localize('chat.voiceMode.questionSequence', "For forms with multiple questions, Voice Mode identifies the current question by number. Answer only that question, then wait for the next one. Each spoken reply fills one field, not several fields.")); content.push(localize('chat.voiceMode.byokAnswers', "In OpenAI BYOK Voice Mode, say approve, approved, accept, accepted, allow, yes, I approve, or I accept to approve the current prompt, and reject, deny, or no to reject it. These approval commands must be complete, unqualified English replies. For questions, say an exact displayed choice or its number; for multiple selections, separate choices with commas or and. Answer text questions directly. To give a custom answer to a selection question that permits it, say other followed by your answer. Forms collect one answer at a time and submit when complete. Say skip only when the form permits skipping. Ambiguous replies ask for clarification without approving anything or sending a new chat request.")); content.push(localize('chat.voiceMode.introduction', 'The first time Voice Mode starts, an introduction appears above the input box. Tab to reach it, then use the arrow keys to move between the available voices; Enter or Space plays a voice and keeps it for future conversations. Its description also contains two links: Settings, which opens the Voice Mode settings, and How It Responds, which opens a file for customizing what the agent says back. Voice Mode stays connected but does not listen while the introduction is open. Press Escape, or activate the Close button, to dismiss it and return to the input box.')); if (type === 'agentView') { diff --git a/src/vs/workbench/contrib/chat/browser/voiceClient/voiceClientService.ts b/src/vs/workbench/contrib/chat/browser/voiceClient/voiceClientService.ts index 75898616e386f7..5038063f299dee 100644 --- a/src/vs/workbench/contrib/chat/browser/voiceClient/voiceClientService.ts +++ b/src/vs/workbench/contrib/chat/browser/voiceClient/voiceClientService.ts @@ -180,6 +180,8 @@ export class VoiceClientService extends Disposable implements IVoiceClientServic private _gptLivePassiveSpeechStarted = false; private _gptLiveDelegationId: string | undefined; private _gptLiveInputTranscript = ''; + private _gptLiveInputContext: string | undefined; + private _gptLiveInputContextAllowed: boolean | undefined; private readonly _gptLiveDelegations = new Set(); private _gptLiveOutputTranscript = ''; private _gptLiveOutputStarted = false; @@ -194,7 +196,7 @@ export class VoiceClientService extends Disposable implements IVoiceClientServic private _gptLiveInputStartMs: number | undefined; private _gptLiveInputLastStartMs: number | undefined; private _gptLiveInputEndMs: number | undefined; - private readonly _gptLiveInputs: { text: string; target: IVoiceLiveInputTarget; turnId?: string; startMs?: number; lastStartMs?: number; endMs?: number; delegated: boolean; answeredByVoice: boolean }[] = []; + private readonly _gptLiveInputs: { text: string; context?: string; voiceResponse: string | undefined; target: IVoiceLiveInputTarget; turnId?: string; startMs?: number; lastStartMs?: number; endMs?: number; delegated: boolean; answeredByVoice: boolean }[] = []; private _gptLiveContext: IVoiceSessionContext | undefined; private _gptLiveInstructionsSent = false; private readonly _gptLiveRequest = this._register(new MutableDisposable()); @@ -741,10 +743,17 @@ export class VoiceClientService extends Disposable implements IVoiceClientServic for (const input of this._gptLiveInputs) { if (input.answeredByVoice) { input.delegated = true; + if (input.voiceResponse === undefined) { + input.text = ''; + } } } } this._gptLiveInputTarget ??= this._gptLiveInputRouter.captureTarget(); + this._gptLiveInputContextAllowed ??= this._canRetainGptLiveVoiceContext(this._gptLiveInputTarget); + if (!this._gptLiveInputTranscript) { + this._gptLiveInputContext = this._gptLiveInputContextAllowed ? this._captureGptLiveVoiceContext(this._gptLiveInputTarget) : undefined; + } const delta = asOptionalString(event.delta) ?? ''; if (typeof event.start_ms === 'number' && Number.isFinite(event.start_ms)) { this._gptLiveInputStartMs ??= event.start_ms; @@ -780,11 +789,14 @@ export class VoiceClientService extends Disposable implements IVoiceClientServic if (!this._gptLiveOutputStarted && !this._gptLiveInputTarget?.session?.pending) { this._finalizeGptLiveInput(); } - const input = this._gptLiveInputs.findLast(candidate => !candidate.delegated && !candidate.target.session?.pending); - if (input) { + const input = this._gptLiveInputs.at(-1); + const delta = asOptionalString(event.delta) ?? ''; + if (input && !input.target.session?.pending && !this._gptLiveOutputSuppressedUntilInput) { input.answeredByVoice = true; + if (input.voiceResponse !== undefined) { + input.voiceResponse += delta; + } } - const delta = asOptionalString(event.delta) ?? ''; this._gptLiveOutputTranscript += delta; if (!this._gptLiveOutputStarted) { if (!this._gptLiveOutputInterrupted && !this._gptLiveOutputSuppressedUntilInput) { @@ -842,9 +854,18 @@ export class VoiceClientService extends Disposable implements IVoiceClientServic break; } input.delegated = true; + input.answeredByVoice = false; + input.voiceResponse = input.voiceResponse === undefined ? undefined : ''; const result = this._gptLiveInputRouter.resolve(delegationId, input.text, input.target); if (result.toolCall) { - this._onToolCall.fire({ ...result.toolCall, ...(input.turnId ? { turnId: input.turnId } : {}) }); + const toolCall = result.toolCall; + this._onToolCall.fire({ + ...toolCall, + args: toolCall.name === 'send_to_chat' && input.context + ? { ...toolCall.args, text: localize('voice.live.conversationContext', "Voice conversation context:\n{0}\n\nUser: {1}", input.context, input.text) } + : toolCall.args, + ...(input.turnId ? { turnId: input.turnId } : {}), + }); } else { this._sendGptLiveAppend('session.commentary.append', result.clarification, delegationId); } @@ -860,6 +881,30 @@ export class VoiceClientService extends Disposable implements IVoiceClientServic } } + private _canRetainGptLiveVoiceContext(target: IVoiceLiveInputTarget): boolean { + if (!target.hasContext || target.session?.pending || (target.session && target.session.agent_state !== 'idle')) { + return false; + } + const current = this._gptLiveContext?.sessions.find(session => session.id === target.session?.id); + return !target.session || (current?.agent_state === 'idle' && !current.pending); + } + + private _captureGptLiveVoiceContext(target: IVoiceLiveInputTarget): string | undefined { + if (!this._canRetainGptLiveVoiceContext(target)) { + return undefined; + } + const turns: string[] = []; + for (let index = this._gptLiveInputs.length - 1; index >= 0; index--) { + const input = this._gptLiveInputs[index]; + if (!input.answeredByVoice || !input.voiceResponse || input.target.session?.pending + || input.target.hasContext !== target.hasContext || input.target.session?.id !== target.session?.id) { + break; + } + turns.push(localize('voice.live.conversationTurn', "User: {0}\nVoice assistant: {1}", input.text, input.voiceResponse)); + } + return turns.length ? turns.reverse().join('\n\n') : undefined; + } + private _finalizeGptLiveInput(): void { if (!this._gptLiveInputTranscript) { return; @@ -874,6 +919,8 @@ export class VoiceClientService extends Disposable implements IVoiceClientServic } this._gptLiveInputs.push({ text, + context: this._gptLiveInputContext, + voiceResponse: this._gptLiveInputContextAllowed ? '' : undefined, target: this._gptLiveInputTarget ?? this._gptLiveInputRouter.captureTarget(), turnId: this._gptLiveTurnId, startMs: this._gptLiveInputStartMs, @@ -886,6 +933,8 @@ export class VoiceClientService extends Disposable implements IVoiceClientServic this._gptLiveInputs.shift(); } this._gptLiveInputTranscript = ''; + this._gptLiveInputContext = undefined; + this._gptLiveInputContextAllowed = undefined; this._gptLiveInputTarget = undefined; this._gptLiveInputStartMs = undefined; this._gptLiveInputLastStartMs = undefined; @@ -1235,6 +1284,8 @@ export class VoiceClientService extends Disposable implements IVoiceClientServic this._usingGptLive = false; this._gptLiveSessionInitSent = false; this._gptLiveTurnId = undefined; + this._gptLiveInputContext = undefined; + this._gptLiveInputContextAllowed = undefined; this._gptLivePassiveTurn = false; this._gptLivePassiveSpeechStarted = false; this._gptLiveDelegationId = undefined; @@ -1312,6 +1363,7 @@ export class VoiceClientService extends Disposable implements IVoiceClientServic this._gptLiveTurnId = turnId; this._gptLiveInputTranscript = ''; this._gptLiveInputTarget = options.passive ? undefined : this._gptLiveInputRouter.captureTarget(); + this._gptLiveInputContextAllowed = this._gptLiveInputTarget ? this._canRetainGptLiveVoiceContext(this._gptLiveInputTarget) : undefined; this._gptLiveInputStartMs = undefined; this._gptLiveInputLastStartMs = undefined; this._gptLiveInputEndMs = undefined; @@ -1373,6 +1425,16 @@ export class VoiceClientService extends Disposable implements IVoiceClientServic const previousContext = this._gptLiveContext; const previous = previousContext?.sessions.find(session => session.is_active); this._gptLiveContext = sessionContext; + for (const input of this._gptLiveInputs) { + if (!this._canRetainGptLiveVoiceContext(input.target)) { + input.context = undefined; + input.voiceResponse = undefined; + } + } + if (this._gptLiveInputTarget && !this._canRetainGptLiveVoiceContext(this._gptLiveInputTarget)) { + this._gptLiveInputContext = undefined; + this._gptLiveInputContextAllowed = false; + } const grounding = (session: typeof active) => session ? { id: session.id, label: session.label, state: session.agent_state, pending_type: session.pending?.type } : null; if (!previousContext || previousContext.display_locale !== sessionContext.display_locale) { this._sendGptLiveAppend('session.instructions.append', `Voice language: ${JSON.stringify(sessionContext.display_locale)}. Speak in this language and interpret the user's speech in it when possible.`, null); @@ -1650,6 +1712,9 @@ export class VoiceClientService extends Disposable implements IVoiceClientServic prepareForInputTargetChange(): void { if (this._usingGptLive) { + for (const input of this._gptLiveInputs) { + input.voiceResponse = undefined; + } this._gptLiveOutputSuppressedUntilInput = true; this._updateGptLiveAudioMuted(); } diff --git a/src/vs/workbench/contrib/chat/browser/voiceClient/voiceInputUtils.ts b/src/vs/workbench/contrib/chat/browser/voiceClient/voiceInputUtils.ts index ec5568e48ea257..8065f514aa5c5a 100644 --- a/src/vs/workbench/contrib/chat/browser/voiceClient/voiceInputUtils.ts +++ b/src/vs/workbench/contrib/chat/browser/voiceClient/voiceInputUtils.ts @@ -5,17 +5,23 @@ import { IChatResponseModel } from '../../common/model/chatModel.js'; import { IChatWidget } from '../chat.js'; +import { ChatRequestQueueKind } from '../../common/chatService/chatService.js'; /** Submit through the owning widget, preserving its input state and normal request options. */ export function acceptVoiceInput(widget: IChatWidget | undefined, text: string, isVoiceModeInput: boolean): boolean | Promise { - if (!text || !widget?.viewModel) { + const viewModel = widget?.viewModel; + if (!text || !widget || !viewModel) { return false; } - if (widget.viewModel.editing) { + if (viewModel.editing) { widget.input.setValue(text, false); return false; } - return widget.acceptInput(combineVoiceInput(widget.getInput(), text), { preserveFocus: true, isVoiceModeInput }); + return widget.acceptInput(combineVoiceInput(widget.getInput(), text), { + preserveFocus: true, + isVoiceModeInput, + ...(viewModel.model?.requestInProgress?.get() === true ? { queue: ChatRequestQueueKind.Steering } : {}), + }); } /** diff --git a/src/vs/workbench/contrib/chat/browser/voiceClient/voiceSessionController.ts b/src/vs/workbench/contrib/chat/browser/voiceClient/voiceSessionController.ts index 1211f942acc7a4..99039e02021d2a 100644 --- a/src/vs/workbench/contrib/chat/browser/voiceClient/voiceSessionController.ts +++ b/src/vs/workbench/contrib/chat/browser/voiceClient/voiceSessionController.ts @@ -36,7 +36,7 @@ import { IAgentSessionsService } from '../agentSessions/agentSessionsService.js' import { AgentSessionStatus } from '../agentSessions/agentSessionsModel.js'; import { toAgentHostBackendSessionUri } from '../agentSessions/agentHost/agentHostSessionUri.js'; import { IAgentHostConnectionsService } from '../../../../../platform/agentHost/common/agentHostConnectionsService.js'; -import { ChatSendResult, ConfirmedReason, IChatConfirmation, IChatElicitationRequest, IChatPlanReview, IChatQuestionCarousel, IChatService, IChatToolInvocation, ToolConfirmKind, IChatModelReference } from '../../common/chatService/chatService.js'; +import { ChatRequestQueueKind, ChatSendResult, ConfirmedReason, IChatConfirmation, IChatElicitationRequest, IChatPlanReview, IChatQuestionCarousel, IChatService, IChatToolInvocation, ToolConfirmKind, IChatModelReference } from '../../common/chatService/chatService.js'; import { getDisplayedQuestionText, getOptionsWithDefaultsFirst } from '../../common/chatService/chatQuestionCarouselHelpers.js'; import { formatQuestionPrompt } from '../../common/voiceClient/voicePendingNarration.js'; import { IChatWidget, IChatWidgetService } from '../chat.js'; @@ -3625,7 +3625,10 @@ export class VoiceSessionController extends Disposable implements IVoiceSessionC private async _sendVoiceRequest(sessionResource: URI, text: string): Promise { const generation = this._connectAttemptGeneration; const initializationGeneration = this._sessionInitializationGeneration; - const result = await this.chatService.sendRequest(sessionResource, text, { isVoiceModeInput: this._isVoiceProgressEnabled() }).catch(err => { + const result = await this.chatService.sendRequest(sessionResource, text, { + isVoiceModeInput: this._isVoiceProgressEnabled(), + ...(this.chatService.getSession(sessionResource)?.requestInProgress.get() ? { queue: ChatRequestQueueKind.Steering } : {}), + }).catch(err => { this.logService.warn('[voice] Error sending transcription:', err); return undefined; }); @@ -5070,7 +5073,7 @@ export class VoiceSessionController extends Disposable implements IVoiceSessionC } return { kind: 'question', - text: formatQuestionPrompt(question, pending.allow_skip === true), + text: formatQuestionPrompt(question, pending.allow_skip === true, pending.message, pending.questions?.length), pending: { pendingId: pending.pending_id }, }; } diff --git a/src/vs/workbench/contrib/chat/common/voiceClient/voiceLiveInputRouter.ts b/src/vs/workbench/contrib/chat/common/voiceClient/voiceLiveInputRouter.ts index 896f79faf03245..183ad6419677aa 100644 --- a/src/vs/workbench/contrib/chat/common/voiceClient/voiceLiveInputRouter.ts +++ b/src/vs/workbench/contrib/chat/common/voiceClient/voiceLiveInputRouter.ts @@ -4,7 +4,8 @@ *--------------------------------------------------------------------------------------------*/ import { localize } from '../../../../../nls.js'; -import { IVoiceDispatchResult, IVoicePendingQuestion, IVoiceSessionContext, IVoiceToolCall } from './voiceClientService.js'; +import { IVoiceDispatchResult, IVoicePendingQuestion, IVoiceSessionContext, IVoiceSessionPending, IVoiceToolCall } from './voiceClientService.js'; +import { formatQuestionPromptTitle } from './voicePendingNarration.js'; import { IBackendQuestionAnswer } from './voiceQuestionAnswers.js'; type VoiceSession = IVoiceSessionContext['sessions'][number]; @@ -221,9 +222,10 @@ function resolveAnswer(question: IVoicePendingQuestion, text: string, language: : undefined; } -function questionPrompt(question: IVoicePendingQuestion, guidance: string): string { +function questionPrompt(question: IVoicePendingQuestion, guidance: string, pending: IVoiceSessionPending, questionIndex: number): string { const options = question.options.map((option, index) => `${index + 1}. ${option.label}`).join(' '); - return [localize('voice.live.questionPrompt', "{0} {1}", question.title, options).trim(), guidance].filter(Boolean).join(' '); + const prompt = formatQuestionPromptTitle(question, pending.message, questionIndex, pending.questions?.length); + return [localize('voice.live.questionPrompt', "{0} {1}", prompt, options).trim(), guidance].filter(Boolean).join(' '); } /** Routes only explicit, deterministic replies to captured, still-current pending occurrences, never model guesses. Ambiguous replies cannot authorize actions, and forms submit only when complete or explicitly skipped. */ @@ -286,8 +288,10 @@ export class VoiceLiveInputRouter { getQuestionPrompt(sessionId: string, pendingId: string): string | undefined { const session = this._context.sessions.find(candidate => candidate.id === sessionId && candidate.pending?.pending_id === pendingId); - const question = session?.pending?.questions?.[this._answers.get(this._key(session))?.answers.length ?? 0]; - return question ? questionPrompt(question, this.getQuestionReplyGuidance()) : undefined; + const index = session ? this._answers.get(this._key(session))?.answers.length ?? 0 : 0; + const pending = session?.pending; + const question = pending?.questions?.[index]; + return question && pending ? questionPrompt(question, this.getQuestionReplyGuidance(), pending, index) : undefined; } captureTarget(): IVoiceLiveInputTarget { @@ -354,15 +358,15 @@ export class VoiceLiveInputRouter { if (!answer) { return { clarification: question.allow_freeform - ? localize('voice.live.chooseOrCustomAnswer', "Please say an exact choice or its number, or say other followed by a custom answer. {0}", questionPrompt(question, this.getQuestionReplyGuidance())) - : localize('voice.live.chooseAnswer', "Please say an exact choice or its number. {0}", questionPrompt(question, this.getQuestionReplyGuidance())) + ? localize('voice.live.chooseOrCustomAnswer', "Please say an exact choice or its number, or say other followed by a custom answer. {0}", questionPrompt(question, this.getQuestionReplyGuidance(), pending, answers.length)) + : localize('voice.live.chooseAnswer', "Please say an exact choice or its number. {0}", questionPrompt(question, this.getQuestionReplyGuidance(), pending, answers.length)) }; } answers.push(answer); this._answers.set(key, { schema: JSON.stringify(pending), answers }); const next = pending.questions?.[answers.length]; if (next) { - return { clarification: questionPrompt(next, this.getQuestionReplyGuidance()) }; + return { clarification: questionPrompt(next, this.getQuestionReplyGuidance(), pending, answers.length) }; } response = { type: 'answer', answers }; } diff --git a/src/vs/workbench/contrib/chat/common/voiceClient/voicePendingNarration.ts b/src/vs/workbench/contrib/chat/common/voiceClient/voicePendingNarration.ts index 9f4981cd38a012..74652a115c4203 100644 --- a/src/vs/workbench/contrib/chat/common/voiceClient/voicePendingNarration.ts +++ b/src/vs/workbench/contrib/chat/common/voiceClient/voicePendingNarration.ts @@ -3,22 +3,28 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import { localize } from '../../../../../nls.js'; import { IVoicePendingQuestion } from './voiceClientService.js'; -/** - * Render the canonical spoken form of a pending question. - * - * Mirrors `format_question_prompt` in the voice backend's `session_pending.py`, - * against the same fixtures. The client speaks the first question of a form and - * the backend speaks the rest, so a divergence is audible mid-form. - * - * Renders the wire shape rather than the carousel, because that is where the - * ordinals the user says back were assigned. Numbering from a second source - * could read out a number that selects something else. - */ -export function formatQuestionPrompt(question: IVoicePendingQuestion, allowSkip: boolean): string { - const parts: string[] = []; +export function formatQuestionPromptTitle(question: IVoicePendingQuestion, context?: string, questionIndex = 0, questionCount = 1): string { const title = question.title.trim(); + if (questionCount > 1) { + // A form-level message can ask for several fields, but each reply fills only the current field. + const prompt = localize('voice.questionNumber', "Question {0} of {1}: {2}", questionIndex + 1, questionCount, title); + return questionIndex === 0 + ? localize('voice.oneQuestionAtATime', "Please answer one question at a time. {0}", prompt) + : prompt; + } + const formContext = context?.trim(); + return formContext && formContext !== title + ? localize('voice.questionWithContext', "{0} {1}", formContext, title).trim() + : title; +} + +/** Render the spoken question and choices, optionally preceded by form-level context. Choice ordinals follow the displayed order in the wire payload. */ +export function formatQuestionPrompt(question: IVoicePendingQuestion, allowSkip: boolean, context?: string, questionCount = 1): string { + const parts: string[] = []; + const title = formatQuestionPromptTitle(question, context, 0, questionCount); if (title) { parts.push(title); } diff --git a/src/vs/workbench/contrib/chat/test/browser/voiceClient/voiceClientService.test.ts b/src/vs/workbench/contrib/chat/test/browser/voiceClient/voiceClientService.test.ts index afcf3da8aedf18..aa14740aa3e578 100644 --- a/src/vs/workbench/contrib/chat/test/browser/voiceClient/voiceClientService.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/voiceClient/voiceClientService.test.ts @@ -1233,7 +1233,7 @@ suite('VoiceClientService', () => { }); }); - test('does not submit a voice-answered turn with a later delegated turn', async () => { + test('delegates the current turn with voice-only history as context, not as another request', async () => { const peer = new TestRtcPeerConnection(); const service = store.add(new TestGptLiveVoiceClientService(peer, new TestMicCaptureService(new TestMediaStream(new TestMediaStreamTrack())), productService)); const calls: string[] = []; @@ -1249,9 +1249,212 @@ suite('VoiceClientService', () => { peer.channel.fireMessage({ type: 'session.input_transcript.delta', delta: 'Fix the tests', is_final: true }); peer.channel.fireMessage({ type: 'session.delegation.created', delegation: { id: 'delegation-coding' } }); - assert.deepStrictEqual(calls, ['Fix the tests']); + assert.deepStrictEqual(calls, ['Voice conversation context:\nUser: Which session am I in?\nVoice assistant: You are in Alpha.\n\nUser: Fix the tests']); }); + for (const finishesDuringAnswer of [false, true]) { + test(`does not retain a voice-only answer while work is in progress${finishesDuringAnswer ? ', even if work finishes during the answer' : ''}`, async () => { + const peer = new TestRtcPeerConnection(); + const service = store.add(new TestGptLiveVoiceClientService(peer, new TestMicCaptureService(new TestMediaStream(new TestMediaStreamTrack())), productService)); + const calls: string[] = []; + store.add(service.onToolCall(event => calls.push(String(event.args.text)))); + await service.connect(createTestWindow()); + peer.channel.fireMessage({ type: 'session.started' }); + const context: IVoiceSessionContext = { sessions: [{ id: 'chat-session:/a', is_active: true, agent_state: 'thinking' }], display_locale: 'en-US' }; + service.sendStartSession(context, 'machine'); + service.sendPttStart('question', { hasActiveSession: true }); + peer.channel.fireMessage({ type: 'session.input_transcript.delta', delta: 'What is TypeScript?', is_final: true }); + peer.channel.fireMessage({ type: 'session.output_transcript.delta', delta: 'TypeScript adds optional static types to JavaScript.' }); + if (finishesDuringAnswer) { + service.sendSessionContext({ ...context, sessions: [{ ...context.sessions[0], agent_state: 'idle' }] }); + } + peer.channel.fireMessage({ type: 'session.output_transcript.delta', delta: ' I have printed one through twenty.' }); + const inputs = Reflect.get(service, '_gptLiveInputs') as { text: string; context?: string; voiceResponse?: string }[]; + const storedAnswer = { context: inputs[0].context, voiceResponse: inputs[0].voiceResponse }; + service.sendPttStart('request', { hasActiveSession: true }); + peer.channel.fireMessage({ type: 'session.input_transcript.delta', delta: 'Okay, now create a file for me', is_final: true }); + peer.channel.fireMessage({ type: 'session.delegation.created', delegation: { id: 'request-delegation' } }); + + assert.deepStrictEqual({ storedAnswer, retiredQuestion: inputs[0].text, calls }, { + storedAnswer: { context: undefined, voiceResponse: undefined }, + retiredQuestion: '', + calls: ['Okay, now create a file for me'], + }); + }); + } + + test('clears idle voice context when work starts, including a partially transcribed reply', async () => { + const peer = new TestRtcPeerConnection(); + const service = store.add(new TestGptLiveVoiceClientService(peer, new TestMicCaptureService(new TestMediaStream(new TestMediaStreamTrack())), productService)); + const calls: string[] = []; + store.add(service.onToolCall(event => calls.push(String(event.args.text)))); + await service.connect(createTestWindow()); + peer.channel.fireMessage({ type: 'session.started' }); + const context: IVoiceSessionContext = { sessions: [{ id: 'chat-session:/a', is_active: true, agent_state: 'idle' }], display_locale: 'en-US' }; + service.sendStartSession(context, 'machine'); + service.sendPttStart('initial', { hasActiveSession: true }); + peer.channel.fireMessage({ type: 'session.input_transcript.delta', delta: 'Add a theme', is_final: true }); + peer.channel.fireMessage({ type: 'session.output_transcript.delta', delta: 'Light or dark?' }); + service.sendPttStart('reply', { hasActiveSession: true }); + peer.channel.fireMessage({ type: 'session.input_transcript.delta', delta: 'What is ' }); + service.sendSessionContext({ ...context, sessions: [{ ...context.sessions[0], agent_state: 'thinking' }] }); + service.sendSessionContext(context); + peer.channel.fireMessage({ type: 'session.input_transcript.delta', delta: 'TypeScript?', is_final: true }); + peer.channel.fireMessage({ type: 'session.output_transcript.delta', delta: 'TypeScript adds types to JavaScript.' }); + service.sendPttStart('request', { hasActiveSession: true }); + peer.channel.fireMessage({ type: 'session.input_transcript.delta', delta: 'Create a file', is_final: true }); + peer.channel.fireMessage({ type: 'session.delegation.created', delegation: { id: 'request-delegation' } }); + + assert.deepStrictEqual(calls, ['Create a file']); + }); + + for (const sessionId of ['chat-session:/a', undefined]) { + test(`preserves GPT-Live clarification questions when handing off to ${sessionId ? 'an existing chat' : 'the new-session composer'}`, async () => { + const clock = sinon.useFakeTimers(); + try { + const peer = new TestRtcPeerConnection(); + const service = store.add(new TestGptLiveVoiceClientService(peer, new TestMicCaptureService(new TestMediaStream(new TestMediaStreamTrack())), productService)); + const calls: IVoiceToolCall[] = []; + const transcriptions: IVoiceTranscription[] = []; + store.add(service.onToolCall(event => calls.push(event))); + store.add(service.onTranscription(event => transcriptions.push(event))); + await service.connect(createTestWindow()); + peer.channel.fireMessage({ type: 'session.started' }); + service.sendStartSession({ sessions: sessionId ? [{ id: sessionId, is_active: true, agent_state: 'idle' }] : [], display_locale: 'en-US' }, 'machine'); + service.sendPttStart('request', { hasActiveSession: !!sessionId }); + peer.channel.fireMessage({ type: 'session.input_transcript.delta', delta: 'Add a theme', is_final: true }); + peer.channel.fireMessage({ type: 'session.output_transcript.delta', delta: 'Should it be ' }); + peer.channel.fireMessage({ type: 'session.output_transcript.delta', delta: 'light or dark?' }); + await clock.tickAsync(750); + service.sendPttStart('answer', { hasActiveSession: !!sessionId, passive: true }); + peer.channel.fireMessage({ type: 'session.input_transcript.delta', delta: 'Dark', is_final: true }); + peer.channel.fireMessage({ type: 'session.delegation.created', delegation: { id: 'answer-delegation' } }); + peer.channel.fireMessage({ type: 'session.delegation.created', delegation: { id: 'answer-delegation' } }); + + assert.deepStrictEqual({ calls, transcriptions }, { + calls: [{ + callId: 'answer-delegation', name: 'send_to_chat', turnId: 'answer', + args: { + text: 'Voice conversation context:\nUser: Add a theme\nVoice assistant: Should it be light or dark?\n\nUser: Dark', + ...(sessionId ? { coding_session_id: sessionId } : {}), + }, + }], + transcriptions: [ + { text: 'Add a theme', status: 'final', turnId: 'request' }, + { text: 'Dark', status: 'final', turnId: 'answer' }, + ], + }); + } finally { + clock.restore(); + } + }); + } + + test('preserves multiple voice-only exchanges and snapshots context before the delegated answer', async () => { + const clock = sinon.useFakeTimers(); + try { + const peer = new TestRtcPeerConnection(); + const service = store.add(new TestGptLiveVoiceClientService(peer, new TestMicCaptureService(new TestMediaStream(new TestMediaStreamTrack())), productService)); + const calls: string[] = []; + store.add(service.onToolCall(event => calls.push(String(event.args.text)))); + await service.connect(createTestWindow()); + peer.channel.fireMessage({ type: 'session.started' }); + service.sendStartSession({ sessions: [{ id: 'chat-session:/a', is_active: true, agent_state: 'idle' }], display_locale: 'en-US' }, 'machine'); + for (const [text, response] of [['Add a theme', 'Light or dark?'], ['Dark', 'Which accent color?']]) { + service.sendPttStart(text, { hasActiveSession: true }); + peer.channel.fireMessage({ type: 'session.input_transcript.delta', delta: text, is_final: true }); + peer.channel.fireMessage({ type: 'session.output_transcript.delta', delta: response }); + await clock.tickAsync(750); + } + service.sendPttStart('answer', { hasActiveSession: true }); + peer.channel.fireMessage({ type: 'session.input_transcript.delta', delta: 'Blue', is_final: true }); + peer.channel.fireMessage({ type: 'session.output_transcript.delta', delta: 'I will send that to chat.' }); + peer.channel.fireMessage({ type: 'session.delegation.created', delegation: { id: 'answer-delegation' } }); + service.sendPttStart('next', { hasActiveSession: true }); + peer.channel.fireMessage({ type: 'session.input_transcript.delta', delta: 'Run the tests', is_final: true }); + peer.channel.fireMessage({ type: 'session.delegation.created', delegation: { id: 'next-delegation' } }); + + assert.deepStrictEqual(calls, [ + 'Voice conversation context:\nUser: Add a theme\nVoice assistant: Light or dark?\n\nUser: Dark\nVoice assistant: Which accent color?\n\nUser: Blue', + 'Run the tests', + ]); + } finally { + clock.restore(); + } + }); + + test('preserves a direct voice question spoken after a chat handoff', async () => { + const peer = new TestRtcPeerConnection(); + const service = store.add(new TestGptLiveVoiceClientService(peer, new TestMicCaptureService(new TestMediaStream(new TestMediaStreamTrack())), productService)); + const calls: string[] = []; + store.add(service.onToolCall(event => calls.push(String(event.args.text)))); + await service.connect(createTestWindow()); + peer.channel.fireMessage({ type: 'session.started' }); + service.sendStartSession({ sessions: [{ id: 'chat-session:/a', is_active: true, agent_state: 'idle' }], display_locale: 'en-US' }, 'machine'); + service.sendPttStart('request', { hasActiveSession: true }); + peer.channel.fireMessage({ type: 'session.input_transcript.delta', delta: 'Add a theme', is_final: true }); + peer.channel.fireMessage({ type: 'session.delegation.created', delegation: { id: 'request-delegation' } }); + peer.channel.fireMessage({ type: 'session.output_transcript.delta', delta: 'Should it be light or dark?' }); + service.sendPttStart('answer', { hasActiveSession: true }); + peer.channel.fireMessage({ type: 'session.input_transcript.delta', delta: 'Dark', is_final: true }); + peer.channel.fireMessage({ type: 'session.delegation.created', delegation: { id: 'answer-delegation' } }); + + assert.deepStrictEqual(calls, [ + 'Add a theme', + 'Voice conversation context:\nUser: Add a theme\nVoice assistant: Should it be light or dark?\n\nUser: Dark', + ]); + }); + + for (const change of ['session', 'target', 'reconnect', 'question', 'approval'] as const) { + test(`does not carry voice-only context across a ${change} change`, async () => { + const peer = new TestRtcPeerConnection(); + const service = store.add(new TestGptLiveVoiceClientService(peer, new TestMicCaptureService(new TestMediaStream(new TestMediaStreamTrack())), productService)); + const calls: IVoiceToolCall[] = []; + store.add(service.onToolCall(event => calls.push(event))); + await service.connect(createTestWindow()); + peer.channel.fireMessage({ type: 'session.started' }); + const context: IVoiceSessionContext = { sessions: [{ id: 'chat-session:/a', is_active: true, agent_state: 'idle' }], display_locale: 'en-US' }; + service.sendStartSession(context, 'machine'); + service.sendPttStart('request', { hasActiveSession: true }); + peer.channel.fireMessage({ type: 'session.input_transcript.delta', delta: 'Add a theme', is_final: true }); + peer.channel.fireMessage({ type: 'session.output_transcript.delta', delta: 'Light or dark?' }); + if (change === 'session') { + service.sendSessionContext({ ...context, sessions: [{ ...context.sessions[0], id: 'chat-session:/b' }] }); + } else if (change === 'target') { + service.prepareForInputTargetChange(); + peer.channel.fireMessage({ type: 'session.output_transcript.delta', delta: 'More speech from the previous input target.' }); + } else if (change === 'reconnect') { + service.disconnect(); + await service.connect(createTestWindow()); + peer.channel.fireMessage({ type: 'session.started' }); + service.sendStartSession(context, 'machine'); + } else { + service.sendSessionContext({ + ...context, + sessions: [{ + ...context.sessions[0], agent_state: 'waiting_for_confirmation', + pending: { + type: change === 'question' ? 'questions' : 'approval', request_id: 'request', pending_id: 'pending', + ...(change === 'question' ? { questions: [{ id: 'theme', title: 'Theme?', type: 'text', options: [], allow_freeform: true }] } : {}), + }, + }], + }); + } + service.sendPttStart('answer', { hasActiveSession: true }); + peer.channel.fireMessage({ type: 'session.input_transcript.delta', delta: change === 'approval' ? 'approve' : 'Dark', is_final: true }); + peer.channel.fireMessage({ type: 'session.delegation.created', delegation: { id: 'answer-delegation' } }); + + assert.deepStrictEqual(calls, [{ + callId: 'answer-delegation', turnId: 'answer', + name: change === 'question' || change === 'approval' ? 'respond_to_session' : 'send_to_chat', + args: change === 'question' || change === 'approval' ? { + coding_session_id: 'chat-session:/a', request_id: 'request', pending_id: 'pending', + response: change === 'approval' ? { type: 'approve' } : { type: 'answer', answers: [{ question_id: 'theme', freeform: 'Dark' }] }, + } : { text: 'Dark', coding_session_id: change === 'session' ? 'chat-session:/b' : 'chat-session:/a' }, + }]); + }); + } + test('routes an annotated session-navigation transcript as an ordinary chat request', async () => { const peer = new TestRtcPeerConnection(); const service = store.add(new TestGptLiveVoiceClientService(peer, new TestMicCaptureService(new TestMediaStream(new TestMediaStreamTrack())), productService)); diff --git a/src/vs/workbench/contrib/chat/test/browser/voiceClient/voiceInputUtils.test.ts b/src/vs/workbench/contrib/chat/test/browser/voiceClient/voiceInputUtils.test.ts index bae8a8f26c87e3..baa117f9909641 100644 --- a/src/vs/workbench/contrib/chat/test/browser/voiceClient/voiceInputUtils.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/voiceClient/voiceInputUtils.test.ts @@ -5,9 +5,12 @@ import assert from 'assert'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; -import { mock } from '../../../../../../base/test/common/mock.js'; +import { mock, upcastPartial } from '../../../../../../base/test/common/mock.js'; import { IChatWidget } from '../../../browser/chat.js'; import { acceptVoiceInput, combineVoiceInput } from '../../../browser/voiceClient/voiceInputUtils.js'; +import { ChatRequestQueueKind } from '../../../common/chatService/chatService.js'; +import { constObservable } from '../../../../../../base/common/observable.js'; +import { IChatModel } from '../../../common/model/chatModel.js'; suite('combineVoiceInput', () => { ensureNoDisposablesAreLeakedInTestSuite(); @@ -36,18 +39,53 @@ suite('combineVoiceInput', () => { suite('acceptVoiceInput', () => { ensureNoDisposablesAreLeakedInTestSuite(); - test('preserves typed input, focus and voice-progress options in the owning widget', async () => { - const sent: { text: string | undefined; options: Parameters[1] }[] = []; - const widget = new class extends mock() { - override readonly viewModel = new class extends mock>() { }(); - override getInput(): string { return 'Typed draft'; } - override async acceptInput(text?: string, options?: Parameters[1]) { - sent.push({ text, options }); - return undefined; - } - }(); - await acceptVoiceInput(widget, 'spoken request', true); - assert.deepStrictEqual(sent, [{ text: 'Typed draft spoken request', options: { preserveFocus: true, isVoiceModeInput: true } }]); + for (const inProgress of [false, true]) { + test(`preserves typed input, focus and voice-progress options and ${inProgress ? 'steers an active request' : 'sends normally when idle'}`, async () => { + const sent: { text: string | undefined; options: Parameters[1] }[] = []; + const widget = new class extends mock() { + override readonly viewModel = new class extends mock>() { + override readonly model = new class extends mock() { + override readonly requestInProgress = constObservable(inProgress); + }(); + }(); + override getInput(): string { return 'Typed draft'; } + override async acceptInput(text?: string, options?: Parameters[1]) { + sent.push({ text, options }); + return undefined; + } + }(); + await acceptVoiceInput(widget, 'spoken request', true); + assert.deepStrictEqual(sent, [{ + text: 'Typed draft spoken request', + options: { preserveFocus: true, isVoiceModeInput: true, ...(inProgress ? { queue: ChatRequestQueueKind.Steering } : {}) }, + }]); + }); + } + + for (const hasModel of [false, true]) { + test(`submits normally when ${hasModel ? 'request progress' : 'the model'} is unavailable`, async () => { + const sent: { text: string | undefined; options: Parameters[1] }[] = []; + const widget = new class extends mock() { + override readonly viewModel = upcastPartial>({ + ...(hasModel ? { model: upcastPartial({}) } : {}), + }); + override getInput(): string { return 'Typed draft'; } + override async acceptInput(text?: string, options?: Parameters[1]) { + sent.push({ text, options }); + return undefined; + } + }(); + await acceptVoiceInput(widget, 'spoken request', true); + assert.deepStrictEqual(sent, [{ + text: 'Typed draft spoken request', + options: { preserveFocus: true, isVoiceModeInput: true }, + }]); + }); + } + + test('rejects input when the widget has no view model', () => { + const widget = new class extends mock() { }(); + assert.strictEqual(acceptVoiceInput(widget, 'spoken request', true), false); }); test('populates an edited request for review rather than submitting it', async () => { diff --git a/src/vs/workbench/contrib/chat/test/browser/voiceClient/voiceSessionController.test.ts b/src/vs/workbench/contrib/chat/test/browser/voiceClient/voiceSessionController.test.ts index 7fd8db1404e681..d53a1100c7b3fc 100644 --- a/src/vs/workbench/contrib/chat/test/browser/voiceClient/voiceSessionController.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/voiceClient/voiceSessionController.test.ts @@ -12,7 +12,7 @@ import { Emitter, Event } from '../../../../../../base/common/event.js'; import { MarkdownString } from '../../../../../../base/common/htmlContent.js'; import { autorun, derived, ISettableObservable, observableFromEvent, observableValue } from '../../../../../../base/common/observable.js'; import { URI } from '../../../../../../base/common/uri.js'; -import { mock } from '../../../../../../base/test/common/mock.js'; +import { mock, upcastPartial } from '../../../../../../base/test/common/mock.js'; import { IAgentHostConnectionsService } from '../../../../../../platform/agentHost/common/agentHostConnectionsService.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; import { IAccessibilityService } from '../../../../../../platform/accessibility/common/accessibility.js'; @@ -40,7 +40,7 @@ import { IMicCaptureService } from '../../../browser/voiceClient/micCaptureServi import { ITtsPlaybackService } from '../../../browser/voiceClient/ttsPlaybackService.js'; import { isVoiceSessionActiveForInput, VoiceNewSessionPreparationResult, VoiceSessionController } from '../../../browser/voiceClient/voiceSessionController.js'; import { IVoiceToolDispatchDelegate, IVoiceToolDispatchService } from '../../../browser/voiceClient/voiceToolDispatchService.js'; -import { ChatSendResult, ConfirmedReason, ElicitationState, IChatConfirmation, IChatModelReference, IChatSendRequestOptions, IChatService, IChatToolInvocation, ToolConfirmKind } from '../../../common/chatService/chatService.js'; +import { ChatRequestQueueKind, ChatSendResult, ConfirmedReason, ElicitationState, IChatConfirmation, IChatModelReference, IChatSendRequestOptions, IChatService, IChatToolInvocation, ToolConfirmKind } from '../../../common/chatService/chatService.js'; import { IPromptsService } from '../../../common/promptSyntax/service/promptsService.js'; import { derivePendingId, isPendingIdResolved, IVoiceAudioResponse, IVoiceBargeIn, IVoiceCheckpointNarrationMetadata, IVoiceClientService, IVoiceDispatchResult, IVoiceFatalDisconnect, IVoiceNarrationAck, IVoiceNarrationSignal, IVoicePttStartOptions, IVoiceSessionContext, IVoiceSpeechStarted, IVoiceToolCall, IVoiceTranscription, markPendingIdResolved, peekPendingId, VoiceConfirmationType, VoiceNarrationKind, VOICE_AGENT_PROGRESS_SETTING } from '../../../common/voiceClient/voiceClientService.js'; import { IChatModel, IChatProgressResponseContent, IChatResponseModel } from '../../../common/model/chatModel.js'; @@ -578,6 +578,7 @@ class NonVisibleTargetChatService extends mock() { } as unknown as IChatResponseModel; private readonly _model = { sessionResource: this._resource, + requestInProgress: observableValue('requestInProgress', true), onDidChange: Event.None, lastRequest: { id: 'held-request', response: this.response }, getRequests: () => [{ id: 'held-request', response: this.response }], @@ -756,12 +757,18 @@ class MaterializingChatWidget extends mock() { constructor(resource: URI) { super(); - this.viewModel = { sessionResource: resource } as IChatWidget['viewModel']; + this.viewModel = upcastPartial>({ + sessionResource: resource, + model: upcastPartial({ requestInProgress: observableValue('requestInProgress', false) }), + }); } materialize(resource: URI): void { const previousSessionResource = this.viewModel?.sessionResource; - this.viewModel = { sessionResource: resource } as IChatWidget['viewModel']; + this.viewModel = upcastPartial>({ + sessionResource: resource, + model: upcastPartial({ requestInProgress: observableValue('requestInProgress', false) }), + }); this._onDidChangeViewModel.fire({ previousSessionResource, currentSessionResource: resource }); } @@ -3454,6 +3461,28 @@ suite('VoiceSessionController', () => { }); }); + for (const inProgress of [false, true]) { + test(`direct voice requests ${inProgress ? 'steer ongoing work' : 'send normally when idle'}`, async () => { + const chatService = new class extends TestChatService { + override getSession(): IChatModel { + return upcastPartial({ + requestInProgress: observableValue('requestInProgress', inProgress), + }); + } + }(); + const controller = createController( + new TestVoiceClientService(), undefined, undefined, undefined, undefined, + new TestConfigurationService({ 'agents.voice.handsFree': false }), chatService, + ); + const sendVoiceRequest = Reflect.get(controller, '_sendVoiceRequest') as (resource: URI, text: string) => Promise; + await sendVoiceRequest.call(controller, URI.parse('chat-session:/target'), 'Use TypeScript instead.'); + assert.deepStrictEqual(chatService.sendRequestOptions, [{ + isVoiceModeInput: false, + ...(inProgress ? { queue: ChatRequestQueueKind.Steering } : {}), + }]); + }); + } + test('delays, coalesces, and preserves throttled voice progress for the shown request', () => { const voiceClientService = new TestVoiceClientService(); const ttsPlaybackService = new TestTtsPlaybackService(); @@ -5146,6 +5175,35 @@ suite('VoiceSessionController', () => { assert.strictEqual(buildPendingPayload.call(controller, pendingPartsModel({ kind: 'questionCarousel', questions: [] })), undefined); }); + test('narrates the carousel-level question as well as the field title and choices', () => { + const controller = createController(new TestVoiceClientService()); + const questionNarratable = Reflect.get(controller, '_questionNarratable') as (model: IChatModel) => { text: string } | undefined; + const carousel = new ChatQuestionCarouselData([{ + id: 'behavior', + type: 'singleSelect', + title: 'Function behavior', + options: [ + { id: 'name', label: 'Accept a name and return { name }, like createTurtle', value: 'name' }, + { id: 'empty', label: 'Leave the function empty for now', value: 'empty' }, + ], + }], false, undefined, undefined, undefined, new MarkdownString('What should candyFactory do?')); + + assert.strictEqual(questionNarratable.call(controller, pendingPartsModel(carousel))?.text, + 'What should candyFactory do? Function behavior Options: 1, Accept a name and return { name }, like createTurtle. 2, Leave the function empty for now. You can also give your own answer.'); + }); + + test('narrates only the first numbered field when the carousel asks multiple questions', () => { + const controller = createController(new TestVoiceClientService()); + const questionNarratable = Reflect.get(controller, '_questionNarratable') as (model: IChatModel) => { text: string } | undefined; + const carousel = new ChatQuestionCarouselData([ + { id: 'filename', type: 'text', title: 'File name' }, + { id: 'contents', type: 'text', title: 'File contents' }, + ], false, undefined, undefined, undefined, new MarkdownString('What should the new file be named, and what should it contain?')); + + assert.strictEqual(questionNarratable.call(controller, pendingPartsModel(carousel))?.text, + 'Please answer one question at a time. Question 1 of 2: File name'); + }); + test('selects the oldest still-open pending part, not the newest', () => { // Voice is a serial channel: a second form arriving must not take the turn // from the one the user was just read out and is part-way through diff --git a/src/vs/workbench/contrib/chat/test/common/voiceClient/voiceLiveInputRouter.test.ts b/src/vs/workbench/contrib/chat/test/common/voiceClient/voiceLiveInputRouter.test.ts index 3f8d0c6ec67798..7d2cdb0606fc0b 100644 --- a/src/vs/workbench/contrib/chat/test/common/voiceClient/voiceLiveInputRouter.test.ts +++ b/src/vs/workbench/contrib/chat/test/common/voiceClient/voiceLiveInputRouter.test.ts @@ -29,6 +29,58 @@ suite('VoiceLiveInputRouter', () => { }; } + test('reads form context with a single question and its retry', () => { + const router = new VoiceLiveInputRouter(); + router.updateContext(context('chat-session:/a', { + ...questions, + message: 'What should candyFactory do?', + questions: [{ ...questions.questions![0], title: 'Function behavior' }], + })); + const initial = router.getQuestionPrompt('chat-session:/a', 'questions'); + const retry = router.resolve('retry', 'not a choice', router.captureTarget()).clarification; + assert.deepStrictEqual({ initial, retry }, { + initial: 'What should candyFactory do? Function behavior 1. West 2. East', + retry: 'Please say an exact choice or its number. What should candyFactory do? Function behavior 1. West 2. East', + }); + }); + + test('asks one numbered field at a time instead of a compound form question', () => { + const router = new VoiceLiveInputRouter(); + router.updateContext(context('chat-session:/a', { + ...questions, + message: 'What should the new file be named, and what should it contain?', + questions: [ + { id: 'filename', type: 'text', title: 'File name', allow_freeform: true, options: [] }, + { id: 'contents', type: 'text', title: 'File contents', allow_freeform: true, options: [] }, + ], + })); + const initial = router.getQuestionPrompt('chat-session:/a', 'questions'); + const first = router.resolve('filename', 'chocolate.ts', router.captureTarget()); + const current = router.getQuestionPrompt('chat-session:/a', 'questions'); + const final = router.resolve('contents', 'A function called chocolate', router.captureTarget()); + assert.deepStrictEqual({ initial, first, current, response: final.toolCall?.args.response }, { + initial: 'Please answer one question at a time. Question 1 of 2: File name', + first: { clarification: 'Question 2 of 2: File contents' }, + current: 'Question 2 of 2: File contents', + response: { type: 'answer', answers: [{ question_id: 'filename', freeform: 'chocolate.ts' }, { question_id: 'contents', freeform: 'A function called chocolate' }] }, + }); + }); + + test('normalizes question titles and form context before formatting or deduplicating them', () => { + const router = new VoiceLiveInputRouter(); + const prompts = [' Deployment settings ', ' Which region? '].map(message => { + router.updateContext(context('chat-session:/a', { + ...questions, message, + questions: [{ ...questions.questions![0], title: ' Which region? ' }], + })); + return router.getQuestionPrompt('chat-session:/a', 'questions'); + }); + assert.deepStrictEqual(prompts, [ + 'Deployment settings Which region? 1. West 2. East', + 'Which region? 1. West 2. East', + ]); + }); + test('omits reply guidance until a voice locale is known', () => { const router = new VoiceLiveInputRouter(); const guidance = () => [router.getQuestionReplyGuidance(), router.getApprovalReplyGuidance()]; @@ -119,7 +171,7 @@ suite('VoiceLiveInputRouter', () => { const first = router.resolve('first', 'option two', router.captureTarget()); const final = router.resolve('final', 'My deployment', router.captureTarget()); assert.deepStrictEqual({ first, final }, { - first: { clarification: 'What name?' }, + first: { clarification: 'Question 2 of 2: What name?' }, final: { toolCall: { callId: 'final', name: 'respond_to_session', args: { @@ -160,7 +212,7 @@ suite('VoiceLiveInputRouter', () => { router.resolve('new-first', 'first', router.captureTarget()); const final = router.resolve('new-second', 'New deployment', router.captureTarget()); assert.deepStrictEqual({ resetIndex, nextPrompt, stale: stale.clarification !== undefined, response: final.toolCall?.args.response }, { - resetIndex: 0, nextPrompt: 'Which region? 1. West 2. East', stale: true, + resetIndex: 0, nextPrompt: 'Please answer one question at a time. Question 1 of 2: Which region? 1. West 2. East', stale: true, response: { type: 'answer', answers: [{ question_id: 'region', value: 'new-westus' }, { question_id: 'name', freeform: 'New deployment' }] }, }); }); @@ -179,7 +231,7 @@ suite('VoiceLiveInputRouter', () => { firstB, staleA: staleA.clarification !== undefined, answers: finalA.toolCall?.args.response, }, { - firstB: { clarification: 'What name?' }, staleA: true, + firstB: { clarification: 'Question 2 of 2: What name?' }, staleA: true, answers: { type: 'answer', answers: [{ question_id: 'region', value: 'westus' }, { question_id: 'name', freeform: 'A deployment' }] }, }); }); @@ -411,9 +463,9 @@ suite('VoiceLiveInputRouter', () => { const next = router.resolve('first', 'second', router.captureTarget()); const final = router.resolve('final', 'My deployment', router.captureTarget()); assert.deepStrictEqual({ initial, invalid, next, response: final.toolCall?.args.response }, { - initial: 'Which region? 1. West 2. East Please answer by voice, or use the controls in chat.', - invalid: { clarification: 'Please say an exact choice or its number. Which region? 1. West 2. East Please answer by voice, or use the controls in chat.' }, - next: { clarification: 'What name? Please answer by voice, or use the controls in chat.' }, + initial: 'Please answer one question at a time. Question 1 of 2: Which region? 1. West 2. East Please answer by voice, or use the controls in chat.', + invalid: { clarification: 'Please say an exact choice or its number. Please answer one question at a time. Question 1 of 2: Which region? 1. West 2. East Please answer by voice, or use the controls in chat.' }, + next: { clarification: 'Question 2 of 2: What name? Please answer by voice, or use the controls in chat.' }, response: { type: 'answer', answers: [{ question_id: 'region', value: 'eastus' }, { question_id: 'name', freeform: 'My deployment' }] }, }); }); @@ -434,8 +486,8 @@ suite('VoiceLiveInputRouter', () => { const first = router.resolve('first', 'Osten', router.captureTarget()); const final = router.resolve('final', 'Meine Bereitstellung', router.captureTarget()); assert.deepStrictEqual({ prompt, first, response: final.toolCall?.args.response }, { - prompt: 'Welche Region? 1. Westen 2. Osten Please answer by voice, or use the controls in chat.', - first: { clarification: 'Welcher Name? Please answer by voice, or use the controls in chat.' }, + prompt: 'Please answer one question at a time. Question 1 of 2: Welche Region? 1. Westen 2. Osten Please answer by voice, or use the controls in chat.', + first: { clarification: 'Question 2 of 2: Welcher Name? Please answer by voice, or use the controls in chat.' }, response: { type: 'answer', answers: [{ question_id: 'region', value: 'eastus' }, { question_id: 'name', freeform: 'Meine Bereitstellung' }] }, }); }); @@ -477,7 +529,7 @@ suite('VoiceLiveInputRouter', () => { const prompt = router.getQuestionPrompt('chat-session:/a', 'questions'); const skipped = router.resolve('skip', 'skip', router.captureTarget()); assert.deepStrictEqual({ prompt, response: skipped.toolCall?.args.response }, { - prompt: 'What name?', response: { type: 'skip', answers: [{ question_id: 'region', value: 'westus' }] }, + prompt: 'Question 2 of 2: What name?', response: { type: 'skip', answers: [{ question_id: 'region', value: 'westus' }] }, }); }); diff --git a/src/vs/workbench/contrib/chat/test/common/voiceClient/voicePendingNarration.test.ts b/src/vs/workbench/contrib/chat/test/common/voiceClient/voicePendingNarration.test.ts index 2aa8ff9838891e..325124eed7c34d 100644 --- a/src/vs/workbench/contrib/chat/test/common/voiceClient/voicePendingNarration.test.ts +++ b/src/vs/workbench/contrib/chat/test/common/voiceClient/voicePendingNarration.test.ts @@ -55,6 +55,24 @@ suite('formatQuestionPrompt', () => { ); }); + test('reads the form-level question before its short field title and options', () => { + assert.strictEqual( + formatQuestionPrompt({ ...single, title: 'Function behavior' }, false, 'What should candyFactory do?'), + 'What should candyFactory do? Function behavior Options: 1, West US. 2, East US.', + ); + }); + + test('does not repeat form context that is also the question text', () => { + assert.strictEqual(formatQuestionPrompt(single, false, ' Which region? '), 'Which region? Options: 1, West US. 2, East US.'); + }); + + test('asks only the first numbered field of a multi-question form', () => { + assert.strictEqual( + formatQuestionPrompt({ ...text, title: 'File name' }, false, 'What should the new file be named, and what should it contain?', 2), + 'Please answer one question at a time. Question 1 of 2: File name', + ); + }); + test('appends the skip hint when the form allows skipping', () => { assert.strictEqual( formatQuestionPrompt(single, true),