Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(providers): integrate speech models into provider setup

JiangJiahaoaf8e32766f51
diff --git a/apps/desktop/scripts/fixtures/provider-speech-setup/provider-speech-setup-fixture.tsx b/apps/desktop/scripts/fixtures/provider-speech-setup/provider-speech-setup-fixture.tsx
new file mode 100644
index 0000000000..721ec4569f
--- /dev/null
+++ b/apps/desktop/scripts/fixtures/provider-speech-setup/provider-speech-setup-fixture.tsx
@@ -0,0 +1,166 @@
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { mountPage, subscription, forbid } from '../../ui-page/harness';
+import {
+ BUNDLED_CATALOG,
+ buildUserProvider,
+ type CustomProviderConfig,
+ type ProviderView,
+} from '@cindy/model-providers';
+import {
+ AddProviderWizard,
+ type WizardEntry,
+} from '../../../src/renderer/components/settings/AddProviderWizard';
+import { AddSpeechModelsDialog } from '../../../src/renderer/components/settings/AddSpeechModelsDialog';
+import { UnifiedModelList } from '../../../src/renderer/components/settings/UnifiedModelList';
+import { Button } from '../../../src/renderer/components/ui/button';
+import { appendSpeechModels, providerSpeechSetup } from '../../../src/shared/speechProviderSetup';
+
+let stored: CustomProviderConfig = {
+ id: 'minimax-personal',
+ name: 'MiniMax · Personal',
+ runtimes: {
+ codex: {
+ baseUrl: 'https://api.minimax.io/v1',
+ wireProtocol: 'openai-chat',
+ models: [{ id: 'MiniMax-M3', name: 'MiniMax M3' }],
+ },
+ },
+};
+function view(): ProviderView {
+ return { ...buildUserProvider(stored), connected: true };
+}
+function Fixture({ scenario }: { scenario: string }) {
+ const { t } = useTranslation();
+ const [provider, setProvider] = useState<ProviderView>(() =>
+ scenario === 'subscription'
+ ? {
+ ...view(),
+ auth: { method: 'oauth', native: 'codex' },
+ id: 'openai',
+ name: 'OpenAI',
+ routing: {},
+ }
+ : view(),
+ );
+ const [wizard, setWizard] = useState<{ entry?: WizardEntry } | null>(null);
+ const [speech, setSpeech] = useState(false);
+ const [saved, setSaved] = useState(false);
+ const setup = providerSpeechSetup(provider);
+ return (
+ <main className="mx-auto flex max-w-[1040px] flex-col gap-4 p-6">
+ <div className="flex items-center justify-between">
+ <h1 className="text-20 font-medium text-[var(--text-primary)]">
+ {t('settings.providers.title')}
+ </h1>
+ <Button variant="secondary" data-testid="add-provider" onClick={() => setWizard({})}>
+ {t('settings.providers.wizard.title')}
+ </Button>
+ </div>
+ <div className="overflow-hidden rounded-2xl border border-[var(--border-default)] bg-[var(--settings-theme-card-bg)]">
+ <h2 className="p-5 text-16 text-[var(--text-primary)]">{provider.name}</h2>
+ <UnifiedModelList
+ provider={provider}
+ onAddSpeechModels={
+ setup
+ ? () => {
+ if (setup.needsApiKey)
+ setWizard({
+ entry: { kind: 'preset', presetId: setup.presetId, speechOnly: true },
+ });
+ else setSpeech(true);
+ }
+ : undefined
+ }
+ />
+ </div>
+ {saved && (
+ <output data-testid="saved" className="text-12 text-[var(--text-secondary)]">
+ {Object.values(stored.runtimes)
+ .flatMap(
+ (runtime) =>
+ runtime?.models
+ .filter((model) => model.defaultEnabled !== false)
+ .map((model) => model.id) ?? [],
+ )
+ .join(', ')}
+ </output>
+ )}
+ {wizard && (
+ <AddProviderWizard
+ providers={[provider]}
+ entry={wizard.entry}
+ onClose={() => setWizard(null)}
+ onOpenCustomForm={forbid('customForm')}
+ onDone={() => {
+ setWizard(null);
+ setProvider(view());
+ setSaved(true);
+ }}
+ />
+ )}
+ {speech && (
+ <AddSpeechModelsDialog
+ provider={provider}
+ onClose={() => setSpeech(false)}
+ onSaved={() => {
+ setSpeech(false);
+ setProvider(view());
+ setSaved(true);
+ }}
+ />
+ )}
+ </main>
+ );
+}
+void mountPage({
+ host: (ctx) => ({
+ safeStorageRead: async () => 'fixture-key',
+ maker: {
+ listProviderPresets: async () => ({
+ presets: BUNDLED_CATALOG.presets!.filter((p) => p.id === 'minimax-global'),
+ }),
+ localModelList: async () => ({
+ status: { runtime: 'ollama', kind: 'absent', appInstalled: false },
+ models: [],
+ }),
+ scanLocalCli: async () => ({ detections: [] }),
+ llamaCppStatus: async () => ({
+ installed: false,
+ supported: true,
+ running: false,
+ models: [],
+ }),
+ onProviderOAuthProgress: subscription('oauthProgress'),
+ onProvidersChanged: subscription('providersChanged'),
+ fetchProviderModels: async () =>
+ ctx.case === 'elevenlabs'
+ ? {
+ ok: true,
+ models: [
+ {
+ id: 'eleven_flash_v2_5',
+ name: 'Eleven Flash v2.5',
+ discoveredMetadata: { mode: 'audio_speech' },
+ },
+ ],
+ }
+ : { ok: false, code: 'NETWORK' },
+ createCustomProvider: async (config: CustomProviderConfig) => {
+ stored = config;
+ return { ok: true };
+ },
+ updateCustomProvider: async (
+ config: CustomProviderConfig,
+ _keys: unknown,
+ options: { appendSpeechModelsOnly?: true },
+ ) => {
+ if (!options.appendSpeechModelsOnly) throw new Error('Expected additions only');
+ stored = appendSpeechModels(stored, config);
+ return { ok: true };
+ },
+ setModelDisable: forbid('setModelDisable'),
+ },
+ }),
+ render: (ctx) => <Fixture scenario={ctx.case} />,
+});
diff --git a/apps/desktop/scripts/fixtures/provider-speech-setup/ui-page.mjs b/apps/desktop/scripts/fixtures/provider-speech-setup/ui-page.mjs
new file mode 100644
index 0000000000..ec33163fb7
--- /dev/null
+++ b/apps/desktop/scripts/fixtures/provider-speech-setup/ui-page.mjs
@@ -0,0 +1,75 @@
+import assert from 'node:assert/strict';
+export default {
+ name: 'provider-speech-setup',
+ entry: './provider-speech-setup-fixture.tsx',
+ viewport: { width: 1120, height: 820 },
+ real: 'AddProviderWizard, UnifiedModelList toolbar, AddSpeechModelsDialog, SpeechModelChoices, model Registry resolution, translations and themes',
+ notCovered:
+ 'Live credentials, provider network calls, OS safe storage, Settings owner changes, OAuth login and actual synthesis; host catalog/save responses are scenario data',
+ cases: {
+ default: { about: 'Existing API-key connection adds speech without replacing its chat model' },
+ minimax: {
+ about:
+ 'Single add-provider flow: MiniMax API key, grouped chat/speech, recommended speech default',
+ },
+ elevenlabs: { about: 'ElevenLabs catalog discovery, TTS-only connection' },
+ bailian: { about: 'Alibaba Cloud API-key connection with Qwen/CosyVoice references' },
+ subscription: { about: 'Existing OpenAI subscription creates a separate API-key connection' },
+ },
+ async ready(page) {
+ await page.getByTestId('provider-model-toolbar').waitFor();
+ },
+ async check(page, ui) {
+ if (['default', 'subscription'].includes(ui.case)) {
+ await page
+ .getByRole('button', {
+ name: await ui.t('settings.providers.speechSetup.add'),
+ exact: true,
+ })
+ .click();
+ } else {
+ await page.getByTestId('add-provider').click();
+ await ui.capture('single-add-entry');
+ const name =
+ ui.case === 'minimax' ? /MiniMax/ : ui.case === 'elevenlabs' ? /ElevenLabs/ : /API/;
+ const buttons = page.getByRole('dialog').getByRole('button').filter({ hasText: name });
+ await buttons.first().click();
+ if (ui.case === 'minimax')
+ await page
+ .getByRole('button', { name: await ui.t('settings.providers.wizard.useApiKey') })
+ .click();
+ }
+ if (ui.case !== 'default') {
+ if (ui.case === 'subscription')
+ await page.getByText(await ui.t('settings.providers.speechSetup.separateKey')).waitFor();
+ await page.getByPlaceholder('sk-…').fill('fixture-key');
+ await ui.capture('connection');
+ await page
+ .getByRole('button', { name: await ui.t('settings.providers.wizard.next'), exact: true })
+ .click();
+ }
+ const recommendedId =
+ ui.case === 'elevenlabs'
+ ? 'eleven_flash_v2_5'
+ : ui.case === 'bailian'
+ ? 'cosyvoice-v3-flash'
+ : ui.case === 'subscription'
+ ? 'gpt-4o-mini-tts'
+ : 'speech-2.8-turbo';
+ const recommended = page.getByRole('checkbox', { name: new RegExp(recommendedId) });
+ await recommended.waitFor();
+ assert.equal(await recommended.getAttribute('aria-checked'), 'true');
+ await recommended.scrollIntoViewIfNeeded();
+ await ui.capture('models');
+ const finish =
+ ui.case === 'default'
+ ? 'settings.providers.wizard.addManualModel'
+ : 'settings.providers.wizard.finish';
+ await page.getByRole('button', { name: await ui.t(finish), exact: true }).click();
+ await page.getByTestId('saved').waitFor();
+ assert.ok((await page.getByTestId('saved').textContent()).includes(recommendedId));
+ if (ui.case === 'default')
+ assert.ok((await page.getByTestId('saved').textContent()).includes('MiniMax-M3'));
+ await ui.capture('saved');
+ },
+};
diff --git a/apps/desktop/src/main/maker-host/__tests__/providerModelFetch.test.ts b/apps/desktop/src/main/maker-host/__tests__/providerModelFetch.test.ts
index b33ed727e4..278eff1fc0 100644
--- a/apps/desktop/src/main/maker-host/__tests__/providerModelFetch.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/providerModelFetch.test.ts
@@ -493,3 +493,20 @@ it.each([401, 403, 429, 503])('does not disguise manifest authorization or avail
expect(result.ok).toBe(false);
expect(fetcher).toHaveBeenCalledOnce();
});
+
+describe('ElevenLabs catalog authentication', () => {
+ it('uses xi-api-key on the official endpoint even when stored in an Anthropic runtime', () => {
+ const result = buildModelsFetchRequest(spec({
+ baseUrl: 'https://api.elevenlabs.io/v1', apiKey: 'fake-eleven-key', authMethod: 'apiKey',
+ headers: { Authorization: 'stale', 'X-Api-Key': 'stale', 'Xi-Api-Key': 'stale', 'anthropic-version': 'stale' },
+ }));
+ expect(result.url).toBe('https://api.elevenlabs.io/v1/models');
+ expect(result.init.headers).toEqual({ 'xi-api-key': 'fake-eleven-key' });
+ });
+ it('does not guess ElevenLabs authentication for a custom host or leak a stale key in no-auth mode', () => {
+ const custom = buildModelsFetchRequest(spec({ agent: 'codex', baseUrl: 'https://elevenlabs.example/v1', apiKey: 'fake-key' }));
+ expect(custom.init.headers).toEqual({ authorization: 'Bearer fake-key' });
+ const noAuth = buildModelsFetchRequest(spec({ baseUrl: 'https://api.elevenlabs.io/v1', apiKey: undefined, authMethod: 'none', headers: { 'Xi-Api-Key': 'stale' } }));
+ expect(noAuth.init.headers).toEqual({});
+ });
+});
diff --git a/apps/desktop/src/main/maker-host/provider-model-fetch.ts b/apps/desktop/src/main/maker-host/provider-model-fetch.ts
index 9fc796693d..a123f47a2b 100644
--- a/apps/desktop/src/main/maker-host/provider-model-fetch.ts
+++ b/apps/desktop/src/main/maker-host/provider-model-fetch.ts
@@ -129,7 +129,7 @@ function withoutCredentialHeaders(
const normalized: Record<string, string> = {};
for (const [name, value] of Object.entries(headers ?? {})) {
const lower = name.toLowerCase();
- if (lower !== 'authorization' && lower !== 'x-api-key' && lower !== 'x-goog-api-key') normalized[lower] = value;
+ if (lower !== 'authorization' && lower !== 'x-api-key' && lower !== 'xi-api-key' && lower !== 'x-goog-api-key') normalized[lower] = value;
}
return normalized;
}
@@ -173,7 +173,15 @@ export function buildModelsFetchRequest(spec: ProviderModelsFetchSpec): {
const discoveryEndpoint = new URL(discoveryUrl);
const longcatOpenAiCatalog = discoveryEndpoint.origin === 'https://api.longcat.chat'
&& discoveryEndpoint.pathname.replace(/\/+$/, '') === '/openai/v1/models';
- if (isOpenRouterModelsUrl(discoveryUrl) || longcatOpenAiCatalog) {
+ if (discoveryEndpoint.origin === 'https://api.elevenlabs.io'
+ && discoveryEndpoint.pathname.replace(/\/+$/, '') === '/v1/models') {
+ // ElevenLabs discovery uses xi-api-key, independently of the chat runtime slot.
+ delete headers.authorization;
+ delete headers['x-api-key'];
+ delete headers['anthropic-version'];
+ delete headers['anthropic-beta'];
+ if (spec.apiKey) headers['xi-api-key'] = spec.apiKey;
+ } else if (isOpenRouterModelsUrl(discoveryUrl) || longcatOpenAiCatalog) {
// Discovery is provider-specific, not the generation harness's wire format.
// OpenRouter's Anthropic view rewrites IDs and defaults to only 20 results.
// LongCat explicitly shares its OpenAI catalog with the Messages runtime.
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts
index 39e100e102..5504e2619f 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts
@@ -4667,3 +4667,67 @@ it('preserves the actual Vertex API through the probe IPC and rejects unknown SD
{ kind: 'adhoc', spec: { ...spec, api: 'invented-sdk' } })).rejects.toThrow(/INVALID_PARAMS/);
expect(deps.testConnection).toHaveBeenCalledOnce();
});
+
+describe('speech additions through the real provider update handler', () => {
+ it('merges into the latest connection, preserving settings, credentials, duplicate IDs and another connection', async () => {
+ mountDb();
+ const harness = new IpcHarness();
+ const deps = makeDeps();
+ registerProviderHandlers(harness, deps);
+ const config: CustomProviderConfig = { id: 'speech-a', name: 'Renamed while dialog open', runtimes: {
+ codex: { baseUrl: 'https://api.minimax.io/v1', wireProtocol: 'openai-chat', models: [
+ { id: 'MiniMax-M3', name: 'My chat', defaultEnabled: false },
+ { id: 'speech-2.8-hd', name: 'My voice', mode: 'audio_speech', defaultEnabled: false },
+ ] },
+ pi: { baseUrl: 'https://api.minimax.io/anthropic', wireProtocol: 'anthropic-messages', models: [{ id: 'MiniMax-M3', name: 'Pi chat' }] },
+ } };
+ await harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_CREATE, config);
+ await harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_CREATE, { ...config, id: 'speech-b' });
+ vi.mocked(deps.storeCustomProviderKey).mockClear();
+ vi.mocked(deps.removeCustomProviderKey).mockClear();
+ const result = await harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_UPDATE, {
+ ...config, name: 'Stale name', runtimes: { codex: { ...config.runtimes.codex, models: [
+ { id: 'speech-2.8-turbo', name: 'Speech 2.8 Turbo' },
+ { id: 'speech-2.8-hd', name: 'Overwrite attempt', mode: 'audio_speech' },
+ ] } },
+ }, {}, { appendSpeechModelsOnly: true });
+ expect(result).toEqual({ ok: true });
+ const saved = await getCustomProvider(config.id);
+ expect(saved?.name).toBe(config.name);
+ expect(saved?.runtimes.pi).toEqual(config.runtimes.pi);
+ expect(saved?.runtimes.codex?.models).toEqual([...config.runtimes.codex!.models, { id: 'speech-2.8-turbo', name: 'Speech 2.8 Turbo' }]);
+ expect((await getCustomProvider('speech-b'))?.runtimes).toEqual(config.runtimes);
+ expect(deps.storeCustomProviderKey).not.toHaveBeenCalled();
+ expect(deps.removeCustomProviderKey).not.toHaveBeenCalled();
+ });
+ it('rejects stale endpoints and attempts to replace credentials without changing membership', async () => {
+ mountDb();
+ const harness = new IpcHarness();
+ const deps = makeDeps();
+ registerProviderHandlers(harness, deps);
+ await harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_CREATE, validConfig);
+ const request = { ...validConfig, runtimes: { codex: { ...validConfig.runtimes.codex, models: [{ id: 'speech-2.8-turbo', name: 'Speech' }] } } };
+ await expect(harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_UPDATE, request, { codex: 'fake-replacement' }, { appendSpeechModelsOnly: true })).rejects.toThrow(/INVALID_PARAMS/);
+ await expect(harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_UPDATE, { ...request, runtimes: { codex: { ...request.runtimes.codex, baseUrl: 'https://changed.example/v1' } } }, {}, { appendSpeechModelsOnly: true })).rejects.toThrow(/INVALID_PARAMS/);
+ expect((await getCustomProvider(validConfig.id))?.runtimes).toEqual(validConfig.runtimes);
+ });
+});
+
+// A saved explicit default becomes omitted in ProviderView; opening Settings must not make it stale.
+it('speech additions accept an unchanged projected default protocol and preserve its declaration', async () => {
+ mountDb();
+ const harness = new IpcHarness();
+ registerProviderHandlers(harness, makeDeps());
+ const config: CustomProviderConfig = { id: 'legacy-speech', name: 'Legacy', runtimes: {
+ codex: { baseUrl: 'https://api.openai.com/v1', wireProtocol: 'openai-responses', models: [{ id: 'gpt-5.4', name: 'Chat' }] },
+ pi: { baseUrl: 'https://api.openai.com/v1', wireProtocol: 'openai-chat', models: [{ id: 'tts-1', name: 'Already added', defaultEnabled: false }] },
+ } };
+ await harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_CREATE, config);
+ await expect(harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_UPDATE, { ...config, runtimes: {
+ codex: { baseUrl: config.runtimes.codex!.baseUrl, models: [{ id: 'gpt-4o-mini-tts', name: 'Speech' }, { id: 'tts-1', name: 'Duplicate' }] },
+ } }, {}, { appendSpeechModelsOnly: true })).resolves.toEqual({ ok: true });
+ const stored = await getCustomProvider(config.id);
+ expect(stored?.runtimes.codex?.wireProtocol).toBe('openai-responses');
+ expect(stored?.runtimes.codex?.models.map(model => model.id)).toEqual(['gpt-5.4', 'gpt-4o-mini-tts']);
+ expect(stored?.runtimes.pi).toEqual(config.runtimes.pi);
+});
diff --git a/apps/desktop/src/main/maker-ipc/providerHandlers.ts b/apps/desktop/src/main/maker-ipc/providerHandlers.ts
index 4ff55184ba..5724eb98a9 100644
--- a/apps/desktop/src/main/maker-ipc/providerHandlers.ts
+++ b/apps/desktop/src/main/maker-ipc/providerHandlers.ts
@@ -1,3 +1,4 @@
+import { appendSpeechModels } from '../../shared/speechProviderSetup.js';
import { setProviderPresentation, retainProviderPresentationAfterAuthChange } from '../maker-host/provider-presentation-store.js';
import { pruneProviderGroupBindings } from '../provider-group/bindings.js';
import { writeProviderGroup } from '../provider-group/store.js';
@@ -195,16 +196,19 @@ function parseCustomProviderUpdateOptions(input: unknown): CustomProviderUpdateO
if (input === undefined) return {};
if (!input || typeof input !== 'object' || Array.isArray(input)) return null;
const entries = Object.entries(input as Record<string, unknown>);
- if (entries.some(([key]) => key !== 'source' && key !== 'codexImageGenerationRestartPolicy'))
+ if (entries.some(([key]) => key !== 'source' && key !== 'codexImageGenerationRestartPolicy' && key !== 'appendSpeechModelsOnly'))
return null;
const source = (input as Record<string, unknown>).source;
if (source !== undefined && source !== 'manual-settings') return null;
const policy = (input as Record<string, unknown>).codexImageGenerationRestartPolicy;
- if (policy === undefined) return source === 'manual-settings' ? { source } : {};
- if (policy !== 'interrupt') return null;
+ const append = (input as Record<string, unknown>).appendSpeechModelsOnly;
+ if (append !== undefined && append !== true) return null;
+ if (policy !== undefined && policy !== 'interrupt') return null;
+ if (append && (source || policy)) return null;
return {
...(source === 'manual-settings' ? { source } : {}),
- codexImageGenerationRestartPolicy: policy,
+ ...(policy ? { codexImageGenerationRestartPolicy: policy } : {}),
+ ...(append ? { appendSpeechModelsOnly: true as const } : {}),
};
}
@@ -2053,7 +2057,14 @@ export function registerProviderHandlers(
const previous = await getCustomProvider(config.id);
assertProviderMutationOwner(ownerAtIngress);
if (!previous) throwIpcError('NOT_FOUND', `custom provider '${config.id}' not found`);
- if (resolveLatest) {
+ if (options.appendSpeechModelsOnly) {
+ if (Object.keys(keys).length) throwIpcError('INVALID_PARAMS', 'speech additions cannot change credentials');
+ try { config = appendSpeechModels(previous, config); }
+ catch { throwIpcError('INVALID_PARAMS', 'connection changed or invalid speech additions'); }
+ const validation = validateCustomProviderConfig(config, { allowLegacyXai: true });
+ if (!validation.ok) throwIpcError(validation.code, validation.message);
+ separated = splitCustomProviderHeaders(config);
+ } else if (resolveLatest) {
// Main-only key import merges under the same queue, never from a stale UI snapshot.
config = resolveLatest(previous);
const latestValidation = validateCustomProviderConfig(config, { allowLegacyXai: true });
diff --git a/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx b/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx
index 22f61e4a41..8fe8390f3b 100644
--- a/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx
@@ -37,6 +37,7 @@ vi.mock('@/lib/toast', () => ({
vi.mock('@/lib/customProviders', () => ({
createCustomProvider: vi.fn(),
updateCustomProvider: vi.fn(),
+ readCustomProviderKey: vi.fn(async () => "fake-stored-key"),
deleteCustomProvider: vi.fn(async () => undefined),
providerViewToCustomProviderConfig: (p: ProviderView) => ({ id: p.id, name: p.name, auth: p.auth, runtimes: Object.fromEntries(p.agents.map(a => [a, { baseUrl: p.routing[a]!.upstream, wireProtocol: p.routing[a]!.wireProtocol, models: p.models[a] }])) }),
}));
@@ -55,7 +56,8 @@ vi.mock('@/components/icons/ProviderLogoMark', () => ({
}));
import { AddProviderWizard, OFFICIAL_API_PRESETS } from '@/components/settings/AddProviderWizard';
-import { createCustomProvider, updateCustomProvider, deleteCustomProvider } from '@/lib/customProviders';
+import { AddSpeechModelsDialog } from '@/components/settings/AddSpeechModelsDialog';
+import { createCustomProvider, updateCustomProvider, deleteCustomProvider, readCustomProviderKey } from '@/lib/customProviders';
const anthropicProvider = {
id: 'anthropic',
@@ -285,7 +287,7 @@ it.each(['openrouter', 'minimax-cn', 'minimax-global', 'moonshot-kimi-code', 'gi
const row = hint.closest('button')!;
expect(row).not.toBeNull();
expect(within(row).queryByText('settings.providers.wizard.metaApiKey')).toBeNull();
- expect(screen.getByText('settings.providers.wizard.metaApiKey')).toBeTruthy();
+ expect(within(screen.getByText('DeepSeek').closest('button')!).getByText('settings.providers.wizard.metaApiKey')).toBeTruthy();
fireEvent.click(row);
expect(await screen.findByRole('button', { name: id === 'openrouter' ? 'settings.providers.button.authorize' : 'settings.providers.wizard.authorizeWithDeviceCode' })).toBeTruthy();
expect(screen.getByText('settings.providers.wizard.useApiKey')).toBeTruthy();
@@ -1493,3 +1495,105 @@ it('sets up Sub2API from one site address and retains discovered capabilities in
contextWindow: 272000, contextWindowMax: 1050000, supportsFastMode: true, supportsImageInput: true });
}
});
+
+describe('speech models in the existing provider wizard', () => {
+ it('reuses server API presets instead of duplicating the same speech service entry', async () => {
+ window.electronAPI.maker.listProviderPresets = vi.fn(async () => ({ presets: [{
+ id: 'aliyun-model-studio-global', name: 'Server Model Studio', runtimes: {
+ codex: { baseUrl: 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1', models: [] },
+ },
+ }] }));
+ render(<AddProviderWizard providers={[]} onClose={vi.fn()} onDone={vi.fn()} onOpenCustomForm={vi.fn()} />);
+ const serverPreset = await screen.findByRole('button', { name: /Server Model Studio/ });
+ expect(screen.queryByText('阿里云百炼 API')).toBeNull();
+ expect(screen.getByText('阿里云百炼 API(中国大陆)')).toBeTruthy();
+ fireEvent.click(serverPreset);
+ fireEvent.change(await screen.findByPlaceholderText('sk-…'), { target: { value: 'fake-test-key' } });
+ fireEvent.click(screen.getByText('settings.providers.wizard.next'));
+ expect((await screen.findByRole('checkbox', { name: /cosyvoice-v3-flash/ })).getAttribute('aria-checked')).toBe('true');
+ });
+ async function enter(presetId: string, speechOnly = false) {
+ render(<AddProviderWizard providers={[]} entry={{ kind: 'preset', presetId, speechOnly }} onClose={vi.fn()} onDone={vi.fn()} onOpenCustomForm={vi.fn()} />);
+ fireEvent.change(await screen.findByPlaceholderText('sk-…'), { target: { value: 'fake-test-key' } });
+ fireEvent.click(screen.getByText('settings.providers.wizard.next'));
+ await waitFor(() => expect(screen.queryByText('settings.providers.wizard.fetching')).toBeNull());
+ }
+ it('defaults to one recommended speech model, allows speech-only and does not save unchecked references', async () => {
+ await enter('openai-api', true);
+ const recommended = await screen.findByRole('checkbox', { name: /gpt-4o-mini-tts/i });
+ expect(recommended.getAttribute('aria-checked')).toBe('true');
+ expect(screen.getByRole('checkbox', { name: /tts-1(?!-hd)/i }).getAttribute('aria-checked')).toBe('false');
+ fireEvent.click(screen.getByText('settings.providers.wizard.finish'));
+ await waitFor(() => expect(createCustomProvider).toHaveBeenCalled());
+ const config = vi.mocked(createCustomProvider).mock.calls[0][0];
+ const enabled = Object.values(config.runtimes).flatMap(rt => rt?.models.filter(model => model.defaultEnabled !== false) ?? []);
+ expect(enabled.map(model => model.id)).toEqual(['gpt-4o-mini-tts']);
+ expect(config.runtimes.codex?.models.some(model => model.id === 'tts-1')).toBe(false);
+ expect(updateCustomProvider).not.toHaveBeenCalled();
+ });
+ it('supports ElevenLabs discovery and explicit false revokes a recommended offline TTS model', async () => {
+ vi.mocked(window.electronAPI.maker.fetchProviderModels).mockResolvedValue({ ok: true, models: parseModelsListResponse([
+ { model_id: 'eleven_flash_v2_5', can_do_text_to_speech: false },
+ { model_id: 'new-voice-model', name: 'New speech model', can_do_text_to_speech: true },
+ ])! });
+ await enter('elevenlabs-api');
+ expect(screen.queryByRole('checkbox', { name: /eleven_flash_v2_5/ })).toBeNull();
+ fireEvent.click(screen.getByText('settings.providers.speechSetup.more'));
+ const discovered = screen.getByRole('checkbox', { name: /New speech model/ });
+ fireEvent.click(discovered);
+ fireEvent.click(screen.getByText('settings.providers.wizard.finish'));
+ await waitFor(() => expect(createCustomProvider).toHaveBeenCalled());
+ const models = vi.mocked(createCustomProvider).mock.calls[0][0].runtimes.codex!.models;
+ expect(models.find(model => model.id === 'new-voice-model')?.discoveredMetadata?.mode).toBe('audio_speech');
+ expect(models.find(model => model.id === 'eleven_flash_v2_5')?.defaultEnabled).toBe(false);
+ });
+ it('retains a user deselection and manual speech ID in the saved connection', async () => {
+ await enter('elevenlabs-api');
+ fireEvent.click(screen.getByRole('checkbox', { name: /eleven_flash_v2_5/i }));
+ fireEvent.click(screen.getByText('settings.providers.speechSetup.manual'));
+ fireEvent.change(screen.getByRole('textbox', { name: 'settings.providers.speechSetup.modelId' }), { target: { value: 'my-private-speech-model' } });
+ fireEvent.click(screen.getByText('settings.providers.wizard.addManualModel'));
+ fireEvent.click(screen.getByText('settings.providers.wizard.finish'));
+ await waitFor(() => expect(createCustomProvider).toHaveBeenCalled());
+ expect(vi.mocked(createCustomProvider).mock.calls[0][0].runtimes.codex?.models).toEqual([
+ expect.objectContaining({ id: 'my-private-speech-model', mode: 'audio_speech' }),
+ ]);
+ });
+});
+
+describe('existing connection speech additions', () => {
+ const provider = { ...buildUserProvider({ id: 'my-minimax', name: 'My connection', runtimes: {
+ codex: { baseUrl: 'https://api.minimax.io/v1', wireProtocol: 'openai-chat', models: [
+ { id: 'MiniMax-M3', name: 'My chat', defaultEnabled: false },
+ { id: 'speech-2.8-hd', name: 'My saved voice', mode: 'audio_speech', defaultEnabled: false },
+ ] },
+ } }), connected: true } as ProviderView;
+ it('uses the saved key and submits only selected additions, leaving existing model switches alone', async () => {
+ vi.mocked(updateCustomProvider).mockResolvedValue({ ok: true });
+ const saved = vi.fn();
+ render(<AddSpeechModelsDialog provider={provider} onClose={vi.fn()} onSaved={saved} />);
+ const recommended = await screen.findByRole('checkbox', { name: /speech-2.8-turbo/ });
+ expect(recommended.getAttribute('aria-checked')).toBe('true');
+ expect((screen.getByRole('checkbox', { name: /speech-2.8-hd/ }) as HTMLButtonElement).disabled).toBe(true);
+ expect(readCustomProviderKey).toHaveBeenCalledWith('my-minimax', 'codex');
+ expect(window.electronAPI.maker.fetchProviderModels).toHaveBeenCalledWith(expect.objectContaining({ savedProviderId: 'my-minimax', apiKey: 'fake-stored-key' }));
+ fireEvent.click(screen.getByText('settings.providers.wizard.addManualModel'));
+ await waitFor(() => expect(saved).toHaveBeenCalled());
+ expect(updateCustomProvider).toHaveBeenCalledWith(expect.objectContaining({
+ id: 'my-minimax', runtimes: { codex: expect.objectContaining({ models: [expect.objectContaining({ id: 'speech-2.8-turbo', defaultEnabled: true })] }) },
+ }), {}, { appendSpeechModelsOnly: true });
+ expect(createCustomProvider).not.toHaveBeenCalled();
+ });
+ it('does not write on cancel and ignores discovery after the dialog unmounts', async () => {
+ let resolve!: (value: { ok: true; models: [] }) => void;
+ vi.mocked(window.electronAPI.maker.fetchProviderModels).mockReturnValue(new Promise(done => { resolve = done; }));
+ const closed = vi.fn();
+ const result = render(<AddSpeechModelsDialog provider={provider} onClose={closed} onSaved={vi.fn()} />);
+ await waitFor(() => expect(window.electronAPI.maker.fetchProviderModels).toHaveBeenCalled());
+ fireEvent.click(screen.getByText('settings.providers.wizard.cancel'));
+ result.unmount();
+ resolve({ ok: true, models: [] });
+ expect(updateCustomProvider).not.toHaveBeenCalled();
+ expect(createCustomProvider).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx b/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx
index a29c732dba..5e61dcd197 100644
--- a/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx
+++ b/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx
@@ -51,6 +51,8 @@ import { LocalOllamaInstall, offersManagedOllamaInstall } from './LocalOllamaIns
import { MANAGED_LLAMACPP_PROVIDER_ID } from '../../../shared/llamaCpp';
import { OAuthBrowserLink, OAuthDeviceCodeCard } from './OAuthDeviceCodeCard';
import { SettingsTextInput } from './SettingsTextInput';
+import { SpeechModelChoices } from './SpeechModelChoices';
+import { isSpeechModel, SPEECH_API_PRESETS, speechReferenceModels, speechSetupTarget, withSpeechApiPresets } from '../../../shared/speechProviderSetup';
import {
PROVIDER_MEDIA_FIELDS,
@@ -76,7 +78,7 @@ import type {
* - preset(引导卡「其他供应商」行):presets 异步载入后直达该预设的表单步。
*/
export type WizardEntry =
- { kind: 'builtin'; providerId: string } | { kind: 'preset'; presetId: string };
+ { kind: 'builtin'; providerId: string } | { kind: 'preset'; presetId: string; speechOnly?: boolean };
interface AddProviderWizardProps {
providers: ProviderView[];
@@ -450,6 +452,8 @@ export function AddProviderWizard({
name: string;
checked: boolean;
recommended: boolean;
+ speechReference?: boolean;
+ manualSpeech?: boolean;
agents: AgentKind[];
/** 列模型端点上报的上下文窗口,**按 agent 分槽**(同一 id 双端可不同,如
* cc=1M / codex=272K);完成创建时按所属 runtime 取值,作为供应商事实单独保存。 */
@@ -469,9 +473,9 @@ export function AddProviderWizard({
void window.electronAPI.maker
.listProviderPresets()
.then((r) => {
- if (!cancelled) setPresets(r.presets);
+ if (!cancelled) setPresets(withSpeechApiPresets(r.presets));
})
- .catch(() => undefined);
+ .catch(() => { if (!cancelled) setPresets(withSpeechApiPresets([])); });
return () => {
cancelled = true;
};
@@ -755,8 +759,8 @@ export function AddProviderWizard({
if (entry?.kind !== 'preset' || presetEntryConsumedRef.current === entry.presetId) return;
if (presets.length === 0) return;
presetEntryConsumedRef.current = entry.presetId;
- const preset = presets.find((p) => p.id === entry.presetId);
- if (preset) pickPreset(preset);
+ const preset = presets.find((p) => p.id === entry.presetId) ?? [...Object.values(OFFICIAL_API_PRESETS), ...SPEECH_API_PRESETS].find(p => p.id === entry.presetId);
+ if (preset) pickPreset(preset, entry.speechOnly === true);
}, [entry, presets, pickPreset]);
const localLoginRef = useRef<{ cancel: () => void } | null>(null);
@@ -971,6 +975,8 @@ export function AddProviderWizard({
name: string;
checked: boolean;
recommended: boolean;
+ speechReference?: boolean;
+ manualSpeech?: boolean;
agents: AgentKind[];
contextWindows?: Partial<Record<AgentKind, number>>;
discoveredCosts?: Partial<Record<AgentKind, import("@cindy/model-providers").ModelCost>>;
@@ -1017,6 +1023,21 @@ export function AddProviderWizard({
}
}
}
+ // Suggestions add no account membership until the user finishes this wizard.
+ // Scope them to one real API-key runtime, never the device-code draft.
+ const speechTarget = !oauthDraftRef.current && speechSetupTarget(Object.fromEntries(
+ agents.map(agent => [agent, { ...preset.runtimes[agent]!, baseUrl: presetRuntimeBaseUrl(preset, agent, presetBaseUrls) }]),
+ ));
+ if (speechTarget) {
+ if (entry?.kind === 'preset' && entry.speechOnly) {
+ for (const value of initial.values()) value.checked = false;
+ }
+ for (const model of speechReferenceModels(speechTarget.service)) {
+ if (initial.has(model.id)) continue;
+ initial.set(model.id, { name: model.name, checked: model.defaultEnabled !== false,
+ recommended: model.defaultEnabled !== false, agents: [speechTarget.agent], speechReference: true });
+ }
+ }
setPicks(initial);
setStep(3);
setFetchState({ status: 'fetching' });
@@ -1169,10 +1190,14 @@ export function AddProviderWizard({
discoveredRoute ||
existing.name !== m.name ||
m.discoveredCost ||
- m.discoveredMetadata
+ m.discoveredMetadata || existing.speechReference
) {
next.set(m.id, {
...existing,
+ speechReference: false,
+ // An explicit non-speech response revokes an offline TTS suggestion.
+ ...(existing.speechReference && m.discoveredMetadata?.mode && m.discoveredMetadata.mode !== 'audio_speech'
+ ? { checked: false, recommended: false } : {}),
name: m.name,
...(m.discoveredCost ? { discoveredCosts: { ...existing.discoveredCosts, [agent]: m.discoveredCost } } : {}),
agents: mergedAgents,
@@ -1220,7 +1245,7 @@ export function AddProviderWizard({
failed: !results.some((r) => r.ok),
empty: !results.some((r) => r.models.length > 0),
});
- }, [sel, apiKey, presetBaseUrls]);
+ }, [sel, apiKey, presetBaseUrls, entry]);
/**
* 零推荐模型的本机代理(例如 LiteLLM)若 `/models` 不可用或返回空清单,仍允许用户
@@ -1293,6 +1318,7 @@ export function AddProviderWizard({
if (!sel || sel.kind !== 'preset') return;
const preset = sel.preset;
const selected = [...picks.entries()]
+ .filter(([, value]) => !value.speechReference || value.checked)
.map(([id, v]) => ({
id,
checked: v.checked,
@@ -1302,6 +1328,7 @@ export function AddProviderWizard({
discoveredMetadata: v.discoveredMetadata,
discoveredCosts: v.discoveredCosts,
routes: v.routes,
+ manualSpeech: v.manualSpeech,
}));
if (!selected.some(model => model.checked)) {
toast.error(t('settings.providers.wizard.noModelSelected'));
@@ -1346,7 +1373,7 @@ export function AddProviderWizard({
...(!m.checked ? { defaultEnabled: false } : {}),
discoveredMetadata,
...(m.discoveredCosts?.[agent] ? { discoveredCost: m.discoveredCosts[agent] } : {}),
- ...(presetModel?.mode ? { mode: presetModel.mode } : {}),
+ ...(m.manualSpeech ? { mode: 'audio_speech' as const } : presetModel?.mode ? { mode: presetModel.mode } : {}),
...(presetModel?.modalities ? { modalities: { input: [...presetModel.modalities.input], output: [...presetModel.modalities.output] } } : {}),
...(presetModel?.officialDocs ? { officialDocs: presetModel.officialDocs } : {}),
// Known models follow the maintained preset after refresh. Only
@@ -1410,7 +1437,7 @@ export function AddProviderWizard({
// 预设单 runtime 时的「仅支持 X」说明(数据驱动的静态灰,见文件头注释)。
const presetAgents = sel?.kind === 'preset' ? configuredPresetAgents(sel.preset) : [];
const presetSingleAgentNote =
- sel?.kind === 'preset' && presetAgents.length === 1
+ sel?.kind === 'preset' && presetAgents.length === 1 && sel.preset.id !== 'elevenlabs-api'
? t('settings.providers.wizard.onlyAgentNote', { agent: AGENT_LABEL[presetAgents[0]] })
: null;
const oauthSingleAgentNote =
@@ -1420,6 +1447,19 @@ export function AddProviderWizard({
})
: null;
+ const speechTarget = sel?.kind === 'preset' && !oauthDraftRef.current
+ ? speechSetupTarget(Object.fromEntries(presetAgents.map(agent => [agent, {
+ ...sel.preset.runtimes[agent]!, baseUrl: presetRuntimeBaseUrl(sel.preset, agent, presetBaseUrls),
+ }]))) : undefined;
+ const speechPicks = [...picks.entries()].filter(([id, value]) => value.manualSpeech || value.agents.some(agent =>
+ isSpeechModel({ id, discoveredMetadata: value.discoveredMetadata?.[agent], mode: sel?.kind === 'preset' ? sel.preset.runtimes[agent]?.models.find(model => model.id === id)?.mode : undefined })));
+ const speechIds = new Set(speechPicks.map(([id]) => id));
+ const generalPicks = [...picks.entries()].filter(([id]) => !speechIds.has(id));
+ const togglePick = (id: string) => setPicks(previous => {
+ const next = new Map(previous); const value = next.get(id);
+ if (value) next.set(id, { ...value, checked: !value.checked });
+ return next;
+ });
const checkedCount = [...picks.values()].filter((v) => v.checked).length;
const presetHasRecommendedModels =
sel?.kind === 'preset' &&
@@ -1428,7 +1468,7 @@ export function AddProviderWizard({
sel?.kind === 'preset' &&
fetchState.status === 'done' &&
(fetchState.failed || fetchState.empty) &&
- !presetHasRecommendedModels;
+ !presetHasRecommendedModels && !speechTarget;
const presetNeedsApiKey = sel?.kind === 'preset' && sel.preset.authMethod !== 'none';
const presetBaseUrlsValid =
sel?.kind === 'preset' &&
@@ -1449,6 +1489,17 @@ export function AddProviderWizard({
presetBaseUrlsValid &&
(!presetNeedsApiKey || apiKey.trim().length > 0);
+ const wizardTitle = sel
+ ? t('settings.providers.wizard.titleWith', {
+ name:
+ sel.kind === 'preset'
+ ? presetDisplayName(sel.preset, i18n.language)
+ : sel.kind === 'ollama-onboarding'
+ ? t('settings.providers.local.title')
+ : sel.provider.name,
+ })
+ : t('settings.providers.wizard.title');
+
return (
<Dialog.Root open={dialog.open} onOpenChange={(open) => { if (!open) handleClose(); }}>
<Dialog.Portal>
@@ -1474,18 +1525,10 @@ export function AddProviderWizard({
<div className="flex items-center justify-between gap-4 px-4 pb-3 pt-4">
<Dialog.Title asChild><h3
className="min-w-0 truncate text-16 font-medium"
+ title={wizardTitle}
style={{ color: 'var(--settings-section-title)' }}
>
- {sel
- ? t('settings.providers.wizard.titleWith', {
- name:
- sel.kind === 'preset'
- ? presetDisplayName(sel.preset, i18n.language)
- : sel.kind === 'ollama-onboarding'
- ? t('settings.providers.local.title')
- : sel.provider.name,
- })
- : t('settings.providers.wizard.title')}
+ {wizardTitle}
</h3></Dialog.Title>
<div className="flex shrink-0 items-center gap-4">
{stepLabels.map((label, i) => {
@@ -2025,6 +2068,7 @@ export function AddProviderWizard({
return null;
})}
</div>
+ {entry?.kind === 'preset' && entry.speechOnly && <InfoLine text={t('settings.providers.speechSetup.separateKey')} />}
{presetSingleAgentNote && <InfoLine text={presetSingleAgentNote} />}
</div>
@@ -2045,12 +2089,13 @@ export function AddProviderWizard({
{fetchState.status === 'done' && fetchState.failed && (
<InfoLine text={t('settings.providers.wizard.fetchFailed')} />
)}
- {picks.size > 0 && (
+ {speechPicks.length > 0 && generalPicks.length > 0 && <p className="text-13 font-medium text-[var(--text-primary)]">{t('settings.providers.speechSetup.otherModels')}</p>}
+ {generalPicks.length > 0 && (
<div
className="flex flex-col overflow-hidden rounded-xl border"
style={{ borderColor: 'var(--border-default)' }}
>
- {[...picks.entries()].map(([id, v], i) => (
+ {generalPicks.map(([id, v], i) => (
<button
key={id}
type="button"
@@ -2117,6 +2162,20 @@ export function AddProviderWizard({
))}
</div>
)}
+ {(speechTarget || speechPicks.length > 0) && <SpeechModelChoices
+ choices={speechPicks.map(([id, value]) => ({ id, ...value, reference: value.speechReference, manual: value.manualSpeech }))}
+ onToggle={togglePick}
+ onAdd={id => {
+ const agent = speechTarget?.agent ?? speechPicks[0]?.[1].agents[0];
+ if (!agent) return;
+ setPicks(previous => {
+ const next = new Map(previous); const existing = next.get(id);
+ next.set(id, { ...existing, name: existing?.name ?? id, checked: true,
+ recommended: existing?.recommended ?? false, agents: existing?.agents ?? [agent],
+ speechReference: false, manualSpeech: true });
+ return next;
+ });
+ }} />}
{showManualModelFallback && (
<div
className="flex flex-col gap-3 rounded-xl border p-3.5"
@@ -2172,7 +2231,7 @@ export function AddProviderWizard({
</div>
)}
<p className="text-11 leading-snug" style={{ color: 'var(--text-tertiary)' }}>
- {t('settings.providers.wizard.modelsHint')}
+ {t(speechPicks.length > 0 ? 'settings.providers.speechSetup.modelsHint' : 'settings.providers.wizard.modelsHint')}
</p>
</>
)}
diff --git a/apps/desktop/src/renderer/components/settings/AddSpeechModelsDialog.tsx b/apps/desktop/src/renderer/components/settings/AddSpeechModelsDialog.tsx
new file mode 100644
index 0000000000..ad188b87ee
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/AddSpeechModelsDialog.tsx
@@ -0,0 +1,269 @@
+import { useEffect, useRef, useState } from 'react';
+import * as Dialog from '@radix-ui/react-dialog';
+import { useTranslation } from 'react-i18next';
+import type { ProviderRuntimeModelConfig, ProviderView } from '@cindy/model-providers';
+import { Button } from '@/components/ui/button';
+import { Spinner } from '@/components/ui/spinner';
+import { useDialogExit } from '@/hooks/useDialogExit';
+import {
+ providerViewToCustomProviderConfig,
+ readCustomProviderKey,
+ updateCustomProvider,
+} from '@/lib/customProviders';
+import { toast } from '@/lib/toast';
+import {
+ providerSpeechSetup,
+ speechReferenceModels,
+ isSpeechModel,
+} from '../../../shared/speechProviderSetup';
+import { SpeechModelChoices, type SpeechModelChoice } from './SpeechModelChoices';
+
+type Choice = SpeechModelChoice & { model: ProviderRuntimeModelConfig };
+
+/** Additions-only: Main merges into the latest config under its existing provider queue. */
+export function AddSpeechModelsDialog({
+ provider,
+ onClose,
+ onSaved,
+}: {
+ provider: ProviderView;
+ onClose: () => void;
+ onSaved: () => void;
+}) {
+ const { t } = useTranslation();
+ const dialog = useDialogExit();
+ // Keep one connection snapshot for this dialog; a late provider refresh cannot reset choices.
+ const [config] = useState(() => providerViewToCustomProviderConfig(provider));
+ const [target] = useState(() => providerSpeechSetup(provider));
+ const [choices, setChoices] = useState<Choice[]>(() => {
+ if (!target) return [];
+ const saved = new Map(
+ Object.values(config.runtimes).flatMap(
+ (runtime) => runtime?.models.map((model) => [model.id, model] as const) ?? [],
+ ),
+ );
+ const references = speechReferenceModels(target.service).map((model) => ({
+ id: model.id,
+ name: saved.get(model.id)?.name ?? model.name,
+ checked: !saved.has(model.id) && model.defaultEnabled !== false,
+ recommended: model.defaultEnabled !== false,
+ reference: true,
+ saved: saved.has(model.id),
+ model,
+ }));
+ const ids = new Set(references.map((model) => model.id));
+ return [
+ ...references,
+ ...[...saved.values()]
+ .filter((model) => isSpeechModel(model) && !ids.has(model.id))
+ .map((model) => ({
+ id: model.id,
+ name: model.name,
+ checked: false,
+ recommended: false,
+ saved: true,
+ model,
+ })),
+ ];
+ });
+ const [loading, setLoading] = useState(true);
+ const [failed, setFailed] = useState(false);
+ const [saving, setSaving] = useState(false);
+ const savingRef = useRef(false);
+ const mounted = useRef(true);
+ useEffect(() => {
+ let cancelled = false;
+ mounted.current = true;
+ void (async () => {
+ if (!target || target.needsApiKey) return;
+ const runtime = config.runtimes[target.agent];
+ if (!runtime) return;
+ try {
+ const apiKey = await readCustomProviderKey(config.id, target.agent);
+ if (cancelled) return;
+ const result = await window.electronAPI.maker.fetchProviderModels({
+ savedProviderId: config.id,
+ agent: target.agent,
+ authMethod: 'apiKey',
+ baseUrl: runtime.baseUrl,
+ wireProtocol: runtime.wireProtocol,
+ modelsUrl: runtime.modelsUrl,
+ apiKey,
+ });
+ if (cancelled) return;
+ setFailed(!result.ok);
+ if (result.ok)
+ setChoices((previous) => {
+ const next = new Map(previous.map((choice) => [choice.id, choice]));
+ const saved = new Set(
+ Object.values(config.runtimes).flatMap(
+ (value) => value?.models.map((model) => model.id) ?? [],
+ ),
+ );
+ for (const model of result.models ?? []) {
+ const old = next.get(model.id);
+ if (!isSpeechModel(model)) {
+ // An explicit non-TTS capability beats an offline reference. Saved membership stays intact.
+ if (old?.reference && model.discoveredMetadata?.mode && !old.saved)
+ next.delete(model.id);
+ continue;
+ }
+ next.set(model.id, {
+ id: model.id,
+ name: old?.saved ? old.name : model.name,
+ checked: old?.checked ?? false,
+ recommended: old?.recommended ?? false,
+ saved: saved.has(model.id),
+ reference: false,
+ model: {
+ id: model.id,
+ name: model.name,
+ discoveredMetadata: model.discoveredMetadata,
+ },
+ });
+ }
+ return [...next.values()];
+ });
+ } catch {
+ if (!cancelled) setFailed(true);
+ } finally {
+ if (!cancelled) setLoading(false);
+ }
+ })();
+ return () => {
+ cancelled = true;
+ mounted.current = false;
+ };
+ }, [config, target]);
+ const selected = choices.filter((choice) => choice.checked && !choice.saved);
+ const close = () => {
+ if (!savingRef.current) dialog.close(onClose);
+ };
+ const save = async () => {
+ if (savingRef.current || !target || target.needsApiKey || selected.length === 0) return;
+ const runtime = config.runtimes[target.agent];
+ if (!runtime) return;
+ savingRef.current = true;
+ setSaving(true);
+ try {
+ const result = await updateCustomProvider(
+ {
+ ...config,
+ runtimes: {
+ [target.agent]: {
+ ...runtime,
+ models: selected.map((choice) => ({ ...choice.model, defaultEnabled: true })),
+ },
+ },
+ },
+ {},
+ { appendSpeechModelsOnly: true },
+ );
+ if (!mounted.current) return;
+ if (!result.ok) {
+ toast.error(t('settings.providers.speechSetup.saveFailed'));
+ return;
+ }
+ dialog.close(onSaved);
+ } catch {
+ if (mounted.current) toast.error(t('settings.providers.speechSetup.saveFailed'));
+ } finally {
+ savingRef.current = false;
+ if (mounted.current) setSaving(false);
+ }
+ };
+ return (
+ <Dialog.Root
+ open={dialog.open}
+ onOpenChange={(open) => {
+ if (!open) close();
+ }}
+ >
+ <Dialog.Portal>
+ <Dialog.Overlay className="modal-scrim fixed inset-0 z-[10000]" />
+ <Dialog.Content
+ aria-describedby={undefined}
+ onOpenAutoFocus={dialog.onOpenAutoFocus}
+ onEscapeKeyDown={(event) => {
+ if (saving) event.preventDefault();
+ }}
+ onPointerDownOutside={(event) => event.preventDefault()}
+ onCloseAutoFocus={dialog.onCloseAutoFocus}
+ className="modal-panel fixed left-1/2 top-1/2 z-[10001] flex max-h-[85vh] w-[min(600px,calc(100vw-32px))] -translate-x-1/2 -translate-y-1/2 flex-col rounded-2xl border border-[var(--border-default)] bg-[var(--settings-theme-card-bg)] text-[var(--text-primary)] shadow-xl"
+ >
+ <div className="p-5">
+ <Dialog.Title className="text-16 font-medium">
+ {t('settings.providers.speechSetup.add')}
+ </Dialog.Title>
+ <p className="mt-1 text-12 text-[var(--text-secondary)]">{provider.name}</p>
+ </div>
+ <div className="flex flex-col gap-3 overflow-y-auto border-y border-[var(--border-default)] p-5">
+ {loading ? (
+ <div role="status" className="flex items-center gap-2 text-12">
+ <Spinner size={14} />
+ {t('settings.providers.wizard.fetching')}
+ </div>
+ ) : (
+ <>
+ {failed && (
+ <p className="text-12 text-[var(--text-secondary)]">
+ {t('settings.providers.speechSetup.fetchFailed')}
+ </p>
+ )}
+ <SpeechModelChoices
+ choices={choices}
+ loading={saving}
+ onToggle={(id) =>
+ setChoices((previous) =>
+ previous.map((choice) =>
+ choice.id === id ? { ...choice, checked: !choice.checked } : choice,
+ ),
+ )
+ }
+ onAdd={(id) =>
+ setChoices((previous) => {
+ const old = previous.find((choice) => choice.id === id);
+ if (old?.saved) return previous;
+ const existing = Object.values(config.runtimes).some((runtime) =>
+ runtime?.models.some((model) => model.id === id),
+ );
+ if (existing) return previous;
+ const choice: Choice = {
+ id,
+ name: old?.name ?? id,
+ checked: true,
+ recommended: old?.recommended ?? false,
+ manual: true,
+ model: { id, name: old?.name ?? id, mode: 'audio_speech' },
+ };
+ return old
+ ? previous.map((value) => (value.id === id ? choice : value))
+ : [...previous, choice];
+ })
+ }
+ />
+ <p className="text-11 leading-relaxed text-[var(--text-tertiary)]">
+ {t('settings.providers.speechSetup.modelsHint')}
+ </p>
+ </>
+ )}
+ </div>
+ <div className="flex justify-end gap-2 p-4">
+ <Button variant="secondary" size="lg" disabled={saving} onClick={close}>
+ {t('settings.providers.wizard.cancel')}
+ </Button>
+ <Button
+ variant="cta"
+ size="lg"
+ loading={saving}
+ disabled={loading || saving || selected.length === 0}
+ onClick={() => void save()}
+ >
+ {t('settings.providers.wizard.addManualModel')}
+ </Button>
+ </div>
+ </Dialog.Content>
+ </Dialog.Portal>
+ </Dialog.Root>
+ );
+}
diff --git a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
index cb50d11e34..83ddd33879 100644
--- a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
@@ -1,3 +1,5 @@
+import { AddSpeechModelsDialog } from './AddSpeechModelsDialog';
+import { providerSpeechSetup } from '../../../shared/speechProviderSetup';
import { useCodexRateLimits } from '@/hooks/useCodexRateLimits';
import { useCodexRateLimitReset } from '@/hooks/useCodexRateLimitReset';
import { CodexResetCredits } from '../status/CodexResetCredits';
@@ -2495,6 +2497,7 @@ export function ProvidersSection() {
ids: Set<string>;
}>({ dataOwnerId, ids: new Set<string>() });
// 向导:null = 关;{ entry } = 打开(entry 指定直达的供应商,来自检测建议)。
+ const [speechProvider, setSpeechProvider] = useState<{ provider: ProviderView; owner: string | null; generation: number | null } | null>(null);
const [wizard, setWizard] = useState<null | { entry?: WizardEntry }>(null);
// 自定义供应商完整表单(编辑,或从向导「自定义端点」进入新建)。
const [dialog, setDialog] = useState<
@@ -3408,6 +3411,11 @@ export function ProvidersSection() {
)}
<UnifiedModelList
provider={effectiveSelected}
+ onAddSpeechModels={providerSpeechSetup(effectiveSelected) ? () => {
+ const setup = providerSpeechSetup(effectiveSelected)!;
+ if (setup.needsApiKey) setWizard({ entry: { kind: 'preset', presetId: setup.presetId, speechOnly: true } });
+ else setSpeechProvider({ provider: effectiveSelected, owner: dataOwnerId, generation: ownerGeneration });
+ } : undefined}
focusModelId={
focusedModel?.providerId === effectiveSelected.id
? focusedModel.modelId
@@ -3509,6 +3517,11 @@ export function ProvidersSection() {
</>)}
+ {speechProvider && speechProvider.owner === dataOwnerId && speechProvider.generation === ownerGeneration && (
+ <AddSpeechModelsDialog key={`${dataOwnerId}:${ownerGeneration}:${speechProvider.provider.id}`}
+ provider={speechProvider.provider} onClose={() => setSpeechProvider(null)}
+ onSaved={() => { setSpeechProvider(null); void refetch(); }} />
+ )}
{wizard && (
<AddProviderWizard
providers={providers}
diff --git a/apps/desktop/src/renderer/components/settings/SpeechModelChoices.tsx b/apps/desktop/src/renderer/components/settings/SpeechModelChoices.tsx
new file mode 100644
index 0000000000..e629728563
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/SpeechModelChoices.tsx
@@ -0,0 +1,143 @@
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Check, Plus, AudioLines } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { SettingsTextInput } from './SettingsTextInput';
+
+export interface SpeechModelChoice {
+ id: string;
+ name: string;
+ checked: boolean;
+ recommended: boolean;
+ reference?: boolean;
+ saved?: boolean;
+ manual?: boolean;
+}
+
+/** Shared by new connections and additions to one existing API-key connection. */
+export function SpeechModelChoices({
+ choices,
+ onToggle,
+ onAdd,
+ loading = false,
+}: {
+ choices: SpeechModelChoice[];
+ onToggle: (id: string) => void;
+ onAdd: (id: string) => void;
+ loading?: boolean;
+}) {
+ const { t } = useTranslation();
+ const [expanded, setExpanded] = useState(false);
+ const [manual, setManual] = useState(false);
+ const [id, setId] = useState('');
+ const visible = expanded
+ ? choices
+ : choices.filter((choice, index) => index < 2 || choice.checked);
+ const hidden = choices.length - visible.length;
+ const add = () => {
+ if (loading || !id.trim()) return;
+ onAdd(id.trim());
+ setId('');
+ };
+ return (
+ <section className="flex flex-col gap-3" aria-label={t('settings.providers.speechSetup.title')}>
+ <div className="flex items-center gap-2 text-13 font-medium text-[var(--text-primary)]">
+ <AudioLines size={16} aria-hidden="true" />
+ {t('settings.providers.speechSetup.title')}
+ </div>
+ <p className="text-12 leading-relaxed text-[var(--text-secondary)]">
+ {t(
+ choices.some((choice) => choice.reference)
+ ? 'settings.providers.speechSetup.referenceHint'
+ : choices.some((choice) => !choice.manual && !choice.saved)
+ ? 'settings.providers.speechSetup.discoveryHint'
+ : 'settings.providers.speechSetup.manualHint',
+ )}
+ </p>
+ {choices.length > 0 && (
+ <div className="overflow-hidden rounded-xl border border-[var(--border-default)]">
+ {visible.map((choice) => (
+ <button
+ key={choice.id}
+ type="button"
+ role="checkbox"
+ aria-checked={choice.checked || choice.saved === true}
+ disabled={loading || choice.saved}
+ onClick={() => onToggle(choice.id)}
+ className="flex min-h-11 w-full items-center gap-3 border-b border-[var(--border-default)] px-3.5 py-3 text-left last:border-b-0 enabled:hover:bg-[var(--settings-menu-bg-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--focus-ring)] disabled:opacity-60"
+ >
+ <span
+ className={`flex h-4 w-4 shrink-0 items-center justify-center rounded border ${choice.checked || choice.saved ? 'border-[var(--accent-cta-bg)] bg-[var(--accent-cta-bg)] text-[var(--surface-on-card)]' : 'border-[var(--text-tertiary)]'}`}
+ >
+ {(choice.checked || choice.saved) && (
+ <Check size={11} strokeWidth={3} aria-hidden="true" />
+ )}
+ </span>
+ <span className="min-w-0 flex-1">
+ <span
+ className="block truncate text-13 text-[var(--text-primary)]"
+ title={choice.name}
+ >
+ {choice.name}
+ </span>
+ <span
+ className="block truncate text-11 text-[var(--text-tertiary)]"
+ title={choice.id}
+ >
+ {choice.id}
+ </span>
+ </span>
+ <span className="shrink-0 text-11 text-[var(--text-secondary)]">
+ {choice.saved
+ ? t('settings.providers.speechSetup.saved')
+ : choice.recommended
+ ? t('settings.providers.wizard.recommended')
+ : choice.reference
+ ? t('settings.providers.speechSetup.reference')
+ : choice.manual
+ ? t('settings.providers.speechSetup.manualSource')
+ : t('settings.providers.speechSetup.discovered')}
+ </span>
+ </button>
+ ))}
+ </div>
+ )}
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ {hidden > 0 && (
+ <Button variant="secondary" tone="quiet" onClick={() => setExpanded(true)}>
+ {t('settings.providers.speechSetup.more', { count: hidden })}
+ </Button>
+ )}
+ <Button
+ variant="secondary"
+ tone="quiet"
+ onClick={() => setManual((value) => !value)}
+ disabled={loading}
+ >
+ <Plus size={14} aria-hidden="true" />
+ {t('settings.providers.speechSetup.manual')}
+ </Button>
+ </div>
+ {manual && (
+ <div className="flex items-center gap-2">
+ <SettingsTextInput
+ aria-label={t('settings.providers.speechSetup.modelId')}
+ placeholder={t('settings.providers.speechSetup.modelId')}
+ value={id}
+ disabled={loading}
+ onChange={setId}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter') {
+ event.preventDefault();
+ add();
+ }
+ }}
+ />
+ <Button variant="secondary" disabled={!id.trim() || loading} onClick={add}>
+ {t('settings.providers.wizard.addManualModel')}
+ </Button>
+ </div>
+ )}
+ </section>
+ );
+}
diff --git a/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx b/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx
index a1693cbb05..cb5c6b7cdf 100644
--- a/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx
+++ b/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx
@@ -443,6 +443,7 @@ export function managementKindOfRow(row: UnionModelRow, userProvider: boolean):
export function UnifiedModelList({
provider,
onRefresh,
+ onAddSpeechModels,
refreshing,
refreshDisabled,
refreshIdleLabel,
@@ -455,6 +456,7 @@ export function UnifiedModelList({
provider: ProviderView;
/** 「刷新模型」;内置供应商走各自真源,自定义供应商走 additions-only 发现。 */
onRefresh?: () => void;
+ onAddSpeechModels?: () => void;
refreshing?: boolean;
/** 其它供应商正在刷新时禁用,避免并发刷新造成反馈归属不清。 */
refreshDisabled?: boolean;
@@ -1093,6 +1095,9 @@ export function UnifiedModelList({
)}
</p>
</div>
+ {onAddSpeechModels && <Button variant="secondary" onClick={onAddSpeechModels}>
+ {t('settings.providers.speechSetup.add')}
+ </Button>}
{onRefresh && (
<button
type="button"
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index e5e321e289..0039d2ab80 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -3866,7 +3866,26 @@
"pending": "Preparing credentials",
"unavailable": "Temporarily unavailable"
},
- "claudeAccountRetired": "Cindy no longer supports signing in to your subscription through this legacy Claude connection. Your Claude account and subscription are unaffected. Use “Sign in with Claude Code” to connect."
+ "claudeAccountRetired": "Cindy no longer supports signing in to your subscription through this legacy Claude connection. Your Claude account and subscription are unaffected. Use “Sign in with Claude Code” to connect.",
+ "speechSetup": {
+ "title": "Speech",
+ "add": "Add speech models",
+ "referenceHint": "Reference models come from the public catalog, not your account entitlements. Availability depends on an actual request.",
+ "discoveryHint": "These models were returned by the provider catalog. Speech execution has not been tested.",
+ "saved": "Added",
+ "reference": "Reference",
+ "discovered": "Discovered",
+ "more": "More speech models ({{count}})",
+ "manual": "Enter a speech model ID",
+ "modelId": "Speech model ID",
+ "modelsHint": "Saving only adds models; it does not call the speech service. Choose voices and sentence playback in companion voice settings.",
+ "otherModels": "Chat and other models",
+ "separateKey": "Speech requires an API key. This creates a separate connection and keeps your subscription or device-code connection.",
+ "fetchFailed": "The model catalog is unavailable. You can still add reference models.",
+ "saveFailed": "Could not add models. Reopen this page and try again.",
+ "manualSource": "Manual",
+ "manualHint": "Enter the speech model ID provided by your supplier."
+ }
},
"experimental": {
"title": "Experimental",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index c634b6c660..4c96f97ec7 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -3835,7 +3835,26 @@
"pending": "認証情報を準備中",
"unavailable": "一時的に利用できません"
},
- "claudeAccountRetired": "Cindy では、この旧式の Claude 接続を使ったサブスクリプションへのログインに対応していません。Claude アカウントとサブスクリプションには影響ありません。「Claude Code でログイン」から接続してください。"
+ "claudeAccountRetired": "Cindy では、この旧式の Claude 接続を使ったサブスクリプションへのログインに対応していません。Claude アカウントとサブスクリプションには影響ありません。「Claude Code でログイン」から接続してください。",
+ "speechSetup": {
+ "title": "音声",
+ "add": "音声モデルを追加",
+ "referenceHint": "参考モデルは公開カタログに基づき、アカウントの利用権限を示すものではありません。実際に利用できるかは呼び出し時に確認されます。",
+ "discoveryHint": "以下はプロバイダーのカタログから取得したモデルです。音声の実行は未検証です。",
+ "saved": "追加済み",
+ "reference": "参考モデル",
+ "discovered": "取得済み",
+ "more": "その他の音声モデル({{count}})",
+ "manual": "音声モデル ID を入力",
+ "modelId": "音声モデル ID",
+ "modelsHint": "保存ではモデルの追加のみを行い、音声サービスは呼び出しません。音声や文ごとの読み上げはパートナーの音声設定で調整できます。",
+ "otherModels": "チャットとその他のモデル",
+ "separateKey": "音声には API キーが必要です。別の接続を作成し、既存のサブスクリプションやデバイスコードの接続は保持します。",
+ "fetchFailed": "モデル一覧を取得できません。参考モデルを選んで追加できます。",
+ "saveFailed": "モデルを追加できませんでした。このページを開き直して再試行してください。",
+ "manualSource": "手動追加",
+ "manualHint": "プロバイダーが提供する音声モデル ID を入力してください。"
+ }
},
"experimental": {
"title": "実験的機能",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 66f9c9d783..2d05355f06 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -3835,7 +3835,26 @@
"pending": "인증 정보 준비 중",
"unavailable": "일시적으로 사용할 수 없음"
},
- "claudeAccountRetired": "Cindy에서는 이 이전 Claude 연결 방식으로 구독에 로그인할 수 없습니다. Claude 계정과 구독에는 영향이 없습니다. ‘Claude Code로 로그인’을 사용해 구독을 연결하세요."
+ "claudeAccountRetired": "Cindy에서는 이 이전 Claude 연결 방식으로 구독에 로그인할 수 없습니다. Claude 계정과 구독에는 영향이 없습니다. ‘Claude Code로 로그인’을 사용해 구독을 연결하세요.",
+ "speechSetup": {
+ "title": "음성",
+ "add": "음성 모델 추가",
+ "referenceHint": "참조 모델은 공개 카탈로그를 기반으로 하며 계정의 이용 권한을 의미하지 않습니다. 실제 사용 가능 여부는 호출 시 확인됩니다.",
+ "discoveryHint": "제공자 카탈로그에서 반환된 모델입니다. 음성 실행은 아직 검증되지 않았습니다.",
+ "saved": "추가됨",
+ "reference": "참조 모델",
+ "discovered": "검색됨",
+ "more": "음성 모델 더 보기 ({{count}})",
+ "manual": "음성 모델 ID 직접 입력",
+ "modelId": "음성 모델 ID",
+ "modelsHint": "저장은 모델만 추가하며 음성 서비스를 호출하지 않습니다. 음색과 문장별 읽기는 파트너 음성 설정에서 조정할 수 있습니다.",
+ "otherModels": "대화 및 기타 모델",
+ "separateKey": "음성에는 API 키가 필요합니다. 별도 연결을 만들고 기존 구독 또는 기기 코드 연결은 유지합니다.",
+ "fetchFailed": "모델 목록을 가져올 수 없습니다. 참조 모델을 선택하여 추가할 수 있습니다.",
+ "saveFailed": "모델을 추가하지 못했습니다. 이 페이지를 다시 열고 시도해 주세요.",
+ "manualSource": "직접 추가",
+ "manualHint": "제공자가 제공한 음성 모델 ID를 입력하세요."
+ }
},
"experimental": {
"title": "실험적 기능",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 0f0fe7389c..8b1c5d7167 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -3835,7 +3835,26 @@
"pending": "凭据准备中",
"unavailable": "暂时不可用"
},
- "claudeAccountRetired": "Cindy 已不再支持通过这条旧版 Claude 连接登录订阅,不影响你的 Claude 账号和订阅。请改用「使用 Claude Code 登录」连接订阅"
+ "claudeAccountRetired": "Cindy 已不再支持通过这条旧版 Claude 连接登录订阅,不影响你的 Claude 账号和订阅。请改用「使用 Claude Code 登录」连接订阅",
+ "speechSetup": {
+ "title": "语音",
+ "add": "添加语音模型",
+ "referenceHint": "参考型号来自公共模型资料,不代表当前账号已开通。是否可用以实际调用为准。",
+ "discoveryHint": "以下型号由供应商目录返回,尚未验证语音调用。",
+ "saved": "已添加",
+ "reference": "参考型号",
+ "discovered": "目录返回",
+ "more": "更多语音型号({{count}})",
+ "manual": "手动输入语音型号",
+ "modelId": "语音模型 ID",
+ "modelsHint": "保存仅添加模型,不会调用语音服务。音色和逐句朗读可在伙伴语音设置中调整。",
+ "otherModels": "对话与其他模型",
+ "separateKey": "语音服务需要 API Key。将创建独立连接,原有订阅或设备码连接会保留。",
+ "fetchFailed": "模型目录暂时无法获取,仍可选择参考型号添加。",
+ "saveFailed": "添加失败,请重新打开此页面后重试。",
+ "manualSource": "手动添加",
+ "manualHint": "输入供应商提供的语音模型 ID。"
+ }
},
"experimental": {
"title": "实验性功能",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index d6cdcbde1a..0da6fe0333 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -3835,7 +3835,26 @@
"pending": "憑證準備中",
"unavailable": "暫時無法使用"
},
- "claudeAccountRetired": "Cindy 已不再支援透過這筆舊版 Claude 連線登入訂閱,不影響你的 Claude 帳號和訂閱。請改用「使用 Claude Code 登入」連線訂閱"
+ "claudeAccountRetired": "Cindy 已不再支援透過這筆舊版 Claude 連線登入訂閱,不影響你的 Claude 帳號和訂閱。請改用「使用 Claude Code 登入」連線訂閱",
+ "speechSetup": {
+ "title": "語音",
+ "add": "新增語音模型",
+ "referenceHint": "參考型號來自公開模型資料,不代表目前帳號已開通。是否可用以實際呼叫為準。",
+ "discoveryHint": "以下型號由供應商目錄傳回,尚未驗證語音呼叫。",
+ "saved": "已新增",
+ "reference": "參考型號",
+ "discovered": "目錄傳回",
+ "more": "更多語音型號({{count}})",
+ "manual": "手動輸入語音型號",
+ "modelId": "語音模型 ID",
+ "modelsHint": "儲存僅新增模型,不會呼叫語音服務。音色和逐句朗讀可在夥伴語音設定中調整。",
+ "otherModels": "對話與其他模型",
+ "separateKey": "語音服務需要 API Key。將建立獨立連線,原有訂閱或裝置碼連線會保留。",
+ "fetchFailed": "暫時無法取得模型目錄,仍可選擇參考型號新增。",
+ "saveFailed": "新增失敗,請重新開啟此頁面後重試。",
+ "manualSource": "手動新增",
+ "manualHint": "輸入供應商提供的語音模型 ID。"
+ }
},
"experimental": {
"title": "實驗性功能",
diff --git a/apps/desktop/src/shared/customProviderUpdate.ts b/apps/desktop/src/shared/customProviderUpdate.ts
index c61d6ec53e..a997160aad 100644
--- a/apps/desktop/src/shared/customProviderUpdate.ts
+++ b/apps/desktop/src/shared/customProviderUpdate.ts
@@ -2,6 +2,8 @@ export type CodexImageGenerationRestartPolicy = 'interrupt';
export interface CustomProviderUpdateOptions {
source?: 'manual-settings';
+ /** Local Settings additions, merged against the latest connection in Main. */
+ appendSpeechModelsOnly?: true;
codexImageGenerationRestartPolicy?: CodexImageGenerationRestartPolicy;
}
diff --git a/apps/desktop/src/shared/speechProviderSetup.ts b/apps/desktop/src/shared/speechProviderSetup.ts
new file mode 100644
index 0000000000..cd0433a644
--- /dev/null
+++ b/apps/desktop/src/shared/speechProviderSetup.ts
@@ -0,0 +1,215 @@
+import {
+ BUNDLED_CATALOG,
+ buildUserProvider,
+ findBaseModel,
+ type AgentKind,
+ type CustomProviderConfig,
+ type ModelMetadata,
+ type ProviderPreset,
+ type ProviderRuntimeModelConfig,
+ type ProviderView,
+} from '@cindy/model-providers';
+
+export type SpeechService = 'minimax' | 'elevenlabs' | 'openai' | 'bailian';
+
+/** Onboarding references only: no account entitlement or synthesis probe is implied. */
+const references: Record<SpeechService, string[]> = {
+ minimax: ['speech-2.8-turbo', 'speech-2.8-hd', 'speech-02-turbo'],
+ elevenlabs: ['eleven_flash_v2_5', 'eleven_multilingual_v2', 'eleven_v3'],
+ openai: ['gpt-4o-mini-tts', 'tts-1', 'tts-1-hd'],
+ bailian: ['cosyvoice-v3-flash', 'qwen3-tts-flash', 'cosyvoice-v3-plus'],
+};
+
+export function speechServiceForUrl(value: string): SpeechService | undefined {
+ try {
+ const url = new URL(value);
+ if (
+ url.protocol !== 'https:' ||
+ url.port ||
+ url.username ||
+ url.password ||
+ url.search ||
+ url.hash
+ )
+ return;
+ const path = url.pathname.replace(/\/+$/, '');
+ if (
+ [
+ 'api.minimax.io',
+ 'api.minimax.cn',
+ 'api.minimaxi.com',
+ 'api.minimax.chat',
+ 'api-uw.minimax.io',
+ ].includes(url.hostname) &&
+ ['', '/v1', '/anthropic'].includes(path)
+ )
+ return 'minimax';
+ if (url.hostname === 'api.elevenlabs.io' && ['', '/v1'].includes(path)) return 'elevenlabs';
+ if (url.hostname === 'api.openai.com' && ['', '/v1'].includes(path)) return 'openai';
+ if (
+ ([
+ 'dashscope.aliyuncs.com',
+ 'dashscope-intl.aliyuncs.com',
+ 'dashscope-us.aliyuncs.com',
+ ].includes(url.hostname) ||
+ /^ws-[a-z0-9]+\.cn-beijing\.maas\.aliyuncs\.com$/.test(url.hostname)) &&
+ ['/api/v1', '/compatible-mode/v1'].includes(path)
+ )
+ return 'bailian';
+ } catch {
+ /* Invalid/unrecognized endpoints keep the manual connection flow. */
+ }
+}
+
+export function isSpeechModel(model: {
+ id: string;
+ mode?: string;
+ discoveredMetadata?: ModelMetadata;
+}): boolean {
+ return (
+ (model.mode ??
+ model.discoveredMetadata?.mode ??
+ findBaseModel(BUNDLED_CATALOG.modelRegistry, model.id)?.defaults.mode) === 'audio_speech'
+ );
+}
+
+export function speechReferenceModels(service: SpeechService): ProviderRuntimeModelConfig[] {
+ // Names/capabilities remain owned by the shared Registry. This list only orders
+ // a few setup suggestions; adding one is an explicit user membership decision.
+ return references[service].flatMap((id, index) => {
+ const base = findBaseModel(BUNDLED_CATALOG.modelRegistry, id);
+ return base?.defaults.mode === 'audio_speech'
+ ? [{ id, name: base.defaults.name ?? id, defaultEnabled: index === 0 }]
+ : [];
+ });
+}
+
+export function speechSetupTarget(runtimes: ProviderPreset['runtimes']) {
+ for (const agent of ['codex', 'pi', 'claude-code'] as const) {
+ const runtime = runtimes[agent];
+ const service = runtime && speechServiceForUrl(runtime.baseUrl);
+ if (service) return { agent, service };
+ }
+}
+
+/** These are local connection forms, like OFFICIAL_API_PRESETS, not Registry entries. */
+export const SPEECH_API_PRESETS: ProviderPreset[] = [
+ {
+ id: 'elevenlabs-api',
+ name: 'ElevenLabs',
+ docsUrl: 'https://elevenlabs.io/app/settings/api-keys',
+ runtimes: {
+ codex: { baseUrl: 'https://api.elevenlabs.io/v1', wireProtocol: 'openai-chat', models: [] },
+ },
+ },
+ ...(['global', 'cn'] as const).map((region): ProviderPreset => ({
+ id: `aliyun-bailian-api-${region}`,
+ name: region === 'cn' ? '阿里云百炼 API(中国大陆)' : '阿里云百炼 API',
+ nameEn:
+ region === 'cn'
+ ? 'Alibaba Cloud Model Studio API (Mainland China)'
+ : 'Alibaba Cloud Model Studio API',
+ nameZhTW: region === 'cn' ? '阿里雲百煉 API(中國大陸)' : '阿里雲百煉 API',
+ regionHint: region,
+ docsUrl: 'https://www.alibabacloud.com/help/en/model-studio/get-api-key',
+ runtimes: {
+ codex: {
+ baseUrl: `https://${region === 'cn' ? 'dashscope' : 'dashscope-intl'}.aliyuncs.com/compatible-mode/v1`,
+ wireProtocol: 'openai-chat',
+ baseUrlEditable: true,
+ models: [{ id: 'qwen-plus', name: 'Qwen Plus' }],
+ },
+ },
+ })),
+];
+
+export function withSpeechApiPresets(presets: ProviderPreset[]): ProviderPreset[] {
+ return [
+ ...presets,
+ ...SPEECH_API_PRESETS.filter((fallback) => {
+ const target = speechSetupTarget(fallback.runtimes)!;
+ const origin = new URL(fallback.runtimes[target.agent]!.baseUrl).origin;
+ return !presets.some((existing) => {
+ if (existing.id === fallback.id) return true;
+ // Prefer the server's official connection form even when it has a newer ID.
+ // Coding/Token Plan endpoints are distinct and must not suppress API access.
+ const existingTarget = speechSetupTarget(existing.runtimes);
+ return (
+ existingTarget?.service === target.service &&
+ new URL(existing.runtimes[existingTarget.agent]!.baseUrl).origin === origin
+ );
+ });
+ }),
+ ];
+}
+
+export function providerSpeechSetup(
+ provider: ProviderView,
+):
+ { agent: AgentKind; service: SpeechService; needsApiKey: boolean; presetId: string } | undefined {
+ if (provider.source === 'organization' || provider.suspended) return;
+ for (const agent of ['codex', 'pi', 'claude-code'] as const) {
+ const upstream = provider.routing[agent]?.upstream;
+ const service = upstream && speechServiceForUrl(upstream);
+ if (!service) continue;
+ if (provider.auth.method === 'apiKey' && provider.source !== 'user') continue;
+ if (!['apiKey', 'oauth'].includes(provider.auth.method)) continue;
+ return {
+ agent,
+ service,
+ needsApiKey: provider.auth.method === 'oauth',
+ presetId:
+ service === 'minimax'
+ ? ['api.minimax.io', 'api-uw.minimax.io'].includes(new URL(upstream!).hostname)
+ ? 'minimax-global'
+ : 'minimax-cn'
+ : service === 'bailian'
+ ? upstream!.includes('dashscope-intl')
+ ? 'aliyun-bailian-api-global'
+ : 'aliyun-bailian-api-cn'
+ : `${service}-api`,
+ };
+ }
+ // Native OpenAI subscription endpoints are deliberately different from its API.
+ if (provider.id === 'openai' || provider.auth.native === 'codex')
+ return { agent: 'codex', service: 'openai', needsApiKey: true, presetId: 'openai-api' };
+}
+
+/** Merge under Main's mutation queue, preserving concurrent edits and all existing models. */
+export function appendSpeechModels(
+ current: CustomProviderConfig,
+ request: CustomProviderConfig,
+): CustomProviderConfig {
+ if ((current.auth?.method ?? 'apiKey') !== 'apiKey')
+ throw new Error('api_key_connection_required');
+ const next = structuredClone(current);
+ // The catalog omits an explicit runtime protocol when it equals the engine default.
+ // Compare the same projection, while keeping the original stored declaration intact.
+ const currentRouting = buildUserProvider(current).routing;
+ const requestedRouting = buildUserProvider(request).routing;
+ const known = new Set(
+ Object.values(next.runtimes).flatMap(
+ (runtime) => runtime?.models.map((model) => model.id) ?? [],
+ ),
+ );
+ for (const [key, draft] of Object.entries(request.runtimes)) {
+ const agent = key as AgentKind;
+ const runtime = next.runtimes[agent];
+ if (
+ !draft ||
+ !runtime ||
+ runtime.baseUrl !== draft.baseUrl ||
+ currentRouting[agent]?.wireProtocol !== requestedRouting[agent]?.wireProtocol ||
+ runtime.requestPath !== draft.requestPath ||
+ runtime.modelsUrl !== draft.modelsUrl
+ )
+ throw new Error('connection_changed');
+ for (const model of draft.models) {
+ if (!isSpeechModel(model)) throw new Error('speech_model_required');
+ if (known.has(model.id)) continue;
+ runtime.models.push(structuredClone(model));
+ known.add(model.id);
+ }
+ }
+ return next;
+}
diff --git a/docs/product-rules/provider-settings.md b/docs/product-rules/provider-settings.md
index 22ce47548c..eac9c994ea 100644
--- a/docs/product-rules/provider-settings.md
+++ b/docs/product-rules/provider-settings.md
@@ -116,3 +116,11 @@ OpenAI、Claude 和 Grok 都允许新增独立登录账号。每次新增生成
- 本机 Claude 刷新被服务端明确拒绝时,仅在现有绑定文件记录该次凭证的 SHA-256 摘要。
重启或手动断开不清除这个标记;同一凭证不能重新连接,来源工具更新凭证或更换账号后可重新连接。
不删除系统凭证,不新增凭证明文副本,不为正常手动断开后的恢复增加网络验证。
+
+## 语音型号接入
+
+- 「添加供应商」保持一个入口。API Key 连接沿用选择供应商、连接、选择模型三步;在同一模型页分组展示对话与其他模型、语音模型。MiniMax、OpenAI API、ElevenLabs、百炼普通 API 提供语音参考型号,默认勾选一个推荐型号,用户可以取消或仅添加语音型号。
+- 已有 API Key 连接在模型管理工具行提供「添加语音模型」。操作绑定连接 ID,追加用户选择的新型号;不重填密钥,不覆盖已有名称、协议、模型类型、开关和其他 runtime。Main 在原有供应商修改队列内合并最新配置,连接地址已变更则要求重新打开;不使用旧快照替换整个连接。
+- 订阅或设备码连接走独立 API Key 连接,不转换、不覆盖原连接。普通百炼 API 与 Coding Plan / Token Plan 入口分开,不推断套餐具有语音额度。
+- 目录返回、公共参考和用户手填是不同来源。参考清单只描述添加建议,名称与能力仍继承公共 Registry;未选中的参考型号不写入账号连接。目录明确返回非 TTS 能力时,不以参考清单把它恢复成语音。
+- 获取目录和保存型号不等于调用成功或已获授权;不自动发起计费合成。音色、试听、逐句朗读属于伙伴语音设置,不进入供应商添加流程。Qwen / CosyVoice 的目录接入不替代各自原生执行器的交付和验证。