Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): add Qwen and CosyVoice native HTTP speech
JiangJiahao28ab21635bb6
diff --git a/apps/desktop/scripts/fixtures/voice-settings/ui-page.mjs b/apps/desktop/scripts/fixtures/voice-settings/ui-page.mjsindex 870d3b9cf0..72dceea5ff 100644--- a/apps/desktop/scripts/fixtures/voice-settings/ui-page.mjs+++ b/apps/desktop/scripts/fixtures/voice-settings/ui-page.mjs@@ -26,6 +26,26 @@ export default {about: 'OpenAI native speed range',data: { protocol: 'openai', modelId: 'gpt-4o-mini-tts', speed: 1.25 },},+ qwen: {+ about: 'Official Qwen3 HTTP reference voice, no unsupported speed control',+ data: { protocol: 'qwen-tts', modelId: 'qwen3-tts-flash', voiceId: 'Cherry' },+ },+ 'qwen-proxy': {+ about: 'Explicit Qwen HTTP proxy protocol in a narrow settings drawer',+ viewport: { width: 320, height: 900 },+ data: { protocol: 'qwen-tts', modelId: 'qwen3-tts-flash', voiceId: 'Cherry', custom: true },+ },+ cosyvoice: {+ about: 'CosyVoice HTTP proxy, reference voice and native speed range',+ viewport: { width: 320, height: 900 },+ data: {+ protocol: 'dashscope-tts',+ modelId: 'cosyvoice-v3-flash',+ voiceId: 'longanyang',+ speed: 1.5,+ custom: true,+ },+ },unsupported: {about: 'Eleven v3 keeps voice and preview but does not offer a speed slider',data: { modelId: 'eleven_v3' },@@ -59,7 +79,12 @@ export default {else if (await page.evaluate(() => window.__uiPage.ctx.data.manual)) {const label = await page.evaluate(() => window.__uiPage.t('bots.voiceMode.voiceId'));await page.getByRole('textbox', { name: label, exact: true }).waitFor();- } else await page.getByText('River — Relaxed, Neutral, Informative').waitFor();+ } else {+ const voice = await page.evaluate(() => window.__uiPage.ctx.data.voiceId);+ await page+ .getByText(voice ?? 'River — Relaxed, Neutral, Informative', { exact: true })+ .waitFor();+ }if (await page.evaluate(() => window.__uiPage.ctx.data.menu)) {const label = await page.evaluate(() => window.__uiPage.t('bots.voiceMode.voice'));await page.getByRole('button', { name: label, exact: true }).click();@@ -160,9 +185,9 @@ export default {return;}const slider = page.getByRole('slider', { name: await ui.t('bots.voiceMode.speed') });- if (ui.data.empty || ui.case === 'unsupported') {+ if (ui.data.empty || ui.case === 'unsupported' || ui.data.protocol === 'qwen-tts') {assert.equal(await slider.count(), 0);- if (ui.case === 'unsupported')+ if (ui.case === 'unsupported' || ui.data.protocol === 'qwen-tts')await page.getByText(await ui.t('bots.voiceMode.speedUnavailable')).waitFor();return;}@@ -175,6 +200,10 @@ export default {await page.getByRole('button', { name: await ui.t('bots.voiceMode.resetPreference'), exact: true }).click();- assert.equal(Number(await slider.getAttribute('aria-valuenow')), 1);+ if (ui.data.custom) {+ // Reset removes the proxy override. With no detected protocol, settings+ // correctly waits for an explicit interface choice before exposing speed.+ assert.equal(await slider.count(), 0);+ } else assert.equal(Number(await slider.getAttribute('aria-valuenow')), 1);},};diff --git a/apps/desktop/scripts/fixtures/voice-settings/voice-settings-fixture.tsx b/apps/desktop/scripts/fixtures/voice-settings/voice-settings-fixture.tsxindex c0f554bf9b..65cee5bf22 100644--- a/apps/desktop/scripts/fixtures/voice-settings/voice-settings-fixture.tsx+++ b/apps/desktop/scripts/fixtures/voice-settings/voice-settings-fixture.tsx@@ -17,7 +17,8 @@ mountPage({host: (ctx) => {const protocol = (ctx.data.protocol ?? 'elevenlabs') as SpeechProtocol;const modelId = String(ctx.data.modelId ?? 'eleven_flash_v2_5');- const initialVoice = ctx.data.manual ? 'custom-voice' : 'river';+ const referenceVoice = String(ctx.data.voiceId ?? 'river');+ const initialVoice = ctx.data.manual ? 'custom-voice' : referenceVoice;const pending = new Map<string, () => void>();const previews: Array<{ voice: string; speed?: number; previewId: string }> = [];const stops: string[] = [];@@ -30,6 +31,7 @@ mountPage({agent: 'codex',modelId,voice: initialVoice,+ ...(ctx.data.custom ? { protocol } : {}),...(typeof ctx.data.speed === 'number' ? { speed: ctx.data.speed } : {}),},customized: ctx.data.speed !== undefined || !!ctx.data.manual,@@ -53,17 +55,22 @@ mountPage({? 'ElevenLabs': protocol === 'minimax'? 'MiniMax'- : 'OpenAI',+ : protocol === 'qwen-tts' || protocol === 'dashscope-tts'+ ? 'Alibaba Cloud'+ : 'OpenAI',agent: 'codex',- protocol,- protocolLocked: true,- defaultVoice: 'river',+ protocol: ctx.data.custom ? undefined : protocol,+ protocolLocked: !ctx.data.custom,+ defaultVoice: referenceVoice,},],voices: async () => ({- source: 'provider',+ source: ctx.data.voiceId ? 'reference' : 'provider',voices: [- { id: 'river', name: 'River — Relaxed, Neutral, Informative' },+ {+ id: referenceVoice,+ name: ctx.data.voiceId ? referenceVoice : 'River — Relaxed, Neutral, Informative',+ },...(ctx.data.menu? [{ id: 'bella', name: 'Bella — Professional, Bright, Warm' },diff --git a/apps/desktop/src/main/voice-conversation/__tests__/models.test.ts b/apps/desktop/src/main/voice-conversation/__tests__/models.test.tsindex c23fc17301..6922290ab2 100644--- a/apps/desktop/src/main/voice-conversation/__tests__/models.test.ts+++ b/apps/desktop/src/main/voice-conversation/__tests__/models.test.ts@@ -309,3 +309,111 @@ it.each(['openai', 'elevenlabs', 'minimax'] as const)(});},);++// Unit tier, real catalog -> connection projection. HTTP protocol selection must+// bind both documented model and official origin; a matching brand is insufficient.+it.each([+ ['https://dashscope.aliyuncs.com/compatible-mode/v1', 'qwen3-tts-flash', 'qwen-tts', 'Cherry'],+ [+ 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1',+ 'qwen3-tts-flash',+ 'qwen-tts',+ 'Cherry',+ ],+ [+ 'https://work.cn-beijing.maas.aliyuncs.com/compatible-mode/v1',+ 'cosyvoice-v3-flash',+ 'dashscope-tts',+ 'longanyang',+ ],+ ['https://work.cn-beijing.maas.aliyuncs.com/api/v1', 'cosyvoice-v3.5-plus', 'dashscope-tts', ''],+ [+ 'https://work.ap-southeast-1.maas.aliyuncs.com/api/v1',+ 'qwen-audio-3.1-tts-flash',+ 'dashscope-tts',+ 'longanhuan_v3.1',+ ],+ [+ 'https://work.ap-southeast-1.maas.aliyuncs.com/api/v1',+ 'qwen-audio-3.0-tts-plus',+ 'dashscope-tts',+ '',+ ],+] as const)(+ 'binds %s %s to its verified HTTP adapter',+ (baseUrl, modelId, protocol, defaultVoice) => {+ const d = deps([+ custom('ali', baseUrl, [+ { id: modelId, name: modelId, mode: 'audio_speech', nativeApi: null },+ ]),+ ]);+ expect(speechModels(d)[0]).toMatchObject({ protocol, protocolLocked: true, defaultVoice });+ expect(+ resolveSpeechConnection(d, {+ providerId: 'ali',+ agent: 'codex',+ modelId,+ protocol: 'elevenlabs',+ }),+ ).toEqual({+ protocol,+ baseUrl: `${new URL(baseUrl).origin}/api/v1`,+ headers: { authorization: 'Bearer ali-codex-key' },+ });+ if (protocol === 'qwen-tts')+ expect(() =>+ resolveSpeechConnection(d, {+ providerId: 'ali',+ agent: 'codex',+ modelId,+ voice: 'Cherry',+ speed: 1,+ }),+ ).toThrow('invalid_speech_speed');+ },+);+it.each([+ ['https://dashscope.aliyuncs.com/api/v1', 'qwen3-tts-flash-realtime'],+ ['https://dashscope.aliyuncs.com/api/v1', 'qwen-future-tts'],+ ['https://dashscope.aliyuncs.com/api/v1', 'cosyvoice-v3-flash'],+ ['https://work.ap-southeast-1.maas.aliyuncs.com/api/v1', 'cosyvoice-v3-flash'],+ ['https://dashscope.aliyuncs.com.untrusted.test/api/v1', 'qwen3-tts-flash'],+ ['http://dashscope.aliyuncs.com/api/v1', 'qwen3-tts-flash'],+ ['https://dashscope.aliyuncs.com:8443/api/v1', 'qwen3-tts-flash'],+])(+ 'does not infer native HTTP from an unsupported model/region/origin: %s %s',+ (baseUrl, modelId) => {+ const d = deps([+ custom('ali', baseUrl, [+ { id: modelId, name: modelId, mode: 'audio_speech', nativeApi: null },+ ]),+ ]);+ expect(speechModels(d)[0]?.protocol).toBeUndefined();+ expect(() =>+ resolveSpeechConnection(d, { providerId: 'ali', agent: 'codex', modelId }),+ ).toThrow('model_unavailable');+ },+);+it.each(['qwen-tts', 'dashscope-tts'] as const)(+ 'keeps explicit %s proxy choices on the same origin, prefix and key',+ (protocol) => {+ const d = deps([+ custom('proxy', 'https://proxy.test/tenant/api/v1', [+ { id: 'speech', name: 'Speech', mode: 'audio_speech', nativeApi: null },+ ]),+ ]);+ expect(speechModels(d)[0].protocolLocked).toBe(false);+ expect(+ resolveSpeechConnection(d, {+ providerId: 'proxy',+ agent: 'codex',+ modelId: 'speech',+ protocol,+ }),+ ).toEqual({+ protocol,+ baseUrl: 'https://proxy.test/tenant/api/v1',+ headers: { authorization: 'Bearer proxy-codex-key' },+ });+ },+);diff --git a/apps/desktop/src/main/voice-conversation/__tests__/preferences.test.ts b/apps/desktop/src/main/voice-conversation/__tests__/preferences.test.tsindex ef41437d19..507c152d40 100644--- a/apps/desktop/src/main/voice-conversation/__tests__/preferences.test.ts+++ b/apps/desktop/src/main/voice-conversation/__tests__/preferences.test.ts@@ -82,3 +82,26 @@ it('defaults to sentence playback, keeps explicit choices across reloads and res.conversationSentencePlayback,).toEqual({ valid: false });});++// Unit tier: exercise the persisted-settings normalizer, not just the UI type;+// native overrides must survive reopen without altering another companion.+it.each(['qwen-tts', 'dashscope-tts'] as const)(+ 'preserves the %s native override across settings reload and reset',+ (protocol) => {+ const choice = { ...a, protocol, modelId: 'private-tts', voice: 'my-clone' };+ const settings = normalizeVoiceInputSettings(+ JSON.parse(+ JSON.stringify({+ conversationSelections: { native: choice, existing: b },+ }),+ ),+ );+ expect(companionVoicePreference(settings, 'native').selection).toEqual(choice);+ const reset = normalizeVoiceInputSettings({+ ...settings,+ conversationSelections: updateCompanionVoicePreference(settings, 'native', null),+ });+ expect(companionVoicePreference(reset, 'native').selection).toBeNull();+ expect(companionVoicePreference(reset, 'existing').selection).toEqual(b);+ },+);diff --git a/apps/desktop/src/main/voice-conversation/__tests__/speech.test.ts b/apps/desktop/src/main/voice-conversation/__tests__/speech.test.tsindex 5e6e849822..966e1161cc 100644--- a/apps/desktop/src/main/voice-conversation/__tests__/speech.test.ts+++ b/apps/desktop/src/main/voice-conversation/__tests__/speech.test.ts@@ -128,7 +128,10 @@ describe('speech transport', () => {});});-function nativeSession(protocol: 'openai' | 'elevenlabs' | 'minimax', response: Response) {+function nativeSession(+ protocol: import('../../../shared/voiceConversation.js').SpeechProtocol,+ response: Response,+) {const fetcher = vi.fn(async () => response);const speech = new SpeechSynthesisSession({connection: () => ({@@ -277,21 +280,245 @@ it('rejects a truncated MiniMax stream instead of claiming completion', async ()await expect(speech.read('one')).rejects.toThrow('format');});-it('cancels a MiniMax read waiting for the remainder of an SSE event', async () => {- const cancelled = vi.fn();- const body = new ReadableStream<Uint8Array>({- start(c) {- c.enqueue(new TextEncoder().encode('data: {'));- },- cancel: cancelled,- });+it.each(['minimax', 'qwen-tts', 'dashscope-tts'] as const)(+ 'cancels a pending %s SSE frame at its reader',+ async (protocol) => {+ const cancelled = vi.fn();+ const body = new ReadableStream<Uint8Array>({+ start(c) {+ c.enqueue(new TextEncoder().encode('data: {'));+ },+ cancel: cancelled,+ });+ const { speech } = nativeSession(+ protocol,+ new Response(body, { headers: { 'Content-Type': 'text/event-stream' } }),+ );+ await speech.start(input);+ const reading = speech.read('one');+ speech.cancel();+ await expect(reading).rejects.toThrow('cancelled');+ expect(cancelled).toHaveBeenCalledOnce();+ },+);++// Unit tier, real SpeechSynthesisSession entry: native SSE is not raw PCM and+// long Qwen replies need multiple requests. Existing MiniMax hex cases cannot+// catch Base64 corruption, URL aggregate replay, or cancellation between segments.+const dashscopeEvents = (bytes = [1, 2]) => [+ { output: { finish_reason: null, audio: { data: Buffer.from(bytes).toString('base64') } } },+ { output: { finish_reason: 'stop', audio: { data: '', url: 'https://audio.test/aggregate' } } },+];+it.each(['qwen-tts', 'dashscope-tts'] as const)(+ 'decodes %s Base64 SSE and ignores the complete-file URL',+ async (protocol) => {+ const { speech, fetcher } = nativeSession(protocol, sse(dashscopeEvents()));+ await speech.start({+ ...input,+ modelId: 'qwen3-tts-flash',+ voice: 'Cherry',+ ...(protocol === 'dashscope-tts' ? { speed: 1.5 } : {}),+ });+ const [url, request] = vi.mocked(fetcher as typeof fetch).mock.calls[0];+ expect(String(url)).toBe(+ 'https://provider.test/proxy/v1/services/' ++ (protocol === 'qwen-tts'+ ? 'aigc/multimodal-generation/generation'+ : 'audio/tts/SpeechSynthesizer'),+ );+ expect(request?.headers).toMatchObject({+ authorization: 'Bearer test-mini-key',+ 'x-dashscope-sse': 'enable',+ });+ expect(JSON.parse(String(request?.body))).toEqual({+ model: 'qwen3-tts-flash',+ input: {+ text: 'hello',+ voice: 'Cherry',+ ...(protocol === 'dashscope-tts' ? { format: 'pcm', sample_rate: 24000, rate: 1.5 } : {}),+ },+ });+ expect([...new Uint8Array((await speech.read('one')).pcm)]).toEqual([1, 2]);+ expect((await speech.read('one')).done).toBe(true);+ expect(fetcher).toHaveBeenCalledOnce();+ },+);+it('joins multi-line data and fragmented UTF-8 before decoding Qwen PCM', async () => {+ const data =+ ': keepalive\r\ndata: {"output": {"original_text": "你好",\r\ndata: "audio":{"data":"AQI="},"finish_reason":null}}\r\n\r\n' ++ 'data: {"output":{"finish_reason":"stop"}}\r\n\r\ndata: [DONE]\r\n\r\n';const { speech } = nativeSession(- 'minimax',- new Response(body, { headers: { 'Content-Type': 'text/event-stream' } }),+ 'qwen-tts',+ new Response(+ new ReadableStream({+ start(controller) {+ for (const byte of new TextEncoder().encode(data))+ controller.enqueue(new Uint8Array([byte]));+ controller.close();+ },+ }),+ { headers: { 'Content-Type': 'text/event-stream' } },+ ),);await speech.start(input);- const reading = speech.read('one');- speech.cancel();- await expect(reading).rejects.toThrow('cancelled');+ expect([...new Uint8Array((await speech.read('one')).pcm)]).toEqual([1, 2]);+ expect((await speech.read('one')).done).toBe(true);+});+it.each([+ [{ code: 'QuotaExceeded', message: 'private upstream text' }],+ [{ output: { audio: { data: 'AQI?' }, finish_reason: 'stop' } }],+ [{ output: { audio: { data: 'AQJ=' }, finish_reason: 'stop' } }],+ [{ output: { audio: { data: 'AQ==' }, finish_reason: 'stop' } }],+ [{ output: { finish_reason: 'stop', audio: { url: 'https://audio.test/aggregate' } } }],+ [{ output: { finish_reason: 'length' } }],+ [dashscopeEvents()[0]],+])(+ 'refuses incomplete, invalid or failed native SSE %# without replaying a URL',+ async (...events) => {+ const { speech, fetcher } = nativeSession('dashscope-tts', sse(events));+ await speech.start(input);+ await expect(+ (async () => {+ while (!(await speech.read('one')).done) {+ /* drain */+ }+ })(),+ ).rejects.toThrow(/^(format|request)$/);+ expect(fetcher).toHaveBeenCalledOnce();+ },+);+it.each([+ ['qwen-tts', 1],+ ['dashscope-tts', 0.4],+ ['dashscope-tts', 2.1],+] as const)('rejects unsupported %s speed %s before fetching', async (protocol, speed) => {+ const { speech, fetcher } = nativeSession(protocol, sse(dashscopeEvents()));+ await expect(speech.start({ ...input, speed })).rejects.toThrow('unavailable');+ expect(fetcher).not.toHaveBeenCalled();+});+function segmentedSession(fetcher = vi.fn<typeof fetch>(async () => sse(dashscopeEvents()))) {+ const assertCurrent = vi.fn();+ const speech = new SpeechSynthesisSession({+ connection: () => ({+ baseUrl: 'https://dashscope-intl.aliyuncs.com/api/v1',+ protocol: 'qwen-tts',+ headers: {},+ }),+ assertCurrent,+ fetch: fetcher,+ });+ return { speech, fetcher, assertCurrent };+}+it('pulls long Qwen text sequentially without lost text, broken Unicode or replayed audio', async () => {+ const { speech, fetcher } = segmentedSession();+ const text = 'a'.repeat(599) + '😀' + '中文。'.repeat(210);+ await speech.start({ ...input, text });+ expect(fetcher).toHaveBeenCalledOnce();+ const pcm: number[] = [];+ while (true) {+ const chunk = await speech.read('one');+ pcm.push(...new Uint8Array(chunk.pcm));+ if (chunk.done) break;+ }+ const texts = fetcher.mock.calls.map(+ ([, request]) => JSON.parse(String(request?.body)).input.text as string,+ );+ expect(texts.length).toBeGreaterThan(2);+ expect(texts.join('')).toBe(text);+ expect(+ texts.every(+ (part) =>+ part.length <= 600 && !/[\uD800-\uDBFF]$/.test(part) && !/^[\uDC00-\uDFFF]/.test(part),+ ),+ ).toBe(true);+ expect(pcm).toEqual(texts.flatMap(() => [1, 2]));+});+it.each(['cancel', 'owner-change'] as const)(+ 'prevents the next paid Qwen segment after %s',+ async (action) => {+ const { speech, fetcher, assertCurrent } = segmentedSession();+ await speech.start({ ...input, text: 'a'.repeat(1201) });+ await speech.read('one');+ if (action === 'cancel') speech.cancel();+ else+ assertCurrent.mockImplementation(() => {+ throw new Error('owner changed');+ });+ await expect(speech.read('one')).rejects.toThrow();+ expect(fetcher).toHaveBeenCalledOnce();+ },+);+it('cancels late segment headers and keeps the replacement speech reader', async () => {+ let release!: (response: Response) => void;+ const cancelled = vi.fn();+ let started!: () => void;+ const headersPending = new Promise<void>((resolve) => {+ started = resolve;+ });+ const fetcher = vi+ .fn<typeof fetch>()+ .mockResolvedValueOnce(sse(dashscopeEvents()))+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ release = resolve;+ started();+ }),+ )+ .mockResolvedValueOnce(sse(dashscopeEvents([3, 4])));+ const { speech } = segmentedSession(fetcher);+ await speech.start({ ...input, text: 'a'.repeat(1201) });+ await speech.read('one');+ const oldRead = speech.read('one');+ const rejected = expect(oldRead).rejects.toThrow('cancelled');+ await headersPending;+ expect(fetcher).toHaveBeenCalledTimes(2);+ await speech.start({ ...input, requestId: 'two' });+ release(+ new Response(new ReadableStream({ cancel: cancelled }), {+ headers: { 'Content-Type': 'text/event-stream' },+ }),+ );+ await rejected;expect(cancelled).toHaveBeenCalledOnce();+ expect([...new Uint8Array((await speech.read('two')).pcm)]).toEqual([3, 4]);+ expect((await speech.read('two')).done).toBe(true);+ expect(fetcher).toHaveBeenCalledTimes(3);+});++it('keeps the safe headers-timeout diagnostic and aborts native synthesis', async () => {+ vi.useFakeTimers();+ try {+ const diagnostic = vi.fn();+ const fetcher = vi.fn<typeof fetch>(+ (_url, init) =>+ new Promise((_resolve, reject) => {+ init?.signal?.addEventListener(+ 'abort',+ () => reject(new Error('private network detail')),+ { once: true },+ );+ }),+ );+ const speech = new SpeechSynthesisSession({+ connection: () => ({+ baseUrl: 'https://provider.test/api/v1',+ protocol: 'qwen-tts',+ headers: {},+ }),+ assertCurrent: () => {},+ fetch: fetcher,+ diagnostic,+ });+ const result = expect(speech.start(input)).rejects.toThrow('request');+ await vi.advanceTimersByTimeAsync(30_000);+ await result;+ expect(+ diagnostic.mock.calls.map(([event]) => event).filter((event) => event.stage === 'error'),+ ).toEqual([expect.objectContaining({ code: 'headers_timeout' })]);+ expect(JSON.stringify(diagnostic.mock.calls)).not.toContain('private network detail');+ expect(fetcher).toHaveBeenCalledOnce();+ } finally {+ vi.useRealTimers();+ }});diff --git a/apps/desktop/src/main/voice-conversation/__tests__/voices.test.ts b/apps/desktop/src/main/voice-conversation/__tests__/voices.test.tsindex a0e52114f5..951cf12dd6 100644--- a/apps/desktop/src/main/voice-conversation/__tests__/voices.test.ts+++ b/apps/desktop/src/main/voice-conversation/__tests__/voices.test.ts@@ -181,3 +181,35 @@ describe('provider voice catalogs', () => {}});});++// Unit tier: native references must not accidentally fall through to ElevenLabs+// account discovery or invent a default for clone-only/unknown model variants.+it.each([+ ['qwen-tts', 'qwen3-tts-flash', 'Cherry'],+ ['qwen-tts', 'qwen3-tts-flash-realtime', undefined],+ ['dashscope-tts', 'cosyvoice-v3-flash', 'longanyang'],+ ['dashscope-tts', 'qwen-audio-3.1-tts-flash', 'longanhuan_v3.1'],+ ['dashscope-tts', 'cosyvoice-v3.5-plus', undefined],+ ['dashscope-tts', 'private-model', undefined],+] as const)(+ 'loads %s %s reference/manual voices without network discovery',+ async (protocol, modelId, voice) => {+ const fetcher = vi.fn();+ expect(await loadSpeechVoices(connection(protocol), modelId, fetcher, () => {})).toEqual({+ source: voice ? 'reference' : 'manual',+ voices: voice ? [{ id: voice, name: voice }] : [],+ });+ expect(fetcher).not.toHaveBeenCalled();+ const choice = {+ providerId: 'ali',+ agent: 'codex',+ modelId,+ protocol,+ voice: voice ?? 'account-clone',+ };+ expect(normalizeVoiceConversationSelection(choice)).toEqual(choice);+ expect(+ normalizeVoiceConversationSelection({ ...choice, providerId: 'xd', agent: undefined }),+ ).toBeUndefined();+ },+);diff --git a/apps/desktop/src/main/voice-conversation/adapters/dashscope.ts b/apps/desktop/src/main/voice-conversation/adapters/dashscope.tsnew file mode 100644index 0000000000..b8dc2c5e19--- /dev/null+++ b/apps/desktop/src/main/voice-conversation/adapters/dashscope.ts@@ -0,0 +1,91 @@+import type { SpeechAdapter } from './types.js';+import { SpeechError } from '../speechError.js';+import { ssePcmStream } from './sse.js';++// Qwen3-TTS HTTP and Qwen-Audio/CosyVoice HTTP use distinct request contracts.+// Both return Base64 24 kHz mono PCM through SSE, not the final downloadable URL.+// https://www.alibabacloud.com/help/en/model-studio/qwen-tts-api+// https://www.alibabacloud.com/help/en/model-studio/qwen-audio-tts-http-api+// https://www.alibabacloud.com/help/en/model-studio/cosyvoice-tts-http-api+export const qwenSpeechAdapter: SpeechAdapter = {+ contentTypes: ['text/event-stream'],+ request(prefix, input) {+ return {+ url: new URL(`${prefix}/services/aigc/multimodal-generation/generation`),+ headers: { 'x-dashscope-sse': 'enable' },+ body: JSON.stringify({+ model: input.modelId,+ input: { text: input.text, voice: input.voice },+ }),+ };+ },+ pcm: dashscopePcmStream,+};+export const dashscopeSpeechAdapter: SpeechAdapter = {+ contentTypes: ['text/event-stream'],+ request(prefix, input) {+ return {+ url: new URL(`${prefix}/services/audio/tts/SpeechSynthesizer`),+ headers: { 'x-dashscope-sse': 'enable' },+ body: JSON.stringify({+ model: input.modelId,+ input: {+ text: input.text,+ voice: input.voice,+ format: 'pcm',+ sample_rate: 24000,+ ...(input.speed !== undefined ? { rate: input.speed } : {}),+ },+ }),+ };+ },+ pcm: dashscopePcmStream,+};++function dashscopePcmStream(body: ReadableStream<Uint8Array>): ReadableStream<Uint8Array> {+ let finished = false;+ return ssePcmStream(+ body,+ (raw) => {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new SpeechError('format');+ const event = raw as {+ code?: unknown;+ status_code?: unknown;+ output?: {+ finish_reason?: unknown;+ audio?: { data?: unknown };+ };+ };+ if (+ (event.code !== undefined && event.code !== '') ||+ (event.status_code !== undefined && event.status_code !== 200)+ )+ throw new SpeechError('request');+ const output = event.output;+ if (!output || typeof output !== 'object' || finished) throw new SpeechError('format');+ if (+ output.finish_reason !== undefined &&+ output.finish_reason !== null &&+ output.finish_reason !== 'stop'+ )+ throw new SpeechError('format');+ finished = output.finish_reason === 'stop';+ const data = output.audio?.data;+ // Sentence boundary events and the final URL do not contain PCM. Never fetch+ // that URL: it is the aggregate and must not be replayed or receive our key.+ if (data === undefined || data === '') return;+ if (+ typeof data !== 'string' ||+ data.length > 1_398_104 ||+ data.length % 4 !== 0 ||+ /[^A-Za-z0-9+/=]/.test(data)+ )+ throw new SpeechError('format');+ const bytes = Buffer.from(data, 'base64');+ // Buffer accepts malformed padding/non-canonical encodings; reject them.+ if (bytes.toString('base64') !== data) throw new SpeechError('format');+ return Uint8Array.from(bytes);+ },+ () => finished,+ );+}diff --git a/apps/desktop/src/main/voice-conversation/adapters/elevenlabs.ts b/apps/desktop/src/main/voice-conversation/adapters/elevenlabs.tsnew file mode 100644index 0000000000..328bc76521--- /dev/null+++ b/apps/desktop/src/main/voice-conversation/adapters/elevenlabs.ts@@ -0,0 +1,18 @@+import type { SpeechAdapter } from './types.js';++export const elevenlabsSpeechAdapter: SpeechAdapter = {+ contentTypes: ['audio/pcm', 'audio/x-pcm', 'application/octet-stream'],+ request(prefix, input) {+ return {+ url: new URL(+ `${prefix}/text-to-speech/${encodeURIComponent(input.voice)}/stream?output_format=pcm_24000`,+ ),+ body: JSON.stringify({+ model_id: input.modelId,+ text: input.text,+ ...(input.speed !== undefined ? { voice_settings: { speed: input.speed } } : {}),+ }),+ };+ },+ pcm: (body) => body,+};diff --git a/apps/desktop/src/main/voice-conversation/adapters/minimax.ts b/apps/desktop/src/main/voice-conversation/adapters/minimax.tsnew file mode 100644index 0000000000..f7535fbe61--- /dev/null+++ b/apps/desktop/src/main/voice-conversation/adapters/minimax.ts@@ -0,0 +1,74 @@+import { ssePcmStream } from './sse.js';+import type { SpeechAdapter } from './types.js';+import { SpeechError } from '../speechError.js';++export const minimaxSpeechAdapter: SpeechAdapter = {+ contentTypes: ['text/event-stream', 'application/json'],+ request(prefix, input) {+ return {+ url: new URL(`${prefix}/t2a_v2`),+ body: JSON.stringify({+ model: input.modelId,+ text: input.text,+ stream: true,+ stream_options: { exclude_aggregated_audio: true },+ output_format: 'hex',+ voice_setting: {+ voice_id: input.voice,+ ...(input.speed !== undefined ? { speed: input.speed } : {}),+ },+ audio_setting: { format: 'pcm', sample_rate: 24000, channel: 1 },+ }),+ };+ },+ pcm: miniMaxPcmStream,+};++/** MiniMax terminal audio is an aggregate, never another chunk.+ * https://platform.minimax.io/docs/api-reference/speech-t2a-http */+function miniMaxPcmStream(body: ReadableStream<Uint8Array>): ReadableStream<Uint8Array> {+ let finished = false;+ return ssePcmStream(+ body,+ (raw) => {+ if (!raw || typeof raw !== 'object') throw new SpeechError('format');+ const event = raw as {+ base_resp?: { status_code?: number };+ extra_info?: {+ audio_sample_rate?: number;+ audio_channel?: number;+ audio_format?: string;+ };+ data?: { status: number; audio?: string };+ };+ if (event.base_resp?.status_code !== undefined && event.base_resp.status_code !== 0)+ throw new SpeechError('request');+ const info = event.extra_info;+ if (+ info &&+ ((info.audio_sample_rate !== undefined && info.audio_sample_rate !== 24000) ||+ (info.audio_channel !== undefined && info.audio_channel !== 1) ||+ (info.audio_format !== undefined && info.audio_format !== 'pcm'))+ )+ throw new SpeechError('format');+ const part = event.data;+ if (!part) return;+ if (finished || ![1, 2].includes(part.status)) throw new SpeechError('format');+ if (part.status === 2) {+ finished = true;+ return;+ }+ const hex = part.audio;+ if (hex === undefined || hex === '') return;+ if (+ typeof hex !== 'string' ||+ hex.length > 2_097_152 ||+ hex.length % 2 !== 0 ||+ /[^\da-f]/i.test(hex)+ )+ throw new SpeechError('format');+ return Uint8Array.from(Buffer.from(hex, 'hex'));+ },+ () => finished,+ );+}diff --git a/apps/desktop/src/main/voice-conversation/adapters/openai.ts b/apps/desktop/src/main/voice-conversation/adapters/openai.tsnew file mode 100644index 0000000000..bd1dc6533c--- /dev/null+++ b/apps/desktop/src/main/voice-conversation/adapters/openai.ts@@ -0,0 +1,18 @@+import type { SpeechAdapter } from './types.js';++export const openaiSpeechAdapter: SpeechAdapter = {+ contentTypes: ['audio/pcm', 'audio/x-pcm', 'application/octet-stream'],+ request(prefix, input) {+ return {+ url: new URL(`${prefix}/audio/speech`),+ body: JSON.stringify({+ model: input.modelId,+ voice: input.voice,+ input: input.text,+ response_format: 'pcm',+ ...(input.speed !== undefined ? { speed: input.speed } : {}),+ }),+ };+ },+ pcm: (body) => body,+};diff --git a/apps/desktop/src/main/voice-conversation/adapters/sse.ts b/apps/desktop/src/main/voice-conversation/adapters/sse.tsnew file mode 100644index 0000000000..fc2596ff76--- /dev/null+++ b/apps/desktop/src/main/voice-conversation/adapters/sse.ts@@ -0,0 +1,62 @@+import { SpeechError } from '../speechError.js';++/** Bounded, pull-driven SSE framing. Join multi-line data before JSON parsing;+ * protocol decoders own completion and must reject truncated/error streams. */+export function ssePcmStream(+ body: ReadableStream<Uint8Array>,+ decode: (event: unknown) => Uint8Array | undefined,+ finished: () => boolean,+): ReadableStream<Uint8Array> {+ const reader = body.getReader();+ const decoder = new TextDecoder('utf-8', { fatal: true });+ let buffer = '';+ let eof = false;+ let encodedBytes = 0;+ return new ReadableStream<Uint8Array>(+ {+ async pull(controller) {+ try {+ while (true) {+ const delimiter = /\r?\n\r?\n/.exec(buffer);+ if (delimiter || (eof && buffer)) {+ const frame = delimiter ? buffer.slice(0, delimiter.index) : buffer;+ buffer = delimiter ? buffer.slice(delimiter.index + delimiter[0].length) : '';+ const data = frame+ .split(/\r?\n/)+ .filter((line) => line.startsWith('data:'))+ .map((line) => line.slice(5).trimStart())+ .join('\n');+ if (!data) continue; // SSE comments/keep-alives.+ if (data === '[DONE]') {+ if (!finished()) throw new SpeechError('format');+ continue;+ }+ const pcm = decode(JSON.parse(data));+ if (!pcm?.byteLength) continue;+ controller.enqueue(pcm);+ return;+ }+ if (eof) {+ if (!finished()) throw new SpeechError('format');+ reader.releaseLock();+ controller.close();+ return;+ }+ const chunk = await reader.read();+ eof = chunk.done;+ encodedBytes += chunk.value?.byteLength ?? 0;+ if ((chunk.value?.byteLength ?? 0) > 2_097_152 || encodedBytes > 64 * 1024 * 1024)+ throw new SpeechError('format');+ buffer += decoder.decode(chunk.value, { stream: !eof });+ if (buffer.length > 2_097_152) throw new SpeechError('format');+ }+ } catch (error) {+ void reader.cancel().catch(() => undefined);+ controller.error(error instanceof SpeechError ? error : new SpeechError('format'));+ }+ },+ cancel: () => reader.cancel(),+ },+ { highWaterMark: 0 },+ );+}diff --git a/apps/desktop/src/main/voice-conversation/adapters/types.ts b/apps/desktop/src/main/voice-conversation/adapters/types.tsnew file mode 100644index 0000000000..60324543d3--- /dev/null+++ b/apps/desktop/src/main/voice-conversation/adapters/types.ts@@ -0,0 +1,17 @@+import type { SpeechProtocol } from '../../../shared/speechProtocols.js';++export type SpeechConnection = {+ baseUrl: string;+ headers: Record<string, string>;+ protocol: SpeechProtocol;+};+export type SpeechInput = { modelId: string; voice: string; text: string; speed?: number };+export type SpeechRequest = { url: URL; body: string; headers?: Record<string, string> };++/** Every adapter produces pull-driven 24 kHz, 16-bit LE mono PCM. A successful+ * EOF means synthesis completed; cancellation must cancel the provider reader. */+export type SpeechAdapter = {+ contentTypes: readonly string[];+ request(prefix: string, input: SpeechInput): SpeechRequest;+ pcm(body: ReadableStream<Uint8Array>): ReadableStream<Uint8Array>;+};diff --git a/apps/desktop/src/main/voice-conversation/models.ts b/apps/desktop/src/main/voice-conversation/models.tsindex 39e2f791e6..57e309df35 100644--- a/apps/desktop/src/main/voice-conversation/models.ts+++ b/apps/desktop/src/main/voice-conversation/models.ts@@ -1,3 +1,8 @@+import {+ isQwenHttpModel,+ isQwenAudioHttpModel,+ isCosyVoiceHttpModel,+} from '../../shared/speechProtocols.js';import {BUNDLED_CATALOG,isLoopbackProviderUrl,@@ -61,8 +66,9 @@ function nativeProtocol(catalog: Catalog, providerId: string, model: ProviderMed: resolveModelNativeApi(BUNDLED_CATALOG.modelRegistry, providerId, model.id);}-/** Official endpoints fix the adapter, independently of model names or catalog metadata. */-function endpointProtocol(base: URL): SpeechProtocol | null {+/** The provider endpoint owns the adapter. Alibaba exposes different APIs on its+ * platform: also require a documented model/region pair, never a brand prefix. */+function endpointProtocol(base: URL, modelId: string): SpeechProtocol | null {if (base.protocol !== 'https:' || base.port) return null;if (base.hostname === 'api.elevenlabs.io') return 'elevenlabs';if (@@ -76,6 +82,20 @@ function endpointProtocol(base: URL): SpeechProtocol | null {)return 'minimax';if (base.hostname === 'api.openai.com') return 'openai';+ if (+ ['dashscope.aliyuncs.com', 'dashscope-intl.aliyuncs.com'].includes(base.hostname) &&+ isQwenHttpModel(modelId)+ )+ return 'qwen-tts';+ const workspace = /^[a-z0-9-]+\.(cn-beijing|ap-southeast-1)\.maas\.aliyuncs\.com$/.exec(+ base.hostname,+ );+ if (+ workspace &&+ (isQwenAudioHttpModel(modelId) ||+ (workspace[1] === 'cn-beijing' && isCosyVoiceHttpModel(modelId)))+ )+ return 'dashscope-tts';return null;}@@ -133,7 +153,7 @@ function bindings(deps: SpeechCatalogDeps, selection?: SpeechModelSelection): Biconst base = apiBase(model.route?.baseUrl ?? route.upstream);const ownerBase = apiBase(route.upstream);if (!base || !ownerBase || base.origin !== ownerBase.origin) continue;- const fixedProtocol = endpointProtocol(base);+ const fixedProtocol = endpointProtocol(base, media.id);const detectedProtocol =fixedProtocol ?? (declared === 'openai-audio-speech' ? 'openai' : null);// A saved override cannot turn an official endpoint into another provider's API.@@ -141,8 +161,10 @@ function bindings(deps: SpeechCatalogDeps, selection?: SpeechModelSelection): Biconst protocol = fixedProtocol ?? selection?.protocol ?? detectedProtocol;// Official native adapters use their documented origin endpoint. Compatible// OpenAI proxies keep the configured prefix (including a non-/v1 API base).- if (fixedProtocol && fixedProtocol !== 'openai') base.pathname = '/v1';- else if (!base.pathname || base.pathname === '/') base.pathname = '/v1';+ const nativeBase =+ protocol === 'qwen-tts' || protocol === 'dashscope-tts' ? '/api/v1' : '/v1';+ if (fixedProtocol && fixedProtocol !== 'openai') base.pathname = nativeBase;+ else if (!base.pathname || base.pathname === '/') base.pathname = nativeBase;const headers: Record<string, string> = {};for (const [name, value] of Object.entries(route.headerOverride ?? {})) {const lower = name.toLowerCase();diff --git a/apps/desktop/src/main/voice-conversation/speech.ts b/apps/desktop/src/main/voice-conversation/speech.tsindex 5679577de0..77ec89db8e 100644--- a/apps/desktop/src/main/voice-conversation/speech.ts+++ b/apps/desktop/src/main/voice-conversation/speech.ts@@ -1,4 +1,9 @@-import { miniMaxPcmStream, speechRequest, type SpeechConnection } from './speechProtocols.js';+import {+ speechAdapter,+ speechRequest,+ speechTextSegments,+ type SpeechConnection,+} from './speechProtocols.js';import { SpeechError } from './speechError.js';export type { SpeechConnection } from './speechProtocols.js';export type SpeechDiagnostic = {@@ -43,7 +48,9 @@ export class SpeechSynthesisSession {const epoch = this.epoch;this.deps.assertCurrent();const connection = this.deps.connection();- const { url, body } = speechRequest(connection, input);+ const texts = speechTextSegments(input.text, connection.protocol);+ const requests = texts.map((text) => speechRequest(connection, { ...input, text }));+ const adapter = speechAdapter(connection.protocol);const controller = new AbortController();this.controller = controller;this.requestId = input.requestId;@@ -58,63 +65,64 @@ export class SpeechSynthesisSession {...details,});this.diagnostic('request');- let timedOut = false;- const timer = setTimeout(() => {- timedOut = true;- controller.abort();- }, 30_000);- let response: Response | undefined;- try {- response = await this.deps.fetch(url, {- method: 'POST',- redirect: 'error',- signal: controller.signal,- headers: { ...connection.headers, 'Content-Type': 'application/json' },- body,- });+ const open = async (index: number): Promise<ReadableStream<Uint8Array>> => {this.deps.assertCurrent();+ if (epoch !== this.epoch || controller.signal.aborted) throw new SpeechError('cancelled');+ const { url, body, headers } = requests[index];+ let timedOut = false;+ const timer = setTimeout(() => {+ timedOut = true;+ controller.abort();+ }, 30_000);+ let response: Response | undefined;+ try {+ response = await this.deps.fetch(url, {+ method: 'POST',+ redirect: 'error',+ signal: controller.signal,+ headers: { ...connection.headers, 'Content-Type': 'application/json', ...headers },+ body,+ });+ this.deps.assertCurrent();+ if (epoch !== this.epoch || controller.signal.aborted) throw new SpeechError('cancelled');+ this.diagnostic?.('headers', { httpStatus: response.status });+ if (!response.ok || !response.body) throw new SpeechError('request');+ const contentType = response.headers+ .get('content-type')+ ?.split(';')[0]+ ?.trim()+ .toLowerCase();+ if (!contentType || !adapter.contentTypes.includes(contentType))+ throw new SpeechError('format');+ return adapter.pcm(response.body);+ } catch (error) {+ if (response?.body && !response.body.locked)+ void response.body.cancel().catch(() => undefined);+ if (timedOut && epoch === this.epoch) {+ this.diagnostic?.('error', { code: 'headers_timeout' });+ this.cancel('failed');+ }+ throw error instanceof SpeechError ? error : new SpeechError('request');+ } finally {+ clearTimeout(timer);+ }+ };+ try {+ const first = await open(0);+ // open() validates before returning; cancel/start can still happen at this+ // await boundary. Never install a stale reader over a replacement request.if (epoch !== this.epoch || controller.signal.aborted) {- await response.body?.cancel();+ void first.cancel().catch(() => undefined);throw new SpeechError('cancelled');}- this.diagnostic('headers', { httpStatus: response.status });- if (!response.ok || !response.body) {- await response.body?.cancel();- throw new SpeechError('request');- }- const contentType = response.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase();- if (- !contentType ||- !(- connection.protocol === 'minimax'- ? ['text/event-stream', 'application/json']- : ['audio/pcm', 'audio/x-pcm', 'application/octet-stream']- ).includes(contentType)- ) {- await response.body.cancel();- throw new SpeechError('format');- }- this.reader = (- connection.protocol === 'minimax' ? miniMaxPcmStream(response.body) : response.body- ).getReader();- // All three adapters request 24 kHz mono PCM; this is not inferred from model mode.+ this.reader = sequentialPcm(first, requests.length, open).getReader();return { sampleRate: 24_000 };} catch (error) {- if (response?.body && !response.body.locked)- void response.body.cancel().catch(() => undefined);if (epoch === this.epoch) {- this.diagnostic?.('error', {- code: timedOut- ? 'headers_timeout'- : error instanceof SpeechError- ? error.code- : 'request',- });+ this.diagnostic?.('error', { code: error instanceof SpeechError ? error.code : 'request' });this.cancel('failed');}throw error instanceof SpeechError ? error : new SpeechError('request');- } finally {- clearTimeout(timer);}}@@ -181,3 +189,54 @@ export class SpeechSynthesisSession {this.totalBytes = 0;}}++/** Open the next segment only after the current PCM is consumed. Cancelling a+ * preview/call aborts its fetch and prevents any remaining billable requests. */+function sequentialPcm(+ first: ReadableStream<Uint8Array>,+ count: number,+ open: (index: number) => Promise<ReadableStream<Uint8Array>>,+): ReadableStream<Uint8Array> {+ let reader = first.getReader();+ let index = 0;+ let bytes = 0;+ let cancelled = false;+ return new ReadableStream<Uint8Array>(+ {+ async pull(controller) {+ try {+ while (!cancelled) {+ const result = await reader.read();+ if (cancelled) return;+ if (!result.done) {+ bytes += result.value.byteLength;+ controller.enqueue(result.value);+ return;+ }+ if (bytes === 0 || bytes % 2 !== 0) throw new SpeechError('format');+ reader.releaseLock();+ if (++index === count) {+ controller.close();+ return;+ }+ const next = await open(index);+ if (cancelled) {+ await next.cancel();+ return;+ }+ reader = next.getReader();+ bytes = 0;+ }+ } catch (error) {+ void reader.cancel().catch(() => undefined);+ controller.error(error);+ }+ },+ cancel() {+ cancelled = true;+ return reader.cancel().catch(() => undefined);+ },+ },+ { highWaterMark: 0 },+ );+}diff --git a/apps/desktop/src/main/voice-conversation/speechProtocols.ts b/apps/desktop/src/main/voice-conversation/speechProtocols.tsindex f825a430e4..f788a2e0cf 100644--- a/apps/desktop/src/main/voice-conversation/speechProtocols.ts+++ b/apps/desktop/src/main/voice-conversation/speechProtocols.ts@@ -1,23 +1,35 @@-import { isSpeechSpeedSupported, type SpeechProtocol } from '../../shared/voiceConversation.js';+import {+ isSpeechSpeedSupported,+ speechTextLimit,+ type SpeechProtocol,+} from '../../shared/speechProtocols.js';import { SpeechError } from './speechError.js';+import { openaiSpeechAdapter } from './adapters/openai.js';+import { elevenlabsSpeechAdapter } from './adapters/elevenlabs.js';+import { minimaxSpeechAdapter } from './adapters/minimax.js';+import { qwenSpeechAdapter, dashscopeSpeechAdapter } from './adapters/dashscope.js';+import type {+ SpeechAdapter,+ SpeechConnection,+ SpeechInput,+ SpeechRequest,+} from './adapters/types.js';+export type { SpeechConnection, SpeechInput } from './adapters/types.js';-export type SpeechConnection = {- baseUrl: string;- headers: Record<string, string>;- protocol: SpeechProtocol;+const adapters: Record<SpeechProtocol, SpeechAdapter> = {+ openai: openaiSpeechAdapter,+ elevenlabs: elevenlabsSpeechAdapter,+ minimax: minimaxSpeechAdapter,+ 'qwen-tts': qwenSpeechAdapter,+ 'dashscope-tts': dashscopeSpeechAdapter,};-export type SpeechInput = { modelId: string; voice: string; text: string; speed?: number };+export function speechAdapter(protocol: SpeechProtocol): SpeechAdapter {+ const adapter = adapters[protocol];+ if (!adapter) throw new SpeechError('unavailable');+ return adapter;+}-/**- * Follow-up before adding more native protocols: extract these branches and response- * decoders into protocol adapters, with shared UI/Main parameter validation and a- * common audio/completion/cancellation contract. Keep wire serialization in code.- * See docs/product-rules/companion-voice-mode.md, "后续扩展计划".- */-export function speechRequest(- connection: SpeechConnection,- input: SpeechInput,-): { url: URL; body: string } {+export function speechRequest(connection: SpeechConnection, input: SpeechInput): SpeechRequest {const base = new URL(connection.baseUrl);if (!['https:', 'http:'].includes(base.protocol) ||@@ -27,135 +39,29 @@ export function speechRequest(base.hash)throw new SpeechError('unavailable');- const prefix = connection.baseUrl.replace(/\/+$/, '');if (!isSpeechSpeedSupported(input.modelId, connection.protocol, input.speed))throw new SpeechError('unavailable');- switch (connection.protocol) {- case 'openai':- return {- url: new URL(`${prefix}/audio/speech`),- body: JSON.stringify({- model: input.modelId,- voice: input.voice,- input: input.text,- response_format: 'pcm',- ...(input.speed !== undefined ? { speed: input.speed } : {}),- }),- };- case 'elevenlabs':- return {- url: new URL(- `${prefix}/text-to-speech/${encodeURIComponent(input.voice)}/stream?output_format=pcm_24000`,- ),- body: JSON.stringify({- model_id: input.modelId,- text: input.text,- ...(input.speed !== undefined ? { voice_settings: { speed: input.speed } } : {}),- }),- };- case 'minimax':- return {- url: new URL(`${prefix}/t2a_v2`),- body: JSON.stringify({- model: input.modelId,- text: input.text,- stream: true,- stream_options: { exclude_aggregated_audio: true },- output_format: 'hex',- voice_setting: {- voice_id: input.voice,- ...(input.speed !== undefined ? { speed: input.speed } : {}),- },- audio_setting: { format: 'pcm', sample_rate: 24000, channel: 1 },- }),- };- }+ return speechAdapter(connection.protocol).request(connection.baseUrl.replace(/\/+$/, ''), input);}-/** MiniMax SSE is JSON + hex. Terminal audio is an aggregate, never another chunk.- * https://platform.minimax.io/docs/api-reference/speech-t2a-http- * Read only on demand; bound both encoded frames and decoded PCM before returning bytes.- */-export function miniMaxPcmStream(body: ReadableStream<Uint8Array>): ReadableStream<Uint8Array> {- const reader = body.getReader();- const decoder = new TextDecoder('utf-8', { fatal: true });- let buffer = '';- let finished = false;- let eof = false;- let encodedBytes = 0;- return new ReadableStream<Uint8Array>(- {- async pull(controller) {- try {- while (true) {- const delimiter = /\r?\n\r?\n/.exec(buffer);- if (delimiter || (eof && buffer)) {- const frame = delimiter ? buffer.slice(0, delimiter.index) : buffer;- buffer = delimiter ? buffer.slice(delimiter.index + delimiter[0].length) : '';- const data = frame- .split(/\r?\n/)- .filter((line) => line.startsWith('data:'))- .map((line) => line.slice(5).trimStart())- .join('\n');- if (!data) continue; // SSE comments/keep-alives.- if (data === '[DONE]') {- if (!finished) throw new SpeechError('format');- continue;- }- const event = JSON.parse(data);- if (!event || typeof event !== 'object') throw new SpeechError('format');- if (event.base_resp?.status_code !== undefined && event.base_resp.status_code !== 0)- throw new SpeechError('request');- const info = event.extra_info;- if (- info &&- ((info.audio_sample_rate !== undefined && info.audio_sample_rate !== 24000) ||- (info.audio_channel !== undefined && info.audio_channel !== 1) ||- (info.audio_format !== undefined && info.audio_format !== 'pcm'))- )- throw new SpeechError('format');- const part = event.data;- if (!part) continue;- if (finished || ![1, 2].includes(part.status)) throw new SpeechError('format');- if (part.status === 2) {- finished = true;- // The provider may still return the full aggregate despite exclude_aggregated_audio.- // Do not replay it after chunks already delivered to the speaker.- continue;- }- const hex = part.audio;- if (hex === undefined || hex === '') continue;- if (- typeof hex !== 'string' ||- hex.length > 2_097_152 ||- hex.length % 2 !== 0 ||- /[^\da-f]/i.test(hex)- )- throw new SpeechError('format');- controller.enqueue(Uint8Array.from(Buffer.from(hex, 'hex')));- return;- }- if (eof) {- if (!finished) throw new SpeechError('format');- reader.releaseLock();- controller.close();- return;- }- const chunk = await reader.read();- eof = chunk.done;- encodedBytes += chunk.value?.byteLength ?? 0;- if ((chunk.value?.byteLength ?? 0) > 2_097_152 || encodedBytes > 64 * 1024 * 1024)- throw new SpeechError('format');- buffer += decoder.decode(chunk.value, { stream: !eof });- if (buffer.length > 2_097_152) throw new SpeechError('format');- }- } catch (error) {- void reader.cancel().catch(() => undefined);- controller.error(error instanceof SpeechError ? error : new SpeechError('format'));- }- },- cancel: () => reader.cancel(),- },- { highWaterMark: 0 },- );+/** Preserve every character, prefer a sentence/word boundary, and never cut a+ * surrogate pair. Segments are sent sequentially as playback pulls more PCM. */+export function speechTextSegments(text: string, protocol: SpeechProtocol): string[] {+ const limit = speechTextLimit(protocol);+ if (!limit || text.length <= limit) return [text];+ const segments: string[] = [];+ while (text.length > limit) {+ let end = limit;+ if (/[\uD800-\uDBFF]/.test(text[end - 1])) end--;+ for (let i = end - 1; i >= limit / 2; i--) {+ if (/[。!?.!?\s]/u.test(text[i])) {+ end = i + 1;+ break;+ }+ }+ segments.push(text.slice(0, end));+ text = text.slice(end);+ }+ if (text) segments.push(text);+ return segments;}diff --git a/apps/desktop/src/main/voice-conversation/voices.ts b/apps/desktop/src/main/voice-conversation/voices.tsindex dcd84d766d..6626eca9f6 100644--- a/apps/desktop/src/main/voice-conversation/voices.ts+++ b/apps/desktop/src/main/voice-conversation/voices.ts@@ -51,7 +51,7 @@ export async function loadSpeechVoices(assertCurrent: () => void,): Promise<SpeechVoiceCatalog> {assertCurrent();- if (connection.protocol === 'openai') {+ if (['openai', 'qwen-tts', 'dashscope-tts'].includes(connection.protocol)) {const voices = referenceSpeechVoices(modelId, connection.protocol).map((id) => ({id,name: id,diff --git a/apps/desktop/src/renderer/features/bots/voice/CompanionVoiceSettings.tsx b/apps/desktop/src/renderer/features/bots/voice/CompanionVoiceSettings.tsxindex c98f35958d..80f99b6761 100644--- a/apps/desktop/src/renderer/features/bots/voice/CompanionVoiceSettings.tsx+++ b/apps/desktop/src/renderer/features/bots/voice/CompanionVoiceSettings.tsx@@ -383,6 +383,8 @@ export function CompanionVoiceSettings(props: Props) {{ value: 'openai', label: t('bots.voiceMode.protocolOpenai') },{ value: 'elevenlabs', label: 'ElevenLabs' },{ value: 'minimax', label: 'MiniMax' },+ { value: 'qwen-tts', label: 'Qwen3-TTS (HTTP)' },+ { value: 'dashscope-tts', label: 'Qwen-Audio / CosyVoice (HTTP)' },]}disabled={!ready || saving}onValueChange={(value) => {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 9356456079..2930231645 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@@ -747,7 +747,7 @@ it('keeps a proxy API override and shows its selector only while a custom endpoiArray.from(field.options).map((option) => option.value).filter(Boolean),- ).toEqual(['openai', 'elevenlabs', 'minimax']);+ ).toEqual(['openai', 'elevenlabs', 'minimax', 'qwen-tts', 'dashscope-tts']);await act(async () => {fireEvent.change(field, { target: { value: 'minimax' } });});@@ -1190,3 +1190,64 @@ it('blocks preview while the companion is waiting for confirmation', async () =>).toBe(true);expect(start).not.toHaveBeenCalled();});++// Unit tier, actual settings/preview entry with the host boundary mocked: switching+// to Qwen must discard an unsupported speed without losing the selected connection.+it.each([+ ['qwen-tts', 'qwen3-tts-flash', 'Cherry', undefined],+ ['dashscope-tts', 'cosyvoice-v3-flash', 'longanyang', 1.5],+] as const)(+ 'saves and previews the %s proxy override with native parameter limits',+ async (protocol, modelId, voice, speed) => {+ models = [{ id: modelId, name: modelId, providerId: 'proxy', agent: 'codex' }];+ vi.mocked(window.electronAPI.voiceConversation.preference).mockResolvedValue({+ selection: {+ providerId: 'proxy',+ agent: 'codex',+ modelId,+ protocol: 'openai',+ voice: 'old-voice',+ speed: 1.5,+ },+ customized: true,+ });+ renderSettings();+ const field = await screen.findByLabelText('bots.voiceMode.protocol');+ await waitFor(() => expect((field as HTMLSelectElement).disabled).toBe(false));+ await act(async () => {+ fireEvent.change(field, { target: { value: protocol } });+ });+ await waitFor(() =>+ expect(window.electronAPI.voiceConversation.setPreference).toHaveBeenLastCalledWith('bot', {+ providerId: 'proxy',+ agent: 'codex',+ modelId,+ protocol,+ voice,+ ...(speed === undefined ? {} : { speed }),+ }),+ );+ const slider = screen.queryByRole('slider', { name: 'bots.voiceMode.speed' });+ if (speed === undefined) expect(slider).toBeNull();+ else {+ expect(slider?.getAttribute('aria-valuemin')).toBe('0.5');+ expect(slider?.getAttribute('aria-valuemax')).toBe('2');+ }+ fireEvent.click(await screen.findByRole('button', { name: 'bots.voiceMode.preview' }));+ await waitFor(() =>+ expect(window.electronAPI.voiceConversation.preview).toHaveBeenCalledWith(+ expect.objectContaining({+ providerId: 'proxy',+ agent: 'codex',+ modelId,+ protocol,+ voice,+ }),+ ),+ );+ expect(vi.mocked(window.electronAPI.voiceConversation.preview).mock.calls[0][0].speed).toBe(+ speed,+ );+ expect(audio.start).not.toHaveBeenCalled();+ },+);diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex c96d05c0d1..be2828e9e8 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -10193,7 +10193,7 @@"refreshVoices": "Refresh voices","voicesLoading": "Loading voices…","voicesError": "Couldn't load voices. Retry or enter a voice ID.",- "voicesReference": "These are OpenAI reference voices for this model. Compatible services may support different voices.",+ "voicesReference": "These are reference voices for this model. Compatible services may support different voices.","voicesTruncated": "Showing part of the voice list. Enter an ID to use an unlisted voice.","voicesManual": "No voice list is available for this interface. Enter a voice ID.","preview": "Preview",@@ -10220,7 +10220,7 @@"voiceHint": "Use a voice name supported by the selected model, such as alloy.","modelUnavailable": "The saved speech model is unavailable. Choose another model.","noModels": "No text-to-speech models available.",- "noModelsSupportedProtocols": "Supports MiniMax, ElevenLabs, and providers with an OpenAI-compatible text-to-speech API.",+ "noModelsSupportedProtocols": "Supports MiniMax, ElevenLabs, Qwen / CosyVoice HTTP APIs, and OpenAI-compatible text-to-speech providers.","noModelsSetupHint": "Connect a provider and enable a speech model to set up your companion’s voice.","openProviders": "Open Model Providers","catalogError": "Could not load or save speech settings. Please try again.",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex b3e58899ce..998191522c 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -10153,7 +10153,7 @@"refreshVoices": "音声リストを更新","voicesLoading": "音声を取得中…","voicesError": "音声を取得できませんでした。再試行するか、音声 ID を入力してください。",- "voicesReference": "このモデルの OpenAI 参考音声です。互換サービスで使える音声は異なる場合があります。",+ "voicesReference": "このモデルの参考音声です。互換サービスで使える音声は異なる場合があります。","voicesTruncated": "音声リストの一部を表示しています。未掲載の音声は ID を入力してください。","voicesManual": "このインターフェースには音声リストがありません。音声 ID を入力してください。","preview": "試聴",@@ -10180,7 +10180,7 @@"voiceHint": "選択したモデルが対応する音声名を入力してください(例:alloy)。","modelUnavailable": "保存した読み上げモデルは利用できません。別のモデルを選んでください。","noModels": "利用可能な音声合成モデルがありません。",- "noModelsSupportedProtocols": "MiniMax、ElevenLabs、および OpenAI 互換の音声合成 API を提供するプロバイダーに対応しています。",+ "noModelsSupportedProtocols": "MiniMax、ElevenLabs、Qwen / CosyVoice の HTTP API、および OpenAI 互換の音声合成 API に対応しています。","noModelsSetupHint": "プロバイダーに接続して音声モデルを有効にすると、パートナーの読み上げ音声を設定できます。","openProviders": "モデルプロバイダーを開く","catalogError": "音声設定の読み込み、または保存に失敗しました。もう一度お試しください。",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 92664dc80f..db92d4023a 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -10153,7 +10153,7 @@"refreshVoices": "음성 목록 새로고침","voicesLoading": "음성 불러오는 중…","voicesError": "음성을 불러오지 못했습니다. 다시 시도하거나 음성 ID를 입력하세요.",- "voicesReference": "이 모델의 OpenAI 참고 음성입니다. 호환 서비스에서 지원하는 음성은 다를 수 있습니다.",+ "voicesReference": "이 모델의 참고 음성입니다. 호환 서비스에서 지원하는 음성은 다를 수 있습니다.","voicesTruncated": "음성 목록의 일부만 표시합니다. 목록에 없는 음성은 ID를 입력하세요.","voicesManual": "이 인터페이스에는 음성 목록이 없습니다. 음성 ID를 입력하세요.","preview": "미리 듣기",@@ -10180,7 +10180,7 @@"voiceHint": "선택한 모델이 지원하는 음성 이름을 입력하세요. 예: alloy.","modelUnavailable": "저장된 읽어주기 모델을 사용할 수 없습니다. 다른 모델을 선택하세요.","noModels": "사용 가능한 음성 합성 모델이 없습니다.",- "noModelsSupportedProtocols": "MiniMax, ElevenLabs 및 OpenAI 호환 음성 합성 API 제공자를 지원합니다.",+ "noModelsSupportedProtocols": "MiniMax, ElevenLabs, Qwen / CosyVoice HTTP API 및 OpenAI 호환 음성 합성 API를 지원합니다.","noModelsSetupHint": "제공자를 연결하고 음성 모델을 활성화하면 파트너의 낭독 음성을 설정할 수 있습니다.","openProviders": "모델 제공자 열기","catalogError": "음성 설정을 불러오거나 저장하지 못했습니다. 다시 시도하세요.",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 5c256b2a20..3de53b4a32 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -10153,7 +10153,7 @@"refreshVoices": "刷新音色列表","voicesLoading": "正在获取音色…","voicesError": "未能获取音色列表。可重试,或手动输入音色 ID。",- "voicesReference": "这是该型号的 OpenAI 参考音色;兼容服务的实际支持可能不同。",+ "voicesReference": "这是该型号的参考音色;兼容服务的实际支持可能不同。","voicesTruncated": "仅显示部分音色;未列出的音色可手动输入 ID。","voicesManual": "此接口没有可用的音色列表,请手动输入音色 ID。","preview": "试听",@@ -10180,7 +10180,7 @@"voiceHint": "填写所选模型支持的音色名称,例如 alloy。","modelUnavailable": "之前选择的朗读模型已不可用,请重新选择。","noModels": "暂无可用的语音合成模型。",- "noModelsSupportedProtocols": "支持 MiniMax、ElevenLabs,以及提供 OpenAI 兼容语音合成接口的供应商。",+ "noModelsSupportedProtocols": "支持 MiniMax、ElevenLabs、Qwen / CosyVoice HTTP,以及 OpenAI 兼容语音合成接口。","noModelsSetupHint": "连接供应商并启用语音模型后,即可设置伙伴的朗读声音。","openProviders": "前往模型供应商","catalogError": "语音设置读取或保存失败,请重试。",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 44eeaba8c6..39d131d596 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -10153,7 +10153,7 @@"refreshVoices": "重新整理音色清單","voicesLoading": "正在取得音色…","voicesError": "無法取得音色清單。請重試,或手動輸入音色 ID。",- "voicesReference": "這是此型號的 OpenAI 參考音色;相容服務的實際支援可能不同。",+ "voicesReference": "這是此型號的參考音色;相容服務的實際支援可能不同。","voicesTruncated": "僅顯示部分音色;未列出的音色可手動輸入 ID。","voicesManual": "此介面沒有可用的音色清單,請手動輸入音色 ID。","preview": "試聽",@@ -10180,7 +10180,7 @@"voiceHint": "填入所選模型支援的音色名稱,例如 alloy。","modelUnavailable": "先前選擇的朗讀模型已無法使用,請重新選擇。","noModels": "目前沒有可用的語音合成模型。",- "noModelsSupportedProtocols": "支援 MiniMax、ElevenLabs,以及提供 OpenAI 相容語音合成介面的供應商。",+ "noModelsSupportedProtocols": "支援 MiniMax、ElevenLabs、Qwen / CosyVoice HTTP,以及 OpenAI 相容語音合成介面。","noModelsSetupHint": "連接供應商並啟用語音模型後,即可設定夥伴的朗讀聲音。","openProviders": "前往模型供應商","catalogError": "語音設定讀取或儲存失敗,請重試。",diff --git a/apps/desktop/src/shared/speechProtocols.ts b/apps/desktop/src/shared/speechProtocols.tsnew file mode 100644index 0000000000..4085ad0592--- /dev/null+++ b/apps/desktop/src/shared/speechProtocols.ts@@ -0,0 +1,78 @@+/** Local Desktop voice UI contract. No credentials, raw paths or remote invoke access. */+export const SPEECH_PROTOCOLS = [+ 'openai',+ 'elevenlabs',+ 'minimax',+ 'qwen-tts',+ 'dashscope-tts',+] as const;+export type SpeechProtocol = (typeof SPEECH_PROTOCOLS)[number];++/** Native synthesis limits, shared by settings and Main. Compatible proxies must+ * implement their selected protocol; this is not a claim about gateway forwarding.+ * Eleven v3 currently excludes speed: https://elevenlabs.io/docs/eleven-creative/playground/text-to-speech#speed+ */+export function speechSpeedRange(modelId: string, protocol?: SpeechProtocol) {+ switch (protocol) {+ case 'elevenlabs':+ return /(?:^|\/)eleven_v3(?:_|$)/i.test(modelId) ? null : { min: 0.7, max: 1.2 };+ case 'dashscope-tts':+ case 'minimax':+ return { min: 0.5, max: 2 };+ case 'openai':+ return { min: 0.25, max: 4 };+ default:+ return null;+ }+}++export function isSpeechSpeedSupported(+ modelId: string,+ protocol: SpeechProtocol,+ speed: number | undefined,+): boolean {+ if (speed === undefined) return true;+ const range = speechSpeedRange(modelId, protocol);+ return !!range && Number.isFinite(speed) && speed >= range.min && speed <= range.max;+}++/** Reconcile an explicit choice when the user changes models, without storing+ * a default for companions that have never customized speed. */+export function resolveSpeechSpeed(+ modelId: string,+ protocol: SpeechProtocol | undefined,+ speed?: number,+) {+ const range = speechSpeedRange(modelId, protocol);+ return range && speed !== undefined && Number.isFinite(speed)+ ? Math.min(range.max, Math.max(range.min, speed))+ : undefined;+}++/** Qwen3-TTS HTTP limits each request to 600 characters. UTF-16 length is+ * conservative for supplementary characters; transport never splits a surrogate. */+export function speechTextLimit(protocol: SpeechProtocol): number | undefined {+ return protocol === 'qwen-tts' ? 600 : undefined;+}++/** Verified HTTP model IDs, not a general family/prefix classifier. Realtime,+ * cloning and future models require their own documented execution contract. */+export function isQwenHttpModel(id: string): boolean {+ return id === 'qwen3-tts-flash';+}+export function isQwenAudioHttpModel(id: string): boolean {+ return [+ 'qwen-audio-3.1-tts-flash',+ 'qwen-audio-3.0-tts-plus',+ 'qwen-audio-3.0-tts-flash',+ ].includes(id);+}+export function isCosyVoiceHttpModel(id: string): boolean {+ return [+ 'cosyvoice-v2',+ 'cosyvoice-v3-plus',+ 'cosyvoice-v3-flash',+ 'cosyvoice-v3.5-plus',+ 'cosyvoice-v3.5-flash',+ ].includes(id);+}diff --git a/apps/desktop/src/shared/speechVoices.ts b/apps/desktop/src/shared/speechVoices.tsindex 815b935b34..7403433900 100644--- a/apps/desktop/src/shared/speechVoices.ts+++ b/apps/desktop/src/shared/speechVoices.ts@@ -1,3 +1,4 @@+import { isQwenHttpModel } from './speechProtocols.js';import type { SpeechProtocol } from './voiceConversation.js';// Model-specific reference lists, not a provider capability declaration. Compatible@@ -24,6 +25,15 @@ export function referenceSpeechVoices(modelId: string,protocol?: SpeechProtocol,): readonly string[] {+ // Model Studio reference examples, not account voice discovery. Custom/cloned+ // voices remain manual and must belong to the selected model and region.+ // https://www.alibabacloud.com/help/en/model-studio/non-realtime-tts-user-guide+ if (protocol === 'qwen-tts') return isQwenHttpModel(modelId) ? ['Cherry'] : [];+ if (protocol === 'dashscope-tts') {+ if (['cosyvoice-v3-plus', 'cosyvoice-v3-flash'].includes(modelId)) return ['longanyang'];+ if (modelId === 'qwen-audio-3.1-tts-flash') return ['longanhuan_v3.1'];+ return []; // Including CosyVoice 3.5: requires a voice bound to that model.+ }if (protocol !== 'openai') return [];if (/^gpt-4o-mini-tts(?:-\d{4}-\d{2}-\d{2})?$/.test(modelId)) return EXPRESSIVE;if (/^tts-1(?:-hd)?(?:-1106)?$/.test(modelId)) return STANDARD;diff --git a/apps/desktop/src/shared/voiceConversation.ts b/apps/desktop/src/shared/voiceConversation.tsindex 07a96b32ca..fccfbf38d8 100644--- a/apps/desktop/src/shared/voiceConversation.ts+++ b/apps/desktop/src/shared/voiceConversation.ts@@ -48,46 +48,10 @@ export function readVoiceCallRecord(value: unknown): VoiceCallRecord | null {* Keep boolean outcomes for local bridge/test compatibility. */export type VoiceExitDecision = boolean | 'submit_then_exit';-/** Local Desktop voice UI contract. No credentials, raw paths or remote invoke access. */-export type SpeechProtocol = 'openai' | 'elevenlabs' | 'minimax';+export { speechSpeedRange, isSpeechSpeedSupported, resolveSpeechSpeed } from './speechProtocols.js';+export type { SpeechProtocol } from './speechProtocols.js';+import { SPEECH_PROTOCOLS, type SpeechProtocol } from './speechProtocols.js';-/** Native synthesis limits, shared by settings and Main. Compatible proxies must- * implement their selected protocol; this is not a claim about gateway forwarding.- * Eleven v3 currently excludes speed: https://elevenlabs.io/docs/eleven-creative/playground/text-to-speech#speed- */-export function speechSpeedRange(modelId: string, protocol?: SpeechProtocol) {- switch (protocol) {- case 'elevenlabs':- return /(?:^|\/)eleven_v3(?:_|$)/i.test(modelId)- ? null- : { min: 0.7, max: 1.2 };- case 'minimax':- return { min: 0.5, max: 2 };- case 'openai':- return { min: 0.25, max: 4 };- default:- return null;- }-}--export function isSpeechSpeedSupported(- modelId: string,- protocol: SpeechProtocol,- speed: number | undefined,-): boolean {- if (speed === undefined) return true;- const range = speechSpeedRange(modelId, protocol);- return !!range && Number.isFinite(speed) && speed >= range.min && speed <= range.max;-}--/** Reconcile an explicit choice when the user changes models, without storing- * a default for companions that have never customized speed. */-export function resolveSpeechSpeed(modelId: string, protocol: SpeechProtocol | undefined, speed?: number) {- const range = speechSpeedRange(modelId, protocol);- return range && speed !== undefined && Number.isFinite(speed)- ? Math.min(range.max, Math.max(range.min, speed))- : undefined;-}// Missing provider/runtime is the original Cindy AI selection, never another connection.export type SpeechModelSelection = {providerId?: string;@@ -231,7 +195,7 @@ export function normalizeSpeechModelSelection(value: unknown): SpeechModelSelectmodelId.length > 256 ||(providerId !== undefined &&(typeof providerId !== 'string' || !providerId.trim() || providerId.length > 256)) ||- (protocol !== undefined && !['openai', 'elevenlabs', 'minimax'].includes(protocol)) ||+ (protocol !== undefined && !SPEECH_PROTOCOLS.includes(protocol)) ||((providerId === undefined || providerId === 'xd') &&protocol !== undefined &&protocol !== 'openai') ||diff --git a/docs/product-rules/companion-voice-mode.md b/docs/product-rules/companion-voice-mode.mdindex 4771a29d29..9ab9298eb0 100644--- a/docs/product-rules/companion-voice-mode.md+++ b/docs/product-rules/companion-voice-mode.md@@ -8,9 +8,9 @@- ASR 能力声明区分片段定稿(`segment-final`)、声学停顿(`acoustic`)、手动提交(`manual`)与语义结束(`semantic`)。`final` 只锁定片段文字,实际 `turnEnd` 需要独立证据;能力声明本身也不是一次轮次结束事件。本阶段不启用语义提前发送、不增加语义断句模型调用,所有模式仍保留 1.25 秒回退。SAUC 传递有效 `end_time`,其 `definite` 不推断语义结束;Qwen 关联同一 item 的 `speech_stopped.audio_end_ms`,只标声学结束;OpenAI 手动模式标明 commit,不能当作用户说完;ElevenLabs Scribe 声明 VAD 能力,但没有时间/结束原因的 committed 文本仍按回退处理。fallback 只继承实际胜出的供应商能力与事件,旧连接回调和恢复后的失配时间戳不能缩短等待。- 普通交流进入本次通话;只有实际执行请求或明确要求后台/主任务处理的工作才交接。已有上下文足以回答的总结、解释、建议、草稿和计划留在通话里;不能仅因“总结/计划/报告”等词就交接,信息不足或行动意图不明确时先询问。通话专用提示与上下文由 maker-core 管理,不改变主任务的系统提示。交接沿用主机生成的“用户原话 + agent 补充”契约,模型不能改写用户原话,也不能扩展权限。不执行桌面斜杠命令。- 默认开启“按句朗读”:可靠标记为 `final_answer` 的回复在输出完整句子后即可开始朗读,未完成的尾句留到后续输出或完成时再处理。关闭后,等整条最终回复经过持久化完成标记确认再朗读。按本次语音发送的 clientId 关联,不朗读历史、过程文字、工具、子代理、内部协调或群来源私信。文本消息始终是对话记录的正本。-- 在“伙伴设置 → 语音”中独立选择朗读模型和音色,按当前账号下的伙伴保存,不改变聊天模型。来源包括有权限的 Cindy AI,以及已连接的本地 BYOK 供应商;候选必须是 `audio_speech`、未停用且具备可用的 API key 或明确的本机免鉴权连接。同名模型按连接 ID、runtime 和上游模型 ID 区分,不能借另一连接的密钥。无候选时显示空状态,不采集麦克风。语音设置页在目录读取成功且候选为空时仅显示介绍(支持 MiniMax、ElevenLabs 与 OpenAI 兼容语音合成接口)和“前往模型供应商”入口,隐藏配置说明、模型选择与刷新、按句朗读、保存说明和恢复默认,不清除已有偏好。跳转复用既有离页保存检查;返回页面时重新读取目录,有可用候选后显示完整配置并隐藏接入提示。首次加载不闪现配置控件;目录读取失败时显示错误和重试入口,不误报为空列表。+- 在“伙伴设置 → 语音”中独立选择朗读模型和音色,按当前账号下的伙伴保存,不改变聊天模型。来源包括有权限的 Cindy AI,以及已连接的本地 BYOK 供应商;候选必须是 `audio_speech`、未停用且具备可用的 API key 或明确的本机免鉴权连接。同名模型按连接 ID、runtime 和上游模型 ID 区分,不能借另一连接的密钥。无候选时显示空状态,不采集麦克风。语音设置页在目录读取成功且候选为空时仅显示介绍(支持 MiniMax、ElevenLabs、Qwen / CosyVoice HTTP 与 OpenAI 兼容语音合成接口)和“前往模型供应商”入口,隐藏配置说明、模型选择与刷新、按句朗读、保存说明和恢复默认,不清除已有偏好。跳转复用既有离页保存检查;返回页面时重新读取目录,有可用候选后显示完整配置并隐藏接入提示。首次加载不闪现配置控件;目录读取失败时显示错误和重试入口,不误报为空列表。- “按句朗读”同样按伙伴保存,未设置时继承开启默认值。显式开关保存在已有语音设置的 `conversationSentencePlayback` 映射中,不另建配置文件;恢复默认删除当前伙伴的覆盖,不影响其他伙伴。切换模型或音色不重置此开关;仅修改开关不丢弃尚未补齐的音色草稿。设置在下一次开始语音对话时生效。-- BYOK 支持 OpenAI 兼容、ElevenLabs、MiniMax 三种语音接口。已知官方 HTTPS 地址自动匹配并固定接口,设置页隐藏接口选择及自动匹配说明,用户只需选择模型和音色;Main 同样采用该官方接口,不接受旧偏好或调用参数切换到其他厂商协议。自定义/中转地址保留手动选择;已声明的 OpenAI speech 协议可作为默认,其余候选(包括显式未验证协议)须用户明确选择。不能只凭模型名、`mode` 或聊天协议推断,切换接口不会更换连接地址或凭证。这个覆盖仅作用于当前伙伴的朗读,不重写公共 Registry 或供应商的聊天协议。音色支持列表选择、手动输入和试听;本次不提供创建或删除克隆音色的能力。+- BYOK 支持 OpenAI 兼容、ElevenLabs、MiniMax、Qwen3-TTS HTTP 和 Qwen-Audio / CosyVoice HTTP 语音接口。已知官方 HTTPS 地址自动匹配并固定接口;Alibaba 平台还需匹配已验证的具体型号及地域,设置页隐藏接口选择及自动匹配说明,用户只需选择模型和音色;Main 同样采用该官方接口,不接受旧偏好或调用参数切换到其他厂商协议。自定义/中转地址保留手动选择;已声明的 OpenAI speech 协议可作为默认,其余候选(包括显式未验证协议)须用户明确选择。不能只凭模型名、`mode` 或聊天协议推断,切换接口不会更换连接地址或凭证。这个覆盖仅作用于当前伙伴的朗读,不重写公共 Registry 或供应商的聊天协议。音色支持列表选择、手动输入和试听;本次不提供创建或删除克隆音色的能力。- 模型、语音接口和音色为伙伴级显式偏好,重开设置、重启后保留。设置页只负责配置与试听,不创建通话。离开设置前等待试听停止和有效音色保存;保存失败保留当前页面。未补齐的型号/接口/音色选择仅作本地草稿,不覆盖此前可用偏好。尚无 canonical 任务时可配置,试听需等待伙伴对话建立。恢复默认删除该伙伴的选择,继续跟随可用目录;已有旧版全局偏好仍可继承,单独重置一个伙伴时以 `null` 清除该伙伴的旧偏好继承,不复制默认模型、不影响其他伙伴。保存失败明确提示。保存的连接消失或停用时保留选择并禁止开始,不静默改用同名模型。- 更换连接、runtime、型号或接口时,不沿用旧音色;目标型号有明确参考默认值才填入,否则等待用户选择或输入。同一连接下的不同型号也不视为音色兼容。已有保存音色不因刷新失败、列表未收录而被覆盖;刷新失败保留已知名称,成功获取后仍未收录的 ID 显示在手动输入中。- 旧偏好中的接口与官方地址冲突时,面板采用官方接口,接口选择仍隐藏,在音色区域上方提示重新选择音色,重新选择前不试听或开始;正确接口下的已有音色继续保留。读取偏好时不写回推导默认值,用户选择音色后通过既有保存流程移除不适用的接口覆盖。自定义/中转地址的显式接口与音色偏好不受影响。@@ -52,7 +52,7 @@- 提前朗读只接受明确标记为 `final_answer` 的顶层回复;没有可靠阶段标记的引擎仍等待最终完成,不靠标点猜测过程文字是否已成为答案。Main 在每次提前合成前检查是否启用回复处理插件;存在时不发起该次合成,等待最终处理及 `ghostReplyPending` 清除后再朗读。若播放开始后才出现需要等待处理的情况,停止本条剩余朗读,不重复读出已播放内容。- 文本缓冲按中文句末标点或英文句末边界释放;英文小数、常见缩写和未完成尾句不会被提前当成完整句子。解析未完成的 Markdown 时跳过代码块、图片、链接地址,暂存未闭合的链接和行内结构。最终快照只补尚未朗读的尾部;若此前已排队的前缀被整体改写,取消剩余音频,不把新全文再读一遍。-- 默认模式每段最多 500 个字符,长句优先沿词或从句边界拆分;完整回复模式沿用最多 3500 个字符分段。复用三类既有 HTTP 音频流接口,只有一个播放器,最多存在当前段和一个预取段。空队列但模型尚未完成时显示思考状态,完成且全部音频播放完才回到监听状态。可能插话时暂停播放与追加预取,识别为空后从原位置恢复;明确插话、结束、账号切换和权限暂停统一取消当前音频与预取;静音仅停止输入,当前音频和预取继续。+- 默认模式每段最多 500 个字符,长句优先沿词或从句边界拆分;完整回复模式沿用最多 3500 个字符分段。复用各供应商的 HTTP 音频流适配器,只有一个播放器,最多存在当前段和一个预取段。空队列但模型尚未完成时显示思考状态,完成且全部音频播放完才回到监听状态。可能插话时暂停播放与追加预取,识别为空后从原位置恢复;明确插话、结束、账号切换和权限暂停统一取消当前音频与预取;静音仅停止输入,当前音频和预取继续。- 按句请求能缩短首句等待,但会增加请求次数,句间音色和语调的连续性取决于供应商;不保证无缝播报。厂商原生文本增量 WebSocket、跨句上下文参数及自适应分句仍属后续适配,不作为本轮已实现能力。## BYOK 音频合同@@ -62,11 +62,26 @@| OpenAI 兼容 | `<base>/audio/speech`,Bearer,`model / voice / input / response_format: pcm` | 原始 24kHz、单声道、16bit little-endian PCM || ElevenLabs | `<base>/text-to-speech/<voiceId>/stream?output_format=pcm_24000`,`xi-api-key`,`model_id / text` | 原始 PCM || MiniMax | `<base>/t2a_v2`,Bearer,`stream: true`、`exclude_aggregated_audio: true`、`output_format: hex`、`voice_setting.voice_id`、24kHz 单声道 PCM | SSE JSON 的 hex 音频;检查业务错误及格式,结束包的聚合音频不重复播放 |+| Qwen3-TTS HTTP | `<base>/services/aigc/multimodal-generation/generation`,Bearer,`x-dashscope-sse: enable`,`model / input.text / input.voice` | SSE Base64 的 24kHz、单声道、16bit little-endian PCM;必须收到 `output.finish_reason: stop` |+| Qwen-Audio / CosyVoice HTTP | `<base>/services/audio/tts/SpeechSynthesizer`,Bearer,同一 SSE header;`input` 中明确 `format: pcm / sample_rate: 24000`,显式语速映射到 `input.rate` | 同上;句子边界帧允许无音频,最终完整文件 URL 不下载、不重复播放 |-已知官方 HTTPS origin(默认端口)固定使用该服务的接口;具体列表由 `main/voice-conversation/models.ts` 维护,不按型号品牌锁定。此规则确定执行适配器,不修改 Registry 的 `nativeApi` 声明,也不证明目录里的型号可执行。ElevenLabs / MiniMax 使用文档规定的 `/v1` 语音端点,MiniMax 的 `/anthropic` 聊天路径不会被沿用。用户指定的兼容代理保留配置的 API base 路径前缀;如果代理提供不同的语音根路径,应在设置中新增独立连接。接口选择不证明供应商的型号、付费方案或音色可用,执行失败仍回到文字。+已知官方 HTTPS origin(默认端口)固定使用该服务的接口;具体列表由 `main/voice-conversation/models.ts` 维护;Alibaba 多接口平台同时核对精确型号和地域,不按品牌前缀推断。此规则确定执行适配器,不修改 Registry 的 `nativeApi` 声明,也不证明目录里的型号可执行。ElevenLabs / MiniMax 使用文档规定的 `/v1` 语音端点,MiniMax 的 `/anthropic` 聊天路径不会被沿用。用户指定的兼容代理保留配置的 API base 路径前缀;如果代理提供不同的语音根路径,应在设置中新增独立连接。接口选择不证明供应商的型号、付费方案或音色可用,执行失败仍回到文字。原生接口依据:[ElevenLabs stream](https://elevenlabs.io/docs/api-reference/text-to-speech/stream)、[MiniMax HTTP TTS](https://platform.minimax.io/docs/api-reference/speech-t2a-http)。响应有类型、大小、超时和完整性检查,重定向被拒绝,上游原始错误不穿过 IPC。流式传输与插话取消共用原有代次检查和播放背压,不增加音频落盘。+### Qwen / CosyVoice HTTP 接入范围++- Qwen3:`qwen3-tts-flash` 在 `dashscope.aliyuncs.com` 或 `dashscope-intl.aliyuncs.com` 自动使用 `/api/v1` 下的多模态合成接口;同 origin 的 `/compatible-mode/v1` 聊天连接可以复用凭证。其他型号(包括 Realtime)不因名称前缀自动匹配。+- Qwen-Audio:`qwen-audio-3.1-tts-flash`、`qwen-audio-3.0-tts-plus`、`qwen-audio-3.0-tts-flash` 使用 `<workspace>.cn-beijing.maas.aliyuncs.com` 或 `<workspace>.ap-southeast-1.maas.aliyuncs.com` 下的 `/api/v1`。CosyVoice 的 `v2`、`v3-plus`、`v3-flash`、`v3.5-plus`、`v3.5-flash` 仅对文档支持的北京 workspace origin 自动匹配;原公共 DashScope 聊天地址不会自动变成 workspace 地址。+- 配置沿用“模型供应商”中的连接、密钥和模型列表:已发现或手动添加并标记为“语音合成”的模型,才进入伙伴设置候选。型号资料不增加账户授权。自定义代理保留 API base 前缀,并可显式选择 `Qwen3-TTS (HTTP)` 或 `Qwen-Audio / CosyVoice (HTTP)`;代理必须实现选中的实际接口。无匹配协议时继续要求用户选择,不换 origin、地域或密钥。+- Qwen3 每个 HTTP 请求最多 600 字符:传输层按 UTF-16 长度保守切分,优先句子/空白边界且不切断代理对,不截断文本。播放拉取到上一段完成后才请求下一段;每段重新核查当前连接,取消、插话、账号变更或读取失败后不再请求剩余段。每段单独检查非空且 PCM 字节对齐。既有整次朗读大小、超时和播放背压上限继续生效。+- Qwen3 HTTP 没有已验证的语速参数,因此隐藏语速滑块,切换到它时不携带旧语速;Qwen-Audio / CosyVoice 支持 `0.5–2`,由 UI 与 Main 共用限制。输出统一为 PCM 24kHz 单声道,不改变播放器。+- 当前只提供文档确认的参考音色:Qwen3 的 `Cherry`、Qwen-Audio 3.1 的 `longanhuan_v3.1`、CosyVoice v3 的 `longanyang`;未提供参考值的型号保留手动输入。CosyVoice v3.5 需填写绑定该型号的音色 ID。不查询私有克隆目录,不创建/删除音色,参考值不保证当前账户可执行。+- SSE 共享有界分帧器,Base64 与 MiniMax hex 分别解码;业务错误、无结束标记、无效编码或空音频都按既有合成失败处理。音频只在内存中;最终 URL 不请求,不向它传递凭证。适配器仍是代码,不接受服务器下发请求模板。+- 这是客户端执行器与本地伙伴偏好的扩展:不修改公共 Registry、服务端 schema、Gateway 鉴权或模型下发;没有服务端合并顺序要求。不包含 Realtime/WebSocket 增量文本、音色克隆、语言/情绪/SSML 设置。真实供应商联调独立记录,单元测试与 UI 截图不代表账户授权或端到端语音验收。++契约来源(2026-10-21 核对):[Qwen3-TTS HTTP](https://www.alibabacloud.com/help/en/model-studio/qwen-tts-api)、[Qwen-Audio HTTP](https://www.alibabacloud.com/help/en/model-studio/qwen-audio-tts-http-api)、[CosyVoice HTTP](https://www.alibabacloud.com/help/en/model-studio/cosyvoice-tts-http-api)、[型号和地域](https://www.alibabacloud.com/help/en/model-studio/non-realtime-tts-user-guide)。+## 音色目录与试听- 音色菜单在悬停或键盘聚焦的行内提供试听按钮;准备和播放中的按钮保持可见并可停止。悬停/聚焦不请求语音,点击试听复用当前模型与语速,保持菜单打开且不改变已选音色;只有点击名称才保存。切换试听对象先停止上一段,关闭菜单(含 Escape/点外部)、改选音色、切换模型或离页均停止试听,复用既有取消与迟到结果保护。菜单由共享 Popover、菜单行和 Button 组成,选择与试听是同级按钮,支持方向键浏览、Tab 到试听及 Enter/Space 激活;不在 listbox option 内嵌交互按钮。菜单内保留试听状态和失败反馈,设置页不再重复展示独立试听区;手动音色在输入框旁保留试听/停止按钮及状态反馈,试听采用当前语速。@@ -126,10 +141,10 @@ SAUC 使用 `result_type=full`,只有 `definite=true` 的分句才不可变;## 后续扩展计划-以下为后续演进方向,本 PR 尚未实现适配器拆分、统一参数描述或公共 Registry schema 扩展,也不包含 Qwen / CosyVoice 原生执行器或厂商文本增量 WebSocket。+HTTP 执行器已拆成独立适配器,语速与文本长度规则由本地共享模块统一;Qwen / CosyVoice HTTP 范围见上节。公共 Registry schema、更多可配置参数及厂商文本增量 WebSocket 仍属于后续演进方向。-- **独立协议适配器**:接入更多原生协议时,先将现有 OpenAI 兼容、ElevenLabs、MiniMax 分支及响应解码整理为独立的 TypeScript 适配器。适配器负责各协议的请求序列化、传输及响应解析;公共层统一音频格式、完成、错误与取消合同,继续复用账号/任务绑定、读取背压、资源上限和迟到音频丢弃,不增加第二套伙伴任务或播放状态机。Qwen / CosyVoice 按所接具体 API 的 HTTP、SSE 或 WebSocket 合同实现,不能只替换 URL。-- **统一参数定义与校验**:用共享的类型化参数描述约定必填项、默认值、枚举、范围和错误语义,让 Renderer 表单与 Main 校验复用同一规则;Main 在执行前再次校验。音色及后续语速、语言等参数按实际协议和型号能力开放,各厂商字段映射仍由适配器负责。当前固定输出格式和参数限制需在迁移时保留,新增能力以适配器实际实现及验证为准。+- **独立协议适配器**:新增接口沿用 `main/voice-conversation/adapters/`;适配器负责请求与解码,共享层维护 PCM 格式、完成、错误、取消及资源上限。WebSocket 若要接入,需实现实际增量文本/任务会话合同,不能只替换 URL,不增加第二套伙伴任务或播放状态机。+- **统一参数定义与校验**:已有语速与请求文本限制由 `shared/speechProtocols.ts` 定义,Main 执行前复核,厂商字段映射留在适配器。后续语言、情绪等枚举/默认值继续按实际型号能力扩展,不将远端资料当作通用序列化程序。- **公共 Registry 扩展**:后续可补充已验证的原生协议标识、型号支持的参数与限制、资料来源。声明须对应实际供应商/型号路由:同一型号通过原厂端点与兼容 Gateway 接入时,协议可以不同;不能从品牌、型号名称或 `audio_speech` 推断。Registry 负责描述能力,协议执行继续保留在代码中,不引入远端 JSON 请求模板或脚本执行机制。- **正本与兼容性**:新增公共字段或协议枚举时,协调更新 cindy-server 正本、客户端 Bean/解析与校验、客户端离线副本及相应契约测试;按既有 schema/能力协商兼容旧客户端。保留未声明与显式 `null` 的区别及用户显式覆盖语义,未知协议不能因此成为已支持协议。分别记录客户端支持、服务端实现与生产部署状态;目录资料不新增用户可访问的模型、授权或执行路由。- **配置存储延续**:API base 和密钥继续复用已有供应商连接与凭证存储,伙伴模型、音色等偏好继续使用现有账号隔离的本地设置,不额外创建通用协议配置文件。若后续把接口覆盖从伙伴偏好调整为连接/型号路由配置,须兼容并保留已有显式选择,不能静默覆盖或丢失设置。