Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(voice): select a default voice after model switches
JiangJiahaob40739af8eb3
diff --git a/apps/desktop/scripts/fixtures/voice-settings/ui-page.mjs b/apps/desktop/scripts/fixtures/voice-settings/ui-page.mjsindex 0386cd57d7..32ce99d456 100644--- a/apps/desktop/scripts/fixtures/voice-settings/ui-page.mjs+++ b/apps/desktop/scripts/fixtures/voice-settings/ui-page.mjs@@ -12,6 +12,30 @@ export default {'const empty = {}; export const EMPTY_LIGHT_STATE = empty; export const makerChatStore = { subscribeLight: () => () => {}, getLightSnapshot: () => empty };',},cases: {+ 'openrouter-auto-voice': {+ about: 'Switching to Qwen chooses its first returned voice; an explicit choice survives refresh',+ data: {+ autoVoice: true, openRouter: true, protocol: 'openai',+ modelId: 'elevenlabs/eleven-v3', voiceId: 'sarah',+ nextModelId: 'qwen/qwen-audio-3.0-tts-plus',+ nextVoices: [+ { id: 'longanlingxin', name: 'longanlingxin' },+ { id: 'longanlufeng', name: 'longanlufeng' },+ ],+ },+ },+ 'minimax-auto-voice': {+ about: 'Native BYOK model switching follows the same automatic voice selection rule',+ viewport: { width: 320, height: 900 },+ data: {+ autoVoice: true, protocol: 'minimax', modelId: 'speech-2.8-turbo',+ voiceId: 'English_Graceful_Lady', nextModelId: 'speech-2.8-hd',+ nextVoices: [+ { id: 'English_Graceful_Lady', name: 'Graceful Lady' },+ { id: 'Chinese (Mandarin)_News_Anchor', name: 'News Anchor' },+ ],+ },+ },openrouter: {about: 'OpenRouter provider voice IDs and no unsupported speed slider',data: { openRouter: true, protocol: 'openai', modelId: 'elevenlabs/eleven-v3', voiceId: 'sarah', speed: 1.5 },@@ -182,6 +206,33 @@ export default {}},async check(page, ui) {+ if (ui.data.autoVoice) {+ assert.equal(await page.evaluate(() => window.__uiPage.ctx.data.saveCount), 0);+ const modelLabel = await ui.t('bots.voiceMode.model');+ await page.getByRole('combobox', { name: modelLabel, exact: true }).click();+ await page.getByRole('option', {+ name: `${ui.data.nextModelId} · ${ui.data.openRouter ? 'OpenRouter' : 'MiniMax'}`,+ exact: true,+ }).click();+ await page.waitForFunction(() => window.__uiPage.ctx.data.savedModelId === window.__uiPage.ctx.data.nextModelId);+ const voiceLabel = await ui.t('bots.voiceMode.voice');+ const voicePicker = page.getByRole('button', { name: voiceLabel, exact: true });+ assert.equal(await voicePicker.getAttribute('value'), `voice:${ui.data.nextVoices[0].id}`);+ assert.equal(await page.evaluate(() => window.__uiPage.ctx.data.savedVoice), ui.data.nextVoices[0].id);+ assert.equal(await page.evaluate(() => window.__uiPage.ctx.data.previewRequests.length), 0);+ await ui.capture('automatic-voice');+ await voicePicker.click();+ await page.getByRole('dialog', { name: voiceLabel }).getByRole('button', { name: ui.data.nextVoices[1].name, exact: true }).click();+ await page.waitForFunction(() => window.__uiPage.ctx.data.saveCount === 2);+ const refreshButton = page.getByRole('button', { name: await ui.t('bots.voiceMode.refreshVoices'), exact: true });+ await refreshButton.click();+ await page.waitForFunction(label => !document.querySelector(`button[aria-label="${label}"]`)?.disabled, await ui.t('bots.voiceMode.refreshVoices'));+ assert.equal(await voicePicker.getAttribute('value'), `voice:${ui.data.nextVoices[1].id}`);+ assert.equal(await page.evaluate(() => window.__uiPage.ctx.data.savedVoice), ui.data.nextVoices[1].id);+ assert.equal(await page.evaluate(() => window.__uiPage.ctx.data.saveCount), 2);+ await ui.capture('explicit-voice-after-refresh');+ return;+ }if (ui.data.openRouter) {assert.equal(await page.getByRole('slider').count(), 0);await page.getByText(await ui.t('bots.voiceMode.speedUnavailable'), { exact: true }).waitFor();diff --git a/apps/desktop/scripts/fixtures/voice-settings/voice-settings-fixture.tsx b/apps/desktop/scripts/fixtures/voice-settings/voice-settings-fixture.tsxindex a78db154af..16f358680b 100644--- a/apps/desktop/scripts/fixtures/voice-settings/voice-settings-fixture.tsx+++ b/apps/desktop/scripts/fixtures/voice-settings/voice-settings-fixture.tsx@@ -4,6 +4,7 @@ import { alibabaSystemVoices } from '../../../src/shared/alibabaSpeechVoices';import { gatewayReferenceSpeechVoices } from '../../../src/shared/speechVoices';import type {SpeechProtocol,+ SpeechModelSelection,VoiceConversationPreference,VoiceConversationSelection,} from '../../../src/shared/voiceConversation';@@ -38,6 +39,7 @@ mountPage({ctx.data.previewRequests = previews;ctx.data.previewStops = stops;ctx.data.savedVoice = initialVoice;+ ctx.data.saveCount = 0;let preference: VoiceConversationPreference = {selection: {providerId,@@ -80,11 +82,24 @@ mountPage({defaultVoice: ctx.data.openRouter ? '' : referenceVoice,...(ctx.data.openRouter ? { speedRange: null } : {}),},+ ...(ctx.data.autoVoice ? [{+ id: String(ctx.data.nextModelId),+ name: String(ctx.data.nextModelId),+ providerId,+ providerName: ctx.data.openRouter ? 'OpenRouter' : 'MiniMax',+ agent,+ protocol,+ protocolLocked: true,+ defaultVoice: '',+ ...(ctx.data.openRouter ? { speedRange: null } : {}),+ }] : []),...(ctx.data.hidden ? [{ id: 'unchecked', name: 'Unchecked speech', providerId: 'fixture', agent: 'codex' as const, pickerVisible: false }] : []),...(ctx.data.hidden && !ctx.data.noPreference ? [{ id: 'visible', name: 'Visible speech', providerId: 'fixture', agent: 'codex' as const, protocol, protocolLocked: true, defaultVoice: 'river' }] : []),],- voices: async () =>- ctx.data.openRouter+ voices: async (route: SpeechModelSelection) =>+ ctx.data.autoVoice && route.modelId === ctx.data.nextModelId+ ? { source: 'provider', voices: ctx.data.nextVoices }+ : ctx.data.openRouter? { source: 'provider', voices: ['sarah', 'george'].map(id => ({ id, name: id })) }: ctx.data.gatewayReference? { source: 'reference', voices: gatewayVoices.map((voice) => ({ ...voice })) }@@ -136,6 +151,8 @@ mountPage({: (sentencePlayback ?? true),};ctx.data.savedVoice = preference.selection?.voice;+ ctx.data.savedModelId = preference.selection?.modelId;+ ctx.data.saveCount = Number(ctx.data.saveCount) + 1;return preference;},// Controlled synthesis boundary: never contacts a provider or emits audio.diff --git a/apps/desktop/src/renderer/features/bots/voice/CompanionVoiceSettings.tsx b/apps/desktop/src/renderer/features/bots/voice/CompanionVoiceSettings.tsxindex 0823f2f47d..898d0cab2a 100644--- a/apps/desktop/src/renderer/features/bots/voice/CompanionVoiceSettings.tsx+++ b/apps/desktop/src/renderer/features/bots/voice/CompanionVoiceSettings.tsx@@ -67,6 +67,9 @@ export function CompanionVoiceSettings(props: Props) {const [catalogError, setCatalogError] = useState(false);const [preference, setPreference] = useState<VoiceConversationSelection | null>(null);const [voice, setVoice] = useState<string>();+ // Only an explicit model switch may fill an empty voice from its catalog.+ // Opening, refreshing or resetting settings must not save inferred defaults.+ const [autoSelectVoice, setAutoSelectVoice] = useState(false);const [speed, setSpeed] = useState<number>();const [speedNotice, setSpeedNotice] = useState<number>();const [customized, setCustomized] = useState(false);@@ -130,6 +133,7 @@ export function CompanionVoiceSettings(props: Props) {setPreferenceError(false);setPreference(null);setVoice(undefined);+ setAutoSelectVoice(false);setSpeed(undefined);setSpeedNotice(undefined);setCustomized(false);@@ -171,6 +175,7 @@ export function CompanionVoiceSettings(props: Props) {++refreshVersion.current;++preferenceVersion.current;setPreferenceOwner(undefined);+ setAutoSelectVoice(false);void preview.stop();}});@@ -193,6 +198,7 @@ export function CompanionVoiceSettings(props: Props) {playback?: boolean | null,): Promise<boolean> => {if (pendingSave.current) return pendingSave.current;+ if (next !== undefined) setAutoSelectVoice(false);const version = preferenceVersion.current;setSaving(true);setPreferenceError(false);@@ -257,7 +263,7 @@ export function CompanionVoiceSettings(props: Props) {};const chooseModel = (key: string) => {const model = models.find((item) => voiceModelKey(item) === key);- if (!model) return;+ if (!model || (preference && voiceModelKey(preference) === key && selectedVoice)) return;const next = carrySpeed({providerId: model.providerId,agent: model.agent,@@ -270,6 +276,7 @@ export function CompanionVoiceSettings(props: Props) {setCustomized(true);setPreference(next);setVoice(next.voice);+ setAutoSelectVoice(!next.voice);if (normalizeVoiceConversationSelection(next) &&resolveVoiceConfiguration(models, next).protocol@@ -435,11 +442,13 @@ export function CompanionVoiceSettings(props: Props) {}}protocol={protocol}voice={selectedVoice}+ autoSelectFirstVoice={autoSelectVoice}speed={effectiveSpeed}disabled={!ready || saving || blocked}previewDisabled={!ready || saving || blocked || !props.sessionId}preview={preview}onChange={(value, save) => {+ setAutoSelectVoice(false);dirty.current = true;setVoice(value);const next = normalizeVoiceConversationSelection({diff --git a/apps/desktop/src/renderer/features/bots/voice/SpeechVoicePicker.tsx b/apps/desktop/src/renderer/features/bots/voice/SpeechVoicePicker.tsxindex d2cba75a2e..e8e1fd45e7 100644--- a/apps/desktop/src/renderer/features/bots/voice/SpeechVoicePicker.tsx+++ b/apps/desktop/src/renderer/features/bots/voice/SpeechVoicePicker.tsx@@ -31,6 +31,7 @@ type Props = {route: SpeechModelSelection;protocol?: SpeechProtocol;voice: string;+ autoSelectFirstVoice: boolean;speed?: number;children?: ReactNode;disabled: boolean;@@ -44,6 +45,7 @@ export function SpeechVoicePicker({route,protocol,voice,+ autoSelectFirstVoice,speed,children,disabled,@@ -157,6 +159,22 @@ export function SpeechVoicePicker({// user override. Main must resolve inferred protocols against its current catalog.}, [routeKey, revision]);+ useEffect(() => {+ // Reuse only this route's successful catalog. Manual input, including an+ // intentionally empty draft, always wins over a late catalog response.+ if (+ !autoSelectFirstVoice ||+ voice ||+ manual ||+ disabled ||+ currentCatalog?.phase !== 'ready' ||+ !isDataOwnerGenerationCurrent(owner)+ )+ return;+ const firstVoice = catalog?.voices[0]?.id;+ if (firstVoice) onChange(firstVoice, true);+ }, [autoSelectFirstVoice, voice, manual, disabled, currentCatalog, catalog, owner, onChange]);+useEffect(() => {if (currentCatalog?.phase !== 'ready' || !catalog || !voice) return;const label = voiceOptions.find((option) => option.value === `voice:${voice}`)?.label;diff --git a/apps/desktop/src/renderer/features/bots/voice/__tests__/CompanionVoiceSettings.test.tsx b/apps/desktop/src/renderer/features/bots/voice/__tests__/CompanionVoiceSettings.test.tsxindex f1354917ec..d08f6dc289 100644--- a/apps/desktop/src/renderer/features/bots/voice/__tests__/CompanionVoiceSettings.test.tsx+++ b/apps/desktop/src/renderer/features/bots/voice/__tests__/CompanionVoiceSettings.test.tsx@@ -1282,7 +1282,7 @@ it('keeps a known voice on refresh failure, allows explicit manual input, and pr);});-it('resets a voice when switching models on the same connection and ignores a late catalog', async () => {+it('selects the new model first voice and ignores a late catalog from the previous model', async () => {models = ['first', 'second'].map((id) => ({id,name: id,@@ -1331,9 +1331,116 @@ it('resets a voice when switching models on the same connection and ignores a lareleaseNew({ source: 'provider', voices: [{ id: 'new', name: 'New voice' }] }),);expect((await openVoices()).getByRole('button', { name: 'New voice' })).toBeTruthy();- expect(voicePicker().value).toBe('');+ expect(voicePicker().value).toBe('voice:new');expect(screen.queryByLabelText('bots.voiceMode.voiceId')).toBeNull();+ expect(window.electronAPI.voiceConversation.setPreference).toHaveBeenCalledExactlyOnceWith(+ 'bot',+ { providerId: 'mine', agent: 'codex', modelId: 'second', voice: 'new' },+ );+});++// Unit regression: the real settings/picker must finish an explicit model switch+// when its asynchronous catalog has voices but defaultVoice is empty. Existing+// settings tests only saved static defaults or expected this switch to stay blank.+const modelSwitchFixture = () => {+ models = ['first', 'second'].map((id) => ({+ id, name: id, providerId: 'mine', agent: 'codex', protocol: 'openai', protocolLocked: true,+ }));+ vi.mocked(window.electronAPI.voiceConversation.preference).mockResolvedValue({+ selection: { providerId: 'mine', agent: 'codex', modelId: 'first', voice: 'saved' },+ customized: true,+ });+ vi.mocked(window.electronAPI.voiceConversation.voices).mockResolvedValueOnce({+ source: 'provider', voices: [{ id: 'saved', name: 'Saved voice' }],+ });+};+const switchToSecondModel = async () => {+ await screen.findByText('Saved voice');+ fireEvent.change(screen.getByLabelText('bots.voiceMode.model'), {+ target: { value: voiceModelKey(models[1]) },+ });+ await waitFor(() => expect(window.electronAPI.voiceConversation.voices).toHaveBeenCalledTimes(2));+};++it.each([+ { source: 'provider', defaultVoice: '', expected: 'first-voice' },+ { source: 'reference', defaultVoice: '', expected: 'first-voice' },+ { source: 'provider', defaultVoice: 'preferred', expected: 'preferred' },+] as const)('completes a model switch using $source voices and default "$defaultVoice", without previewing or reselecting on refresh', async ({ source, defaultVoice, expected }) => {+ modelSwitchFixture();+ models[1].defaultVoice = defaultVoice;+ const voices = [+ { id: 'first-voice', name: 'First voice' },+ { id: 'preferred', name: 'Preferred voice' },+ ];+ vi.mocked(window.electronAPI.voiceConversation.voices).mockResolvedValue({ source, voices });+ renderSettings();+ await switchToSecondModel();+ await waitFor(() => expect(voicePicker().value).toBe(`voice:${expected}`));+ expect(window.electronAPI.voiceConversation.setPreference).toHaveBeenCalledExactlyOnceWith(+ 'bot', { providerId: 'mine', agent: 'codex', modelId: 'second', voice: expected },+ );+ vi.mocked(window.electronAPI.voiceConversation.voices).mockResolvedValue({ source, voices: [...voices].reverse() });+ fireEvent.click(screen.getByRole('button', { name: 'bots.voiceMode.refreshVoices' }));+ await waitFor(() => expect(window.electronAPI.voiceConversation.voices).toHaveBeenCalledTimes(3));+ expect(voicePicker().value).toBe(`voice:${expected}`);+ expect(window.electronAPI.voiceConversation.setPreference).toHaveBeenCalledTimes(1);+ expect(window.electronAPI.voiceConversation.preview).not.toHaveBeenCalled();+ expect(start).not.toHaveBeenCalled();+ expect(audio.start).not.toHaveBeenCalled();+});++it.each(['empty', 'failed'] as const)('keeps the previous saved route on a %s catalog and fills the pending model after a successful retry', async (outcome) => {+ modelSwitchFixture();+ if (outcome === 'failed')+ vi.mocked(window.electronAPI.voiceConversation.voices).mockRejectedValueOnce(new Error('offline'));+ else vi.mocked(window.electronAPI.voiceConversation.voices).mockResolvedValueOnce({ source: 'provider', voices: [] });+ renderSettings();+ await switchToSecondModel();+ expect((await screen.findByLabelText('bots.voiceMode.voiceId') as HTMLInputElement).value).toBe('');expect(window.electronAPI.voiceConversation.setPreference).not.toHaveBeenCalled();+ vi.mocked(window.electronAPI.voiceConversation.voices).mockResolvedValue({+ source: 'provider', voices: [{ id: 'available', name: 'Available voice' }],+ });+ fireEvent.click(screen.getByRole('button', { name: 'bots.voiceMode.refreshVoices' }));+ await waitFor(() => expect(voicePicker().value).toBe('voice:available'));+ expect(window.electronAPI.voiceConversation.setPreference).toHaveBeenCalledExactlyOnceWith(+ 'bot', { providerId: 'mine', agent: 'codex', modelId: 'second', voice: 'available' },+ );+});++it.each(['private-voice', ''])('preserves a manual voice draft "%s" against the pending model catalog', async (manualVoice) => {+ modelSwitchFixture();+ vi.mocked(window.electronAPI.voiceConversation.voices).mockResolvedValueOnce({ source: 'provider', voices: [] });+ renderSettings();+ await switchToSecondModel();+ const input = await screen.findByLabelText('bots.voiceMode.voiceId');+ let release!: (catalog: SpeechVoiceCatalog) => void;+ vi.mocked(window.electronAPI.voiceConversation.voices).mockReturnValueOnce(new Promise(resolve => { release = resolve; }));+ fireEvent.click(screen.getByRole('button', { name: 'bots.voiceMode.refreshVoices' }));+ await waitFor(() => expect(window.electronAPI.voiceConversation.voices).toHaveBeenCalledTimes(3));+ fireEvent.change(input, { target: { value: 'typing' } });+ fireEvent.change(input, { target: { value: manualVoice } });+ await act(async () => release({ source: 'provider', voices: [{ id: 'default', name: 'Default voice' }] }));+ expect((screen.getByLabelText('bots.voiceMode.voiceId') as HTMLInputElement).value).toBe(manualVoice);+ expect(voicePicker().value).toBe('manual');+ expect(window.electronAPI.voiceConversation.setPreference).not.toHaveBeenCalled();+});++it('discards pending automatic selection on reset and does not save defaults on page load', async () => {+ modelSwitchFixture();+ let release!: (catalog: SpeechVoiceCatalog) => void;+ vi.mocked(window.electronAPI.voiceConversation.voices).mockReturnValueOnce(new Promise(resolve => { release = resolve; }));+ renderSettings();+ await switchToSecondModel();+ vi.mocked(window.electronAPI.voiceConversation.voices).mockResolvedValue({+ source: 'provider', voices: [{ id: 'saved', name: 'Saved voice' }],+ });+ fireEvent.click(screen.getByRole('button', { name: 'bots.voiceMode.resetPreference' }));+ await waitFor(() => expect(window.electronAPI.voiceConversation.voices).toHaveBeenCalledTimes(3));+ await act(async () => release({ source: 'provider', voices: [{ id: 'late', name: 'Late voice' }] }));+ expect(voicePicker().value).toBe('');+ expect(window.electronAPI.voiceConversation.setPreference).toHaveBeenCalledExactlyOnceWith('bot', null, null);});it('flushes a manually typed voice before leaving and keeps the page open on save failure', async () => {diff --git a/docs/product-rules/companion-voice-mode.md b/docs/product-rules/companion-voice-mode.mdindex 0ead62deea..161b49b16f 100644--- a/docs/product-rules/companion-voice-mode.md+++ b/docs/product-rules/companion-voice-mode.md@@ -127,6 +127,7 @@ OpenRouter 没有统一的型号语速范围,部分上游会拒绝非默认值- **BYOK MiniMax**:调用 `<base>/get_voice`,`voice_type: all`,合并 `system_voice`、`voice_cloning`、`voice_generation`;名称与 ID 分开,缺名称时显示 ID。音色 ID 接受真实型号所需的空格、括号等字符,保留长度、控制字符和路径分隔符校验。[资料来源](https://platform.minimax.io/docs/api-reference/voice-management-get)。- 音色选项与当前选中项默认只显示名称及供应商提供的风格说明;同名音色附加短 ID 尾缀,尾缀冲突时延长至可区分,缺名称时回退为完整 ID。不提供已选音色的 ID 展示栏或复制入口;手动输入仅作为目录外音色的兜底。显示缩写不改变选择值、伙伴偏好或合成请求中的完整 ID,也不触发已有偏好重写。- 进入页面先读取该伙伴已保存的选择,并显示所选音色上次成功获取的名称,再后台刷新目录;名称变化只更新显示,不改选音色、不重写伙伴偏好。没有名称缓存时,在原选择框内显示加载状态,不提前判定已选音色缺失或展开手动输入框。同一路由刷新保留现有名称和列表,刷新失败保留已知名称并提供重试提示;没有已知名称且获取失败、返回空列表或成功获取后已选 ID 未收录时才进入手动输入兜底,用户也可主动选择手动输入。切换伙伴、连接、runtime、型号或接口后立即隔离旧列表,迟到结果不能覆盖当前页面。加载状态使用既有控件和 Spinner,不通过新增、移除一整块表单表达加载。+- 用户主动切换朗读模型时,优先使用该型号的已知默认音色;没有默认音色则在当前路由的音色目录成功返回后选择第一项,通过既有伙伴偏好保存完整选择,适用于所有供应商。空列表或查询失败不保存不完整选择,重试成功可继续补选;用户开始手动选择或输入(包括清空输入)后取消自动补选。打开页面、恢复默认和已有选择的目录刷新不触发补选或偏好重写;不跨模型沿用音色,不增加逐模型历史记忆,也不自动试听。实现与回归见 `CompanionVoiceSettings.tsx`、`SpeechVoicePicker.tsx` 与 `CompanionVoiceSettings.test.tsx`。- 目录请求只在 Main 使用当前连接的凭证,拒绝重定向,限制 15 秒、每页 2MB 和最多 1000 个音色 / 10 页;超过显示范围时提示手动输入兜底。账号、密钥或路由在请求期间变化则丢弃结果。账号专属完整音色列表只留在面板内存,不写入公共 Registry 或新的配置文件;已有伙伴偏好仅保存所选 ID,不自动迁移或重写。所选音色的显示名称单独缓存在现有 Renderer localStorage,按账号、伙伴、完整模型路由及音色 ID 匹配,每个账号最多 64 条,不含凭证或执行权限;重开、Renderer 重载后可复用,缓存损坏或不可用不影响真实配置。账号切换前发起的迟到请求不得写入缓存。- 用户点击试听后,以当前连接、型号、接口和音色合成短示例文本,并明确提示可能产生用量。复用既有 PCM 合成、解码和播放;不采集麦克风、不发送伙伴消息、不调用聊天模型,不使用供应商返回的任意 `preview_url`。试听结果表示这次调用结果,不持久标记整个账号或型号已验证。- 试听与语音模式/听写互斥,绑定可信窗口、账号和伙伴 canonical 任务。生成过程中也可停止;改选、隐藏页面、关面板、账号变化、系统挂起或权限阻塞时取消;开始语音前等待试听停止。窗口销毁与 60 秒总时限均释放 Main 的语音占用。晚到的结果不恢复播放、不覆盖新选择。