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。

fix(desktop): simplify companion voice labels and reveal IDs on demand

JiangJiahao3ce983eedf2c
diff --git a/apps/desktop/src/renderer/features/bots/voice/SpeechVoicePicker.tsx b/apps/desktop/src/renderer/features/bots/voice/SpeechVoicePicker.tsx
index c945d96d6c..20f971b40e 100644
--- a/apps/desktop/src/renderer/features/bots/voice/SpeechVoicePicker.tsx
+++ b/apps/desktop/src/renderer/features/bots/voice/SpeechVoicePicker.tsx
@@ -1,10 +1,11 @@
-import { useEffect, useRef, useState, useSyncExternalStore } from 'react';
+import { useEffect, useId, useMemo, useRef, useState, useSyncExternalStore } from 'react';
import { useTranslation } from 'react-i18next';
-import { RefreshCw, Square, Volume2 } from 'lucide-react';
+import { ChevronRight, Copy, RefreshCw, Square, Volume2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { FormField } from '@/components/ui/form-field';
import { Input } from '@/components/ui/input';
import { Select } from '@/components/ui/select';
+import { toast } from '@/lib/toast';
import {
normalizeVoiceConversationSelection,
type SpeechModelSelection,
@@ -39,6 +40,8 @@ export function SpeechVoicePicker({
const [loading, setLoading] = useState(false);
const [revision, setRevision] = useState(0);
const [manual, setManual] = useState(false);
+ const [showVoiceId, setShowVoiceId] = useState(false);
+ const voiceIdDetailsId = useId();
const version = useRef(0);
const routeKey = JSON.stringify([route, protocol]);
const phase = useSyncExternalStore(preview.subscribe, preview.getSnapshot);
@@ -46,6 +49,35 @@ export function SpeechVoicePicker({
const selection = normalizeVoiceConversationSelection({ ...route, voice });
const listed = catalog?.voices.some((item) => item.id === voice);
const showManual = manual || (!!voice && !listed) || !catalog?.voices.length;
+ const voiceOptions = useMemo(() => {
+ const voices = (catalog?.voices ?? []).map((item) => ({
+ ...item,
+ name: item.name.trim() || item.id,
+ }));
+ const idsByName = new Map<string, string[]>();
+ for (const item of voices) {
+ const ids = idsByName.get(item.name) ?? [];
+ ids.push(item.id);
+ idsByName.set(item.name, ids);
+ }
+ return voices.map((item) => {
+ const peers = idsByName.get(item.name)!;
+ let label = item.name;
+ if (peers.length > 1) {
+ // Short IDs only distinguish duplicate labels; selection and storage keep
+ // the full provider ID. Extend colliding suffixes until they are distinct.
+ let length = 6;
+ while (
+ length < item.id.length &&
+ peers.some((id) => id !== item.id && id.slice(-length) === item.id.slice(-length))
+ ) {
+ length++;
+ }
+ label += ` · ${length < item.id.length ? '…' : ''}${item.id.slice(-length)}`;
+ }
+ return { value: `voice:${item.id}`, label };
+ });
+ }, [catalog]);
useEffect(() => {
const request = ++version.current;
@@ -74,6 +106,7 @@ export function SpeechVoicePicker({
useEffect(() => {
setManual(false);
+ setShowVoiceId(false);
void preview.stop();
return () => {
void preview.stop();
@@ -92,13 +125,7 @@ export function SpeechVoicePicker({
{...control}
label={t('bots.voiceMode.voice')}
value={showManual ? MANUAL : listed ? `voice:${voice}` : ''}
- options={[
- ...(catalog?.voices ?? []).map((item) => ({
- value: `voice:${item.id}`,
- label: item.name === item.id ? item.name : `${item.name} · ${item.id}`,
- })),
- { value: MANUAL, label: t('bots.voiceMode.manualVoice') },
- ]}
+ options={[...voiceOptions, { value: MANUAL, label: t('bots.voiceMode.manualVoice') }]}
disabled={disabled}
onValueChange={(value) => {
void preview.stop();
@@ -155,6 +182,49 @@ export function SpeechVoicePicker({
/>
)}
</FormField>
+ ) : voice ? (
+ <div className="min-w-0 space-y-2">
+ <Button
+ variant="secondary"
+ tone="quiet"
+ size="sm"
+ compact
+ aria-expanded={showVoiceId}
+ aria-controls={voiceIdDetailsId}
+ onClick={() => setShowVoiceId((value) => !value)}
+ >
+ <ChevronRight
+ size={14}
+ aria-hidden="true"
+ className={showVoiceId ? 'rotate-90' : undefined}
+ />
+ {t('bots.voiceMode.voiceId')}
+ </Button>
+ <div id={voiceIdDetailsId} hidden={!showVoiceId}>
+ <div className="flex min-w-0 items-start gap-2">
+ <code className="min-w-0 flex-1 select-text break-all py-1 text-12 text-[var(--text-secondary)]">
+ {voice}
+ </code>
+ <Button
+ variant="secondary"
+ size="sm"
+ compact
+ aria-label={t('bots.voiceMode.copyVoiceId')}
+ title={t('bots.voiceMode.copyVoiceId')}
+ onClick={async () => {
+ try {
+ await navigator.clipboard.writeText(voice);
+ toast.success(t('bots.voiceMode.voiceIdCopied'));
+ } catch {
+ toast.error(t('bots.voiceMode.voiceIdCopyFailed'));
+ }
+ }}
+ >
+ <Copy size={14} aria-hidden="true" />
+ </Button>
+ </div>
+ </div>
+ </div>
) : null}
<div className="flex flex-wrap items-center gap-2">
<Button
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.tsx
index 9a99252f15..1c0e0f9530 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
@@ -1,6 +1,7 @@
// @vitest-environment jsdom
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { voiceModelKey, type VoiceConversationModel } from '@/../shared/voiceConversation';
+import { toast } from '@/lib/toast';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
vi.mock('@/components/ui/select', () => ({
@@ -33,6 +34,7 @@ vi.mock('@/components/ui/select', () => ({
),
}));
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+vi.mock('@/lib/toast', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
vi.mock('@/hooks/useVoiceInputSettings', () => ({
getVoiceInputSettings: () => ({ microphoneDeviceId: null }),
}));
@@ -423,6 +425,101 @@ it('retries a failed preference load and still lists BYOK when Gateway refresh f
expect(window.electronAPI.voiceConversation.preference).toHaveBeenCalledTimes(2);
});
+it('shows names by default and reveals and copies the complete saved voice ID without changing it', async () => {
+ const voice = 'SAz9YHcvj6GT2YYXdXww';
+ const name = 'River - Relaxed, Neutral, Informative';
+ models = [
+ {
+ id: 'speech',
+ name: 'ElevenLabs',
+ providerId: 'mine',
+ agent: 'codex',
+ protocol: 'elevenlabs',
+ },
+ ];
+ vi.mocked(window.electronAPI.voiceConversation.voices).mockResolvedValue({
+ source: 'provider',
+ voices: [{ id: voice, name }],
+ });
+ vi.mocked(window.electronAPI.voiceConversation.preference).mockResolvedValue({
+ selection: { providerId: 'mine', agent: 'codex', modelId: 'speech', voice },
+ customized: true,
+ });
+ const writeText = vi.fn(async () => {});
+ const clipboard = Object.getOwnPropertyDescriptor(navigator, 'clipboard');
+ Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } });
+ try {
+ renderSettings();
+ const option = (await screen.findByRole('option', { name })) as HTMLOptionElement;
+ expect(option.selected).toBe(true);
+ expect(option.value).toBe(`voice:${voice}`);
+ expect(screen.queryByRole('button', { name: 'bots.voiceMode.copyVoiceId' })).toBeNull();
+ const details = screen.getByRole('button', { name: 'bots.voiceMode.voiceId' });
+ expect(details.getAttribute('aria-expanded')).toBe('false');
+ fireEvent.click(details);
+ expect(details.getAttribute('aria-expanded')).toBe('true');
+ const fullId = screen.getByText(voice);
+ expect(fullId.closest('[hidden]')).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'bots.voiceMode.copyVoiceId' }));
+ await waitFor(() => expect(toast.success).toHaveBeenCalledWith('bots.voiceMode.voiceIdCopied'));
+ expect(writeText).toHaveBeenCalledWith(voice);
+
+ writeText.mockRejectedValueOnce(new Error('clipboard unavailable'));
+ fireEvent.click(screen.getByRole('button', { name: 'bots.voiceMode.copyVoiceId' }));
+ await waitFor(() =>
+ expect(toast.error).toHaveBeenCalledWith('bots.voiceMode.voiceIdCopyFailed'),
+ );
+ expect(fullId.closest('[hidden]')).toBeNull();
+ expect(window.electronAPI.voiceConversation.setPreference).not.toHaveBeenCalled();
+ expect(window.electronAPI.voiceConversation.preview).not.toHaveBeenCalled();
+ expect(start).not.toHaveBeenCalled();
+ expect(audio.start).not.toHaveBeenCalled();
+ } finally {
+ if (clipboard) Object.defineProperty(navigator, 'clipboard', clipboard);
+ else Reflect.deleteProperty(navigator, 'clipboard');
+ }
+});
+
+it('disambiguates duplicate names even when short ID suffixes collide and preserves full IDs', async () => {
+ models = [
+ {
+ id: 'speech',
+ name: 'ElevenLabs',
+ providerId: 'mine',
+ agent: 'codex',
+ protocol: 'elevenlabs',
+ },
+ ];
+ vi.mocked(window.electronAPI.voiceConversation.voices).mockResolvedValue({
+ source: 'provider',
+ voices: [
+ { id: 'voice-a-123456', name: 'River' },
+ { id: 'voice-b-123456', name: 'River' },
+ { id: 'unnamed-voice-id', name: ' ' },
+ { id: 'already-the-name', name: 'already-the-name' },
+ ],
+ });
+ renderSettings();
+ await screen.findByRole('option', { name: 'River · …a-123456' });
+ const other = (await screen.findByRole('option', {
+ name: 'River · …b-123456',
+ })) as HTMLOptionElement;
+ expect(other.value).toBe('voice:voice-b-123456');
+ expect(screen.getByRole('option', { name: 'unnamed-voice-id' })).toBeTruthy();
+ expect(screen.getByRole('option', { name: 'already-the-name' })).toBeTruthy();
+ fireEvent.change(screen.getByLabelText('bots.voiceMode.voice'), {
+ target: { value: other.value },
+ });
+ await waitFor(() =>
+ expect(window.electronAPI.voiceConversation.setPreference).toHaveBeenCalledWith('bot', {
+ providerId: 'mine',
+ agent: 'codex',
+ modelId: 'speech',
+ voice: 'voice-b-123456',
+ }),
+ );
+});
+
it('selects an account voice, keeps manual IDs on catalog failure, and previews without capturing audio', async () => {
models = [
{ id: 'speech', name: 'MiniMax', providerId: 'mine', agent: 'codex', protocol: 'minimax' },
@@ -434,7 +531,7 @@ it('selects an account voice, keeps manual IDs on catalog failure, and previews
})
.mockRejectedValueOnce(new Error('offline'));
renderSettings();
- await screen.findByRole('option', { name: 'News Anchor · Chinese (Mandarin)_News_Anchor' });
+ await screen.findByRole('option', { name: 'News Anchor' });
fireEvent.change(screen.getByLabelText('bots.voiceMode.voice'), {
target: { value: 'voice:Chinese (Mandarin)_News_Anchor' },
});
@@ -497,11 +594,11 @@ it('resets a voice when switching models on the same connection and ignores a la
fireEvent.change(screen.getByLabelText('bots.voiceMode.model'), {
target: { value: voiceModelKey(models[1]) },
});
- await screen.findByRole('option', { name: 'New voice · new' });
+ await screen.findByRole('option', { name: 'New voice' });
expect((screen.getByLabelText('bots.voiceMode.voice') as HTMLSelectElement).value).toBe('');
expect(screen.queryByLabelText('bots.voiceMode.voiceId')).toBeNull();
release({ source: 'provider', voices: [{ id: 'old', name: 'Old voice' }] });
- await waitFor(() => expect(screen.queryByRole('option', { name: 'Old voice · old' })).toBeNull());
+ await waitFor(() => expect(screen.queryByRole('option', { name: 'Old voice' })).toBeNull());
expect(window.electronAPI.voiceConversation.setPreference).not.toHaveBeenCalled();
});
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 4e9c0831cf..665246d8e5 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -9383,6 +9383,9 @@
"incompleteSettings": "Choose a speech API and voice to save automatically.",
"previewNeedsChat": "Start a conversation with this companion to preview a voice.",
"voiceId": "Voice ID",
+ "copyVoiceId": "Copy voice ID",
+ "voiceIdCopied": "Voice ID copied",
+ "voiceIdCopyFailed": "Could not copy. Select the voice ID and copy it manually.",
"manualVoice": "Enter a voice ID",
"voiceCatalogHint": "Choose a voice, then preview it to check that it works with the selected model.",
"refreshVoices": "Refresh voices",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 738f4761f6..68b607ddea 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -9346,6 +9346,9 @@
"incompleteSettings": "音声 API と声を選択すると自動で保存されます。",
"previewNeedsChat": "パートナーとの会話を開始すると試聴できます。",
"voiceId": "音声 ID",
+ "copyVoiceId": "音声 ID をコピー",
+ "voiceIdCopied": "音声 ID をコピーしました",
+ "voiceIdCopyFailed": "コピーできませんでした。音声 ID を選択して手動でコピーしてください。",
"manualVoice": "音声 ID を手動入力",
"voiceCatalogHint": "音声を選び、現在のモデルで使えるか試聴で確認してください。",
"refreshVoices": "音声リストを更新",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index c083ddc7a8..1a55674d42 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -9346,6 +9346,9 @@
"incompleteSettings": "음성 API와 음성을 선택하면 자동으로 저장됩니다.",
"previewNeedsChat": "파트너와 대화를 시작하면 음성을 미리 들을 수 있습니다.",
"voiceId": "음성 ID",
+ "copyVoiceId": "음성 ID 복사",
+ "voiceIdCopied": "음성 ID를 복사했어요",
+ "voiceIdCopyFailed": "복사하지 못했습니다. 음성 ID를 선택해 직접 복사하세요.",
"manualVoice": "음성 ID 직접 입력",
"voiceCatalogHint": "음성을 선택한 후 미리 들어 현재 모델에서 사용할 수 있는지 확인하세요.",
"refreshVoices": "음성 목록 새로고침",
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 cb5eea2bd5..41b69d79ae 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -9346,6 +9346,9 @@
"incompleteSettings": "选择语音接口和音色后自动保存。",
"previewNeedsChat": "与伙伴开始对话后可试听。",
"voiceId": "音色 ID",
+ "copyVoiceId": "复制音色 ID",
+ "voiceIdCopied": "已复制音色 ID",
+ "voiceIdCopyFailed": "复制失败,请选中音色 ID 后手动复制。",
"manualVoice": "手动输入音色 ID",
"voiceCatalogHint": "选择音色后试听,确认当前模型可以使用它。",
"refreshVoices": "刷新音色列表",
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 b33aa70575..ab8e2ac57f 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -9346,6 +9346,9 @@
"incompleteSettings": "選擇語音介面和音色後自動儲存。",
"previewNeedsChat": "與夥伴開始對話後可試聽。",
"voiceId": "音色 ID",
+ "copyVoiceId": "複製音色 ID",
+ "voiceIdCopied": "已複製音色 ID",
+ "voiceIdCopyFailed": "複製失敗,請選取音色 ID 後手動複製。",
"manualVoice": "手動輸入音色 ID",
"voiceCatalogHint": "選擇音色後試聽,確認目前的模型可以使用它。",
"refreshVoices": "重新整理音色清單",
diff --git a/docs/product-rules/companion-voice-mode.md b/docs/product-rules/companion-voice-mode.md
index c2c39979fe..abacf99681 100644
--- a/docs/product-rules/companion-voice-mode.md
+++ b/docs/product-rules/companion-voice-mode.md
@@ -49,6 +49,7 @@
- **OpenAI 兼容**:仅对已知精确型号及已知格式的日期版本提供代码内的官方参考列表;`gpt-4o-mini-tts` 与 `tts-1` / `tts-1-hd` 的集合分开。未知型号不强行填 `alloy`,也不探测不存在的通用 `/voices`。兼容服务可能只实现部分音色,列表明确标注为参考,是否可用仍需试听。[资料来源](https://developers.openai.com/api/docs/guides/text-to-speech#voice-options)。
- **ElevenLabs**:从对应连接的 `/v2/voices` 分页查询账号音色;由既有 `/v1` base 替换末段,保留代理 origin 和路径前缀。无版本后缀的自定义代理尝试其 `<base>/voices` 旧接口。`high_quality_base_model_ids` 不作为模型可用性的硬过滤条件。失败时允许重试或手动输入。[资料来源](https://elevenlabs.io/docs/api-reference/voices/search)。
- **MiniMax**:调用 `<base>/get_voice`,`voice_type: all`,合并 `system_voice`、`voice_cloning`、`voice_generation`;名称与 ID 分开,缺名称时显示 ID。音色 ID 接受真实型号所需的空格、括号等字符,保留长度、控制字符和路径分隔符校验。[资料来源](https://platform.minimax.io/docs/api-reference/voice-management-get)。
+- 音色选项与当前选中项默认只显示名称及供应商提供的风格说明;同名音色附加短 ID 尾缀,尾缀冲突时延长至可区分,缺名称时回退为完整 ID。已选音色的完整 ID 可展开查看、复制,手动输入入口保留。显示缩写不改变选择值、伙伴偏好或合成请求中的完整 ID,也不触发已有偏好重写。
- 目录请求只在 Main 使用当前连接的凭证,拒绝重定向,限制 15 秒、每页 2MB 和最多 1000 个音色 / 10 页;超过显示范围时提示手动输入兜底。账号、密钥或路由在请求期间变化则丢弃结果。账号专属音色列表只留在面板内存,不写入公共 Registry 或新的配置文件;已有伙伴偏好仅保存所选 ID,不自动迁移或重写。
- 用户点击试听后,以当前连接、型号、接口和音色合成短示例文本,并明确提示可能产生用量。复用既有 PCM 合成、解码和播放;不采集麦克风、不发送伙伴消息、不调用聊天模型,不使用供应商返回的任意 `preview_url`。试听结果表示这次调用结果,不持久标记整个账号或型号已验证。
- 试听与语音模式/听写互斥,绑定可信窗口、账号和伙伴 canonical 任务。生成过程中也可停止;改选、隐藏页面、关面板、账号变化、系统挂起或权限阻塞时取消;开始语音前等待试听停止。窗口销毁与 60 秒总时限均释放 Main 的语音占用。晚到的结果不恢复播放、不覆盖新选择。