Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(tts): add voice profile management with cloud TTS voice cloning (#2162)
qbc41c3ada4c32e
diff --git a/docs/NEWS.md b/docs/NEWS.mdindex 13ccf52fe..612f2f9e7 100644--- a/docs/NEWS.md+++ b/docs/NEWS.md@@ -2,6 +2,7 @@<!-- The first 10 items are automatically synced to README.md and README_zh.md via GitHub Actions. --><!-- To update news in READMEs, modify this file and push to trigger the workflow. -->+- **[2026-10] `FEAT`:** Voice profile management and voice cloning supported — select saved voices in chat, with DashScope and OpenAI voice cloning clients available in the Python SDK.- **[2026-10] `FEAT` `Experimental`:** Agent service supports realtime voice conversations over WebRTC, with text and voice sharing the same session history.- **[2026-09] `FEAT` `Experimental`:** SOP supported — run multi-step tasks as standard operating procedures, in both the framework and agent service. [Docs](https://docs.agentscope.io/latest/en/building-blocks/sop) | [Service](https://docs.agentscope.io/latest/en/deploy/sop)- **[2026-09] `FEAT`:** `TeamPipeline` supported — a leader agent delegates tasks to member agents. [Docs](https://docs.agentscope.io/latest/en/building-blocks/pipeline/team)diff --git a/docs/NEWS_zh.md b/docs/NEWS_zh.mdindex 067f61c90..f8db372e0 100644--- a/docs/NEWS_zh.md+++ b/docs/NEWS_zh.md@@ -2,6 +2,7 @@<!-- The first 10 items are automatically synced to README.md and README_zh.md via GitHub Actions. --><!-- To update news in READMEs, modify this file and push to trigger the workflow. -->+- **[2026-10] `功能`:** 支持音色配置管理与语音复刻,可在聊天中选择已保存的音色;Python SDK 新增 DashScope 和 OpenAI 音色复刻客户端。- **[2026-10] `功能` `实验性`:** 智能体服务支持基于 WebRTC 的实时语音对话,文本与语音模式共享同一会话历史。- **[2026-09] `功能` `实验性`:** 支持 SOP(标准作业流程)—— 将多步骤任务按标准流程执行,框架与智能体服务均已支持。[文档](https://docs.agentscope.io/latest/zh/building-blocks/sop) | [服务](https://docs.agentscope.io/latest/zh/deploy/sop)- **[2026-09] `功能`:** 支持 `TeamPipeline` —— 由 leader 智能体向成员智能体分派任务。[文档](https://docs.agentscope.io/latest/zh/building-blocks/pipeline/team)diff --git a/examples/web_ui/frontend/src/App.tsx b/examples/web_ui/frontend/src/App.tsxindex c1050096a..15e35e3a1 100644--- a/examples/web_ui/frontend/src/App.tsx+++ b/examples/web_ui/frontend/src/App.tsx@@ -19,6 +19,7 @@ import { CredentialPage } from '@/pages/credential';import { KnowledgePage } from '@/pages/knowledge';import { SchedulePage } from '@/pages/schedule';import { SetupPage } from '@/pages/setup';+import { VoiceProfilePage } from '@/pages/voice-profile';function SetupPageRoute() {const navigate = useNavigate();@@ -58,6 +59,7 @@ const router = createBrowserRouter([{ path: '/skill/:hubId', element: <SkillHubPage /> },{ path: '/knowledge', element: <KnowledgePage /> },{ path: '/knowledge/:kbId', element: <KnowledgePage /> },+ { path: '/voice-profile', element: <VoiceProfilePage /> },],},],diff --git a/examples/web_ui/frontend/src/api/index.ts b/examples/web_ui/frontend/src/api/index.tsindex cfb666349..0ecb3712c 100644--- a/examples/web_ui/frontend/src/api/index.ts+++ b/examples/web_ui/frontend/src/api/index.ts@@ -11,5 +11,14 @@ export { scheduleApi } from './schedule';export { embeddingModelApi, modelApi, realtimeModelApi, ttsModelApi } from './model';export { realtimeApi } from './realtime';export { knowledgeBaseApi } from './knowledgeBase';+export { voiceProfileApi } from './voiceProfile';+export type {+ VoiceProfileData,+ VoiceProfileRecord,+ ListVoiceProfilesResponse,+ CreateVoiceProfileResponse,+ EngineInfo,+} from './voiceProfile';+export type { TTSModelCard } from './types';export { channelApi } from './channel';export { healthApi } from './health';diff --git a/examples/web_ui/frontend/src/api/types.ts b/examples/web_ui/frontend/src/api/types.tsindex 4fe651231..eca9f3d35 100644--- a/examples/web_ui/frontend/src/api/types.ts+++ b/examples/web_ui/frontend/src/api/types.ts@@ -18,6 +18,7 @@ export interface TTSModelConfig {type: string;credential_id: string;model: string;+ voice_profile_id?: string | null;parameters: Record<string, unknown>;}@@ -1318,6 +1319,7 @@ export interface TTSModelCard {input_types: string[];output_types: string[];realtime: boolean;+ voice_cloning: boolean;parameter_schema: Record<string, unknown>;parameters_overrides: Record<string, Record<string, unknown>>;}diff --git a/examples/web_ui/frontend/src/api/voiceProfile.ts b/examples/web_ui/frontend/src/api/voiceProfile.tsnew file mode 100644index 000000000..f827ada43--- /dev/null+++ b/examples/web_ui/frontend/src/api/voiceProfile.ts@@ -0,0 +1,97 @@+import { client } from './client';+import type { TTSModelCard } from './types';++export interface VoiceProfileData {+ name: string;+ engine?: string | null;+ model?: string | null;+ credential_id?: string | null;+ voice?: string | null;+ metadata?: Record<string, unknown> | null;+}++export interface VoiceProfileRecord {+ id: string;+ user_id: string;+ created_at: string;+ updated_at: string;+ data: VoiceProfileData;+}++export interface ListVoiceProfilesResponse {+ profiles: VoiceProfileRecord[];+ total: number;+}++export interface CreateVoiceProfileResponse {+ profile_id: string;+}++export interface CredentialRef {+ id: string;+ label: string;+}++export interface EngineInfo {+ name: string;+ credential_type: string;+ models: (TTSModelCard & { enrollment_model: string | null })[];+ voice_cloning: boolean;+ credentials: CredentialRef[];+}++export interface AvailableEnginesResponse {+ engine_details: EngineInfo[];+}++export interface CloneVoiceRequest {+ engine: string;+ credential_id: string;+ model?: string | null;+ audio_base64?: string | null;+ audio_filename?: string;+ audio_url?: string | null;+ text?: string | null;+ prefix?: string;+ consent?: string | null;+}++export interface CloneVoiceResponse {+ voice_id: string;+ credential_id: string;+}++export interface OpenAIConsentRequest {+ credential_id: string;+ name?: string;+ language?: string;+ audio_base64: string;+ audio_filename?: string;+}++export interface OpenAIConsentResponse {+ consent_id: string;+}++export const voiceProfileApi = {+ list: () => client.get<ListVoiceProfilesResponse>('/voice-profile/'),++ get: (profileId: string) => client.get<VoiceProfileRecord>(`/voice-profile/${profileId}`),++ create: (data: VoiceProfileData) =>+ client.post<CreateVoiceProfileResponse>('/voice-profile/', { data }),++ update: (profileId: string, data: VoiceProfileData) =>+ client.patch<VoiceProfileRecord>(`/voice-profile/${profileId}`, { data }),++ delete: (profileId: string) => client.delete(`/voice-profile/${profileId}`),++ availableEngines: () =>+ client.get<AvailableEnginesResponse>('/voice-profile/available-engines'),++ cloneVoice: (data: CloneVoiceRequest) =>+ client.post<CloneVoiceResponse>('/voice-profile/clone', data),++ uploadOpenAIConsent: (data: OpenAIConsentRequest) =>+ client.post<OpenAIConsentResponse>('/voice-profile/openai-consent', data),+};diff --git a/examples/web_ui/frontend/src/components/layout/AppSidebar.tsx b/examples/web_ui/frontend/src/components/layout/AppSidebar.tsxindex 2bbc1d91f..1eb4a3e2b 100644--- a/examples/web_ui/frontend/src/components/layout/AppSidebar.tsx+++ b/examples/web_ui/frontend/src/components/layout/AppSidebar.tsx@@ -1,4 +1,5 @@import {+ AudioWaveform,BookText,BotMessageSquare,Cable,@@ -145,6 +146,16 @@ export function AppSidebar() {<LibraryBig /></SidebarMenuButton></SidebarMenuItem>+ <SidebarMenuItem>+ <SidebarMenuButton+ tooltip={{ children: t('common.voiceProfile'), hidden: false }}+ isActive={location.pathname === '/voice-profile'}+ onClick={() => navigate('/voice-profile')}+ className="px-2"+ >+ <AudioWaveform />+ </SidebarMenuButton>+ </SidebarMenuItem></SidebarMenu></SidebarGroupContent></SidebarGroup>diff --git a/examples/web_ui/frontend/src/components/popover/ModelParametersPopover.tsx b/examples/web_ui/frontend/src/components/popover/ModelParametersPopover.tsxindex 030ddca9a..e0a64a6bd 100644--- a/examples/web_ui/frontend/src/components/popover/ModelParametersPopover.tsx+++ b/examples/web_ui/frontend/src/components/popover/ModelParametersPopover.tsx@@ -9,6 +9,8 @@ import type {RealtimeModelConfig,TTSModelCard,TTSModelConfig,+ VoiceProfileRecord,+ EngineInfo,} from '@/api';import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';@@ -33,6 +35,8 @@ import { Switch } from '@/components/ui/switch';import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';import { useAvailableModels } from '@/hooks/useAvailableModels';import { useAvailableTTSModels } from '@/hooks/useAvailableTTSModels';+import { useVoiceEngines } from '@/hooks/useVoiceEngines';+import { useVoiceProfiles } from '@/hooks/useVoiceProfiles';import { useTranslation } from '@/i18n/useI18n';import { cn } from '@/lib/utils';import { credentialLabel } from '@/utils/common';@@ -65,6 +69,38 @@ interface ResolvedType {enumValues: unknown[] | null;}+interface ResolvedVoiceProfileBinding {+ type: string;+ credentialId: string;+ modelName: string;+ schema?: ParameterSchema;+}++/**+ * Resolve only the exact credential/model binding stored by a voice profile.+ * Returning a fallback here would create a config rejected by the backend's+ * authorization binding checks.+ */+function resolveVoiceProfileBinding(+ profile: VoiceProfileRecord,+ engineDetails: EngineInfo[],+): ResolvedVoiceProfileBinding | null {+ const { engine, credential_id: credentialId, model, voice } = profile.data;+ if (!engine || !credentialId || !model || !voice) return null;++ const engineInfo = engineDetails.find((item) => item.name === engine);+ if (!engineInfo?.credentials.some((item) => item.id === credentialId)) return null;+ const type = engineInfo.credential_type;+ const modelCard = engineInfo.models.find((item) => item.name === model);++ return {+ type,+ credentialId,+ modelName: model,+ schema: modelCard?.parameter_schema as ParameterSchema | undefined,+ };+}+/** Resolve a property's effective scalar type and enum values, looking* through ``anyOf`` and ignoring ``null`` variants. */function resolveType(prop: ParameterProperty): ResolvedType {@@ -334,6 +370,8 @@ export function ModelParametersPopover({const { t } = useTranslation();const { groups } = useAvailableModels();const { groups: ttsGroups } = useAvailableTTSModels();+ const { profiles: voiceProfiles } = useVoiceProfiles();+ const { engineDetails } = useVoiceEngines(selectedTTSModel !== undefined);const schema = modelCard?.parameter_schema as ParameterSchema | undefined;const properties = schema?.properties ?? {};@@ -387,7 +425,27 @@ export function ModelParametersPopover({.map(([type, items]) => [type, items.filter((i) => i.models.length > 0)] as const).filter(([, usable]) => usable.length > 0);const ttsGroupEntries = Object.entries(ttsGroups)- .map(([type, items]) => [type, items.filter((i) => i.models.length > 0)] as const)+ .map(+ ([type, items]) =>+ [+ type,+ items+ .map((item) => ({+ ...item,+ models: item.models.filter((model) => {+ // Hide models with no preset voices from manual selection.+ const schema = model.parameter_schema as+ | ParameterSchema+ | undefined;+ const voice = schema?.properties?.voice;+ if (!voice) return true;+ const { enumValues } = resolveType(voice);+ return enumValues !== null && enumValues.length > 0;+ }),+ }))+ .filter((item) => item.models.length > 0),+ ] as const,+ ).filter(([, usable]) => usable.length > 0);const hasFallbackOptions = fallbackGroups.length > 0;const parametersOnly = onFallbackChange === undefined && onTTSChange === undefined;@@ -618,7 +676,85 @@ export function ModelParametersPopover({<span className="truncate">{t('model-parameters.ttsLabel')}</span></DropdownMenuSubTrigger><DropdownMenuSubContent className="max-h-96 overflow-y-auto">- {ttsGroupEntries.length === 0 ? (+ {/* Voice Profiles section */}+ {voiceProfiles.length > 0 && (+ <>+ <DropdownMenuLabel>+ {t('model-parameters.voiceProfiles')}+ </DropdownMenuLabel>+ {voiceProfiles.map((vp) => {+ const isProfileActive =+ selectedTTSModel != null &&+ selectedTTSModel.voice_profile_id === vp.id;+ const binding = resolveVoiceProfileBinding(+ vp,+ engineDetails,+ );+ const unavailable = binding === null;+ const item = (+ <DropdownMenuCheckboxItem+ key={vp.id}+ checked={isProfileActive}+ disabled={unavailable}+ onSelect={(e) => e.preventDefault()}+ onCheckedChange={(checked) => {+ if (!checked || !binding) return;++ const params: Record<string, unknown> = {};+ if (binding.schema?.properties) {+ for (const [k, p] of Object.entries(+ binding.schema.properties,+ )) {+ if (p.default !== undefined) {+ params[k] = p.default;+ }+ }+ }+ if (vp.data.voice) {+ params.voice = vp.data.voice;+ }++ onTTSChange({+ type: binding.type,+ credential_id: binding.credentialId,+ model: binding.modelName,+ voice_profile_id: vp.id,+ parameters: params,+ });+ }}+ >+ <span className="truncate">{vp.data.name}</span>+ {vp.data.engine && (+ <Badge+ variant="secondary"+ className="ml-1.5 text-[10px] px-1 py-0"+ >+ {vp.data.engine}+ </Badge>+ )}+ </DropdownMenuCheckboxItem>+ );++ if (!unavailable) {+ return item;+ }++ return (+ <Tooltip key={vp.id}>+ <TooltipTrigger asChild>+ <div className="cursor-not-allowed">{item}</div>+ </TooltipTrigger>+ <TooltipContent side="left">+ {t('model-parameters.voiceProfileUnavailable')}+ </TooltipContent>+ </Tooltip>+ );+ })}+ <DropdownMenuSeparator />+ </>+ )}++ {ttsGroupEntries.length === 0 && voiceProfiles.length === 0 ? (<div className="px-2 py-3 text-center text-sm text-muted-foreground"><p>{t('model-parameters.ttsEmpty')}</p></div>@@ -632,6 +768,7 @@ export function ModelParametersPopover({) =>models.map((m) => {const isSelected =+ !selectedTTSModel?.voice_profile_id &&selectedTTSModel?.credential_id === credential.id &&selectedTTSModel?.model === m.name;return (@@ -680,6 +817,7 @@ export function ModelParametersPopover({: usable.map(({ credential, models }) => {const hasSelected = models.some((m) =>+ !selectedTTSModel?.voice_profile_id &&selectedTTSModel?.credential_id ===credential.id &&selectedTTSModel?.model === m.name,@@ -713,7 +851,7 @@ export function ModelParametersPopover({)}{/* TTS parameters sub-panel (hover to expand right) */}- {selectedTTSModel && (+ {selectedTTSModel && !selectedTTSModel.voice_profile_id && (<><DropdownMenuSeparator /><DropdownMenuSub>diff --git a/examples/web_ui/frontend/src/hooks/useMessages.ts b/examples/web_ui/frontend/src/hooks/useMessages.tsindex 86e47a1c1..17c0672ff 100644--- a/examples/web_ui/frontend/src/hooks/useMessages.ts+++ b/examples/web_ui/frontend/src/hooks/useMessages.ts@@ -12,10 +12,12 @@ import { appendEvent, AssistantMsg, UserMsg } from '@agentscope-ai/agentscope/meimport type { Msg, ContentBlock } from '@agentscope-ai/agentscope/message';import type { ToolCallBlock } from '@agentscope-ai/agentscope/message';import { useState, useCallback, useRef, useEffect } from 'react';+import { toast } from 'sonner';import { sessionApi, takeFreshlyCreated } from '@/api';import { chatApi } from '@/api';import { useAudioManager } from '@/context/AudioContext';+import { useTranslation } from '@/i18n/useI18n';/*** One pending subagent HITL request, projected from a team *member*@@ -138,6 +140,7 @@ export function useMessages(sendRealtimeUserConfirm?: (event: UserConfirmResultEvent) => Promise<void>;},) {+ const { t } = useTranslation();const [msgs, setMsgs] = useState<Msg[]>([]);// The (agent, session) pair `msgs` actually belongs to. Loading is// derived from it rather than set inside the fetch effect: an effect@@ -152,6 +155,7 @@ export function useMessages(const msgsRef = useRef<Msg[]>([]);const currentReplyRef = useRef<Msg | null>(null);+ const ttsConfigurationWarningsRef = useRef(new Set<string>());const abortRef = useRef<AbortController | null>(null);const rafRef = useRef<number | null>(null);// Timer that reverts ``interrupting`` back to ``idle`` if the@@ -186,7 +190,17 @@ export function useMessages(// reply content — route them to callbacks and skip appendEvent.if (event.type === EventType.CUSTOM) {const custom = event as CustomEvent;- if (custom.name === 'team_updated') {+ if (custom.name === 'tts_error') {+ const failure = custom.value as { stage?: string; reply_id?: string };+ const sessionKey = JSON.stringify([agentId, sessionId]);+ if (failure.stage === 'configuration') {+ if (ttsConfigurationWarningsRef.current.has(sessionKey)) return;+ ttsConfigurationWarningsRef.current.add(sessionKey);+ }+ toast.warning(t('chat.ttsFailed'), {+ id: `tts-error-${sessionKey}-${failure.reply_id ?? custom.id}`,+ });+ } else if (custom.name === 'team_updated') {optionsRef.current?.onTeamUpdated?.();} else if (custom.name === 'state_updated' && custom.value) {optionsRef.current?.onStateUpdated?.(custom.value as Record<string, unknown>);@@ -294,7 +308,7 @@ export function useMessages(scheduleUpdate();},- [scheduleUpdate, audioManager, clearInterruptTimer],+ [scheduleUpdate, audioManager, clearInterruptTimer, t, agentId, sessionId],);// ── Lifecycle: fetch history + open SSE stream ──────────────────diff --git a/examples/web_ui/frontend/src/hooks/useVoiceEngines.ts b/examples/web_ui/frontend/src/hooks/useVoiceEngines.tsnew file mode 100644index 000000000..876c6133f--- /dev/null+++ b/examples/web_ui/frontend/src/hooks/useVoiceEngines.ts@@ -0,0 +1,24 @@+import { useQuery } from '@tanstack/react-query';++import { voiceProfileApi } from '@/api';+import type { EngineInfo } from '@/api';++const EMPTY_ENGINES: EngineInfo[] = [];++/** Share engine capabilities and owned credentials across voice controls. */+export function useVoiceEngines(enabled = true) {+ const { data, isFetching, isSuccess, refetch } = useQuery({+ queryKey: ['voice-engines'],+ queryFn: () => voiceProfileApi.availableEngines(),+ enabled,+ staleTime: 30_000,+ retry: false,+ });++ return {+ engineDetails: data?.engine_details ?? EMPTY_ENGINES,+ loading: isFetching,+ ready: isSuccess,+ refetch,+ };+}diff --git a/examples/web_ui/frontend/src/hooks/useVoiceProfiles.ts b/examples/web_ui/frontend/src/hooks/useVoiceProfiles.tsnew file mode 100644index 000000000..99fa6b4ca--- /dev/null+++ b/examples/web_ui/frontend/src/hooks/useVoiceProfiles.ts@@ -0,0 +1,14 @@+import { useQuery } from '@tanstack/react-query';++import { voiceProfileApi } from '@/api';++export const VOICE_PROFILES_KEY = ['voice-profiles'];++export function useVoiceProfiles() {+ const { data, isPending, refetch } = useQuery({+ queryKey: VOICE_PROFILES_KEY,+ queryFn: () => voiceProfileApi.list(),+ });++ return { profiles: data?.profiles ?? [], loading: isPending, refetch };+}diff --git a/examples/web_ui/frontend/src/i18n/locales/en.json b/examples/web_ui/frontend/src/i18n/locales/en.jsonindex 165800f4e..9b2fd6af7 100644--- a/examples/web_ui/frontend/src/i18n/locales/en.json+++ b/examples/web_ui/frontend/src/i18n/locales/en.json@@ -17,6 +17,7 @@"error": "Something went wrong","information": "Information","knowledge": "Knowledge Bases",+ "voiceProfile": "Voice Profiles","loading": "Loading...","shownCount": "{{count}} shown","selectedCount": "{{selected}} of {{total}} selected",@@ -137,6 +138,7 @@"copy": "Copy"},"chat": {+ "ttsFailed": "Speech generation failed. Text replies will continue.","inputPlaceholder": "Type a message...","confirmToolCall": "Allow this action?","subagentConfirmTitle": "{{name}} requests confirmation",@@ -570,6 +572,8 @@"ttsEmpty": "No TTS models available.","ttsParameters": "Parameters","ttsParametersDescription": "Adjust parameters for the selected TTS model.",+ "voiceProfiles": "Voice Profiles",+ "voiceProfileUnavailable": "The bound credential or model is unavailable.","noTts": "No TTS"},"setup": {@@ -880,5 +884,50 @@"empty": "This folder is empty","pressEnter": "Press Enter to check this path first","gitTooltip": "{{staged}} staged · {{unstaged}} modified · {{untracked}} untracked\nLine counts exclude untracked files"+ },+ "voiceProfile": {+ "title": "Voice Profiles",+ "subtitle": "Manage voice profiles for Agent TTS",+ "newProfile": "New Profile",+ "noProfiles": "No voice profiles",+ "noProfilesDescription": "Create a voice profile to configure TTS voice settings for your agents.",+ "createTitle": "Create Voice Profile",+ "editTitle": "Edit Voice Profile",+ "name": "Name",+ "namePlaceholder": "My Voice Profile",+ "engine": "Engine",+ "enginePlaceholder": "Select an engine",+ "model": "Speech synthesis model",+ "modelPlaceholder": "Select a speech synthesis model",+ "customModel": "Custom model",+ "customModelPlaceholder": "Enter a model or deployment name",+ "unavailableCredential": "Unavailable credential: {{id}}",+ "credential": "Credential",+ "credentialPlaceholder": "Select a credential",+ "loadingModels": "Loading models...",+ "voice": "Voice",+ "voicePlaceholderPreset": "Preset voice name",+ "voicePlaceholderClone": "Preset name or cloned voice ID",+ "cloneVoice": "Voice Cloning",+ "enrollmentModel": "Voice cloning model (automatic)",+ "enrollmentModelHint": "The cloning model creates the voice; the synthesis model generates speech. The cloning model is matched automatically to your selected synthesis model.",+ "cloning": "Cloning...",+ "clone": "Clone",+ "uploadAudio": "Upload Audio to Clone",+ "cloneUrlPlaceholder": "https://publicly-accessible-audio-url",+ "consentPlaceholder": "OpenAI Consent ID (cons_xxx)",+ "consentRequired": "Please enter the OpenAI Consent ID first",+ "uploadConsent": "Upload Consent Recording",+ "consentLanguage": "Consent recording language",+ "consentRecordingHint": "Read the following statement exactly in the selected language, then upload the recording.",+ "consentRequirements": "View OpenAI recording requirements",+ "openaiCloneHint": "OpenAI cloning requires 2 steps: 1) Upload a consent recording (voice actor reading a consent phrase) to get a Consent ID; 2) Upload a voice sample to create the voice.",+ "fileTooLarge": "File too large, max {{max}}MB allowed",+ "deleteTitle": "Delete Voice Profile",+ "deleteDescription": "Are you sure you want to delete \"{{name}}\"? This action cannot be undone.",+ "noEngines": "No TTS credentials configured. Please add a credential first.",+ "saving": "Saving...",+ "save": "Save",+ "cancel": "Cancel"}}diff --git a/examples/web_ui/frontend/src/i18n/locales/zh.json b/examples/web_ui/frontend/src/i18n/locales/zh.jsonindex 4e675fa0a..11df20889 100644--- a/examples/web_ui/frontend/src/i18n/locales/zh.json+++ b/examples/web_ui/frontend/src/i18n/locales/zh.json@@ -17,6 +17,7 @@"error": "出错了","information": "信息","knowledge": "知识库",+ "voiceProfile": "语音配置","loading": "加载中...","shownCount": "已显示 {{count}} 个","selectedCount": "已选中 {{selected}} 个,共 {{total}} 个",@@ -137,6 +138,7 @@"copy": "复制"},"chat": {+ "ttsFailed": "语音生成失败,文字回复继续。","inputPlaceholder": "输入消息...","confirmToolCall": "允许此操作?","subagentConfirmTitle": "{{name}} 请求确认",@@ -570,6 +572,8 @@"ttsEmpty": "暂无可用的语音合成模型。","ttsParameters": "参数","ttsParametersDescription": "调整所选语音合成模型的参数。",+ "voiceProfiles": "语音配置",+ "voiceProfileUnavailable": "绑定的凭证或模型不可用。","noTts": "不使用语音合成"},"setup": {@@ -880,5 +884,50 @@"empty": "此文件夹为空","pressEnter": "先按回车校验该路径","gitTooltip": "{{staged}} 已暂存 · {{unstaged}} 已修改 · {{untracked}} 未跟踪\n行数不含未跟踪文件"+ },+ "voiceProfile": {+ "title": "语音配置",+ "subtitle": "管理 Agent 使用的语音配置",+ "newProfile": "新建配置",+ "noProfiles": "暂无语音配置",+ "noProfilesDescription": "创建语音配置以为您的 Agent 设置 TTS 语音参数。",+ "createTitle": "创建语音配置",+ "editTitle": "编辑语音配置",+ "name": "名称",+ "namePlaceholder": "我的语音配置",+ "engine": "引擎",+ "enginePlaceholder": "选择引擎",+ "model": "语音合成模型",+ "modelPlaceholder": "选择语音合成模型",+ "customModel": "自定义模型",+ "customModelPlaceholder": "输入模型或部署名称",+ "unavailableCredential": "凭据不可用:{{id}}",+ "credential": "凭据",+ "credentialPlaceholder": "选择凭据",+ "loadingModels": "加载模型列表...",+ "voice": "音色",+ "voicePlaceholderPreset": "预设音色名",+ "voicePlaceholderClone": "预设音色名或克隆音色 ID",+ "cloneVoice": "声音克隆",+ "enrollmentModel": "音色复刻模型(自动匹配)",+ "enrollmentModelHint": "复刻模型用于创建音色,合成模型用于生成语音。复刻模型根据所选合成模型自动匹配。",+ "cloning": "克隆中...",+ "clone": "克隆",+ "uploadAudio": "上传音频克隆",+ "cloneUrlPlaceholder": "https://公开可访问的音频文件URL",+ "consentPlaceholder": "OpenAI Consent ID (cons_xxx)",+ "consentRequired": "请先填写 OpenAI Consent ID",+ "uploadConsent": "上传同意录音",+ "consentLanguage": "同意录音语言",+ "consentRecordingHint": "请按所选语言逐字朗读以下声明,并上传录音。",+ "consentRequirements": "查看 OpenAI 官方录音要求",+ "openaiCloneHint": "OpenAI 克隆需要两步:1) 上传声优朗读同意声明的录音获取 Consent ID;2) 上传音频样本创建音色。",+ "fileTooLarge": "文件过大,最大支持 {{max}}MB",+ "deleteTitle": "删除语音配置",+ "deleteDescription": "确定要删除「{{name}}」吗?此操作无法撤销。",+ "noEngines": "尚未配置 TTS 凭据,请先添加凭据。",+ "saving": "保存中...",+ "save": "保存",+ "cancel": "取消"}}diff --git a/examples/web_ui/frontend/src/pages/voice-profile/index.tsx b/examples/web_ui/frontend/src/pages/voice-profile/index.tsxnew file mode 100644index 000000000..1031eb15f--- /dev/null+++ b/examples/web_ui/frontend/src/pages/voice-profile/index.tsx@@ -0,0 +1,845 @@+import { useQueryClient } from '@tanstack/react-query';+import {+ AudioWaveform,+ Plus,+ Pencil,+ Trash2,+ Mic,+ AlertCircle,+ Upload,+ Loader2,+} from 'lucide-react';+import { useState, useEffect, useCallback, useRef } from 'react';++import { voiceProfileApi } from '@/api';+import type { VoiceProfileRecord, VoiceProfileData, EngineInfo } from '@/api';+import { DeleteDialog } from '@/components/dialog/DeleteDialog';+import { Alert, AlertDescription } from '@/components/ui/alert';+import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';+import { Card, CardAction, CardContent, CardHeader, CardTitle } from '@/components/ui/card';+import {+ Dialog,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog';+import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from '@/components/ui/empty';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select';+import { Textarea } from '@/components/ui/textarea';+import { useVoiceEngines } from '@/hooks/useVoiceEngines';+import { useVoiceProfiles, VOICE_PROFILES_KEY } from '@/hooks/useVoiceProfiles';+import { useTranslation } from '@/i18n/useI18n';++const EMPTY_MODELS: EngineInfo['models'] = [];++const CUSTOM_MODEL = '__custom_model__';++const ENGINE_LABELS: Record<string, string> = {+ cosyvoice: 'CosyVoice',+ dashscope_tts: 'DashScope TTS',+ openai_tts: 'OpenAI TTS',+ gemini_tts: 'Gemini TTS',+};++/** Read preset choices without treating an unlisted voice as invalid. */+function voiceSettings(card: EngineInfo['models'][number] | undefined) {+ const props = (card?.parameter_schema as Record<string, unknown> | undefined)?.properties as+ | Record<string, Record<string, unknown>>+ | undefined;+ const options = (props?.voice?.enum as string[] | undefined) ?? [];+ const defaultVoice = props?.voice?.default;+ return {+ options,+ defaultVoice:+ typeof defaultVoice === 'string' && options.includes(defaultVoice)+ ? defaultVoice+ : (options[0] ?? ''),+ };+}++/** Read a File as base64 string (without the data URL prefix). */+function fileToBase64(file: File): Promise<string> {+ return new Promise((resolve, reject) => {+ const reader = new FileReader();+ reader.onload = () => {+ const result = reader.result as string;+ const base64 = result.split(',')[1] || '';+ resolve(base64);+ };+ reader.onerror = () => reject(reader.error);+ reader.readAsDataURL(file);+ });+}++const MAX_AUDIO_SIZE_MB = 10;+const MAX_AUDIO_SIZE_BYTES = MAX_AUDIO_SIZE_MB * 1024 * 1024;++// These fixed declarations must match the selected recording language.+// Source: https://developers.openai.com/api/docs/guides/custom-voices+const OPENAI_CONSENT_PHRASES: Record<string, string> = {+ en: 'I am the owner of this voice and I consent to OpenAI using this voice to create a synthetic voice model.',+ zh: '我是此声音的拥有者并授权OpenAI使用此声音创建语音合成模型',+};++function VoiceProfileDialog({+ open,+ onOpenChange,+ profile,+ onSaved,+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ profile?: VoiceProfileRecord | null;+ onSaved: () => void;+}) {+ const { t, i18n } = useTranslation();+ const [name, setName] = useState('');+ const [engine, setEngine] = useState<string | undefined>(undefined);+ const [model, setModel] = useState<string | undefined>(undefined);+ const [voice, setVoice] = useState('');+ const [customModelMode, setCustomModelMode] = useState(false);+ const [saving, setSaving] = useState(false);+ const {+ engineDetails,+ loading: enginesLoading,+ ready: enginesReady,+ refetch: refetchEngines,+ } = useVoiceEngines(open);+ const selectedEngine = engineDetails.find((item) => item.name === engine);+ const modelOptions = selectedEngine?.models ?? EMPTY_MODELS;+ const availableEngines = engineDetails.map((detail) => detail.name);+ const [cloning, setCloning] = useState(false);+ const [cloneError, setCloneError] = useState('');+ const [cloneUrl, setCloneUrl] = useState('');+ const [consentId, setConsentId] = useState('');+ const [consentLanguage, setConsentLanguage] = useState(() =>+ i18n.language.startsWith('zh') ? 'zh' : 'en',+ );+ const [credentialId, setCredentialId] = useState<string | null>(null);+ const fileInputRef = useRef<HTMLInputElement>(null);+ const consentFileRef = useRef<HTMLInputElement>(null);++ useEffect(() => {+ if (open) void refetchEngines({ cancelRefetch: false });+ }, [open, refetchEngines]);++ useEffect(() => {+ setCustomModelMode(false);+ setConsentId('');+ setCloneError('');+ setCloneUrl('');+ if (profile) {+ setName(profile.data.name);+ setEngine(profile.data.engine || undefined);+ setModel(profile.data.model || undefined);+ setVoice(profile.data.voice || '');+ setCredentialId(profile.data.credential_id || null);+ } else {+ setName('');+ setEngine(undefined);+ setModel(undefined);+ setVoice('');+ setCredentialId(null);+ }+ }, [profile, open]);++ const selectedCard = modelOptions.find((item) => item.name === model);+ const credentialIsAvailable = selectedEngine?.credentials.some(+ (item) => item.id === credentialId,+ );+ const isCustomModel = customModelMode || (!!model && !selectedCard);+ const { options: voiceOptions, defaultVoice } = voiceSettings(selectedCard);++ const handleEngineChange = (nextEngine: string) => {+ if (nextEngine === engine) return;+ const info = engineDetails.find((item) => item.name === nextEngine);+ const nextModel = info?.models.find((item) => item.voice_cloning) ?? info?.models[0];+ const credentials = info?.credentials ?? [];+ setEngine(nextEngine);+ setModel(nextModel?.name);+ setCustomModelMode(false);+ setVoice(voiceSettings(nextModel).defaultVoice);+ setCredentialId(+ credentials.some((item) => item.id === credentialId)+ ? credentialId+ : credentials.length === 1+ ? credentials[0].id+ : null,+ );+ setConsentId('');+ setCloneError('');+ };++ const handleModelChange = (nextModel: string | undefined) => {+ if (nextModel === model) return;+ setModel(nextModel);+ setVoice(voiceSettings(modelOptions.find((item) => item.name === nextModel)).defaultVoice);+ setCloneError('');+ };++ const handleCustomModelChange = (value: string) => {+ setCustomModelMode(true);+ handleModelChange(value || undefined);+ };++ const handleCredentialChange = (nextCredentialId: string) => {+ if (nextCredentialId === credentialId) return;+ setCredentialId(nextCredentialId);+ setVoice((current) => (voiceOptions.includes(current) ? current : defaultVoice));+ setConsentId('');+ setCloneError('');+ };++ const canClone = !!credentialIsAvailable && (selectedEngine?.voice_cloning ?? false);++ const selectedModelSupportsClone = selectedCard?.voice_cloning ?? false;+ const cloneSupportsUpload = engine === 'dashscope_tts' || engine === 'openai_tts';+ const enrollmentModel = selectedCard?.enrollment_model;++ const handleConsentUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {+ const file = e.target.files?.[0];+ if (!file || !credentialId) return;+ if (file.size > MAX_AUDIO_SIZE_BYTES) {+ setCloneError(t('voiceProfile.fileTooLarge', { max: MAX_AUDIO_SIZE_MB }));+ return;+ }+ setCloning(true);+ setCloneError('');+ try {+ const base64 = await fileToBase64(file);+ const res = await voiceProfileApi.uploadOpenAIConsent({+ credential_id: credentialId,+ language: consentLanguage,+ audio_base64: base64,+ audio_filename: file.name,+ });+ setConsentId(res.consent_id);+ } catch (err: unknown) {+ const msg = err instanceof Error ? err.message : String(err);+ setCloneError(msg);+ } finally {+ setCloning(false);+ if (consentFileRef.current) {+ consentFileRef.current.value = '';+ }+ }+ };++ const handleCloneUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {+ const file = e.target.files?.[0];+ if (!file || !engine || !credentialId) return;+ if (file.size > MAX_AUDIO_SIZE_BYTES) {+ setCloneError(t('voiceProfile.fileTooLarge', { max: MAX_AUDIO_SIZE_MB }));+ return;+ }+ if (engine !== 'openai_tts' && !model) {+ setCloneError(t('voiceProfile.modelPlaceholder'));+ return;+ }+ if (engine === 'openai_tts' && !consentId.trim()) {+ setCloneError(t('voiceProfile.consentRequired'));+ return;+ }+ setCloning(true);+ setCloneError('');+ try {+ const base64 = await fileToBase64(file);+ const res = await voiceProfileApi.cloneVoice({+ engine,+ credential_id: credentialId,+ model,+ audio_base64: base64,+ audio_filename: file.name,+ ...(engine === 'openai_tts' ? { consent: consentId.trim() } : {}),+ });+ setVoice(res.voice_id);+ setCredentialId(res.credential_id);+ } catch (err: unknown) {+ const msg = err instanceof Error ? err.message : String(err);+ setCloneError(msg);+ } finally {+ setCloning(false);+ if (fileInputRef.current) {+ fileInputRef.current.value = '';+ }+ }+ };++ const handleCloneFromUrl = async () => {+ if (!engine || !model || !credentialId) {+ setCloneError(t('voiceProfile.modelPlaceholder'));+ return;+ }+ if (!cloneUrl.trim()) {+ setCloneError(t('voiceProfile.cloneUrlPlaceholder'));+ return;+ }+ setCloning(true);+ setCloneError('');+ try {+ const res = await voiceProfileApi.cloneVoice({+ engine,+ credential_id: credentialId,+ model,+ audio_url: cloneUrl.trim(),+ });+ setVoice(res.voice_id);+ setCredentialId(res.credential_id);+ setCloneUrl('');+ } catch (err: unknown) {+ const msg = err instanceof Error ? err.message : String(err);+ setCloneError(msg);+ } finally {+ setCloning(false);+ }+ };++ const handleSave = async () => {+ if (cloning || saving || !name.trim()) return;+ setSaving(true);+ try {+ const data: VoiceProfileData = {+ name: name.trim(),+ engine: engine || null,+ model: model || null,+ credential_id: credentialId,+ voice: voice.trim() || null,+ metadata: profile?.data.metadata ?? null,+ };+ if (profile) {+ await voiceProfileApi.update(profile.id, data);+ } else {+ await voiceProfileApi.create(data);+ }+ onSaved();+ onOpenChange(false);+ } catch {+ // Keep the form open; the API client already displays the error.+ } finally {+ setSaving(false);+ }+ };++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="max-h-[90dvh] overflow-y-auto sm:max-w-md">+ <DialogHeader>+ <DialogTitle>+ {profile ? t('voiceProfile.editTitle') : t('voiceProfile.createTitle')}+ </DialogTitle>+ </DialogHeader>+ <div className="flex flex-col gap-4 py-4">+ <div className="flex flex-col gap-2">+ <Label htmlFor="vp-name">{t('voiceProfile.name')}</Label>+ <Input+ id="vp-name"+ value={name}+ onChange={(e) => setName(e.target.value)}+ placeholder={t('voiceProfile.namePlaceholder')}+ />+ </div>+ <div className="flex flex-col gap-2">+ <Label htmlFor="vp-engine">{t('voiceProfile.engine')}</Label>+ {!enginesLoading && availableEngines.length === 0 ? (+ <Alert variant="destructive">+ <AlertCircle className="size-4" />+ <AlertDescription>{t('voiceProfile.noEngines')}</AlertDescription>+ </Alert>+ ) : (+ <Select+ value={engine}+ onValueChange={handleEngineChange}+ disabled={enginesLoading || cloning}+ >+ <SelectTrigger id="vp-engine">+ <SelectValue+ placeholder={t('voiceProfile.enginePlaceholder')}+ />+ </SelectTrigger>+ <SelectContent>+ {availableEngines.map((eng) => (+ <SelectItem key={eng} value={eng}>+ {ENGINE_LABELS[eng] ?? eng}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )}+ </div>+ {engine &&+ (() => {+ const engineInfo = engineDetails?.find((d) => d.name === engine);+ const creds = engineInfo?.credentials || [];+ if (creds.length === 0 && !credentialId) return null;+ if (creds.length === 1 && creds[0].id === credentialId) {+ return (+ <div className="flex flex-col gap-2">+ <Label htmlFor="vp-credential">+ {t('voiceProfile.credential')}+ </Label>+ <p className="text-sm text-muted-foreground px-3 py-2 border rounded-md bg-muted/30">+ {creds[0].label}+ </p>+ </div>+ );+ }+ return (+ <div className="flex flex-col gap-2">+ <Label htmlFor="vp-credential">+ {t('voiceProfile.credential')}+ </Label>+ <Select+ value={credentialId || undefined}+ onValueChange={handleCredentialChange}+ disabled={cloning}+ >+ <SelectTrigger id="vp-credential">+ <SelectValue+ placeholder={t(+ 'voiceProfile.credentialPlaceholder',+ )}+ />+ </SelectTrigger>+ <SelectContent>+ {credentialId && !credentialIsAvailable && (+ <SelectItem value={credentialId} disabled>+ {t('voiceProfile.unavailableCredential', {+ id: credentialId,+ })}+ </SelectItem>+ )}+ {creds.map((c) => (+ <SelectItem key={c.id} value={c.id}>+ {c.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ );+ })()}+ {engine && (+ <div className="flex flex-col gap-2">+ <Label htmlFor="vp-model">{t('voiceProfile.model')}</Label>+ {enginesLoading ? (+ <div className="flex items-center gap-2 text-sm text-muted-foreground">+ <Loader2 className="size-4 animate-spin" />+ {t('voiceProfile.loadingModels')}+ </div>+ ) : modelOptions.length > 0 ? (+ <Select+ value={isCustomModel ? CUSTOM_MODEL : model}+ onValueChange={(value) => {+ const custom = value === CUSTOM_MODEL;+ setCustomModelMode(custom);+ handleModelChange(custom ? undefined : value);+ }}+ disabled={cloning}+ >+ <SelectTrigger id="vp-model">+ <SelectValue+ placeholder={t('voiceProfile.modelPlaceholder')}+ />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value={CUSTOM_MODEL}>+ {t('voiceProfile.customModel')}+ </SelectItem>+ {modelOptions.map((m) => (+ <SelectItem key={m.name} value={m.name}>+ {m.label || m.name}+ {m.voice_cloning && ' (VC)'}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ ) : (+ <Input+ id="vp-model"+ disabled={cloning}+ value={model || ''}+ onChange={(e) => handleCustomModelChange(e.target.value)}+ placeholder={t('voiceProfile.modelPlaceholder')}+ />+ )}+ {!enginesLoading && modelOptions.length > 0 && isCustomModel && (+ <Input+ id="vp-custom-model"+ aria-label={t('voiceProfile.customModel')}+ disabled={cloning}+ value={model || ''}+ onChange={(e) => handleCustomModelChange(e.target.value)}+ placeholder={t('voiceProfile.customModelPlaceholder')}+ />+ )}+ </div>+ )}+ {engine && (+ <div className="flex flex-col gap-2">+ <Label htmlFor="vp-voice">{t('voiceProfile.voice')}</Label>+ {voiceOptions.length > 0 && (!voice || voiceOptions.includes(voice)) ? (+ <Select value={voice} onValueChange={setVoice}>+ <SelectTrigger id="vp-voice">+ <SelectValue+ placeholder={t('voiceProfile.voicePlaceholderPreset')}+ />+ </SelectTrigger>+ <SelectContent>+ {voiceOptions.map((v) => (+ <SelectItem key={v} value={v}>+ {v}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ ) : (+ <Input+ id="vp-voice"+ value={voice}+ onChange={(e) => setVoice(e.target.value)}+ placeholder={+ canClone+ ? t('voiceProfile.voicePlaceholderClone')+ : t('voiceProfile.voicePlaceholderPreset')+ }+ />+ )}+ </div>+ )}+ {canClone && selectedModelSupportsClone && (+ <div className="flex flex-col gap-2">+ <Label>{t('voiceProfile.cloneVoice')}</Label>+ {enrollmentModel && (+ <div className="flex flex-col gap-2">+ <Label htmlFor="vp-enrollment-model">+ {t('voiceProfile.enrollmentModel')}+ </Label>+ <Input+ id="vp-enrollment-model"+ value={enrollmentModel}+ readOnly+ aria-describedby="vp-enrollment-model-hint"+ className="bg-muted/30 font-mono text-sm"+ />+ <p+ id="vp-enrollment-model-hint"+ className="text-xs text-muted-foreground"+ >+ {t('voiceProfile.enrollmentModelHint')}+ </p>+ </div>+ )}+ {engine === 'openai_tts' && (+ <div className="flex flex-col gap-2">+ <p className="text-xs text-muted-foreground">+ {t('voiceProfile.openaiCloneHint')}+ </p>+ <Label htmlFor="vp-consent-language">+ {t('voiceProfile.consentLanguage')}+ </Label>+ <Select+ value={consentLanguage}+ onValueChange={(language) => {+ setConsentLanguage(language);+ setConsentId('');+ }}+ disabled={cloning}+ >+ <SelectTrigger id="vp-consent-language">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="zh">中文</SelectItem>+ <SelectItem value="en">English</SelectItem>+ </SelectContent>+ </Select>+ <p className="text-xs text-muted-foreground">+ {t('voiceProfile.consentRecordingHint')}+ </p>+ <blockquote className="rounded-md border bg-muted/30 px-3 py-2 text-sm">+ {OPENAI_CONSENT_PHRASES[consentLanguage]}+ </blockquote>+ <a+ href="https://developers.openai.com/api/docs/guides/custom-voices"+ target="_blank"+ rel="noreferrer"+ className="text-xs text-muted-foreground underline underline-offset-4"+ >+ {t('voiceProfile.consentRequirements')}+ </a>+ <div className="flex items-center gap-2">+ <Input+ value={consentId}+ disabled={cloning}+ onChange={(e) => setConsentId(e.target.value)}+ placeholder={t('voiceProfile.consentPlaceholder')}+ className="flex-1"+ />+ <input+ ref={consentFileRef}+ type="file"+ accept="audio/*"+ className="hidden"+ onChange={handleConsentUpload}+ />+ <Button+ type="button"+ variant="outline"+ size="sm"+ disabled={cloning || !credentialId}+ onClick={() => consentFileRef.current?.click()}+ >+ {t('voiceProfile.uploadConsent')}+ </Button>+ </div>+ </div>+ )}+ {cloneSupportsUpload ? (+ <div className="flex items-center gap-2">+ <input+ ref={fileInputRef}+ type="file"+ accept="audio/*"+ className="hidden"+ onChange={handleCloneUpload}+ />+ <Button+ type="button"+ variant="outline"+ size="sm"+ disabled={cloning || !credentialId}+ onClick={() => fileInputRef.current?.click()}+ >+ {cloning ? (+ <Loader2 className="size-4 mr-1.5 animate-spin" />+ ) : (+ <Upload className="size-4 mr-1.5" />+ )}+ {cloning+ ? t('voiceProfile.cloning')+ : t('voiceProfile.uploadAudio')}+ </Button>+ </div>+ ) : (+ <div className="flex flex-col gap-2">+ <Textarea+ value={cloneUrl}+ onChange={(e) => setCloneUrl(e.target.value)}+ placeholder={t('voiceProfile.cloneUrlPlaceholder')}+ rows={3}+ className="text-sm break-all resize-none"+ />+ <Button+ type="button"+ variant="outline"+ size="sm"+ disabled={cloning || !cloneUrl.trim() || !credentialId}+ onClick={handleCloneFromUrl}+ >+ {cloning ? (+ <Loader2 className="size-4 mr-1.5 animate-spin" />+ ) : (+ <Upload className="size-4 mr-1.5" />+ )}+ {cloning+ ? t('voiceProfile.cloning')+ : t('voiceProfile.clone')}+ </Button>+ </div>+ )}+ {cloneError && <p className="text-sm text-destructive">{cloneError}</p>}+ </div>+ )}+ </div>+ <DialogFooter>+ <Button variant="outline" onClick={() => onOpenChange(false)}>+ {t('voiceProfile.cancel')}+ </Button>+ <Button+ onClick={handleSave}+ disabled={+ saving ||+ cloning ||+ enginesLoading ||+ !enginesReady ||+ !name.trim() ||+ !engine ||+ !credentialIsAvailable ||+ !model ||+ !voice.trim()+ }+ >+ {saving ? t('voiceProfile.saving') : t('voiceProfile.save')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}++export function VoiceProfilePage() {+ const { t } = useTranslation();+ const { profiles, loading: initialLoading } = useVoiceProfiles();+ const queryClient = useQueryClient();+ const [dialogOpen, setDialogOpen] = useState(false);+ const [editProfile, setEditProfile] = useState<VoiceProfileRecord | null>(null);+ const [deleteProfile, setDeleteProfile] = useState<VoiceProfileRecord | null>(null);+ const { engineDetails } = useVoiceEngines();++ const loadProfiles = useCallback(+ () => queryClient.invalidateQueries({ queryKey: VOICE_PROFILES_KEY }),+ [queryClient],+ );++ const getCredentialLabel = (profile: VoiceProfileRecord): string | null => {+ if (!profile.data.credential_id || !profile.data.engine) return null;+ const info = engineDetails.find((d) => d.name === profile.data.engine);+ const cred = info?.credentials.find((c) => c.id === profile.data.credential_id);+ return cred?.label || null;+ };++ const handleDelete = async () => {+ if (!deleteProfile) return;+ try {+ await voiceProfileApi.delete(deleteProfile.id);+ setDeleteProfile(null);+ await loadProfiles();+ } catch {+ // Keep the dialog open; the API client already displays the error.+ }+ };++ return (+ <div className="flex flex-col h-full p-6 gap-6 overflow-auto">+ <div className="flex items-center justify-between">+ <div className="flex flex-col gap-1">+ <div className="flex items-center gap-3">+ <AudioWaveform className="size-6 text-muted-foreground" />+ <h1 className="text-2xl font-semibold tracking-tight">+ {t('voiceProfile.title')}+ </h1>+ </div>+ <p className="text-sm text-muted-foreground ml-9">+ {t('voiceProfile.subtitle')}+ </p>+ </div>+ <Button+ onClick={() => {+ setEditProfile(null);+ setDialogOpen(true);+ }}+ >+ <Plus className="size-4 mr-1.5" />+ {t('voiceProfile.newProfile')}+ </Button>+ </div>++ {initialLoading ? (+ <div className="grid gap-4 grid-cols-1 md:grid-cols-2 lg:grid-cols-3">+ {[1, 2, 3].map((i) => (+ <Card key={i} className="animate-pulse">+ <CardHeader>+ <div className="h-5 w-32 bg-muted rounded" />+ </CardHeader>+ <CardContent>+ <div className="h-4 w-24 bg-muted rounded" />+ </CardContent>+ </Card>+ ))}+ </div>+ ) : profiles.length === 0 ? (+ <Empty>+ <EmptyHeader>+ <Mic className="size-10 text-muted-foreground" />+ </EmptyHeader>+ <EmptyTitle>{t('voiceProfile.noProfiles')}</EmptyTitle>+ <EmptyDescription>{t('voiceProfile.noProfilesDescription')}</EmptyDescription>+ </Empty>+ ) : (+ <div className="grid gap-4 grid-cols-1 md:grid-cols-2 lg:grid-cols-3">+ {profiles.map((profile) => (+ <Card key={profile.id}>+ <CardHeader>+ <CardTitle className="flex items-center gap-2">+ <AudioWaveform className="size-4 text-muted-foreground" />+ {profile.data.name}+ </CardTitle>+ <CardAction>+ <Button+ size="icon-sm"+ variant="ghost"+ onClick={() => {+ setEditProfile(profile);+ setDialogOpen(true);+ }}+ >+ <Pencil className="size-3.5" />+ </Button>+ <Button+ size="icon-sm"+ variant="ghost"+ onClick={() => setDeleteProfile(profile)}+ >+ <Trash2 className="size-3.5" />+ </Button>+ </CardAction>+ </CardHeader>+ <CardContent>+ <div className="flex flex-wrap gap-2">+ {(() => {+ const credLabel = getCredentialLabel(profile);+ if (!credLabel) return null;+ return <Badge variant="secondary">{credLabel}</Badge>;+ })()}+ {profile.data.engine && (+ <Badge variant="secondary">+ {ENGINE_LABELS[profile.data.engine] ??+ profile.data.engine}+ </Badge>+ )}+ {profile.data.model && (+ <Badge variant="secondary">{profile.data.model}</Badge>+ )}+ {profile.data.voice && (+ <Badge variant="secondary">{profile.data.voice}</Badge>+ )}+ </div>+ </CardContent>+ </Card>+ ))}+ </div>+ )}++ {dialogOpen && (+ <VoiceProfileDialog+ open={dialogOpen}+ onOpenChange={setDialogOpen}+ profile={editProfile}+ onSaved={loadProfiles}+ />+ )}++ <DeleteDialog+ open={!!deleteProfile}+ onOpenChange={(open) => {+ if (!open) setDeleteProfile(null);+ }}+ onConfirm={handleDelete}+ title={t('voiceProfile.deleteTitle')}+ description={t('voiceProfile.deleteDescription', {+ name: deleteProfile?.data.name,+ })}+ />+ </div>+ );+}diff --git a/pyproject.toml b/pyproject.tomlindex 791822f59..e82d54589 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -22,7 +22,7 @@ dependencies = ["aioitertools","anthropic","certifi>=2026.10.19",- "dashscope",+ "dashscope>=1.20.0","docstring_parser","filetype","json5",diff --git a/src/agentscope/app/_app.py b/src/agentscope/app/_app.pyindex 8ed7f6037..097495114 100644--- a/src/agentscope/app/_app.py+++ b/src/agentscope/app/_app.py@@ -27,6 +27,7 @@ from ._router import (model_router,realtime_router,tts_model_router,+ voice_profile_router,schedule_router,session_router,skill_router,@@ -448,6 +449,7 @@ def create_app(model_router,realtime_router,tts_model_router,+ voice_profile_router,embedding_model_router,channel_router,):diff --git a/src/agentscope/app/_router/__init__.py b/src/agentscope/app/_router/__init__.pyindex 1b237afe5..9c05e276b 100644--- a/src/agentscope/app/_router/__init__.py+++ b/src/agentscope/app/_router/__init__.py@@ -16,6 +16,7 @@ from ._sop import sop_routerfrom ._model import model_routerfrom ._realtime import realtime_routerfrom ._tts_model import tts_model_router+from ._voice_profile import voice_profile_routerfrom ._workspace import workspace_router__all__ = [@@ -25,6 +26,7 @@ __all__ = ["realtime_router","embedding_model_router","tts_model_router",+ "voice_profile_router","chat_router","credential_router","health_router",diff --git a/src/agentscope/app/_router/_schema/__init__.py b/src/agentscope/app/_router/_schema/__init__.pyindex 6510a64c4..1c4da4f16 100644--- a/src/agentscope/app/_router/_schema/__init__.py+++ b/src/agentscope/app/_router/_schema/__init__.py@@ -104,6 +104,20 @@ from ._session import (TeamDetailResponse,TeamMemberView,)+from ._voice_profile import (+ AvailableEnginesResponse,+ CloneVoiceRequest,+ CloneVoiceResponse,+ CreateVoiceProfileRequest,+ CreateVoiceProfileResponse,+ CredentialRef,+ EngineInfo,+ EngineModelInfo,+ ListVoiceProfilesResponse,+ OpenAIConsentRequest,+ OpenAIConsentResponse,+ UpdateVoiceProfileRequest,+)__all__ = [# Health@@ -208,4 +222,17 @@ __all__ = ["SessionView","TeamDetailResponse","TeamMemberView",+ # Voice Profile+ "AvailableEnginesResponse",+ "CloneVoiceRequest",+ "CloneVoiceResponse",+ "CreateVoiceProfileRequest",+ "CreateVoiceProfileResponse",+ "CredentialRef",+ "EngineInfo",+ "EngineModelInfo",+ "ListVoiceProfilesResponse",+ "OpenAIConsentRequest",+ "OpenAIConsentResponse",+ "UpdateVoiceProfileRequest",]diff --git a/src/agentscope/app/_router/_schema/_voice_profile.py b/src/agentscope/app/_router/_schema/_voice_profile.pynew file mode 100644index 000000000..fde47d2ed--- /dev/null+++ b/src/agentscope/app/_router/_schema/_voice_profile.py@@ -0,0 +1,153 @@+# -*- coding: utf-8 -*-+"""Schema models for the voice profile router."""+from pydantic import BaseModel, Field++from ...storage._model import VoiceProfileData, VoiceProfileRecord+from ....tts import TTSModelCard++MAX_AUDIO_SIZE_BYTES = 10 * 1024 * 1024+MAX_AUDIO_BASE64_LENGTH = 4 * ((MAX_AUDIO_SIZE_BYTES + 2) // 3)+++class CreateVoiceProfileRequest(BaseModel):+ """Request body for creating a voice profile."""++ data: VoiceProfileData+ """The voice profile configuration."""+++class CreateVoiceProfileResponse(BaseModel):+ """Response body for creating a voice profile."""++ profile_id: str+ """The created profile's unique identifier."""+++class ListVoiceProfilesResponse(BaseModel):+ """Response body for listing voice profiles."""++ profiles: list[VoiceProfileRecord]+ """All voice profiles for the user."""++ total: int+ """Total count of profiles."""+++class UpdateVoiceProfileRequest(BaseModel):+ """Request body for updating a voice profile."""++ data: VoiceProfileData+ """The updated voice profile configuration."""+++class CredentialRef(BaseModel):+ """Minimal credential reference for engine binding."""++ id: str+ """Credential ID."""++ label: str+ """Display label (credential name or type)."""+++class EngineModelInfo(TTSModelCard):+ """A selectable synthesis model and its enrollment model, if any."""++ enrollment_model: str | None = None+ """Separate model used for voice enrollment, supplied by the SDK client."""+++class EngineInfo(BaseModel):+ """Metadata about a TTS engine."""++ name: str+ """The engine name (e.g. 'dashscope_tts')."""++ credential_type: str+ """Credential provider required by the engine."""++ models: list[EngineModelInfo] = []+ """Synthesis model cards belonging to this engine."""++ voice_cloning: bool = False+ """Whether the engine supports voice cloning."""++ credentials: list[CredentialRef] = []+ """Available credentials for this engine."""+++class AvailableEnginesResponse(BaseModel):+ """Response body for available TTS engines."""++ engine_details: list[EngineInfo] = []+ """Available engines with credentials and capabilities, sorted by name."""+++class CloneVoiceRequest(BaseModel):+ """Request body for voice cloning."""++ engine: str+ """TTS engine to clone for."""++ credential_id: str+ """Owner-scoped credential used for cloning and later synthesis."""++ model: str | None = None+ """Target model (required for DashScope, optional for OpenAI)."""++ audio_base64: str | None = Field(+ default=None,+ max_length=MAX_AUDIO_BASE64_LENGTH,+ )+ """Base64-encoded audio (for Qwen-TTS/OpenAI upload)."""++ audio_filename: str = "voice.wav"+ """Original filename (used for MIME detection)."""++ audio_url: str | None = None+ """Publicly accessible audio URL (for CosyVoice)."""++ text: str | None = None+ """Audio transcript (improves Qwen-TTS quality)."""++ prefix: str = "agentscope"+ """Prefix for the generated voice name."""++ consent: str | None = None+ """OpenAI consent token (required for OpenAI cloning)."""+++class CloneVoiceResponse(BaseModel):+ """Response body for voice cloning."""++ voice_id: str+ """The cloned voice identifier."""++ credential_id: str+ """The credential used for cloning (must match synthesis)."""+++class OpenAIConsentRequest(BaseModel):+ """Request body for uploading an OpenAI consent recording."""++ credential_id: str+ """Owner-scoped OpenAI credential used for the consent recording."""++ name: str = "agentscope_consent"+ """Label for the consent recording."""++ language: str = "en-US"+ """BCP 47 language tag for the consent phrase."""++ audio_base64: str = Field(max_length=MAX_AUDIO_BASE64_LENGTH)+ """Base64-encoded consent audio recording."""++ audio_filename: str = "consent.wav"+ """Original filename (used for MIME detection)."""+++class OpenAIConsentResponse(BaseModel):+ """Response body for OpenAI consent upload."""++ consent_id: str+ """The consent recording identifier (cons_xxx)."""diff --git a/src/agentscope/app/_router/_session.py b/src/agentscope/app/_router/_session.pyindex 7082782c1..c1f27c5bb 100644--- a/src/agentscope/app/_router/_session.py+++ b/src/agentscope/app/_router/_session.py@@ -39,6 +39,7 @@ from .._service import (SessionStatus,SessionProjection,SubagentHitlProjector,+ validate_tts_model_config,)from ..storage import (ChatModelConfig,@@ -330,7 +331,12 @@ async def create_session(user_id,body.fallback_chat_model_config,)- await _ensure_credential_exists(access, user_id, body.tts_model_config)+ await validate_tts_model_config(+ user_id,+ body.tts_model_config,+ access,+ storage,+ )await _ensure_credential_exists(access,user_id,@@ -520,7 +526,12 @@ async def update_session(user_id,body.fallback_chat_model_config,)- await _ensure_credential_exists(access, user_id, body.tts_model_config)+ await validate_tts_model_config(+ user_id,+ body.tts_model_config,+ access,+ storage,+ )await _ensure_credential_exists(access,user_id,diff --git a/src/agentscope/app/_router/_voice_profile.py b/src/agentscope/app/_router/_voice_profile.pynew file mode 100644index 000000000..7d2867bb0--- /dev/null+++ b/src/agentscope/app/_router/_voice_profile.py@@ -0,0 +1,585 @@+# -*- coding: utf-8 -*-+"""Voice profile router — CRUD endpoints."""+import base64+import binascii++from fastapi import APIRouter, Depends, HTTPException, status++from ..access import ResourceKind+from ..deps import (+ get_current_user_id,+ get_resource_access_service,+ get_storage,+)+from .._service import ResourceAccessService, validate_voice_profile_model+from ..storage import StorageBase, VoiceProfileData, VoiceProfileRecord+from ..storage._model import (+ ENGINE_TO_CREDENTIAL_TYPE,+ get_missing_voice_profile_binding_fields,+)+from ...credential import (+ CredentialFactory,+ OpenAICredential,+)+from ...tts import (+ OpenAIVoiceCloningClient,+ TTSModelCard,+ VoiceCloningError,+)+from ._schema import (+ AvailableEnginesResponse,+ CloneVoiceRequest,+ CloneVoiceResponse,+ CreateVoiceProfileRequest,+ CreateVoiceProfileResponse,+ CredentialRef,+ EngineInfo,+ EngineModelInfo,+ ListVoiceProfilesResponse,+ OpenAIConsentRequest,+ OpenAIConsentResponse,+ UpdateVoiceProfileRequest,+)+from ._schema._voice_profile import MAX_AUDIO_SIZE_BYTES++voice_profile_router = APIRouter(+ prefix="/voice-profile",+ tags=["voice_profile"],+ responses={404: {"description": "Not found"}},+)+++async def _resolve_owned_credential(+ access: ResourceAccessService,+ user_id: str,+ credential_id: str,+ expected_type: str,+) -> dict:+ """Resolve an owner-scoped credential and validate its provider type.++ Args:+ access: Resource access service.+ user_id: Authenticated user id.+ credential_id: Credential selected for the voice.+ expected_type: Credential type required by the engine.+ """+ record = await access.resolve_credential(+ user_id,+ credential_id,+ )+ if record.user_id != user_id:+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail=(+ "Custom voices require a credential owned by the "+ "authenticated user; shared credentials are not allowed."+ ),+ )++ actual_type = record.data.get("type")+ if actual_type != expected_type:+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail=(+ f"Credential {credential_id!r} has type {actual_type!r}; "+ f"expected {expected_type!r}."+ ),+ )+ return record.data+++async def _validate_voice_profile_data(+ access: ResourceAccessService,+ user_id: str,+ data: VoiceProfileData,+) -> None:+ """Validate an authorization binding before storing a voice profile.++ Runtime use is independently guarded by+ ``_service._tts_model._validate_voice_binding``. Both layers share the+ required-field definition so stored and runtime validation stay aligned.+ """+ missing = get_missing_voice_profile_binding_fields(data)+ if missing:+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail="Voice profile requires " + ", ".join(missing) + ".",+ )++ assert data.engine is not None+ assert data.credential_id is not None+ credential_data = await _resolve_owned_credential(+ access,+ user_id,+ data.credential_id,+ ENGINE_TO_CREDENTIAL_TYPE[data.engine],+ )+ validate_voice_profile_model(+ CredentialFactory.from_dict(credential_data),+ data,+ )+++@voice_profile_router.get(+ "/available-engines",+ response_model=AvailableEnginesResponse,+ summary="List available TTS engines",+)+async def list_available_engines(+ user_id: str = Depends(get_current_user_id),+ access: ResourceAccessService = Depends(+ get_resource_access_service,+ ),+) -> AvailableEnginesResponse:+ """Return TTS engines for which the user has a credential.++ Args:+ user_id (`str`): Injected authenticated user ID.+ access (`ResourceAccessService`): Injected access service.++ Returns:+ `AvailableEnginesResponse`: Available engine names.+ """+ credentials = await access.list_resource(+ user_id,+ ResourceKind.CREDENTIAL,+ )++ # Map cred_type -> list of (id, label)+ cred_by_type: dict[str, list[CredentialRef]] = {}+ for cred in credentials:+ # Sharing a provider credential must not implicitly share every custom+ # voice in the upstream account.+ if cred.user_id != user_id:+ continue+ cred_type = cred.data.get("type")+ if cred_type:+ label = cred.data.get("name") or cred_type+ cred_by_type.setdefault(cred_type, []).append(+ CredentialRef(id=cred.id, label=label),+ )++ engines: list[str] = []+ for engine, required_type in ENGINE_TO_CREDENTIAL_TYPE.items():+ if required_type in cred_by_type:+ engines.append(engine)+ engines.sort()++ details = []+ models_by_type: dict[str, list[TTSModelCard]] = {}+ for eng in engines:+ credential_type = ENGINE_TO_CREDENTIAL_TYPE[eng]+ cred_cls = CredentialFactory.get_credential_class(credential_type)+ client_cls = (+ cred_cls.get_voice_cloning_client_class() if cred_cls else None+ )+ if credential_type not in models_by_type:+ models_by_type[credential_type] = (+ cred_cls.list_tts_models() if cred_cls else []+ )+ models = models_by_type[credential_type]+ if credential_type == "dashscope_credential":+ # The App groups Qwen models together, including Qwen Audio.+ models = [+ card+ for card in models+ if card.name.startswith("cosyvoice-") == (eng == "cosyvoice")+ ]+ details.append(+ EngineInfo(+ name=eng,+ credential_type=credential_type,+ models=[+ EngineModelInfo(+ **card.model_dump(),+ enrollment_model=client_cls.get_enrollment_model(+ card.name,+ )+ if client_cls and card.voice_cloning+ else None,+ )+ for card in models+ ],+ voice_cloning=client_cls is not None,+ credentials=cred_by_type.get(+ credential_type,+ [],+ ),+ ),+ )+ return AvailableEnginesResponse(+ engine_details=details,+ )+++@voice_profile_router.get(+ "/",+ response_model=ListVoiceProfilesResponse,+ summary="List all voice profiles",+)+async def list_voice_profiles(+ user_id: str = Depends(get_current_user_id),+ storage: StorageBase = Depends(get_storage),+) -> ListVoiceProfilesResponse:+ """Return all voice profiles for the authenticated user.++ Args:+ user_id (`str`): Injected authenticated user ID.+ storage (`StorageBase`): Injected storage backend.++ Returns:+ `ListVoiceProfilesResponse`: All voice profiles.+ """+ profiles = await storage.list_voice_profiles(user_id)+ return ListVoiceProfilesResponse(+ profiles=profiles,+ total=len(profiles),+ )+++@voice_profile_router.get(+ "/{profile_id}",+ response_model=VoiceProfileRecord,+ summary="Get a voice profile",+)+async def get_voice_profile(+ profile_id: str,+ user_id: str = Depends(get_current_user_id),+ storage: StorageBase = Depends(get_storage),+) -> VoiceProfileRecord:+ """Fetch a single voice profile by id.++ Args:+ profile_id (`str`): The voice profile id.+ user_id (`str`): Injected authenticated user ID.+ storage (`StorageBase`): Injected storage backend.++ Returns:+ `VoiceProfileRecord`: The voice profile record.+ """+ record = await storage.get_voice_profile(user_id, profile_id)+ if record is None:+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND,+ detail=f"Voice profile {profile_id!r} not found.",+ )+ return record+++@voice_profile_router.post(+ "/",+ response_model=CreateVoiceProfileResponse,+ status_code=status.HTTP_201_CREATED,+ summary="Create a new voice profile",+)+async def create_voice_profile(+ body: CreateVoiceProfileRequest,+ user_id: str = Depends(get_current_user_id),+ storage: StorageBase = Depends(get_storage),+ access: ResourceAccessService = Depends(+ get_resource_access_service,+ ),+) -> CreateVoiceProfileResponse:+ """Create a new voice profile.++ Args:+ body (`CreateVoiceProfileRequest`): The profile data.+ user_id (`str`): Injected authenticated user ID.+ storage (`StorageBase`): Injected storage backend.+ access (`ResourceAccessService`): Injected access service.++ Returns:+ `CreateVoiceProfileResponse`: The created profile id.+ """+ await _validate_voice_profile_data(+ access,+ user_id,+ body.data,+ )+ # Check for duplicate name+ existing_profiles = await storage.list_voice_profiles(user_id)+ for p in existing_profiles:+ if p.data.name == body.data.name:+ raise HTTPException(+ status_code=status.HTTP_409_CONFLICT,+ detail=(+ f"Voice profile named '{body.data.name}' "+ f"already exists."+ ),+ )+ record = VoiceProfileRecord(+ user_id=user_id,+ data=body.data,+ )+ profile_id = await storage.upsert_voice_profile(+ user_id,+ record,+ )+ return CreateVoiceProfileResponse(profile_id=profile_id)+++@voice_profile_router.patch(+ "/{profile_id}",+ response_model=VoiceProfileRecord,+ summary="Update a voice profile",+)+async def update_voice_profile(+ profile_id: str,+ body: UpdateVoiceProfileRequest,+ user_id: str = Depends(get_current_user_id),+ storage: StorageBase = Depends(get_storage),+ access: ResourceAccessService = Depends(+ get_resource_access_service,+ ),+) -> VoiceProfileRecord:+ """Update an existing voice profile.++ Args:+ profile_id (`str`): The voice profile id.+ body (`UpdateVoiceProfileRequest`): New profile data.+ user_id (`str`): Injected authenticated user ID.+ storage (`StorageBase`): Injected storage backend.+ access (`ResourceAccessService`): Injected access service.++ Returns:+ `VoiceProfileRecord`: The updated voice profile.+ """+ await _validate_voice_profile_data(+ access,+ user_id,+ body.data,+ )+ existing = await storage.get_voice_profile(+ user_id,+ profile_id,+ )+ if existing is None:+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND,+ detail=f"Voice profile {profile_id!r} not found.",+ )+ # Check for duplicate name (exclude self)+ all_profiles = await storage.list_voice_profiles(user_id)+ for p in all_profiles:+ if p.id != profile_id and p.data.name == body.data.name:+ raise HTTPException(+ status_code=status.HTTP_409_CONFLICT,+ detail=(+ f"Voice profile named '{body.data.name}' "+ f"already exists."+ ),+ )+ existing.data = body.data+ await storage.upsert_voice_profile(user_id, existing)+ updated = await storage.get_voice_profile(+ user_id,+ profile_id,+ )+ if updated is None:+ raise RuntimeError(+ f"Voice profile {profile_id!r} disappeared " "after upsert.",+ )+ return updated+++@voice_profile_router.delete(+ "/{profile_id}",+ status_code=status.HTTP_204_NO_CONTENT,+ summary="Delete a voice profile",+)+async def delete_voice_profile(+ profile_id: str,+ user_id: str = Depends(get_current_user_id),+ storage: StorageBase = Depends(get_storage),+) -> None:+ """Delete a voice profile.++ Args:+ profile_id (`str`): The voice profile id.+ user_id (`str`): Injected authenticated user ID.+ storage (`StorageBase`): Injected storage backend.+ """+ deleted = await storage.delete_voice_profile(+ user_id,+ profile_id,+ )+ if not deleted:+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND,+ detail=f"Voice profile {profile_id!r} not found.",+ )+++# ------------------------------------------------------------------+# Voice Cloning+# ------------------------------------------------------------------+++def _decode_audio(audio_base64: str) -> bytes:+ """Decode a non-empty audio payload or reject malformed input."""+ try:+ audio = base64.b64decode(audio_base64, validate=True)+ except (binascii.Error, ValueError) as exc:+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail="audio_base64 must contain valid base64 audio.",+ ) from exc+ if not audio:+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail="audio_base64 must contain non-empty audio.",+ )+ if len(audio) > MAX_AUDIO_SIZE_BYTES:+ raise HTTPException(+ status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,+ detail="Audio must not exceed 10 MiB.",+ )+ return audio+++@voice_profile_router.post(+ "/openai-consent",+ response_model=OpenAIConsentResponse,+ summary="Upload OpenAI consent recording",+)+async def upload_openai_consent(+ body: OpenAIConsentRequest,+ user_id: str = Depends(get_current_user_id),+ access: ResourceAccessService = Depends(+ get_resource_access_service,+ ),+) -> OpenAIConsentResponse:+ """Upload a consent recording to OpenAI to obtain a consent ID.++ The consent recording must contain the voice actor reading+ a specific consent phrase (see OpenAI docs).++ Args:+ body: Consent request with audio and language.+ user_id: Injected authenticated user ID.+ access: Injected access service.++ Returns:+ OpenAIConsentResponse with the consent_id.+ """+ cred_data = await _resolve_owned_credential(+ access,+ user_id,+ body.credential_id,+ "openai_credential",+ )+ audio = _decode_audio(body.audio_base64)+ client = OpenAIVoiceCloningClient(+ OpenAICredential.model_validate(cred_data),+ )+ try:+ consent_id = await client.create_consent(+ audio,+ name=body.name,+ language=body.language,+ filename=body.audio_filename,+ )+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ except VoiceCloningError as exc:+ raise HTTPException(status_code=502, detail=str(exc)) from exc++ return OpenAIConsentResponse(consent_id=consent_id)+++@voice_profile_router.post(+ "/clone",+ response_model=CloneVoiceResponse,+ summary="Clone a voice from audio",+)+async def clone_voice(+ body: CloneVoiceRequest,+ user_id: str = Depends(get_current_user_id),+ access: ResourceAccessService = Depends(+ get_resource_access_service,+ ),+) -> CloneVoiceResponse:+ """Clone a voice using OpenAI or DashScope voice enrollment.++ Supports OpenAI and Qwen-TTS uploads and CosyVoice audio URLs.++ Args:+ body: Clone request with engine, model, and audio.+ user_id: Injected authenticated user ID.+ access: Injected access service.++ Returns:+ CloneVoiceResponse with the generated voice_id.+ """+ cred_type = ENGINE_TO_CREDENTIAL_TYPE.get(body.engine)+ cred_cls = (+ CredentialFactory.get_credential_class(cred_type)+ if cred_type is not None+ else None+ )+ client_cls = (+ cred_cls.get_voice_cloning_client_class() if cred_cls else None+ )+ if client_cls is None:+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail=f"Engine '{body.engine}' does not support voice cloning.",+ )++ if body.model and cred_cls is not None:+ card = next(+ (c for c in cred_cls.list_tts_models() if c.name == body.model),+ None,+ )+ if card is not None and not card.voice_cloning:+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail=f"Model '{body.model}' does not support voice cloning.",+ )++ assert cred_type is not None+ cred_data = await _resolve_owned_credential(+ access,+ user_id,+ body.credential_id,+ cred_type,+ )+ # Adapt existing HTTP fields to provider options without SDK dependencies+ # on App schemas. New provider-specific UI fields belong in this adapter.+ values = {+ "name": body.prefix,+ "prefix": body.prefix,+ "target_model": body.model,+ "text": body.text,+ "consent": body.consent,+ }+ audio = (+ _decode_audio(body.audio_base64)+ if body.audio_base64 is not None+ else None+ )+ try:+ credential = CredentialFactory.from_dict(cred_data)+ client = client_cls(credential)+ parameters = client.Parameters.model_validate(+ {+ name: value+ for name, value in values.items()+ if name in client.Parameters.model_fields+ },+ )+ voice_id = await client.create_voice(+ audio,+ filename=body.audio_filename,+ audio_url=body.audio_url,+ parameters=parameters,+ )+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ except VoiceCloningError as exc:+ raise HTTPException(status_code=502, detail=str(exc)) from exc++ return CloneVoiceResponse(+ voice_id=voice_id,+ credential_id=body.credential_id,+ )diff --git a/src/agentscope/app/_service/__init__.py b/src/agentscope/app/_service/__init__.pyindex 8c89d99a8..fdceb6800 100644--- a/src/agentscope/app/_service/__init__.py+++ b/src/agentscope/app/_service/__init__.py@@ -20,7 +20,11 @@ from ._index_worker import IndexWorkerfrom ._knowledge_base import KnowledgeBaseServicefrom ._mcp_render import MCPRenderError, render_mcpfrom ._model import get_model, get_realtime_model-from ._tts_model import get_tts_model+from ._tts_model import (+ get_tts_model,+ validate_tts_model_config,+ validate_voice_profile_model,+)from ._session import SessionService, SessionStatusfrom ._session_projection import SessionProjectionfrom ._projectors import SubagentHitlProjector@@ -61,6 +65,8 @@ __all__ = ["get_model","get_realtime_model","get_tts_model",+ "validate_tts_model_config",+ "validate_voice_profile_model","get_toolkit","render_mcp",]diff --git a/src/agentscope/app/_service/_chat.py b/src/agentscope/app/_service/_chat.pyindex baba54fb6..ae06c0ded 100644--- a/src/agentscope/app/_service/_chat.py+++ b/src/agentscope/app/_service/_chat.py@@ -1025,8 +1025,21 @@ class ChatService:user_id,tts_cfg,self._access,+ self._storage,)- middlewares.append(TTSMiddleware(tts_model))+ if tts_model is not None:+ middlewares.append(+ TTSMiddleware(tts_model, continue_on_error=True),+ )+ else:+ await publish_session_event(+ self._message_bus,+ session_id,+ CustomEvent(+ name="tts_error",+ value={"stage": "configuration"},+ ).model_dump(mode="json"),+ )# -------------------------------------------------------------# 2c. Knowledge-base middleware — inject when the session hasdiff --git a/src/agentscope/app/_service/_tts_model.py b/src/agentscope/app/_service/_tts_model.pyindex 88c7a5a67..03332f925 100644--- a/src/agentscope/app/_service/_tts_model.py+++ b/src/agentscope/app/_service/_tts_model.py@@ -1,21 +1,29 @@# -*- coding: utf-8 -*-"""TTS model service: builds a TTSModelBase from stored credential + config."""+import refrom typing import Typefrom fastapi import HTTPException, status+from pydantic import BaseModel, SecretStr, ValidationErrorfrom ._access import ResourceAccessService-from ..storage import TTSModelConfig-from ...credential import CredentialFactory-from ...tts import TTSModelBase+from ..storage import StorageBase, TTSModelConfig, VoiceProfileData+from ..storage._model import (+ ENGINE_TO_CREDENTIAL_TYPE,+ get_missing_voice_profile_binding_fields,+)+from ...credential import CredentialBase, CredentialFactory+from ...tts import OpenAITTSModel, TTSModelBase, TTSModelCard+from ..._logging import loggerasync def get_tts_model(user_id: str,config: TTSModelConfig,access: ResourceAccessService,-) -> TTSModelBase:- """Build a TTS model instance from a stored credential and config.+ storage: StorageBase,+) -> TTSModelBase | None:+ """Build a TTS model using the latest owned voice profile, if bound.Args:user_id (`str`):@@ -25,15 +33,182 @@ async def get_tts_model(The TTS model configuration.access (`ResourceAccessService`):Injected resource access service.+ storage (`StorageBase`):+ Owner-scoped storage used to validate custom voice profiles.Returns:- `TTSModelBase`:- The TTS model instance.+ `TTSModelBase | None`:+ The TTS model instance, or ``None`` when its configuration+ is no longer valid or accessible."""+ credential = None+ data = None+ try:+ if config.voice_profile_id is not None:+ data = await _get_voice_profile_data(+ user_id,+ config.voice_profile_id,+ storage,+ )+ assert data.engine is not None+ provider_type = ENGINE_TO_CREDENTIAL_TYPE[data.engine]+ values = (+ dict(config.parameters)+ if config.type == provider_type and config.model == data.model+ else {}+ )+ values["voice"] = data.voice+ config = config.model_copy(+ update={+ "type": provider_type,+ "credential_id": data.credential_id,+ "model": data.model,+ "parameters": values,+ },+ )+ credential, tts_cls = await _validate_and_resolve_tts_config(+ user_id,+ config,+ access,+ storage,+ resolved_profile=data,+ )+ parameters = _tts_parameters(tts_cls, config)+ return tts_cls(+ credential=credential,+ model=config.model,+ parameters=parameters,+ )+ except (HTTPException, ValueError) as exc:+ logger.warning(+ "Skipping TTS for user %r, model %r: %s",+ user_id,+ config.model,+ _config_error_detail(exc, credential),+ )+ return None+++def _config_error_detail(+ exc: HTTPException | ValueError,+ credential: CredentialBase | None,+) -> str:+ """Keep diagnostic fields while excluding submitted values and secrets."""+ if isinstance(exc, ValidationError):+ return "; ".join(+ f"{'.'.join(map(str, item['loc']))}: {item['type']}"+ for item in exc.errors(include_input=False, include_context=False)+ )[:500]+ detail = str(exc.detail if isinstance(exc, HTTPException) else exc)++ if credential is not None:+ for value in credential.model_dump().values():+ if isinstance(value, SecretStr) and value.get_secret_value():+ detail = detail.replace(value.get_secret_value(), "[redacted]")+ detail = re.sub(r"(?:https?|wss?)://\S+", "[URL]", detail)+ return f"{type(exc).__name__}: {detail}"[:500]+++async def validate_tts_model_config(+ user_id: str,+ config: TTSModelConfig | None,+ access: ResourceAccessService,+ storage: StorageBase,+) -> None:+ """Validate a TTS config before it is persisted on a session."""+ if config is None:+ return+ _, tts_cls = await _validate_and_resolve_tts_config(+ user_id,+ config,+ access,+ storage,+ )++ try:+ _tts_parameters(tts_cls, config)+ except ValueError as exc:+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail="Invalid TTS parameters for the selected model.",+ ) from exc+++def _tts_parameters(+ tts_cls: Type[TTSModelBase],+ config: TTSModelConfig,+) -> BaseModel:+ """Validate parameters, adapting profile voice IDs for OpenAI."""+ values = dict(config.parameters)+ card = _find_model_card(tts_cls, config.model)+ if issubclass(tts_cls, OpenAITTSModel) and config.voice_profile_id:+ voice = values.get("voice")+ if isinstance(voice, str) and voice not in _get_preset_voices(card):+ values["voice"] = {"id": voice}+ return tts_cls.Parameters(**values)+++def validate_voice_profile_model(+ credential: CredentialBase,+ data: VoiceProfileData,+) -> None:+ """Reject known incompatible profiles without blocking new deployments."""+ classes = credential.get_tts_model_classes()+ if not classes:+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail="Credential does not support TTS models.",+ )+ assert data.model is not None+ tts_cls = _resolve_tts_class(classes, data.model)+ _validate_profile_model(_find_model_card(tts_cls, data.model), data.voice)+ try:+ tts_cls.Parameters(voice=data.voice)+ except ValueError as exc:+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail="Invalid voice for the selected model.",+ ) from exc+++def _validate_profile_model(+ card: TTSModelCard | None,+ voice: object,+) -> None:+ """Known models must support either this preset or custom voices."""+ if (+ card is not None+ and not card.voice_cloning+ and not (isinstance(voice, str) and voice in _get_preset_voices(card))+ ):+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail=f"Model {card.name!r} does not support custom voices.",+ )+++async def _validate_and_resolve_tts_config(+ user_id: str,+ config: TTSModelConfig,+ access: ResourceAccessService,+ storage: StorageBase,+ *,+ resolved_profile: VoiceProfileData | None = None,+) -> tuple[CredentialBase, Type[TTSModelBase]]:+ """Resolve the provider and enforce custom voice ownership."""credential_record = await access.resolve_credential(user_id,config.credential_id,)+ credential_type = credential_record.data.get("type")+ if credential_type != config.type:+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail=(+ f"TTS config type {config.type!r} does not match credential "+ f"type {credential_type!r}."+ ),+ )credential = CredentialFactory.from_dict(credential_record.data)tts_classes = credential.get_tts_model_classes()@@ -44,16 +219,169 @@ async def get_tts_model()tts_cls = _resolve_tts_class(tts_classes, config.model)- parameters = (- tts_cls.Parameters(**config.parameters) if config.parameters else None+ card = _find_model_card(tts_cls, config.model)+ await _validate_voice_binding(+ user_id=user_id,+ config=config,+ credential_owner_id=credential_record.user_id,+ storage=storage,+ card=card,+ resolved_profile=resolved_profile,)- return tts_cls(- credential=credential,- model=config.model,- parameters=parameters,+ if config.voice_profile_id or (+ issubclass(tts_cls, OpenAITTSModel)+ and isinstance(config.parameters.get("voice"), dict)+ ):+ _validate_profile_model(card, config.parameters.get("voice"))+ return credential, tts_cls+++async def _validate_voice_binding(+ *,+ user_id: str,+ config: TTSModelConfig,+ credential_owner_id: str,+ storage: StorageBase,+ card: TTSModelCard | None,+ resolved_profile: VoiceProfileData | None = None,+) -> None:+ """Validate preset voices or an exact owner-scoped custom voice profile.++ Profile CRUD performs the write-time counterpart in+ ``_router._voice_profile._validate_voice_profile_data``. Runtime+ validation remains here as defense against stale or externally persisted+ data, while both layers share the required binding-field definition.+ """+ voice = config.parameters.get("voice")+ preset_voices = _get_preset_voices(card)+ if config.voice_profile_id is None:+ if credential_owner_id == user_id and voice is not None:+ return+ if _requires_voice_profile(card, preset_voices):+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail=(+ f"TTS model {config.model!r} requires a cloned voice "+ "profile."+ ),+ )+ if voice is None:+ return+ if isinstance(voice, str) and voice in preset_voices:+ return+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail=("A non-preset voice requires an owned voice_profile_id."),+ )++ data = resolved_profile+ if data is None:+ data = await _get_voice_profile_data(+ user_id,+ config.voice_profile_id,+ storage,+ )++ assert data.engine is not None+ assert data.credential_id is not None+ if credential_owner_id != user_id:+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail="Custom voices cannot use a shared credential.",+ )++ # Runtime already derived its config from this owner-scoped snapshot.+ # Persisted session writes still require an exact binding comparison.+ if resolved_profile is not None:+ return+ expected_type = ENGINE_TO_CREDENTIAL_TYPE[data.engine]+ bindings = {+ "credential_id": (config.credential_id, data.credential_id),+ "provider type": (config.type, expected_type),+ "model": (config.model, data.model),+ "voice": (voice, data.voice),+ }+ mismatches = [+ name+ for name, (actual, expected) in bindings.items()+ if actual != expected+ ]+ if mismatches:+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail=(+ "TTS config does not match voice profile "+ f"{config.voice_profile_id!r}: " + ", ".join(mismatches) + "."+ ),+ )+++async def _get_voice_profile_data(+ user_id: str,+ profile_id: str,+ storage: StorageBase,+) -> VoiceProfileData:+ """Load a complete profile using an owner-scoped lookup."""+ profile = await storage.get_voice_profile(user_id, profile_id)+ if profile is None:+ # Do not reveal whether another tenant owns the supplied profile id.+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND,+ detail=f"Voice profile {profile_id!r} not found.",+ )+ missing = get_missing_voice_profile_binding_fields(profile.data)+ if missing:+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail=(+ f"Voice profile {profile.id!r} is incomplete: "+ + ", ".join(missing)+ + "."+ ),+ )+ return profile.data+++def _find_model_card(+ tts_cls: Type[TTSModelBase],+ model: str,+) -> TTSModelCard | None:+ """Return the exact model card used to classify preset voices."""+ return next(+ (card for card in tts_cls.list_models() if card.name == model),+ None,)+def _get_preset_voices(card: TTSModelCard | None) -> set[str]:+ """Return the provider-declared preset voices for a model card."""+ if card is None:+ return set()+ properties = card.parameter_schema.get("properties", {})+ voice_schema = properties.get("voice", {})+ voices = voice_schema.get("enum", [])+ if not isinstance(voices, list):+ return set()+ return {voice for voice in voices if isinstance(voice, str)}+++def _requires_voice_profile(+ card: TTSModelCard | None,+ preset_voices: set[str] | None = None,+) -> bool:+ """Return whether a model can only synthesize with a cloned voice.++ A voice-cloning model with no provider-declared preset voices is treated+ as clone-only. In particular, omitting ``voice`` must not fall through to+ a shared parameter class default that is invalid for that model.+ """+ if card is None or not card.voice_cloning:+ return False+ if preset_voices is None:+ preset_voices = _get_preset_voices(card)+ return not preset_voices++def _resolve_tts_class(classes: list[Type[TTSModelBase]],model: str,diff --git a/src/agentscope/app/storage/__init__.py b/src/agentscope/app/storage/__init__.pyindex f681cb8fa..85a70e36a 100644--- a/src/agentscope/app/storage/__init__.py+++ b/src/agentscope/app/storage/__init__.py@@ -54,6 +54,8 @@ from ._model import (TeamMember,AgentChatConfig,InviteConfig,+ VoiceProfileData,+ VoiceProfileRecord,)if TYPE_CHECKING:@@ -137,4 +139,6 @@ __all__ = ["ScheduleData","ScheduleRecord","ScheduleSource",+ "VoiceProfileData",+ "VoiceProfileRecord",]diff --git a/src/agentscope/app/storage/_base.py b/src/agentscope/app/storage/_base.pyindex 2dbc2ba43..0408387de 100644--- a/src/agentscope/app/storage/_base.py+++ b/src/agentscope/app/storage/_base.py@@ -22,6 +22,7 @@ from ._model import (SOPRecord,SOPRunRecord,TeamRecord,+ VoiceProfileRecord,)from ...credential import CredentialBasefrom ...message import Msg@@ -1445,3 +1446,80 @@ class StorageBase(ABC):`list[KnowledgeDocumentRecord]`:Orphan ``pending`` documents to redispatch."""++ # ------------------------------------------------------------------+ # Voice profile persistence+ # ------------------------------------------------------------------++ @abstractmethod+ async def upsert_voice_profile(+ self,+ user_id: str,+ record: VoiceProfileRecord,+ ) -> str:+ """Create or update a voice profile record.++ Args:+ user_id (`str`):+ The owner user id.+ record (`VoiceProfileRecord`):+ The voice profile record to persist.++ Returns:+ `str`:+ The id of the stored voice profile.+ """++ @abstractmethod+ async def get_voice_profile(+ self,+ user_id: str,+ profile_id: str,+ ) -> VoiceProfileRecord | None:+ """Fetch a single voice profile record by id.++ Args:+ user_id (`str`):+ The owner user id.+ profile_id (`str`):+ The voice profile id.++ Returns:+ `VoiceProfileRecord | None`:+ The record, or ``None`` if not found.+ """++ @abstractmethod+ async def list_voice_profiles(+ self,+ user_id: str,+ ) -> list[VoiceProfileRecord]:+ """List all voice profiles for a given user.++ Args:+ user_id (`str`):+ The owner user id.++ Returns:+ `list[VoiceProfileRecord]`:+ All voice profile records for the user.+ """++ @abstractmethod+ async def delete_voice_profile(+ self,+ user_id: str,+ profile_id: str,+ ) -> bool:+ """Delete a voice profile record.++ Args:+ user_id (`str`):+ The owner user id.+ profile_id (`str`):+ The voice profile id.++ Returns:+ `bool`:+ ``True`` if deleted, ``False`` if not found.+ """diff --git a/src/agentscope/app/storage/_model/__init__.py b/src/agentscope/app/storage/_model/__init__.pyindex 6b9b074ca..007d00b87 100644--- a/src/agentscope/app/storage/_model/__init__.py+++ b/src/agentscope/app/storage/_model/__init__.py@@ -53,6 +53,12 @@ from ._sop import ()from ._team import TeamRecord, TeamData, TeamMemberfrom ._user import UserRecord+from ._voice_profile import (+ ENGINE_TO_CREDENTIAL_TYPE,+ get_missing_voice_profile_binding_fields,+ VoiceProfileData,+ VoiceProfileRecord,+)__all__ = ["AgentData",@@ -104,4 +110,8 @@ __all__ = ["UserRecord","AgentChatConfig","InviteConfig",+ "ENGINE_TO_CREDENTIAL_TYPE",+ "get_missing_voice_profile_binding_fields",+ "VoiceProfileData",+ "VoiceProfileRecord",]diff --git a/src/agentscope/app/storage/_model/_session.py b/src/agentscope/app/storage/_model/_session.pyindex 2d414a408..73e2db43b 100644--- a/src/agentscope/app/storage/_model/_session.py+++ b/src/agentscope/app/storage/_model/_session.py@@ -140,6 +140,14 @@ class TTSModelConfig(BaseModel):model: str"""The TTS model name."""+ voice_profile_id: str | None = None+ """The owner-scoped voice profile used for a custom voice.++ Profiles bind the voice to its owner, credential and synthesis model.+ Direct voice IDs remain supported with owned credentials. Shared+ credentials may only use default or known preset voices without a profile.+ """+parameters: dict"""TTS parameters (voice, language, etc.)."""diff --git a/src/agentscope/app/storage/_model/_voice_profile.py b/src/agentscope/app/storage/_model/_voice_profile.pynew file mode 100644index 000000000..e20336130--- /dev/null+++ b/src/agentscope/app/storage/_model/_voice_profile.py@@ -0,0 +1,108 @@+# -*- coding: utf-8 -*-+"""The voice profile storage model."""+from typing import Literal++from pydantic import BaseModel, Field++from ...._utils._common import _generate_id+from ._base import _RecordBase+++_ENGINE_TYPE = Literal[+ "cosyvoice",+ "dashscope_tts",+ "openai_tts",+ "gemini_tts",+]++ENGINE_TO_CREDENTIAL_TYPE: dict[str, str] = {+ "cosyvoice": "dashscope_credential",+ "dashscope_tts": "dashscope_credential",+ "openai_tts": "openai_credential",+ "gemini_tts": "gemini_credential",+}+++class VoiceProfileData(BaseModel):+ """The voice profile data model."""++ name: str = Field(+ description="Display name for this voice profile.",+ title="Name",+ )++ engine: _ENGINE_TYPE | None = Field(+ default=None,+ description=(+ "Preferred TTS engine: cosyvoice, "+ "dashscope_tts, openai_tts, or gemini_tts."+ ),+ title="Engine",+ )++ model: str | None = Field(+ default=None,+ description=(+ "Specific TTS model name for synthesis "+ "(e.g. 'qwen3-tts-flash', 'cosyvoice-v3-flash')."+ ),+ title="Model",+ )++ credential_id: str | None = Field(+ default=None,+ description=(+ "Credential ID used for voice cloning and "+ "synthesis. Ensures the same API key is used "+ "for both operations."+ ),+ title="Credential ID",+ )++ voice: str | None = Field(+ default=None,+ description=(+ "Voice identifier: preset name (e.g. 'alloy')"+ " or cloned voice ID from API."+ ),+ title="Voice",+ )++ metadata: dict | None = Field(+ default=None,+ description="Engine-specific extra configuration.",+ title="Metadata",+ )+++def get_missing_voice_profile_binding_fields(+ data: VoiceProfileData,+) -> list[str]:+ """Return missing fields required to authorize and use a voice profile.++ Both profile CRUD validation and runtime TTS validation must use this+ definition so a profile accepted at write time is also usable later.+ """+ binding_fields = {+ "engine": data.engine,+ "credential_id": data.credential_id,+ "model": data.model,+ "voice": data.voice,+ }+ return [+ name+ for name, value in binding_fields.items()+ if not isinstance(value, str) or not value.strip()+ ]+++class VoiceProfileRecord(_RecordBase):+ """The voice profile ORM model."""++ user_id: str = Field(+ default_factory=_generate_id,+ )+ """The owner user id."""++ data: VoiceProfileData+ """The voice profile data."""diff --git a/src/agentscope/app/storage/_redis_storage.py b/src/agentscope/app/storage/_redis_storage.pyindex d42a80697..81054850b 100644--- a/src/agentscope/app/storage/_redis_storage.py+++ b/src/agentscope/app/storage/_redis_storage.py@@ -28,6 +28,7 @@ from ._model import (SOPRecord,SOPRunRecord,TeamRecord,+ VoiceProfileRecord,)from ._utils import _dump_with_secretsfrom ...credential import CredentialBase@@ -145,6 +146,11 @@ class RedisStorage(StorageBase):"agentscope:user:{user_id}"":knowledge_base:{knowledge_base_id}:documents")++ voice_profile: str = (+ "agentscope:user:{user_id}" ":voice_profile:{profile_id}"+ )+ voice_profile_index: str = "agentscope:user:{user_id}:voice_profiles"# Global index of every document key as ``user_id:kb_id:doc_id``;# used by the lease sweeper, never by per-user listing.knowledge_document_global_index: str = "agentscope:knowledge_documents"@@ -2578,3 +2584,99 @@ class RedisStorage(StorageBase):if record.created_at < threshold:records.append(record)return records++ # ------------------------------------------------------------------+ # Voice profile persistence+ # ------------------------------------------------------------------++ async def upsert_voice_profile(+ self,+ user_id: str,+ record: VoiceProfileRecord,+ ) -> str:+ """Create or update a voice profile record.++ Args:+ user_id (`str`): The owner user id.+ record (`VoiceProfileRecord`): The voice profile record.++ Returns:+ `str`: The id of the stored voice profile.+ """+ record.user_id = user_id+ record.updated_at = datetime.now()+ key = self._key(+ self.key_config.voice_profile,+ user_id=user_id,+ profile_id=record.id,+ )+ index_key = self._key(+ self.key_config.voice_profile_index,+ user_id=user_id,+ )+ await self._client.set(+ key,+ record.model_dump_json(),+ )+ await self._client.sadd(index_key, record.id)+ return record.id++ async def get_voice_profile(+ self,+ user_id: str,+ profile_id: str,+ ) -> VoiceProfileRecord | None:+ """Fetch a single voice profile record by id."""+ key = self._key(+ self.key_config.voice_profile,+ user_id=user_id,+ profile_id=profile_id,+ )+ raw = await self._client.get(key)+ if raw:+ return VoiceProfileRecord.model_validate_json(raw)+ return None++ async def list_voice_profiles(+ self,+ user_id: str,+ ) -> list[VoiceProfileRecord]:+ """List all voice profiles for a given user."""+ index_key = self._key(+ self.key_config.voice_profile_index,+ user_id=user_id,+ )+ ids = await self._client.smembers(index_key)+ records: list[VoiceProfileRecord] = []+ for profile_id in ids:+ raw = await self._client.get(+ self._key(+ self.key_config.voice_profile,+ user_id=user_id,+ profile_id=profile_id,+ ),+ )+ if raw:+ records.append(+ VoiceProfileRecord.model_validate_json(raw),+ )+ return records++ async def delete_voice_profile(+ self,+ user_id: str,+ profile_id: str,+ ) -> bool:+ """Delete a voice profile record."""+ key = self._key(+ self.key_config.voice_profile,+ user_id=user_id,+ profile_id=profile_id,+ )+ index_key = self._key(+ self.key_config.voice_profile_index,+ user_id=user_id,+ )+ deleted = await self._client.delete(key)+ await self._client.srem(index_key, profile_id)+ return deleted > 0diff --git a/src/agentscope/app/storage/_sql/_alembic/env.py b/src/agentscope/app/storage/_sql/_alembic/env.pyindex dbd442c76..e5ee6f689 100644--- a/src/agentscope/app/storage/_sql/_alembic/env.py+++ b/src/agentscope/app/storage/_sql/_alembic/env.py@@ -32,7 +32,11 @@ config = context.configurl_from_env = os.getenv("AGENTSCOPE_SQL_URL")if url_from_env and not config.get_main_option("sqlalchemy.url"):- config.set_main_option("sqlalchemy.url", url_from_env)+ # ConfigParser requires literal percent signs to be escaped.+ config.set_main_option(+ "sqlalchemy.url",+ url_from_env.replace("%", "%%"),+ )target_metadata = _Base.metadatadiff --git a/src/agentscope/app/storage/_sql/_alembic/versions/0005_voice_profiles.py b/src/agentscope/app/storage/_sql/_alembic/versions/0005_voice_profiles.pynew file mode 100644index 000000000..2b6e67709--- /dev/null+++ b/src/agentscope/app/storage/_sql/_alembic/versions/0005_voice_profiles.py@@ -0,0 +1,45 @@+# -*- coding: utf-8 -*-+"""Voice profile table.++Revision ID: 0005_voice_profiles+Revises: 0004_sops+Create Date: 2026-10-28 00:00:00.000000+"""+from typing import Sequence, Union++from alembic import op+import sqlalchemy as sa+++revision: str = "0005_voice_profiles"+down_revision: Union[str, None] = "0004_sops"+branch_labels: Union[str, Sequence[str], None] = None+depends_on: Union[str, Sequence[str], None] = None+++def upgrade() -> None:+ """Create voice profiles and their timestamp and ownership indexes."""+ op.create_table(+ "voice_profiles",+ sa.Column("user_id", sa.String(length=255), nullable=False),+ sa.Column("id", sa.String(length=255), nullable=False),+ sa.Column("created_at", sa.DateTime(), nullable=False),+ sa.Column("updated_at", sa.DateTime(), nullable=False),+ sa.Column("payload", sa.JSON(), nullable=False),+ sa.PrimaryKeyConstraint("id"),+ )+ with op.batch_alter_table("voice_profiles", schema=None) as batch_op:+ for column in ("created_at", "updated_at", "user_id"):+ batch_op.create_index(+ batch_op.f(f"ix_voice_profiles_{column}"),+ [column],+ unique=False,+ )+++def downgrade() -> None:+ """Drop the voice profile table and its indexes."""+ with op.batch_alter_table("voice_profiles", schema=None) as batch_op:+ for column in ("user_id", "updated_at", "created_at"):+ batch_op.drop_index(batch_op.f(f"ix_voice_profiles_{column}"))+ op.drop_table("voice_profiles")diff --git a/src/agentscope/app/storage/_sql/_storage.py b/src/agentscope/app/storage/_sql/_storage.pyindex d1e26ca23..c58a84831 100644--- a/src/agentscope/app/storage/_sql/_storage.py+++ b/src/agentscope/app/storage/_sql/_storage.py@@ -19,6 +19,8 @@ need no dialect-specific timezone handling.from datetime import datetime, timedelta, timezonefrom typing import TYPE_CHECKING, Any, Self+import sqlalchemy as sa+from .._base import StorageBasefrom .._model._session import _origin_kwargsfrom .._model import (@@ -37,6 +39,7 @@ from .._model import (SOPRecord,SOPRunRecord,TeamRecord,+ VoiceProfileRecord,)from .._utils import _dump_with_secretsfrom ._mappers import _from_record, _to_record@@ -55,6 +58,7 @@ from ._tables import (SOPRow,SOPRunRow,TeamRow,+ VoiceProfileRow,)from ....credential import CredentialBasefrom ....message import Msg@@ -236,7 +240,8 @@ class AsyncSQLAlchemyStorage(StorageBase):alembic_dir = Path(__file__).resolve().parent / "_alembic"cfg = Config(str(alembic_dir / "alembic.ini"))cfg.set_main_option("script_location", str(alembic_dir))- cfg.set_main_option("sqlalchemy.url", self._url)+ # ConfigParser requires literal percent signs to be escaped.+ cfg.set_main_option("sqlalchemy.url", self._url.replace("%", "%%"))await asyncio.to_thread(command.upgrade, cfg, "head")@@ -2221,3 +2226,113 @@ class AsyncSQLAlchemyStorage(StorageBase):.all())return [_to_record(r, KnowledgeDocumentRecord) for r in rows]++ # ---- Voice Profile ----++ async def upsert_voice_profile(+ self,+ user_id: str,+ record: VoiceProfileRecord,+ ) -> str:+ """Insert a voice profile or update it under an ownership predicate.++ Primary-key collisions never transfer ownership. Concurrent writes+ from the same owner may update the payload; a different owner gets+ ``PermissionError``. Updates preserve the stored creation time.+ """+ record.user_id = user_id+ record.created_at = _to_naive_utc(record.created_at)+ record.updated_at = _utcnow()+ row = _from_record(VoiceProfileRow, record)+ async with self._session() as sess:+ try:+ await sess.execute(+ sa.insert(VoiceProfileRow).values(+ id=record.id,+ user_id=user_id,+ created_at=record.created_at,+ updated_at=record.updated_at,+ payload=row.payload,+ ),+ )+ except sa.exc.IntegrityError as exc:+ await sess.rollback()+ # Ownership is enforced by the write itself, not a precheck.+ owned = (+ VoiceProfileRow.id == record.id,+ VoiceProfileRow.user_id == user_id,+ )+ result = await sess.execute(+ sa.update(VoiceProfileRow)+ .where(*owned)+ .values(payload=row.payload, updated_at=record.updated_at),+ )+ if result.rowcount == 0:+ owner = await sess.scalar(+ sa.select(VoiceProfileRow.user_id).where(+ VoiceProfileRow.id == record.id,+ ),+ )+ if owner is not None and owner != user_id:+ raise PermissionError(+ "Cannot overwrite another user's voice profile.",+ ) from exc+ raise+ record.created_at = (+ await sess.execute(+ sa.select(VoiceProfileRow.created_at).where(*owned),+ )+ ).scalar_one()+ await sess.commit()+ return record.id++ async def get_voice_profile(+ self,+ user_id: str,+ profile_id: str,+ ) -> VoiceProfileRecord | None:+ """Fetch one voice profile; owner-scoped."""+ async with self._session() as sess:+ row = await sess.get(VoiceProfileRow, profile_id)+ if row is None or row.user_id != user_id:+ return None+ return _to_record(row, VoiceProfileRecord)++ async def list_voice_profiles(+ self,+ user_id: str,+ ) -> list[VoiceProfileRecord]:+ """Return all voice profiles for *user_id*."""+ from sqlalchemy import select++ async with self._session() as sess:+ rows = (+ (+ await sess.execute(+ select(VoiceProfileRow).where(+ VoiceProfileRow.user_id == user_id,+ ),+ )+ )+ .scalars()+ .all()+ )+ return [_to_record(r, VoiceProfileRecord) for r in rows]++ async def delete_voice_profile(+ self,+ user_id: str,+ profile_id: str,+ ) -> bool:+ """Delete a voice profile; owner-scoped."""+ from sqlalchemy import delete++ async with self._session() as sess:+ result = await sess.execute(+ delete(VoiceProfileRow).where(+ VoiceProfileRow.id == profile_id,+ VoiceProfileRow.user_id == user_id,+ ),+ )+ await sess.commit()+ return result.rowcount > 0diff --git a/src/agentscope/app/storage/_sql/_tables.py b/src/agentscope/app/storage/_sql/_tables.pyindex 9625b6b6f..d06a4701b 100644--- a/src/agentscope/app/storage/_sql/_tables.py+++ b/src/agentscope/app/storage/_sql/_tables.py@@ -119,6 +119,20 @@ class CredentialRow(_JsonRecordMixin):_indexed_fields = ("user_id",)+class VoiceProfileRow(_JsonRecordMixin):+ """One row per :class:`~agentscope.app.storage.VoiceProfileRecord`."""++ __tablename__ = "voice_profiles"++ user_id: Mapped[str] = mapped_column(+ String(_ID_LEN),+ nullable=False,+ index=True,+ )++ _indexed_fields = ("user_id",)++class AgentRow(_JsonRecordMixin):"""One row per :class:`~agentscope.app.storage.AgentRecord`."""diff --git a/src/agentscope/credential/_base.py b/src/agentscope/credential/_base.pyindex 223c3fc92..bb0375f53 100644--- a/src/agentscope/credential/_base.py+++ b/src/agentscope/credential/_base.py@@ -11,7 +11,7 @@ if TYPE_CHECKING:from ..embedding import EmbeddingModelBasefrom ..model import ChatModelBase, ModelCardfrom ..realtime import RealtimeModelBase, RealtimeModelCard- from ..tts import TTSModelBase+ from ..tts import TTSModelBase, VoiceCloningClientBasefrom ..tts._tts_model_card import TTSModelCard@@ -57,6 +57,13 @@ class CredentialBase(BaseModel):"""return [cls.get_chat_model_class()]+ @classmethod+ def get_voice_cloning_client_class(+ cls,+ ) -> Type["VoiceCloningClientBase"] | None:+ """Return the voice creation client, or None when unsupported."""+ return None+@classmethoddef get_tts_model_classes(cls) -> list[Type["TTSModelBase"]]:"""Return the TTS model classes supported by this credential.diff --git a/src/agentscope/credential/_dashscope.py b/src/agentscope/credential/_dashscope.pyindex 9799b5203..dcdd479bf 100644--- a/src/agentscope/credential/_dashscope.py+++ b/src/agentscope/credential/_dashscope.py@@ -2,7 +2,13 @@"""The DashScope credential."""from typing import Literal, Type, TYPE_CHECKING-from pydantic import ConfigDict, Field, SecretStr+from pydantic import (+ ConfigDict,+ Field,+ SecretStr,+ SerializerFunctionWrapHandler,+ model_serializer,+)from ._base import CredentialBase@@ -10,7 +16,7 @@ if TYPE_CHECKING:from ..embedding import EmbeddingModelBasefrom ..model import ChatModelBasefrom ..realtime import RealtimeModelBase- from ..tts import TTSModelBase+ from ..tts import TTSModelBase, VoiceCloningClientBase_DASHSCOPE_BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"@@ -38,6 +44,27 @@ class DashScopeCredential(CredentialBase):),)+ websocket_url: str | None = Field(+ default=None,+ pattern=r"^wss?://[^/?#]+(?:[/?#].*)?$",+ title="TTS WebSocket URL",+ description=(+ "Optional CosyVoice/Qwen Audio WebSocket endpoint for gateways. "+ "Overrides automatic resolution and DashScope SDK settings."+ ),+ )++ @model_serializer(mode="wrap")+ def _serialize_endpoint_choice(+ self,+ handler: SerializerFunctionWrapHandler,+ ) -> dict:+ """Keep an implicit endpoint implicit across storage round trips."""+ data = handler(self)+ if "base_url" not in self.model_fields_set:+ data.pop("base_url", None)+ return data+@classmethoddef get_chat_model_class(cls) -> Type["ChatModelBase"]:"""Return the DashScopeChatModel class."""@@ -45,6 +72,15 @@ class DashScopeCredential(CredentialBase):return DashScopeChatModel+ @classmethod+ def get_voice_cloning_client_class(+ cls,+ ) -> Type["VoiceCloningClientBase"] | None:+ """Return the voice creation client, or None when unsupported."""+ from ..tts import DashScopeVoiceCloningClient++ return DashScopeVoiceCloningClient+@classmethoddef get_tts_model_classes(cls) -> list[Type["TTSModelBase"]]:"""Return the DashScope TTS model classes."""diff --git a/src/agentscope/credential/_openai.py b/src/agentscope/credential/_openai.pyindex 4b7fdd2f3..51a352e7a 100644--- a/src/agentscope/credential/_openai.py+++ b/src/agentscope/credential/_openai.py@@ -11,7 +11,7 @@ if TYPE_CHECKING:from ..embedding import EmbeddingModelBasefrom ..model import ChatModelBasefrom ..realtime import RealtimeModelBase- from ..tts import TTSModelBase+ from ..tts import TTSModelBase, VoiceCloningClientBaseclass OpenAICredential(CredentialBase):@@ -68,6 +68,15 @@ class OpenAICredential(CredentialBase):return OpenAIEmbeddingModel+ @classmethod+ def get_voice_cloning_client_class(+ cls,+ ) -> Type["VoiceCloningClientBase"] | None:+ """Return the voice creation client, or None when unsupported."""+ from ..tts import OpenAIVoiceCloningClient++ return OpenAIVoiceCloningClient+@classmethoddef get_tts_model_classes(cls) -> list[Type["TTSModelBase"]]:"""Return the OpenAI TTS model classes."""diff --git a/src/agentscope/middleware/_tts_middleware.py b/src/agentscope/middleware/_tts_middleware.pyindex 32c1d9560..15c172523 100644--- a/src/agentscope/middleware/_tts_middleware.py+++ b/src/agentscope/middleware/_tts_middleware.py@@ -1,11 +1,14 @@# -*- coding: utf-8 -*-"""Middleware that turns reasoning text into speech and injects it as``DATA_BLOCK_*`` events into the agent's event stream."""+from contextlib import AsyncExitStack, aclosingfrom typing import TYPE_CHECKING, AsyncGenerator, Callablefrom ._base import MiddlewareBase+from .._logging import loggerfrom .._utils._common import _generate_idfrom ..event import (+ CustomEvent,DataBlockDeltaEvent,DataBlockEndEvent,DataBlockStartEvent,@@ -36,17 +39,30 @@ class TTSMiddleware(MiddlewareBase):Each ``DataBlockDeltaEvent.data`` carries an **incremental** base64 PCMchunk; the full audio is the concatenation of every delta's decodedbytes (the data block is keyed by ``block_id``).++ Provider failures propagate by default. With ``continue_on_error=True``,+ they disable speech for this reply and emit ``CustomEvent("tts_error")``+ with a reply ID and failure stage, while text continues. Upstream errors,+ injected consumer errors and task cancellation always propagate."""- def __init__(self, tts_model: TTSModelBase) -> None:+ def __init__(+ self,+ tts_model: TTSModelBase,+ *,+ continue_on_error: bool = False,+ ) -> None:"""Initialize the TTS middleware.Args:tts_model (`TTSModelBase`):The TTS model used to synthesize speech for assistant textblocks produced during reasoning.+ continue_on_error (`bool`, defaults to `False`):+ Emit a failure notification and continue text on TTS errors."""self.tts = tts_model+ self.continue_on_error = continue_on_errorasync def on_reply(self,@@ -60,54 +76,69 @@ class TTSMiddleware(MiddlewareBase):audio_block_id: str | None = Noneaudio_media_type: str | None = None- async with self.tts:+ enabled = True+ cleanup_failed = False+ propagating_error: BaseException | None = None+ stack = AsyncExitStack()+ try:+ await stack.enter_async_context(self.tts)+ except Exception as exc:+ if not self.continue_on_error:+ raise+ logger.warning("Skipping TTS initialization: %s", exc)+ enabled = False++ try:+ if not enabled:+ yield self._failure_event(agent, "initialization")async for evt in next_handler(**input_kwargs):yield evt-+ if not enabled:+ continue+ push = Falseif isinstance(evt, TextBlockDeltaEvent):text_buffer += evt.delta- if self.tts.realtime and evt.delta:- tts_res = await self.tts.push(evt.delta)- async for audio_evt in self._emit_chunk(- agent,- tts_res,- audio_block_id,- audio_media_type,- ):- if isinstance(audio_evt, DataBlockStartEvent):- audio_block_id = audio_evt.block_id- audio_media_type = audio_evt.media_type- yield audio_evt-+ if not self.tts.realtime or not evt.delta:+ continue+ text = evt.delta+ push = Trueelif isinstance(evt, TextBlockEndEvent):text = text_buffertext_buffer = ""+ else:+ continue- if self.tts.realtime:- res = await self.tts.synthesize()- async for audio_evt in self._emit_synth_result(- agent,- res,- audio_block_id,- audio_media_type,- ):- if isinstance(audio_evt, DataBlockStartEvent):- audio_block_id = audio_evt.block_id- audio_media_type = audio_evt.media_type- yield audio_evt- elif text.strip():- res = await self.tts.synthesize(text)- async for audio_evt in self._emit_synth_result(- agent,- res,- audio_block_id,- audio_media_type,- ):- if isinstance(audio_evt, DataBlockStartEvent):- audio_block_id = audio_evt.block_id- audio_media_type = audio_evt.media_type- yield audio_evt+ # Catch errors from advancing TTS only. Outward yields must+ # stay outside the handler so consumer athrow() propagates.+ pending = self._audio_events(+ agent,+ text,+ push,+ audio_block_id,+ audio_media_type,+ )+ async with aclosing(pending):+ while True:+ try:+ audio_evt = await anext(pending)+ except StopAsyncIteration:+ break+ except Exception as exc:+ if not self.continue_on_error:+ raise+ logger.warning(+ "Skipping TTS for the rest of this reply: %s",+ exc,+ )+ enabled = False+ text_buffer = ""+ break+ if isinstance(audio_evt, DataBlockStartEvent):+ audio_block_id = audio_evt.block_id+ audio_media_type = audio_evt.media_type+ yield audio_evt+ if not push or not enabled:if audio_block_id is not None:yield DataBlockEndEvent(reply_id=agent.state.reply_id,@@ -115,6 +146,74 @@ class TTSMiddleware(MiddlewareBase):)audio_block_id = Noneaudio_media_type = None+ if not enabled:+ yield self._failure_event(agent, "synthesis")+ except BaseException as exc:+ propagating_error = exc+ raise+ finally:+ error = (+ (+ type(propagating_error),+ propagating_error,+ propagating_error.__traceback__,+ )+ if propagating_error is not None+ else (None, None, None)+ )+ try:+ await stack.__aexit__(*error)+ except Exception as exc:+ # Cleanup must not replace an upstream/consumer exception.+ if propagating_error is None and not self.continue_on_error:+ raise+ logger.warning("TTS cleanup failed: %s", exc)+ cleanup_failed = True+ if cleanup_failed and enabled:+ yield self._failure_event(agent, "cleanup")++ @staticmethod+ def _failure_event(agent: "Agent", stage: str) -> CustomEvent:+ """Notify consumers without exposing upstream response contents."""+ return CustomEvent(+ name="tts_error",+ value={"reply_id": agent.state.reply_id, "stage": stage},+ )++ async def _audio_events(+ self,+ agent: "Agent",+ text: str,+ push: bool,+ audio_block_id: str | None,+ audio_media_type: str | None,+ ) -> AsyncGenerator:+ """Perform one TTS operation and yield its incremental audio."""+ if push:+ result = await self.tts.push(text)+ events = self._emit_chunk(+ agent,+ result,+ audio_block_id,+ audio_media_type,+ )+ else:+ if not self.tts.realtime and not text.strip():+ return+ result = (+ await self.tts.synthesize()+ if self.tts.realtime+ else await self.tts.synthesize(text)+ )+ events = self._emit_synth_result(+ agent,+ result,+ audio_block_id,+ audio_media_type,+ )+ async with aclosing(events):+ async for event in events:+ yield eventasync def _emit_synth_result(self,@@ -126,17 +225,18 @@ class TTSMiddleware(MiddlewareBase):"""Normalize ``synthesize()`` returns (single response or asyncgenerator) into a stream of ``DATA_BLOCK_*`` events."""if isinstance(res, AsyncGenerator):- async for chunk in res:- async for ae in self._emit_chunk(- agent,- chunk,- audio_block_id,- audio_media_type,- ):- if isinstance(ae, DataBlockStartEvent):- audio_block_id = ae.block_id- audio_media_type = ae.media_type- yield ae+ async with aclosing(res):+ async for chunk in res:+ async for ae in self._emit_chunk(+ agent,+ chunk,+ audio_block_id,+ audio_media_type,+ ):+ if isinstance(ae, DataBlockStartEvent):+ audio_block_id = ae.block_id+ audio_media_type = ae.media_type+ yield aeelse:async for ae in self._emit_chunk(agent,diff --git a/src/agentscope/tts/__init__.py b/src/agentscope/tts/__init__.pyindex 95199ce2f..4cbbb33c4 100644--- a/src/agentscope/tts/__init__.py+++ b/src/agentscope/tts/__init__.py@@ -4,13 +4,16 @@from ._tts_base import TTSModelBasefrom ._tts_model_card import TTSModelCardfrom ._tts_response import TTSResponse, TTSUsage+from ._voice_utils import VoiceCloningError+from ._voice_cloning_client_base import VoiceCloningClientBasefrom ._dashscope import (DashScopeCosyVoiceTTSModel,DashScopeTTSModel,DashScopeRealtimeTTSModel,+ DashScopeVoiceCloningClient,)from ._gemini import GeminiTTSModel-from ._openai import OpenAITTSModel+from ._openai import OpenAITTSModel, OpenAIVoiceCloningClient__all__ = ["TTSModelBase",@@ -22,4 +25,8 @@ __all__ = ["DashScopeRealtimeTTSModel","GeminiTTSModel","OpenAITTSModel",+ "OpenAIVoiceCloningClient",+ "DashScopeVoiceCloningClient",+ "VoiceCloningError",+ "VoiceCloningClientBase",]diff --git a/src/agentscope/tts/_dashscope/__init__.py b/src/agentscope/tts/_dashscope/__init__.pyindex 03599ae96..1aa9ca178 100644--- a/src/agentscope/tts/_dashscope/__init__.py+++ b/src/agentscope/tts/_dashscope/__init__.py@@ -4,9 +4,11 @@from ._cosyvoice_model import DashScopeCosyVoiceTTSModelfrom ._model import DashScopeTTSModelfrom ._realtime_model import DashScopeRealtimeTTSModel+from ._voice_cloning_client import DashScopeVoiceCloningClient__all__ = ["DashScopeCosyVoiceTTSModel","DashScopeTTSModel","DashScopeRealtimeTTSModel",+ "DashScopeVoiceCloningClient",]diff --git a/src/agentscope/tts/_dashscope/_cosyvoice_model.py b/src/agentscope/tts/_dashscope/_cosyvoice_model.pyindex d5a26a0c7..34a3c368a 100644--- a/src/agentscope/tts/_dashscope/_cosyvoice_model.py+++ b/src/agentscope/tts/_dashscope/_cosyvoice_model.py@@ -5,6 +5,7 @@ import base64import ioimport osfrom typing import Any, AsyncGenerator, Literal, TYPE_CHECKING+from urllib.parse import urlsplitimport wavefrom pydantic import BaseModel, Field@@ -12,6 +13,7 @@ from pydantic import BaseModel, Fieldfrom .._tts_base import TTSModelBasefrom .._tts_model_card import TTSModelCardfrom .._tts_response import TTSResponse+from ._endpoints import _dashscope_urlfrom ._cosyvoice_utils import (_BITS_PER_SAMPLE,_CHANNELS,@@ -28,7 +30,14 @@ if TYPE_CHECKING:class DashScopeCosyVoiceTTSModel(TTSModelBase):- """DashScope CosyVoice TTS model using the WebSocket SpeechSynthesizer."""+ """DashScope CosyVoice TTS model using the WebSocket SpeechSynthesizer.++ ``credential.websocket_url`` takes precedence. Non-default official+ endpoints and gateways with an API suffix derive the WebSocket route+ from ``base_url``. The default base URL and other gateway layouts keep+ the SDK's environment/global WebSocket configuration. For gateways with+ separate HTTP and WebSocket routes, set both credential URLs explicitly.+ """class Parameters(BaseModel):"""Frontend-exposed parameters for DashScope CosyVoice TTS models."""@@ -176,11 +185,34 @@ class DashScopeCosyVoiceTTSModel(TTSModelBase):callback_cls = _make_cosyvoice_callback_class()callback_instance = callback_cls()+ url = self.credential.websocket_url+ if url is None:+ base_url = self.credential.base_url.rstrip("/")+ parsed = urlsplit(base_url)+ default_url = DashScopeCredential.model_fields["base_url"].default+ official = parsed.hostname in {+ "dashscope.aliyuncs.com",+ "dashscope-intl.aliyuncs.com",+ "dashscope-us.aliyuncs.com",+ } or (parsed.hostname or "").endswith(".maas.aliyuncs.com")+ standard_path = parsed.path.rstrip("/").endswith(+ ("/compatible-mode/v1", "/api/v1"),+ )+ if base_url != default_url and (official or standard_path):+ url = _dashscope_url(+ base_url,+ "/api-ws/v1/inference",+ websocket=True,+ )+ # Omitting url preserves SDK environment/global overrides for legacy+ # defaults and gateways whose WebSocket route cannot be inferred.+ endpoint = {"url": url} if url is not None else {}synthesizer = SpeechSynthesizer(model=self.model,voice=self.parameters.voice,format=AudioFormat.PCM_24000HZ_MONO_16BIT,callback=callback_instance,+ **endpoint,)return synthesizer, callback_instancediff --git a/src/agentscope/tts/_dashscope/_cosyvoice_models/cosyvoice-v3-flash.yaml b/src/agentscope/tts/_dashscope/_cosyvoice_models/cosyvoice-v3-flash.yamlindex 5810bfd1d..8975f247b 100644--- a/src/agentscope/tts/_dashscope/_cosyvoice_models/cosyvoice-v3-flash.yaml+++ b/src/agentscope/tts/_dashscope/_cosyvoice_models/cosyvoice-v3-flash.yaml@@ -1,6 +1,7 @@name: cosyvoice-v3-flashlabel: CosyVoice-v3-Flashstatus: active+voice_cloning: trueinput_types:- text/plaindiff --git a/src/agentscope/tts/_dashscope/_cosyvoice_models/cosyvoice-v3-plus.yaml b/src/agentscope/tts/_dashscope/_cosyvoice_models/cosyvoice-v3-plus.yamlindex fa68a04b5..b6434aa3d 100644--- a/src/agentscope/tts/_dashscope/_cosyvoice_models/cosyvoice-v3-plus.yaml+++ b/src/agentscope/tts/_dashscope/_cosyvoice_models/cosyvoice-v3-plus.yaml@@ -1,6 +1,7 @@name: cosyvoice-v3-pluslabel: CosyVoice-v3-Plusstatus: active+voice_cloning: trueinput_types:- text/plaindiff --git a/src/agentscope/tts/_dashscope/_cosyvoice_models/cosyvoice-v3.5-flash.yaml b/src/agentscope/tts/_dashscope/_cosyvoice_models/cosyvoice-v3.5-flash.yamlnew file mode 100644index 000000000..f7dcc9d88--- /dev/null+++ b/src/agentscope/tts/_dashscope/_cosyvoice_models/cosyvoice-v3.5-flash.yaml@@ -0,0 +1,14 @@+name: cosyvoice-v3.5-flash+label: CosyVoice-v3.5-Flash+status: active+voice_cloning: true++input_types:+ - text/plain++output_types:+ - audio/wav++voices: []++parameter_overrides: {}diff --git a/src/agentscope/tts/_dashscope/_cosyvoice_models/cosyvoice-v3.5-plus.yaml b/src/agentscope/tts/_dashscope/_cosyvoice_models/cosyvoice-v3.5-plus.yamlnew file mode 100644index 000000000..8249f919b--- /dev/null+++ b/src/agentscope/tts/_dashscope/_cosyvoice_models/cosyvoice-v3.5-plus.yaml@@ -0,0 +1,14 @@+name: cosyvoice-v3.5-plus+label: CosyVoice-v3.5-Plus+status: active+voice_cloning: true++input_types:+ - text/plain++output_types:+ - audio/wav++voices: []++parameter_overrides: {}diff --git a/src/agentscope/tts/_dashscope/_cosyvoice_models/qwen-audio-3.0-tts-flash.yaml b/src/agentscope/tts/_dashscope/_cosyvoice_models/qwen-audio-3.0-tts-flash.yamlindex 2171971d0..0ceb235d7 100644--- a/src/agentscope/tts/_dashscope/_cosyvoice_models/qwen-audio-3.0-tts-flash.yaml+++ b/src/agentscope/tts/_dashscope/_cosyvoice_models/qwen-audio-3.0-tts-flash.yaml@@ -3,6 +3,7 @@name: qwen-audio-3.0-tts-flashlabel: Qwen Audio 3.0 TTS Flashstatus: active+voice_cloning: trueinput_types:- text/plaindiff --git a/src/agentscope/tts/_dashscope/_cosyvoice_models/qwen-audio-3.0-tts-plus.yaml b/src/agentscope/tts/_dashscope/_cosyvoice_models/qwen-audio-3.0-tts-plus.yamlindex 4ef677ab3..8a7fd1ad8 100644--- a/src/agentscope/tts/_dashscope/_cosyvoice_models/qwen-audio-3.0-tts-plus.yaml+++ b/src/agentscope/tts/_dashscope/_cosyvoice_models/qwen-audio-3.0-tts-plus.yaml@@ -3,6 +3,7 @@name: qwen-audio-3.0-tts-pluslabel: Qwen Audio 3.0 TTS Plusstatus: active+voice_cloning: trueinput_types:- text/plaindiff --git a/src/agentscope/tts/_dashscope/_cosyvoice_models/qwen-audio-3.1-tts-flash.yaml b/src/agentscope/tts/_dashscope/_cosyvoice_models/qwen-audio-3.1-tts-flash.yamlindex 9d3e8a48f..d46fcf6cc 100644--- a/src/agentscope/tts/_dashscope/_cosyvoice_models/qwen-audio-3.1-tts-flash.yaml+++ b/src/agentscope/tts/_dashscope/_cosyvoice_models/qwen-audio-3.1-tts-flash.yaml@@ -3,6 +3,7 @@name: qwen-audio-3.1-tts-flashlabel: Qwen Audio 3.1 TTS Flashstatus: active+voice_cloning: trueinput_types:- text/plaindiff --git a/src/agentscope/tts/_dashscope/_cosyvoice_models/qwen-audio-3.1-tts-plus.yaml b/src/agentscope/tts/_dashscope/_cosyvoice_models/qwen-audio-3.1-tts-plus.yamlindex fb098fe7d..e63397ec3 100644--- a/src/agentscope/tts/_dashscope/_cosyvoice_models/qwen-audio-3.1-tts-plus.yaml+++ b/src/agentscope/tts/_dashscope/_cosyvoice_models/qwen-audio-3.1-tts-plus.yaml@@ -3,6 +3,7 @@name: qwen-audio-3.1-tts-pluslabel: Qwen Audio 3.1 TTS Plusstatus: active+voice_cloning: trueinput_types:- text/plaindiff --git a/src/agentscope/tts/_dashscope/_endpoints.py b/src/agentscope/tts/_dashscope/_endpoints.pynew file mode 100644index 000000000..12c73f029--- /dev/null+++ b/src/agentscope/tts/_dashscope/_endpoints.py@@ -0,0 +1,44 @@+# -*- coding: utf-8 -*-+"""Credential endpoint resolution shared by enrollment and synthesis."""+from urllib.parse import urlsplit++from ...credential import DashScopeCredential+++def _qwen_http_url(credential: DashScopeCredential, path: str) -> str:+ """Share Qwen enrollment/synthesis routing without changing SDK globals."""+ if "base_url" in credential.model_fields_set:+ return _dashscope_url(credential.base_url, path)++ import dashscope++ parsed = urlsplit(dashscope.base_http_api_url)+ return parsed._replace(+ path=parsed.path.rstrip("/") + path.removeprefix("/api/v1"),+ fragment="",+ ).geturl()+++def _dashscope_url(+ base_url: str,+ path: str,+ *,+ websocket: bool = False,+) -> str:+ """Replace the API suffix, preserving the host and proxy path prefix."""+ parsed = urlsplit(base_url)+ if parsed.scheme not in {"http", "https"} or not parsed.netloc:+ raise ValueError("DashScope base_url must be an absolute HTTP(S) URL")+ prefix = parsed.path.rstrip("/")+ for suffix in ("/compatible-mode/v1", "/api/v1"):+ if prefix.endswith(suffix):+ prefix = prefix[: -len(suffix)]+ break+ scheme = parsed.scheme+ if websocket:+ scheme = "wss" if scheme == "https" else "ws"+ return parsed._replace(+ scheme=scheme,+ path=prefix + path,+ fragment="",+ ).geturl()diff --git a/src/agentscope/tts/_dashscope/_model.py b/src/agentscope/tts/_dashscope/_model.pyindex cb08e8ec9..784e5bc73 100644--- a/src/agentscope/tts/_dashscope/_model.py+++ b/src/agentscope/tts/_dashscope/_model.py@@ -14,6 +14,7 @@ from typing import (from pydantic import BaseModel, Field+from ._endpoints import _qwen_http_urlfrom .._tts_base import TTSModelBasefrom .._tts_response import TTSResponse, TTSUsagefrom ..._utils._audio import _build_streaming_wav_header@@ -84,6 +85,8 @@ class DashScopeTTSModel(TTSModelBase):Args:credential (`DashScopeCredential`):The DashScope credential used to authenticate the API call.+ An explicit ``base_url`` selects the HTTP endpoint; otherwise+ the SDK global HTTP setting is used, as in voice enrollment.model (`str`, defaults to ``"qwen3-tts-flash"``):The TTS model name. Supported models include``qwen3-tts-flash``, ``qwen-tts``, etc.@@ -116,6 +119,7 @@ class DashScopeTTSModel(TTSModelBase):The text to be synthesized.**kwargs (`Any`):Additional keyword arguments to pass to the TTS API call.+ ``base_address`` explicitly overrides the credential endpoint.Returns:`TTSResponse | AsyncGenerator[TTSResponse, None]`:@@ -131,6 +135,10 @@ class DashScopeTTSModel(TTSModelBase):"model": self.model,"text": text,"voice": self.parameters.voice,+ "base_address": _qwen_http_url(+ self.credential,+ "/api/v1",+ ),}request_kwargs.update(kwargs)request_kwargs["api_key"] = self.credential.api_key.get_secret_value()diff --git a/src/agentscope/tts/_dashscope/_voice_cloning_client.py b/src/agentscope/tts/_dashscope/_voice_cloning_client.pynew file mode 100644index 000000000..df507d46e--- /dev/null+++ b/src/agentscope/tts/_dashscope/_voice_cloning_client.py@@ -0,0 +1,148 @@+# -*- coding: utf-8 -*-+"""DashScope voice enrollment for Qwen-TTS and CosyVoice."""+import base64+from typing import Any++from pydantic import BaseModel, Field++from ._endpoints import _dashscope_url, _qwen_http_url+from ...credential import DashScopeCredential+from .._voice_cloning_client_base import VoiceCloningClientBase+from .._voice_utils import (+ VoiceCloningError,+ _audio_file,+ _post_voice_request,+)++_CLONE_PATH = "/api/v1/services/audio/tts/customization"+++class DashScopeVoiceCloningClient(VoiceCloningClientBase):+ """Create custom voices using the credential's DashScope endpoint.++ The credential's ``base_url`` selects the host and optional proxy prefix.+ Its API suffix is replaced with the audio enrollment path.+ Qwen-TTS uses the SDK global HTTP endpoint when ``base_url`` is omitted.+ Reuse the credential and target model for synthesis.+ Methods raise ``ValueError`` for invalid inputs and ``VoiceCloningError``+ for failed provider requests.+ """++ class Parameters(VoiceCloningClientBase.Parameters):+ """DashScope model and enrollment options."""++ target_model: str = Field(min_length=1)+ """Synthesis model supporting the enrolled voice."""++ prefix: str = Field(default="agentscope", min_length=1)+ """Provider-supported prefix for the voice name."""++ text: str | None = None+ """Optional transcript for the Qwen voice enrollment protocol."""++ credential: DashScopeCredential++ def __init__(self, credential: DashScopeCredential) -> None:+ """Bind the credential used for voice enrollment."""+ super().__init__(credential)++ @classmethod+ def get_enrollment_model(cls, model: str) -> str:+ """Resolve the enrollment model used for a synthesis model family."""+ if model.startswith(("cosyvoice-", "qwen-audio-")):+ return "voice-enrollment"+ if model.startswith("qwen"):+ return "qwen-voice-enrollment"+ raise ValueError(+ f"Unsupported DashScope voice model family: {model!r}",+ )++ async def create_voice(+ self,+ audio: bytes | None = None,+ *,+ filename: str = "voice.wav",+ audio_url: str | None = None,+ parameters: BaseModel | None = None,+ ) -> str:+ """Enroll a voice and return its provider ID.++ Args:+ audio: Encoded sample bytes for Qwen-TTS. Supply either this or+ ``audio_url``, never both.+ filename: Sample filename used to determine its MIME type.+ audio_url: Publicly accessible sample URL for CosyVoice.+ parameters: ``Parameters`` specifying the target model, prefix+ and optional transcript. Qwen Audio ignores the transcript.++ Returns:+ The voice ID to pass as the synthesis model's ``voice`` value.+ """+ options = self.Parameters.model_validate(+ parameters.model_dump() if parameters is not None else {},+ )+ target_model = options.target_model+ if (audio is None) == (audio_url is None):+ raise ValueError("Provide exactly one of audio or audio_url")+ enrollment = self.get_enrollment_model(target_model)++ inputs: dict[str, Any] = {+ "action": "create_voice",+ "target_model": target_model,+ "prefix": options.prefix,+ }+ if target_model.startswith("cosyvoice-"):+ if audio is not None:+ raise ValueError(+ "CosyVoice requires audio_url, not audio bytes",+ )+ if not audio_url:+ raise ValueError("audio_url must not be empty")+ inputs["url"] = audio_url+ else:+ if audio is None:+ raise ValueError(+ "Qwen-TTS requires audio bytes, not audio_url",+ )+ _, _, mime_type = _audio_file(filename, audio)+ encoded = base64.b64encode(audio).decode("ascii")+ data_uri = f"data:{mime_type};base64,{encoded}"+ if target_model.startswith("qwen-audio-"):+ inputs["audio"] = data_uri+ else:+ inputs = {+ "action": "create",+ "target_model": target_model,+ "preferred_name": options.prefix,+ "audio": {"data": data_uri},+ }+ if options.text:+ inputs["text"] = options.text+ result = await _post_voice_request(+ _qwen_http_url(self.credential, _CLONE_PATH)+ if enrollment == "qwen-voice-enrollment"+ else _dashscope_url(self.credential.base_url, _CLONE_PATH),+ provider="DashScope",+ operation="voice clone",+ headers={+ "Authorization": (+ f"Bearer {self.credential.api_key.get_secret_value()}"+ ),+ "Content-Type": "application/json",+ },+ json={"model": enrollment, "input": inputs},+ )+ output = result.get("output")+ voice_id = (+ output.get("voice")+ or output.get("voice_id")+ or output.get("voice_name")+ if isinstance(output, dict)+ else None+ )+ if not isinstance(voice_id, str) or not voice_id:+ raise VoiceCloningError(+ "DashScope returned success but no "+ f"voice found in response: {str(result)[:500]}",+ )+ return voice_iddiff --git a/src/agentscope/tts/_openai/__init__.py b/src/agentscope/tts/_openai/__init__.pyindex 153f72178..2685a8d57 100644--- a/src/agentscope/tts/_openai/__init__.py+++ b/src/agentscope/tts/_openai/__init__.py@@ -2,7 +2,9 @@"""The OpenAI TTS module."""from ._model import OpenAITTSModel+from ._voice_cloning_client import OpenAIVoiceCloningClient__all__ = ["OpenAITTSModel",+ "OpenAIVoiceCloningClient",]diff --git a/src/agentscope/tts/_openai/_model.py b/src/agentscope/tts/_openai/_model.pyindex fcd4b407e..7a5058458 100644--- a/src/agentscope/tts/_openai/_model.py+++ b/src/agentscope/tts/_openai/_model.py@@ -52,10 +52,10 @@ class OpenAITTSModel(TTSModelBase):class Parameters(BaseModel):"""Frontend-exposed parameters for OpenAI TTS models."""- voice: str = Field(+ voice: str | dict[str, str] = Field(default="alloy",title="Voice",- description="The voice to use for synthesis.",+ description="A preset voice name or a custom voice id object.",)response_format: Literal[diff --git a/src/agentscope/tts/_openai/_models/gpt-4o-mini-tts.yaml b/src/agentscope/tts/_openai/_models/gpt-4o-mini-tts.yamlindex 49171714c..37397e522 100644--- a/src/agentscope/tts/_openai/_models/gpt-4o-mini-tts.yaml+++ b/src/agentscope/tts/_openai/_models/gpt-4o-mini-tts.yaml@@ -1,6 +1,7 @@name: gpt-4o-mini-ttslabel: GPT-4o Mini TTSstatus: active+voice_cloning: trueinput_types:- text/plain@@ -26,5 +27,7 @@ voices:- sage- shimmer- verse+ - marin+ - cedarparameter_overrides: {}diff --git a/src/agentscope/tts/_openai/_models/tts-1-hd.yaml b/src/agentscope/tts/_openai/_models/tts-1-hd.yamlindex 744cbba03..33196ea4d 100644--- a/src/agentscope/tts/_openai/_models/tts-1-hd.yaml+++ b/src/agentscope/tts/_openai/_models/tts-1-hd.yaml@@ -17,7 +17,6 @@ voices:# Source: https://platform.openai.com/docs/guides/text-to-speech- alloy- ash- - ballad- coral- echo- fable@@ -25,7 +24,6 @@ voices:- nova- sage- shimmer- - verseparameter_overrides:# The instructions parameter is not supported by tts-1-hd, hide it fromdiff --git a/src/agentscope/tts/_openai/_models/tts-1.yaml b/src/agentscope/tts/_openai/_models/tts-1.yamlindex 755d21274..5fc66e67f 100644--- a/src/agentscope/tts/_openai/_models/tts-1.yaml+++ b/src/agentscope/tts/_openai/_models/tts-1.yaml@@ -17,7 +17,6 @@ voices:# Source: https://platform.openai.com/docs/guides/text-to-speech- alloy- ash- - ballad- coral- echo- fable@@ -25,7 +24,6 @@ voices:- nova- sage- shimmer- - verseparameter_overrides:# The instructions parameter is not supported by tts-1, hide it fromdiff --git a/src/agentscope/tts/_openai/_voice_cloning_client.py b/src/agentscope/tts/_openai/_voice_cloning_client.pynew file mode 100644index 000000000..05c8ce9e7--- /dev/null+++ b/src/agentscope/tts/_openai/_voice_cloning_client.py@@ -0,0 +1,145 @@+# -*- coding: utf-8 -*-+"""OpenAI voice creation and consent recording uploads."""+import os++from pydantic import BaseModel, Field++from ...credential import OpenAICredential+from .._voice_cloning_client_base import VoiceCloningClientBase+from .._voice_utils import (+ VoiceCloningError,+ _audio_file,+ _post_voice_request,+)+++class OpenAIVoiceCloningClient(VoiceCloningClientBase):+ """Create OpenAI custom voices independently of a synthesis model.++ Reuse the same credential for creation and synthesis. Consent recordings+ must contain the provider's exact declaration in the supplied language.+ Methods raise ``ValueError`` for invalid inputs and ``VoiceCloningError``+ for failed provider requests. No App service or storage is required.+ """++ class Parameters(VoiceCloningClientBase.Parameters):+ """OpenAI voice creation options."""++ name: str = Field(default="agentscope", min_length=1)+ """Label for the created voice."""++ consent: str = Field(min_length=1)+ """ID of the speaker's consent recording."""++ credential: OpenAICredential++ def __init__(self, credential: OpenAICredential) -> None:+ """Bind the credential used for voice and consent creation."""+ super().__init__(credential)++ def _request_config(self) -> tuple[str, dict[str, str]]:+ """Match OpenAI endpoint, organization and project defaults."""+ base_url = (+ self.credential.base_url+ or os.getenv("OPENAI_BASE_URL")+ or "https://api.openai.com/v1"+ )+ headers = {+ "Authorization": (+ f"Bearer {self.credential.api_key.get_secret_value()}"+ ),+ }+ organization = self.credential.organization or os.getenv(+ "OPENAI_ORG_ID",+ )+ if organization:+ headers["OpenAI-Organization"] = organization+ project = os.getenv("OPENAI_PROJECT_ID")+ if project:+ headers["OpenAI-Project"] = project+ return base_url.rstrip("/"), headers++ async def create_consent(+ self,+ audio: bytes,+ *,+ name: str,+ language: str,+ filename: str = "consent.wav",+ ) -> str:+ """Upload a consent recording and return its provider ID.++ Args:+ audio: Encoded recording bytes, not base64 or raw PCM.+ name: Label for the consent recording.+ language: BCP 47 language tag matching the recorded declaration.+ filename: Recording filename used to determine its MIME type.++ Returns:+ The consent ID required by :meth:`create_voice`.+ """+ if not name or not language:+ raise ValueError("name and language must not be empty")+ recording = _audio_file(filename, audio)+ base_url, headers = self._request_config()+ result = await _post_voice_request(+ f"{base_url}/audio/voice_consents",+ provider="OpenAI",+ operation="consent upload",+ success_codes=(200, 201),+ headers=headers,+ data={"name": name, "language": language},+ files={"recording": recording},+ )+ consent_id = result.get("id")+ if not isinstance(consent_id, str) or not consent_id:+ raise VoiceCloningError(+ "OpenAI returned success but no consent "+ f"id in response: {result}",+ )+ return consent_id++ async def create_voice(+ self,+ audio: bytes | None = None,+ *,+ filename: str = "voice.wav",+ audio_url: str | None = None,+ parameters: BaseModel | None = None,+ ) -> str:+ """Create a custom voice and return its provider ID.++ Args:+ audio: Encoded sample bytes from the consenting speaker.+ filename: Sample filename used to determine its MIME type.+ audio_url: Unsupported by OpenAI; must be ``None``.+ parameters: ``Parameters`` containing the name and consent ID+ returned by :meth:`create_consent`.++ Returns:+ The voice ID. Pass ``{"id": voice_id}`` as the ``voice`` parameter+ of a compatible ``OpenAITTSModel`` when synthesizing speech.+ """+ options = self.Parameters.model_validate(+ parameters.model_dump() if parameters is not None else {},+ )+ if audio_url is not None or audio is None:+ raise ValueError("OpenAI requires audio bytes, not audio_url")+ sample = _audio_file(filename, audio)+ base_url, headers = self._request_config()+ result = await _post_voice_request(+ f"{base_url}/audio/voices",+ provider="OpenAI",+ operation="voice clone",+ success_codes=(200, 201),+ headers=headers,+ data={"name": options.name, "consent": options.consent},+ files={"audio_sample": sample},+ )+ voice_id = result.get("id")+ if not isinstance(voice_id, str) or not voice_id:+ raise VoiceCloningError(+ "OpenAI returned success but no voice "+ f"id in response: {result}",+ )+ return voice_iddiff --git a/src/agentscope/tts/_tts_model_card.py b/src/agentscope/tts/_tts_model_card.pyindex 55ad4f2a8..505069139 100644--- a/src/agentscope/tts/_tts_model_card.py+++ b/src/agentscope/tts/_tts_model_card.py@@ -55,6 +55,13 @@ class TTSModelCard(BaseModel):)"""Whether the model supports streaming input."""+ voice_cloning: bool = Field(+ default=False,+ description="Whether the model supports voice cloning.",+ title="Voice Cloning",+ )+ """Whether the model supports voice cloning."""+parameter_schema: dict"""The parameters schema."""@@ -129,6 +136,7 @@ class TTSModelCard(BaseModel):input_types=config.get("input_types", ["text/plain"]),output_types=config.get("output_types", ["audio/wav"]),realtime=config.get("realtime", False),+ voice_cloning=config.get("voice_cloning", False),parameter_schema=final_schema,parameters_overrides=config.get("parameter_overrides", {}),)diff --git a/src/agentscope/tts/_voice_cloning_client_base.py b/src/agentscope/tts/_voice_cloning_client_base.pynew file mode 100644index 000000000..451a8ff43--- /dev/null+++ b/src/agentscope/tts/_voice_cloning_client_base.py@@ -0,0 +1,55 @@+# -*- coding: utf-8 -*-+"""Common interface for provider-specific voice creation clients."""+from abc import ABC, abstractmethod++from pydantic import BaseModel, ConfigDict++from ..credential import CredentialBase+++class VoiceCloningClientBase(ABC):+ """Create a voice independently of speech synthesis and App storage.++ Providers declare their creation options in ``Parameters``. The common+ method returns a provider voice ID and raises ``ValueError`` for invalid+ input or ``VoiceCloningError`` for provider failures. Consent management+ is a provider-specific capability, not a requirement of this interface.+ """++ class Parameters(BaseModel):+ """Provider-specific options for one voice creation request."""++ model_config = ConfigDict(extra="forbid")++ def __init__(self, credential: CredentialBase) -> None:+ """Bind the credential used for voice creation."""+ self.credential = credential++ @classmethod+ # pylint: disable-next=unused-argument+ def get_enrollment_model(cls, model: str) -> str | None:+ """Return the separate enrollment model, if the provider uses one."""+ return None++ @abstractmethod+ async def create_voice(+ self,+ audio: bytes | None = None,+ *,+ filename: str = "voice.wav",+ audio_url: str | None = None,+ parameters: BaseModel | None = None,+ ) -> str:+ """Create a voice from one audio source and return its provider ID.++ Args:+ audio: Encoded audio bytes, if uploads are supported.+ filename: Filename used to determine the uploaded audio format.+ audio_url: Public audio URL, if supported. Mutually exclusive+ with ``audio``; implementations validate supported inputs.+ parameters: An instance of the client's ``Parameters`` model.+ When omitted, provider parameter defaults are validated.++ Returns:+ The provider's voice ID for use with a compatible TTS model.+ """diff --git a/src/agentscope/tts/_voice_utils.py b/src/agentscope/tts/_voice_utils.pynew file mode 100644index 000000000..7f7269c9d--- /dev/null+++ b/src/agentscope/tts/_voice_utils.py@@ -0,0 +1,54 @@+# -*- coding: utf-8 -*-+"""Shared transport and validation for voice creation clients."""+from typing import Any+import mimetypes++import httpx+++class VoiceCloningError(RuntimeError):+ """A voice creation provider failed or returned an invalid response."""+++def _audio_file(filename: str, audio: bytes) -> tuple[str, bytes, str]:+ """Validate an audio upload and infer its MIME type from the filename."""+ if not audio:+ raise ValueError("audio must not be empty")+ if not filename:+ raise ValueError("filename must not be empty")+ mime_type, _ = mimetypes.guess_type(filename)+ return filename, audio, mime_type or "audio/wav"+++async def _post_voice_request(+ url: str,+ *,+ provider: str,+ operation: str,+ success_codes: tuple[int, ...] = (200,),+ **kwargs: Any,+) -> dict:+ """Send one creation request without retrying non-idempotent operations."""+ try:+ async with httpx.AsyncClient(timeout=60.0) as client:+ response = await client.post(url, **kwargs)+ except httpx.HTTPError as exc:+ raise VoiceCloningError(+ f"Network error calling {provider}: {exc}",+ ) from exc+ if response.status_code not in success_codes:+ raise VoiceCloningError(+ f"{provider} {operation} failed "+ f"({response.status_code}): {response.text[:500]}",+ )+ try:+ result = response.json()+ except ValueError as exc:+ raise VoiceCloningError(+ f"{provider} returned an invalid JSON response.",+ ) from exc+ if not isinstance(result, dict):+ raise VoiceCloningError(+ f"{provider} returned an invalid JSON response.",+ )+ return resultdiff --git a/tests/service_chat_run_context_test.py b/tests/service_chat_run_context_test.pyindex cc82b02ca..0eb4f59a6 100644--- a/tests/service_chat_run_context_test.py+++ b/tests/service_chat_run_context_test.py@@ -5,7 +5,7 @@from types import SimpleNamespacefrom typing import AsyncGeneratorfrom unittest import IsolatedAsyncioTestCase-from unittest.mock import patch+from unittest.mock import AsyncMock, patchfrom agentscope.agent import ContextConfig, ReActConfigfrom agentscope.app._service import ChatService@@ -18,7 +18,10 @@ from agentscope.app.storage import (SessionRecord,TeamData,TeamRecord,+ TTSModelConfig,)+from agentscope.middleware import TTSMiddleware+from agentscope.state import AgentStateclass _Storage:@@ -82,6 +85,14 @@ class TestRunContextResolution(IsolatedAsyncioTestCase):async def test_worker_run_fetches_team_once(self) -> None:"""One ``get_team`` read serves both consumers of the role."""+ await self._assert_worker_run(tts_available=True)++ async def test_missing_voice_profile_does_not_block_reply(self) -> None:+ """A missing profile skips TTS while the worker still replies."""+ await self._assert_worker_run(tts_available=False)++ async def _assert_worker_run(self, tts_available: bool) -> None:+ """Exercise assembly and reply with or without a usable TTS model."""user_id = "user-1"worker_agent = AgentRecord(id="agent-w",@@ -110,6 +121,13 @@ class TestRunContextResolution(IsolatedAsyncioTestCase):model="m",parameters={},),+ tts_model_config=TTSModelConfig(+ type="openai_credential",+ credential_id="cred-tts",+ model="gpt-4o-mini-tts",+ voice_profile_id="profile-1",+ parameters={"voice": "voice-custom"},+ ),)worker_session = SessionRecord(id="session-w",@@ -137,19 +155,29 @@ class TestRunContextResolution(IsolatedAsyncioTestCase):team=team,)equipped: list[list] = []+ replies: list[object] = []class _Agent:"""Capture the middlewares; reply without doing anything."""- def __init__(self, *, middlewares: list, **_: object) -> None:+ def __init__(+ self,+ *,+ middlewares: list,+ state: AgentState,+ name: str,+ **_: object,+ ) -> None:equipped.append(middlewares)+ self.state = state+ self.name = nameasync def reply_stream(self,inputs: object,) -> AsyncGenerator[object, None]:"""Yield nothing."""- del inputs+ replies.append(inputs)if False:yield object()@@ -184,7 +212,17 @@ class TestRunContextResolution(IsolatedAsyncioTestCase):new=_get_toolkit,),patch("agentscope.app._service._chat.get_model", new=_get_model),+ patch(+ "agentscope.app._service._chat.get_tts_model",+ autospec=True,+ ) as get_tts_model,+ patch(+ "agentscope.app._service._chat.publish_session_event",+ new_callable=AsyncMock,+ ) as publish,):+ if not tts_available:+ get_tts_model.return_value = Noneawait service._run_impl(user_id,worker_session.id,@@ -192,11 +230,48 @@ class TestRunContextResolution(IsolatedAsyncioTestCase):None,)+ failures = [+ call.args[2]+ for call in publish.await_args_list+ if call.args[2].get("name") == "tts_error"+ ]+ self.assertEqual(+ [+ {"name": item["name"], "value": item["value"]}+ for item in failures+ ],+ []+ if tts_available+ else [+ {+ "name": "tts_error",+ "value": {"stage": "configuration"},+ },+ ],+ )+ for middlewares in equipped:+ for middleware in middlewares:+ if isinstance(middleware, TTSMiddleware):+ self.assertTrue(middleware.continue_on_error)++ get_tts_model.assert_awaited_once_with(+ user_id,+ config.tts_model_config,+ service._access,+ storage,+ )self.assertDictEqual({"get_team_calls": storage.get_team_calls,"team_role": toolkit_kwargs["team_role"],"channel_tools": toolkit_kwargs["channel_tools"],+ "replies": replies,+ "tts_models": [+ mw.tts+ for mws in equipped+ for mw in mws+ if isinstance(mw, TTSMiddleware)+ ],"leader_names": [mw._leader_namefor mws in equipped@@ -208,6 +283,10 @@ class TestRunContextResolution(IsolatedAsyncioTestCase):"get_team_calls": 1,"team_role": "worker","channel_tools": [],+ "replies": [None],+ "tts_models": (+ [get_tts_model.return_value] if tts_available else []+ ),"leader_names": ["Leader"],},)diff --git a/tests/session_config_patch_test.py b/tests/session_config_patch_test.pyindex e2d8f9d49..cd7b8566e 100644--- a/tests/session_config_patch_test.py+++ b/tests/session_config_patch_test.py@@ -26,8 +26,11 @@ from agentscope.app.storage import (AgentRecord,RealtimeModelConfig,RedisStorage,+ VoiceProfileData,+ VoiceProfileRecord,)from agentscope.app.workspace_manager import LocalWorkspaceManager+from agentscope.credential import OpenAICredentialfrom agentscope.permission import PermissionModefrom agentscope.message import UserMsgfrom agentscope.state import Task@@ -208,6 +211,67 @@ class SessionConfigPatchTest(IsolatedAsyncioTestCase):},)+ async def test_voice_profile_and_realtime_configs_coexist(self) -> None:+ """Create and update keep both voice configs and validate ownership."""+ credential_id = await self.storage.upsert_credential(+ "alice",+ OpenAICredential(api_key="test-key"),+ )+ profile_id = await self.storage.upsert_voice_profile(+ "alice",+ VoiceProfileRecord(+ user_id="alice",+ data=VoiceProfileData(+ name="Custom voice",+ engine="openai_tts",+ credential_id=credential_id,+ model="gpt-4o-mini-tts",+ voice="voice-custom",+ ),+ ),+ )+ configs = {+ "tts_model_config": {+ "type": "openai_credential",+ "credential_id": credential_id,+ "model": "gpt-4o-mini-tts",+ "voice_profile_id": profile_id,+ "parameters": {"voice": "voice-custom"},+ },+ "realtime_model_config": {+ "type": "openai_realtime",+ "credential_id": credential_id,+ "model": "gpt-realtime",+ "parameters": {},+ },+ }+ for operation in ("create", "update"):+ with self.subTest(operation=operation):+ if operation == "create":+ response = self.client.post(+ "/sessions/",+ headers=HEADERS,+ json={"agent_id": self.agent_id, **configs},+ )+ self.assertEqual(response.status_code, 201)+ session_id = response.json()["session_id"]+ else:+ response = self._patch(configs)+ self.assertEqual(response.status_code, 200)+ session_id = self.session_id+ record = await self.storage.get_session(+ "alice",+ self.agent_id,+ session_id,+ )+ self.assertEqual(+ {+ key: getattr(record.config, key).model_dump()+ for key in configs+ },+ configs,+ )+def test_permission_mode_patch_writes_only_that_field(self) -> None:"""``permission_mode`` is the one field that must carry state."""response = self._patch({"permission_mode": "accept_edits"})diff --git a/tests/storage_redis_test.py b/tests/storage_redis_test.pyindex 536e7eb06..4816da654 100644--- a/tests/storage_redis_test.py+++ b/tests/storage_redis_test.py@@ -2,6 +2,7 @@# pylint: disable=protected-access"""Unit tests for RedisStorage using fakeredis."""+from datetime import datetime as DateTimefrom unittest.async_case import IsolatedAsyncioTestCasefrom unittest.mock import patch@@ -11,6 +12,8 @@ from utils import AnyStringfrom agentscope.app.storage import (RedisStorage,+ VoiceProfileData,+ VoiceProfileRecord,AgentRecord,SessionConfig,SessionRecord,@@ -2080,3 +2083,28 @@ class TestSOP(IsolatedAsyncioTestCase):"call_id": "c1",},)+++class TestVoiceProfileTimestamps(IsolatedAsyncioTestCase):+ """Voice profile writes refresh timestamps in Redis as in SQL."""++ async def test_upsert_refreshes_updated_at(self) -> None:+ """Insert and update refresh the stored record's modification time."""+ storage = make_storage()+ self.addAsyncCleanup(storage._client.aclose)+ record = VoiceProfileRecord(+ user_id="owner",+ data=VoiceProfileData(name="Voice"),+ )+ created_at = record.created_at+ for moment in (DateTime(2026, 1, 1), DateTime(2026, 1, 2)):+ with self.subTest(moment=moment):+ with patch(+ "agentscope.app.storage._redis_storage.datetime",+ ) as clock:+ clock.now.return_value = moment+ await storage.upsert_voice_profile("owner", record)+ self.assertEqual(record.updated_at, moment)+ self.assertEqual(record.created_at, created_at)+ stored = await storage.get_voice_profile("owner", record.id)+ self.assertEqual(stored.model_dump(), record.model_dump())diff --git a/tests/storage_sql_test.py b/tests/storage_sql_test.pyindex 3b9d2b6a5..bdee1a6f1 100644--- a/tests/storage_sql_test.py+++ b/tests/storage_sql_test.py@@ -1,5 +1,5 @@# -*- coding: utf-8 -*--# pylint: disable=too-many-public-methods+# pylint: disable=too-many-public-methods,protected-access"""Round-trip and semantic tests for :class:`AsyncSQLAlchemyStorage`.Runs against an in-memory SQLite database via ``sqlite+aiosqlite``@@ -9,18 +9,31 @@ backend implements, mirroring the shape (though not always theliteral assertions) of the Redis backend's tests so both backendsstay behavioural equivalents."""+import asynciofrom contextlib import AsyncExitStackfrom datetime import datetime, timedelta, timezonefrom importlib import import_module+from os import environ+from pathlib import Path+from tempfile import TemporaryDirectory+from typing import Anyfrom unittest import TestCasefrom unittest.async_case import IsolatedAsyncioTestCase+from unittest.mock import patch+from alembic import command+from alembic.config import Configfrom pydantic import SecretStr+import sqlalchemy as safrom sqlalchemy.dialects import mysql+from sqlalchemy.engine import URL+from sqlalchemy.ext.asyncio import AsyncSession+from sqlalchemy.sql.dml import Insertfrom utils import AnyStringfrom agentscope.app.storage._sql._mappers import _to_record+from agentscope.app.storage._sql import _storage as sql_storagefrom agentscope.app.storage._sql._tables import AgentRow, SessionRowfrom agentscope.app.storage import (AgentData,@@ -55,6 +68,8 @@ from agentscope.app.storage import (TeamData,TeamMember,TeamRecord,+ VoiceProfileData,+ VoiceProfileRecord,)from agentscope.app.storage._sql._tables import ChannelRowfrom agentscope.agent import ContextConfig, ReActConfig@@ -1923,3 +1938,294 @@ class ChannelSessionLookupTest(IsolatedAsyncioTestCase):chat_name="产品群",),)+++class VoiceProfileSQLTest(IsolatedAsyncioTestCase):+ """Migration-only CRUD and ownership guarantees on a real database."""++ async def asyncSetUp(self) -> None:+ """Use a file database shared by Alembic and concurrent sessions."""+ directory = TemporaryDirectory(prefix="agentscope-voice-%sql-")+ self.addCleanup(directory.cleanup)+ self.url = URL.create(+ "sqlite+aiosqlite",+ database=str(Path(directory.name) / "voice.db"),+ ).render_as_string(hide_password=False)+ alembic_dir = Path(sql_storage.__file__).parent / "_alembic"+ self.config = Config(str(alembic_dir / "alembic.ini"))+ self.config.set_main_option("script_location", str(alembic_dir))+ self.config.set_main_option(+ "sqlalchemy.url",+ self.url.replace("%", "%%"),+ )++ async def test_migrations_accept_url_from_environment(self) -> None:+ """Environment URLs with percent signs reach the intended database."""+ self.config.set_main_option("sqlalchemy.url", "")+ with patch.dict(environ, {"AGENTSCOPE_SQL_URL": self.url}):+ await asyncio.to_thread(command.upgrade, self.config, "head")+ self.assertEqual(+ self.config.get_main_option("sqlalchemy.url"),+ self.url,+ )+ async with AsyncSQLAlchemyStorage(+ self.url,+ create_tables=False,+ ) as storage:+ record = VoiceProfileRecord(+ user_id="owner",+ data=VoiceProfileData(name="Environment URL voice"),+ )+ await storage.upsert_voice_profile("owner", record)+ self.assertEqual(+ (+ await storage.get_voice_profile("owner", record.id)+ ).model_dump(),+ record.model_dump(),+ )++ async def test_migrations_alone_support_voice_profile_crud(self) -> None:+ """The migration supplies the entire table, indexes and CRUD path."""+ async with AsyncSQLAlchemyStorage(+ self.url,+ auto_migrate=True,+ create_tables=False,+ ) as storage:+ async with storage._engine.connect() as connection:+ indexes = await connection.run_sync(+ lambda conn: sa.inspect(conn).get_indexes(+ "voice_profiles",+ ),+ )+ self.assertEqual(+ {item["name"]: item["column_names"] for item in indexes},+ {+ "ix_voice_profiles_created_at": ["created_at"],+ "ix_voice_profiles_updated_at": ["updated_at"],+ "ix_voice_profiles_user_id": ["user_id"],+ },+ )+ record = VoiceProfileRecord(+ user_id="owner",+ data=VoiceProfileData(name="Voice"),+ )+ self.assertEqual(+ await storage.upsert_voice_profile("owner", record),+ record.id,+ )+ self.assertEqual(+ (+ await storage.get_voice_profile("owner", record.id)+ ).model_dump(),+ record.model_dump(),+ )+ self.assertEqual(+ [+ item.model_dump()+ for item in await storage.list_voice_profiles("owner")+ ],+ [record.model_dump()],+ )+ self.assertIsNone(+ await storage.get_voice_profile("other", record.id),+ )+ self.assertEqual(await storage.list_voice_profiles("other"), [])+ self.assertFalse(+ await storage.delete_voice_profile("other", record.id),+ )+ original_created = record.created_at+ record.data.name = "Updated voice"+ record.created_at = datetime(2000, 1, 1)+ await storage.upsert_voice_profile("owner", record)+ self.assertEqual(record.created_at, original_created)+ self.assertEqual(+ (+ await storage.get_voice_profile("owner", record.id)+ ).model_dump(),+ record.model_dump(),+ )+ with self.assertRaises(PermissionError):+ await storage.upsert_voice_profile(+ "other",+ VoiceProfileRecord(+ id=record.id,+ user_id="other",+ data=VoiceProfileData(name="Not the owner"),+ ),+ )+ self.assertEqual(+ (+ await storage.get_voice_profile("owner", record.id)+ ).model_dump(),+ record.model_dump(),+ )+ self.assertTrue(+ await storage.delete_voice_profile("owner", record.id),+ )+ self.assertFalse(+ await storage.delete_voice_profile("owner", record.id),+ )+ self.assertEqual(await storage.list_voice_profiles("owner"), [])++ async def test_upgrade_from_0004_and_downgrade(self) -> None:+ """Upgrade an existing schema without touching its stored records."""+ await asyncio.to_thread(command.upgrade, self.config, "0004_sops")+ async with AsyncSQLAlchemyStorage(+ self.url,+ create_tables=False,+ ) as storage:+ agent = _agent_record("owner")+ await storage.upsert_agent("owner", agent)+ before = agent.model_dump()+ async with AsyncSQLAlchemyStorage(+ self.url,+ auto_migrate=True,+ create_tables=False,+ ) as storage:+ profile = VoiceProfileRecord(+ user_id="owner",+ data=VoiceProfileData(name="Migrated voice"),+ )+ await storage.upsert_voice_profile("owner", profile)+ self.assertEqual(+ (+ await storage.get_voice_profile("owner", profile.id)+ ).model_dump(),+ profile.model_dump(),+ )+ self.assertEqual(+ (await storage.get_agent("owner", agent.id)).model_dump(),+ before,+ )+ await asyncio.to_thread(command.downgrade, self.config, "0004_sops")+ async with AsyncSQLAlchemyStorage(+ self.url,+ create_tables=False,+ ) as storage:+ async with storage._engine.connect() as connection:+ exists = await connection.run_sync(+ lambda conn: sa.inspect(conn).has_table("voice_profiles"),+ )+ self.assertFalse(exists)+ self.assertEqual(+ (await storage.get_agent("owner", agent.id)).model_dump(),+ before,+ )++ async def test_concurrent_voice_profile_id_collision(self) -> None:+ """Two completed prechecks cannot authorize an ownership overwrite."""+ async with AsyncSQLAlchemyStorage(self.url) as storage:+ for same_owner in (False, True):+ with self.subTest(same_owner=same_owner):+ await self._assert_concurrent_collision(+ storage,+ same_owner,+ )++ async def _assert_concurrent_collision(+ self,+ storage: AsyncSQLAlchemyStorage,+ same_owner: bool,+ ) -> None:+ """Control insert ordering and verify the winning record in full."""+ records = [+ VoiceProfileRecord(+ id="contested-profile",+ user_id=owner,+ data=VoiceProfileData(name=name),+ )+ for owner, name in (+ ("owner-a", "First writer"),+ (+ "owner-a" if same_owner else "owner-b",+ "Second writer",+ ),+ )+ ]+ ready = asyncio.Event()+ first_done = asyncio.Event()+ arrivals = 0+ execute = AsyncSession.execute++ async def gated_execute(+ session: AsyncSession,+ statement: Any,+ *args: Any,+ **kwargs: Any,+ ) -> Any:+ """Hold both INSERTs until any prechecks have passed."""+ nonlocal arrivals+ if (+ isinstance(statement, Insert)+ and statement.table.name == "voice_profiles"+ ):+ arrivals += 1+ if arrivals == 2:+ ready.set()+ await ready.wait()+ if asyncio.current_task().get_name() == "second":+ await first_done.wait()+ return await execute(+ session,+ statement,+ *args,+ **kwargs,+ )++ async def write(index: int) -> str:+ """Commit the first writer before releasing the next."""+ try:+ record = records[index]+ return await storage.upsert_voice_profile(+ record.user_id,+ record,+ )+ finally:+ if index == 0:+ first_done.set()++ with patch.object(+ AsyncSession,+ "execute",+ new=gated_execute,+ ):+ results = await asyncio.wait_for(+ asyncio.gather(+ asyncio.create_task(write(0), name="first"),+ asyncio.create_task(write(1), name="second"),+ return_exceptions=True,+ ),+ timeout=10,+ )+ self.assertEqual(results[0], "contested-profile")+ if same_owner:+ self.assertEqual(results, ["contested-profile"] * 2)+ self.assertEqual(+ records[1].created_at,+ records[0].created_at,+ )+ expected = records[1]+ else:+ self.assertIsInstance(results[1], PermissionError)+ self.assertEqual(+ str(results[1]),+ "Cannot overwrite another user's voice profile.",+ )+ expected = records[0]+ self.assertEqual(+ [+ item.model_dump()+ for item in await storage.list_voice_profiles(+ "owner-a",+ )+ ],+ [expected.model_dump()],+ )+ self.assertEqual(+ await storage.list_voice_profiles("owner-b"),+ [],+ )+ await storage.delete_voice_profile(+ "owner-a",+ "contested-profile",+ )diff --git a/tests/tts_dashscope_test.py b/tests/tts_dashscope_test.pyindex 783af6679..83120939d 100644--- a/tests/tts_dashscope_test.py+++ b/tests/tts_dashscope_test.py@@ -20,14 +20,20 @@ import ioimport wavefrom typing import Any, AsyncGeneratorfrom unittest import IsolatedAsyncioTestCase-from unittest.mock import MagicMock, Mock, patch+from unittest.mock import AsyncMock, MagicMock, Mock, patch++import dashscope+import httpx+from dashscope.audio.tts_v2 import AudioFormatfrom utils import AnyString, AnyValuefrom agentscope.app._service._tts_model import _resolve_tts_class-from agentscope.credential import DashScopeCredential+from agentscope.credential import CredentialFactory, DashScopeCredential+from agentscope.app.storage._utils import _dump_with_secretsfrom agentscope.tts import (DashScopeCosyVoiceTTSModel,+ DashScopeVoiceCloningClient,DashScopeTTSModel,DashScopeRealtimeTTSModel,TTSModelBase,@@ -210,6 +216,175 @@ def _parse_wav_payload(wav_bytes: bytes) -> bytes:return wav.readframes(wav.getnframes())+class TestQwenCloneEndpoints(IsolatedAsyncioTestCase):+ """Verify Qwen enrollment and real SDK request routing together."""++ async def test_implicit_endpoint_survives_serialization(self) -> None:+ """Implicit defaults follow SDK settings across serialization."""+ parameters_cls = DashScopeTTSModel.Parameters+ for global_url in (+ "https://dashscope-intl.aliyuncs.com/api/v1",+ "https://gateway.example.com/tenant/custom-api",+ ):+ with (+ patch.object(dashscope, "base_http_api_url", global_url),+ patch(+ "agentscope.tts._dashscope._voice_cloning_client."+ "_post_voice_request",+ new_callable=AsyncMock,+ return_value={"output": {"voice": "cloned-voice"}},+ ) as post,+ patch(+ "dashscope.api_entities.api_request_factory.HttpRequest",+ ) as request,+ ):+ for explicit in (False, True):+ options = {"api_key": "test"}+ if explicit:+ options[+ "base_url"+ ] = "https://dashscope.aliyuncs.com/compatible-mode/v1"+ credential = DashScopeCredential(**options)+ base_url = (+ "https://dashscope.aliyuncs.com/api/v1"+ if explicit+ else global_url+ )+ versions = (+ credential,+ CredentialFactory.from_dict(credential.model_dump()),+ CredentialFactory.from_dict(+ _dump_with_secrets(credential),+ ),+ DashScopeCredential.model_validate_json(+ credential.model_dump_json(),+ ),+ )+ for index, restored in enumerate(versions):+ for stream in (False, True):+ with self.subTest(+ explicit=explicit,+ index=index,+ stream=stream,+ ):+ self.assertEqual(+ "base_url" in restored.model_fields_set,+ explicit,+ )+ client = DashScopeVoiceCloningClient(restored)+ voice = await client.create_voice(+ audio=b"sample",+ parameters=client.Parameters(+ target_model="qwen3-tts-flash",+ ),+ )+ self.assertEqual(+ post.call_args.args,+ (+ base_url+ + "/services/audio/tts/customization",+ ),+ )+ for selected_voice in ("Cherry", voice):+ call = request.return_value.call+ call.return_value = iter(())+ model = DashScopeTTSModel(+ credential=restored,+ parameters=parameters_cls(+ voice=selected_voice,+ ),+ stream=stream,+ )+ result = await model.synthesize("Hello")+ if stream:+ _ = [chunk async for chunk in result]+ self.assertEqual(+ request.call_args.kwargs["url"],+ base_url + "/services/aigc/"+ "multimodal-generation/generation",+ )+ self.assertEqual(+ dashscope.base_http_api_url,+ global_url,+ )++ async def test_clone_and_synthesis_use_credential_region(self) -> None:+ """Interleaved credentials keep their routes in both output modes."""+ origins = (+ "https://dashscope-intl.aliyuncs.com",+ "https://dashscope.aliyuncs.com",+ "https://workspace.cn-beijing.maas.aliyuncs.com",+ "http://localhost:8080/gateway",+ )+ global_url = "https://global.invalid/api/v1"+ with (+ patch.object(dashscope, "base_http_api_url", global_url),+ patch(+ "agentscope.tts._dashscope._voice_cloning_client."+ "_post_voice_request",+ new_callable=AsyncMock,+ return_value={"output": {"voice": "cloned-voice"}},+ ) as post,+ patch(+ "dashscope.api_entities.api_request_factory.HttpRequest",+ ) as request,+ ):+ for stream in (False, True):+ for suffix in ("/compatible-mode/v1/", "/api/v1", "/"):+ models = []+ for origin in origins:+ credential = DashScopeCredential(+ api_key="test",+ base_url=origin + suffix,+ )+ client = DashScopeVoiceCloningClient(credential)+ voice = await client.create_voice(+ audio=b"sample",+ parameters=client.Parameters(+ target_model="qwen3-tts-flash",+ ),+ )+ self.assertEqual(+ post.call_args.args,+ (+ origin+ + "/api/v1/services/audio/tts/customization",+ ),+ )+ models.append(+ DashScopeTTSModel(+ credential=credential,+ parameters=DashScopeTTSModel.Parameters(+ voice=voice,+ ),+ stream=stream,+ ),+ )+ for index in (0, 1, 2, 3, 0):+ with self.subTest(+ stream=stream,+ suffix=suffix,+ index=index,+ ):+ request.return_value.call.return_value = iter(())+ result = await models[index].synthesize("Hello")+ if stream:+ _ = [chunk async for chunk in result]+ self.assertEqual(+ (+ request.call_args.kwargs["url"],+ request.call_args.kwargs["api_key"],+ dashscope.base_http_api_url,+ ),+ (+ origins[index] + "/api/v1/services/aigc/"+ "multimodal-generation/generation",+ "test",+ global_url,+ ),+ )++class TestDashScopeTTSModel(IsolatedAsyncioTestCase):"""The unittests for DashScope TTS model (non-realtime)."""@@ -295,6 +470,9 @@ class TestDashScopeTTSModel(IsolatedAsyncioTestCase):"api_key": "test","text": "Hello","voice": expected,+ "base_address": (+ "https://dashscope.aliyuncs.com/api/v1"+ ),"stream": True,},)@@ -331,6 +509,7 @@ class TestDashScopeTTSModel(IsolatedAsyncioTestCase):language_type="English",api_key="ignored",stream=False,+ base_address="https://override.invalid/api/v1",)responses = ([chunk async for chunk in result] if stream else [result]@@ -343,6 +522,7 @@ class TestDashScopeTTSModel(IsolatedAsyncioTestCase):"text": "Hello","voice": "Serena","language_type": "English",+ "base_address": "https://override.invalid/api/v1","stream": True,},)@@ -1658,3 +1838,257 @@ class TestDashScopeCosyVoiceRealtimeMode(self.mock_synthesizer.close.assert_called_once()self.assertTrue(model._connected)self.assertIsNot(model._callback, old_callback)+++class TestDashScopeVoiceEndpoints(IsolatedAsyncioTestCase):+ """Exercise the public clone-to-synthesis flow without network calls."""++ def setUp(self) -> None:+ """Mock provider I/O while keeping real model and callback code."""+ transport = patch("agentscope.tts._voice_utils.httpx.AsyncClient")+ client = transport.start()+ self.addCleanup(transport.stop)+ self.post = AsyncMock(+ return_value=httpx.Response(+ 200,+ json={"output": {"voice_id": "cloned-voice"}},+ ),+ )+ client.return_value.__aenter__.return_value.post = self.post+ synth = patch(+ "dashscope.audio.tts_v2.SpeechSynthesizer",+ side_effect=self._make_synthesizer,+ )+ self.synth_factory = synth.start()+ self.addCleanup(synth.stop)+ for name, value in (+ ("api_key", "test"),+ ("base_websocket_api_url", "wss://global.invalid/inference"),+ ):+ setting = patch.object(dashscope, name, value)+ setting.start()+ self.addCleanup(setting.stop)++ @staticmethod+ def _make_synthesizer(**kwargs: Any) -> Mock:+ """Simulate audio completion for batch, streaming and realtime."""+ synth = Mock()+ callback = kwargs["callback"]+ if callback is None:+ synth.call.return_value = b"\x00\x00"+ else:++ def complete(**_kwargs: Any) -> None:+ """Produce PCM and signal a completed synthesis request."""+ callback.on_data(b"\x00\x00")+ callback.on_complete()++ synth.call.side_effect = complete+ synth.streaming_complete.side_effect = complete+ return synth++ async def _assert_clone_to_synthesis(+ self,+ base_url: str,+ clone_url: str,+ synthesis_url: str | None,+ *,+ name: str = "cosyvoice-v3-plus",+ stream: bool = False,+ realtime: bool = False,+ ) -> None:+ """Clone a voice and verify the synthesis request uses its endpoint."""+ self.post.reset_mock()+ self.synth_factory.reset_mock()+ credential = DashScopeCredential(api_key="test", base_url=base_url)+ client = DashScopeVoiceCloningClient(credential)+ voice = await client.create_voice(+ audio=b"sample" if name.startswith("qwen") else None,+ audio_url="https://example.com/sample.mp3"+ if name.startswith("cosyvoice")+ else None,+ parameters=client.Parameters(target_model=name),+ )+ model = DashScopeCosyVoiceTTSModel(+ credential=credential,+ model=name,+ parameters=DashScopeCosyVoiceTTSModel.Parameters(+ voice=voice,+ realtime=realtime,+ ),+ stream=stream,+ )+ async with model:+ result = await model.synthesize("Hello")+ chunks = [chunk async for chunk in result] if stream else [result]+ self.assertTrue(chunks[-1].is_last)+ self.assertIsNotNone(chunks[0].content)+ callback = self.synth_factory.call_args.kwargs["callback"]+ self.synth_factory.assert_called_once_with(+ model=name,+ voice="cloned-voice",+ format=AudioFormat.PCM_24000HZ_MONO_16BIT,+ callback=callback,+ **({"url": synthesis_url} if synthesis_url else {}),+ )+ self.post.assert_awaited_once()+ self.assertEqual(self.post.call_args.args, (clone_url,))+ self.assertEqual(+ dashscope.base_websocket_api_url,+ "wss://global.invalid/inference",+ )++ async def test_clone_and_synthesis_share_credential_endpoint(self) -> None:+ """Verify regional hosts and API suffixes without crossing modes."""+ origins = (+ (+ "https://dashscope.aliyuncs.com",+ "wss://dashscope.aliyuncs.com",+ ),+ (+ "https://dashscope-intl.aliyuncs.com",+ "wss://dashscope-intl.aliyuncs.com",+ ),+ (+ "https://workspace.ap-southeast-1.maas.aliyuncs.com",+ "wss://workspace.ap-southeast-1.maas.aliyuncs.com",+ ),+ (+ "https://proxy.example.test:8443/gateway/dashscope",+ "wss://proxy.example.test:8443/gateway/dashscope",+ ),+ (+ "http://localhost:8080/dashscope",+ "ws://localhost:8080/dashscope",+ ),+ )+ for http_origin, ws_origin in origins:+ for suffix in ("/", "/compatible-mode/v1/", "/api/v1/"):+ with self.subTest(origin=http_origin, suffix=suffix):+ legacy_default = (+ http_origin == "https://dashscope.aliyuncs.com"+ and suffix == "/compatible-mode/v1/"+ ) or (+ http_origin.startswith(+ ("https://proxy.", "http://localhost"),+ )+ and suffix == "/"+ )+ await self._assert_clone_to_synthesis(+ http_origin + suffix,+ http_origin+ + "/api/v1/services/audio/tts/customization",+ None+ if legacy_default+ else ws_origin + "/api-ws/v1/inference",+ )++ async def test_all_synthesis_modes_use_cloned_voice_endpoint(self) -> None:+ """Both model families honor the endpoint in all synthesis modes."""+ for name in ("cosyvoice-v3-plus", "qwen-audio-3.1-tts-flash"):+ for stream, realtime in (+ (False, False),+ (True, False),+ (False, True),+ (True, True),+ ):+ with self.subTest(name=name, stream=stream, realtime=realtime):+ await self._assert_clone_to_synthesis(+ "https://dashscope-intl.aliyuncs.com"+ "/compatible-mode/v1",+ "https://dashscope-intl.aliyuncs.com/api/v1/services/"+ "audio/tts/customization",+ "wss://dashscope-intl.aliyuncs.com"+ "/api-ws/v1/inference",+ name=name,+ stream=stream,+ realtime=realtime,+ )++ async def test_interleaved_reconnect_keeps_instance_endpoint(self) -> None:+ """Connecting another credential cannot redirect a reconnect."""+ models = [+ DashScopeCosyVoiceTTSModel(+ credential=DashScopeCredential(+ api_key="test",+ base_url=base_url,+ ),+ parameters=DashScopeCosyVoiceTTSModel.Parameters(+ realtime=True,+ ),+ )+ for base_url in (+ "https://dashscope-intl.aliyuncs.com/compatible-mode/v1",+ "https://dashscope.aliyuncs.com/api/v1",+ )+ ]+ try:+ await models[0].connect()+ await models[1].connect()+ await models[0]._reconnect()+ self.assertEqual(+ [+ call.kwargs.get("url")+ for call in self.synth_factory.call_args_list+ ],+ [+ "wss://dashscope-intl.aliyuncs.com/api-ws/v1/inference",+ "wss://dashscope.aliyuncs.com/api-ws/v1/inference",+ "wss://dashscope-intl.aliyuncs.com/api-ws/v1/inference",+ ],+ )+ self.assertEqual(+ dashscope.base_websocket_api_url,+ "wss://global.invalid/inference",+ )+ finally:+ for model in models:+ await model.close()++ async def test_query_parameters_are_preserved_on_both_endpoints(+ self,+ ) -> None:+ """Proxy routing parameters survive API path and scheme conversion."""+ await self._assert_clone_to_synthesis(+ "https://proxy.example.test/tts/compatible-mode/v1/"+ "?tenant=demo#ignored",+ "https://proxy.example.test/tts/api/v1/services/audio/tts/"+ "customization?tenant=demo",+ "wss://proxy.example.test/tts/api-ws/v1/inference?tenant=demo",+ )++ async def test_explicit_gateway_websocket_overrides_inference(+ self,+ ) -> None:+ """An arbitrary gateway route can explicitly choose its WS service."""+ credential = DashScopeCredential(+ api_key="test",+ base_url="https://gateway.test/custom/http",+ websocket_url="wss://speech.gateway.test/custom/socket?tenant=1",+ )+ model = DashScopeCosyVoiceTTSModel(credential, stream=False)+ async with model:+ await model.synthesize("Hello")+ self.assertEqual(+ self.synth_factory.call_args.kwargs["url"],+ credential.websocket_url,+ )++ async def test_default_and_arbitrary_gateway_preserve_sdk_settings(+ self,+ ) -> None:+ """Existing global WebSocket overrides remain effective by default."""+ for base in (+ "https://dashscope.aliyuncs.com/compatible-mode/v1",+ "https://gateway.test/custom/http",+ ):+ with self.subTest(base=base):+ credential = DashScopeCredential(api_key="test", base_url=base)+ model = DashScopeCosyVoiceTTSModel(credential, stream=False)+ async with model:+ await model.synthesize("Hello")+ self.assertNotIn("url", self.synth_factory.call_args.kwargs)+ self.assertEqual(+ dashscope.base_websocket_api_url,+ "wss://global.invalid/inference",+ )diff --git a/tests/tts_middleware_test.py b/tests/tts_middleware_test.pyindex a4dd54daa..bc355e49a 100644--- a/tests/tts_middleware_test.py+++ b/tests/tts_middleware_test.py@@ -1,5 +1,6 @@# -*- coding: utf-8 -*-"""Unit tests for TTSMiddleware."""+import asyncioimport base64from typing import Any, AsyncGeneratorfrom unittest import IsolatedAsyncioTestCase@@ -7,6 +8,7 @@ from unittest.mock import AsyncMock, MagicMockfrom agentscope import set_id_factoryfrom agentscope.event import (+ CustomEvent,DataBlockDeltaEvent,DataBlockEndEvent,DataBlockStartEvent,@@ -434,3 +436,299 @@ class TestTTSMiddlewareRealtime(IsolatedAsyncioTestCase):},],)+++class TestTTSFailureIsolation(IsolatedAsyncioTestCase):+ """TTS failures preserve text and never swallow upstream cancellation."""++ def setUp(self) -> None:+ self.tts = MagicMock(spec=TTSModelBase)+ self.tts.realtime = False+ self.tts.__aenter__ = AsyncMock(return_value=self.tts)+ self.tts.__aexit__ = AsyncMock(return_value=None)+ self.tts.synthesize = AsyncMock(return_value=None)+ self.tts.push = AsyncMock(return_value=None)+ self.events = [+ event+ for block in ("first", "second")+ for event in (+ TextBlockDeltaEvent(+ reply_id="reply-1",+ block_id=block,+ delta=block,+ ),+ TextBlockEndEvent(reply_id="reply-1", block_id=block),+ )+ ]++ async def _text(self, **_kwargs: Any) -> AsyncGenerator:+ for event in self.events:+ yield event++ async def _collect(self, continue_on_error: bool | None = True) -> list:+ options = (+ {}+ if continue_on_error is None+ else {"continue_on_error": continue_on_error}+ )+ return [+ event+ async for event in TTSMiddleware(self.tts, **options).on_reply(+ _make_agent_stub(),+ {},+ self._text,+ )+ ]++ async def test_init_push_synthesis_and_cleanup_failures_preserve_text(+ self,+ ) -> None:+ """A provider failure disables only speech for the current reply."""+ for operation in ("__aenter__", "push", "synthesize", "__aexit__"):+ with self.subTest(operation=operation):+ self.tts.realtime = operation == "push"+ failing = getattr(self.tts, operation)+ failing.side_effect = RuntimeError("provider unavailable")+ stage, position = {+ "__aenter__": ("initialization", 0),+ "push": ("synthesis", 1),+ "synthesize": ("synthesis", 2),+ "__aexit__": ("cleanup", len(self.events)),+ }[operation]+ expected = list(self.events)+ expected.insert(+ position,+ CustomEvent(+ name="tts_error",+ value={"reply_id": "reply-1", "stage": stage},+ ),+ )+ self.assertEqual(+ [_dump(event) for event in await self._collect()],+ [_dump(event) for event in expected],+ )+ failing.assert_awaited_once()+ failing.side_effect = None+ self.tts.reset_mock()++ async def test_stream_failure_closes_audio_block_and_continues_text(+ self,+ ) -> None:+ """Partially emitted audio is closed before the next text block."""++ async def audio() -> AsyncGenerator:+ yield _make_tts_response("AAAA")+ raise RuntimeError("stream disconnected")++ self.tts.synthesize.return_value = audio()+ result = await self._collect()+ self.assertEqual(+ [+ _dump(event)+ for event in result+ if isinstance(+ event,+ (TextBlockDeltaEvent, TextBlockEndEvent),+ )+ ],+ [_dump(event) for event in self.events],+ )+ block_id = result[2].block_id+ expected_audio = [+ DataBlockStartEvent(+ reply_id="reply-1",+ block_id=block_id,+ media_type="audio/wav",+ ),+ DataBlockDeltaEvent(+ reply_id="reply-1",+ block_id=block_id,+ media_type="audio/wav",+ data="AAAA",+ ),+ DataBlockEndEvent(reply_id="reply-1", block_id=block_id),+ ]+ self.assertEqual(+ [_dump(event) for event in result],+ [+ _dump(event)+ for event in self.events[:2]+ + expected_audio+ + [+ CustomEvent(+ name="tts_error",+ value={"reply_id": "reply-1", "stage": "synthesis"},+ ),+ ]+ + self.events[2:]+ ],+ )+ self.tts.synthesize.assert_awaited_once_with("first")+ self.tts.__aexit__.assert_awaited_once()++ async def test_upstream_errors_and_cancellation_propagate(self) -> None:+ """Text failures and cancellation bypass TTS exception handling."""+ for error in (+ RuntimeError("text model failed"),+ asyncio.CancelledError(),+ ):+ with self.subTest(error=type(error)):++ async def next_handler(+ failure: BaseException = error,+ **_kwargs: Any,+ ) -> AsyncGenerator:+ yield self.events[0]+ raise failure++ with self.assertRaises(type(error)):+ async for _ in TTSMiddleware(self.tts).on_reply(+ _make_agent_stub(),+ {},+ next_handler,+ ):+ pass+ self.tts.__aexit__.assert_awaited_once()+ self.tts.reset_mock()++ self.tts.synthesize.side_effect = asyncio.CancelledError()+ with self.assertRaises(asyncio.CancelledError):+ await self._collect()+ self.tts.__aexit__.assert_awaited_once()++ async def test_sdk_default_propagates_provider_failures(self) -> None:+ """Existing SDK callers retain exceptions unless they opt in."""+ for operation in ("__aenter__", "push", "synthesize", "__aexit__"):+ with self.subTest(operation=operation):+ self.tts.realtime = operation == "push"+ failing = getattr(self.tts, operation)+ error = RuntimeError("provider failure")+ failing.side_effect = error+ try:+ with self.assertRaises(RuntimeError) as ctx:+ await self._collect(continue_on_error=None)+ self.assertIs(ctx.exception, error)+ finally:+ failing.side_effect = None+ self.tts.reset_mock()++ async def test_consumer_athrow_propagates_and_closes_audio(self) -> None:+ """An exception injected at any audio yield is never a TTS failure."""+ for continue_on_error in (False, True):+ for target in (+ DataBlockStartEvent,+ DataBlockDeltaEvent,+ DataBlockEndEvent,+ ):+ with self.subTest(policy=continue_on_error, target=target):+ closed = asyncio.Event()++ async def audio(+ cleanup: asyncio.Event = closed,+ ) -> AsyncGenerator:+ try:+ yield _make_tts_response("AAAA")+ finally:+ cleanup.set()++ self.tts.synthesize.return_value = audio()+ stream = TTSMiddleware(+ self.tts,+ continue_on_error=continue_on_error,+ ).on_reply(_make_agent_stub(), {}, self._text)+ try:+ async for event in stream:+ if isinstance(event, target):+ error = RuntimeError("consumer failure")+ with self.assertRaises(RuntimeError) as ctx:+ await stream.athrow(error)+ self.assertIs(ctx.exception, error)+ break+ else:+ self.fail("Expected audio event was not emitted")+ self.assertTrue(closed.is_set())+ self.tts.__aexit__.assert_awaited_once()+ finally:+ await stream.aclose()+ self.tts.reset_mock()++ async def test_notification_consumer_error_and_close_propagate(+ self,+ ) -> None:+ """Failure notifications are safe to close or inject errors into."""+ self.tts.__aenter__.side_effect = RuntimeError("initialization failed")+ for close in (False, True):+ with self.subTest(close=close):+ stream = TTSMiddleware(+ self.tts,+ continue_on_error=True,+ ).on_reply(_make_agent_stub(), {}, self._text)+ event = await anext(stream)+ self.assertIsInstance(event, CustomEvent)+ if close:+ await stream.aclose()+ else:+ with self.assertRaisesRegex(RuntimeError, "consumer"):+ await stream.athrow(RuntimeError("consumer"))++ async def test_caller_except_does_not_hide_cleanup_failure(self) -> None:+ """A handled caller exception is not a propagating generator error."""+ for continue_on_error in (False, True):+ with self.subTest(continue_on_error=continue_on_error):+ cleanup_error = RuntimeError("cleanup failure")+ self.tts.__aexit__.side_effect = cleanup_error+ try:+ raise ValueError("already handled by caller")+ except ValueError:+ if continue_on_error:+ events = await self._collect(continue_on_error=True)+ self.assertEqual(+ [_dump(event) for event in events],+ [_dump(event) for event in self.events]+ + [+ _dump(+ CustomEvent(+ name="tts_error",+ value={+ "reply_id": "reply-1",+ "stage": "cleanup",+ },+ ),+ ),+ ],+ )+ else:+ with self.assertRaises(RuntimeError) as ctx:+ await self._collect(continue_on_error=None)+ self.assertIs(ctx.exception, cleanup_error)+ self.assertEqual(+ self.tts.__aexit__.call_args.args[-3:],+ (None, None, None),+ )+ self.tts.reset_mock()++ async def test_cleanup_keeps_actual_propagating_error(self) -> None:+ """Cleanup failure cannot replace text errors or cancellation."""+ self.tts.__aexit__.side_effect = RuntimeError("cleanup failure")+ for error in (ValueError("text failure"), asyncio.CancelledError()):+ with self.subTest(error=type(error)):++ async def upstream(+ failure: BaseException = error,+ **_kwargs: Any,+ ) -> AsyncGenerator:+ yield self.events[0]+ raise failure++ with self.assertRaises(type(error)) as ctx:+ async for _ in TTSMiddleware(self.tts).on_reply(+ _make_agent_stub(),+ {},+ upstream,+ ):+ pass+ self.assertIs(ctx.exception, error)+ exit_args = self.tts.__aexit__.call_args.args[-3:]+ self.assertEqual(exit_args[:2], (type(error), error))+ self.assertIsNotNone(exit_args[2])+ self.tts.reset_mock()diff --git a/tests/tts_openai_test.py b/tests/tts_openai_test.pyindex 3f8c3993a..16f346d93 100644--- a/tests/tts_openai_test.py+++ b/tests/tts_openai_test.py@@ -93,6 +93,88 @@ class TestOpenAITTSModel(IsolatedAsyncioTestCase):self.assertIsNone(result.content)mock_client.audio.speech.create.assert_not_called()+ async def test_preset_and_custom_voice_payloads(self) -> None:+ """Both output modes preserve named and custom voice API shapes."""+ for stream in (False, True):+ for voice in ("alloy", {"id": "voice_123"}):+ with self.subTest(stream=stream, voice=voice):+ model = OpenAITTSModel(+ credential=OpenAICredential(api_key="test"),+ model="gpt-4o-mini-tts",+ stream=stream,+ parameters=OpenAITTSModel.Parameters(voice=voice),+ )+ client = _make_mock_client(b"AAAA", [b"AAAA"])+ model.client = client+ result = await model.synthesize("Hello")+ if stream:+ async for _ in result:+ pass+ create = (+ client.audio.speech.with_streaming_response.create+ if stream+ else client.audio.speech.create+ )+ self.assertEqual(+ create.call_args.kwargs,+ {+ "model": "gpt-4o-mini-tts",+ "voice": voice,+ "input": "Hello",+ "response_format": "mp3",+ },+ )++ def test_custom_voice_model_cards(self) -> None:+ """Only the supported synthesis model advertises custom voices."""+ self.assertEqual(+ {c.name: c.voice_cloning for c in OpenAITTSModel.list_models()},+ {+ "tts-1": False,+ "tts-1-hd": False,+ "gpt-4o-mini-tts": True,+ },+ )++ def test_model_specific_preset_voices(self) -> None:+ """Legacy models expose fewer presets than GPT-4o mini TTS."""+ legacy_voices = [+ "alloy",+ "ash",+ "coral",+ "echo",+ "fable",+ "onyx",+ "nova",+ "sage",+ "shimmer",+ ]+ self.assertEqual(+ {+ card.name: card.parameter_schema["properties"]["voice"]["enum"]+ for card in OpenAITTSModel.list_models()+ },+ {+ "tts-1": legacy_voices,+ "tts-1-hd": legacy_voices,+ "gpt-4o-mini-tts": [+ "alloy",+ "ash",+ "ballad",+ "coral",+ "echo",+ "fable",+ "onyx",+ "nova",+ "sage",+ "shimmer",+ "verse",+ "marin",+ "cedar",+ ],+ },+ )+async def test_empty_string_short_circuits(self) -> None:"""``synthesize("")`` returns an empty response without touchingthe API."""diff --git a/tests/tts_voice_cloning_client_test.py b/tests/tts_voice_cloning_client_test.pynew file mode 100644index 000000000..001d8502b--- /dev/null+++ b/tests/tts_voice_cloning_client_test.py@@ -0,0 +1,520 @@+# -*- coding: utf-8 -*-+"""Voice creation SDK tests, independent of App and FastAPI."""+import inspect+from typing import Any+from unittest import IsolatedAsyncioTestCase+from unittest.mock import AsyncMock, patch++import httpx++from agentscope.credential import (+ CredentialBase,+ DashScopeCredential,+ OpenAICredential,+)+from agentscope.tts import (+ DashScopeVoiceCloningClient,+ OpenAIVoiceCloningClient,+ VoiceCloningError,+ VoiceCloningClientBase,+)+++class TestVoiceCloningClients(IsolatedAsyncioTestCase):+ """Verify complete wire payloads, validation and provider failures."""++ def setUp(self) -> None:+ """Isolate network and environment settings for every test."""+ environment = patch.dict("os.environ", {}, clear=True)+ environment.start()+ self.addCleanup(environment.stop)+ transport = patch("agentscope.tts._voice_utils.httpx.AsyncClient")+ self.transport = transport.start()+ self.addCleanup(transport.stop)+ self.post = AsyncMock()+ self.transport.return_value.__aenter__.return_value.post = self.post+ self.openai = OpenAIVoiceCloningClient(+ OpenAICredential(api_key="test"),+ )+ self.dashscope = DashScopeVoiceCloningClient(+ DashScopeCredential(api_key="test"),+ )++ async def _create(self, operation: str) -> str:+ """Exercise a public SDK operation with a valid input."""+ if operation == "consent":+ return await self.openai.create_consent(+ b"\x00\x01\x02",+ name="Test consent",+ language="zh",+ filename="sample.mp3",+ )+ if operation == "openai":+ return await self.openai.create_voice(+ b"\x00\x01\x02",+ parameters=self.openai.Parameters(+ name="Test voice",+ consent="consent-1",+ ),+ filename="sample.mp3",+ )+ return await self.dashscope.create_voice(+ parameters=self.dashscope.Parameters(+ target_model="cosyvoice-v3-plus",+ ),+ audio_url="https://example.com/sample.mp3",+ )++ def test_common_client_contract_and_discovery(self) -> None:+ """Providers expose the same method and are found via credentials."""+ self.assertEqual(+ {+ cls.__name__: cls.get_voice_cloning_client_class()+ for cls in (+ CredentialBase,+ OpenAICredential,+ DashScopeCredential,+ )+ },+ {+ "CredentialBase": None,+ "OpenAICredential": OpenAIVoiceCloningClient,+ "DashScopeCredential": DashScopeVoiceCloningClient,+ },+ )+ for client in (self.openai, self.dashscope):+ with self.subTest(client=type(client)):+ self.assertIsInstance(client, VoiceCloningClientBase)+ self.assertEqual(+ inspect.signature(type(client).create_voice),+ inspect.signature(VoiceCloningClientBase.create_voice),+ )+ with self.assertRaises(TypeError):+ # pylint: disable-next=abstract-class-instantiated+ VoiceCloningClientBase(CredentialBase())++ async def test_parameters_reject_missing_or_unknown_options(self) -> None:+ """Required and misspelled provider options cannot pass silently."""+ for client, valid in (+ (self.openai, {"consent": "cons-1"}),+ (self.dashscope, {"target_model": "qwen-audio-3.1-tts-flash"}),+ ):+ with self.subTest(client=type(client)):+ with self.assertRaises(ValueError):+ await client.create_voice(b"sample")+ with self.assertRaises(ValueError):+ client.Parameters(**valid, unsupported_option=True)+ self.transport.assert_not_called()++ async def test_model_audio_source_mismatch_is_rejected(self) -> None:+ """Input types cannot silently select a different model protocol."""+ cases = (+ ("cosyvoice-v3-plus", {"audio": b"sample"}),+ (+ "qwen-audio-3.1-tts-flash",+ {"audio_url": "https://example.com/sample.mp3"},+ ),+ (+ "qwen3-tts-vc-realtime-2025-11-27",+ {"audio_url": "https://example.com/sample.mp3"},+ ),+ ("unknown-model", {"audio": b"sample"}),+ )+ for model, inputs in cases:+ with self.subTest(model=model):+ with self.assertRaises(ValueError):+ await self.dashscope.create_voice(+ **inputs,+ parameters=self.dashscope.Parameters(+ target_model=model,+ ),+ )+ for inputs in (+ {"audio_url": "https://example.com/sample.mp3"},+ {+ "audio": b"sample",+ "audio_url": "https://example.com/sample.mp3",+ },+ ):+ with self.subTest(inputs=inputs):+ with self.assertRaises(ValueError):+ await self.openai.create_voice(+ **inputs,+ parameters=self.openai.Parameters(consent="cons-1"),+ )+ self.transport.assert_not_called()++ async def test_openai_uploads(self) -> None:+ """Both uploads honor credentials, environment and multipart fields."""+ cases = (+ ({}, {}, "https://api.openai.com/v1", {}),+ (+ {+ "base_url": "https://proxy.example.test/v1/",+ "organization": "org-credential",+ },+ {+ "OPENAI_BASE_URL": "https://ignored.example.test/v1",+ "OPENAI_ORG_ID": "org-environment",+ },+ "https://proxy.example.test/v1",+ {"OpenAI-Organization": "org-credential"},+ ),+ (+ {},+ {+ "OPENAI_BASE_URL": "https://environment.example.test/v1/",+ "OPENAI_ORG_ID": "org-environment",+ "OPENAI_PROJECT_ID": "proj-environment",+ },+ "https://environment.example.test/v1",+ {+ "OpenAI-Organization": "org-environment",+ "OpenAI-Project": "proj-environment",+ },+ ),+ )+ for settings, environment, base_url, headers in cases:+ for operation in ("consent", "openai"):+ for status in (200, 201):+ with self.subTest(+ settings=settings,+ operation=operation,+ status=status,+ ), patch.dict("os.environ", environment, clear=True):+ self.openai = OpenAIVoiceCloningClient(+ OpenAICredential(api_key="test", **settings),+ )+ self.post.reset_mock()+ self.post.return_value = httpx.Response(+ status,+ json={"id": "created-id"},+ )+ self.assertEqual(+ await self._create(operation),+ "created-id",+ )+ is_consent = operation == "consent"+ endpoint = "voice_consents" if is_consent else "voices"+ field = "recording" if is_consent else "audio_sample"+ self.post.assert_awaited_once_with(+ f"{base_url}/audio/{endpoint}",+ headers={+ "Authorization": "Bearer test",+ **headers,+ },+ data={"name": "Test consent", "language": "zh"}+ if is_consent+ else {+ "name": "Test voice",+ "consent": "consent-1",+ },+ files={+ field: (+ "sample.mp3",+ b"\x00\x01\x02",+ "audio/mpeg",+ ),+ },+ )++ async def test_dashscope_protocols(self) -> None:+ """Preserve Qwen Audio, Qwen voice enrollment and CosyVoice formats."""+ cases: list[tuple[str, dict[str, Any], str, dict[str, Any]]] = [+ (+ f"qwen-audio-{version}-tts-{tier}",+ {"audio": b"\x00\x01\x02"},+ "voice-enrollment",+ {+ "action": "create_voice",+ "prefix": "testvoice",+ "audio": "data:audio/mpeg;base64,AAEC",+ },+ )+ for version in ("3.0", "3.1")+ for tier in ("flash", "plus")+ ]+ cases.extend(+ [+ (+ "qwen3-tts-vc-realtime-2025-11-27",+ {"audio": b"\x00\x01\x02"},+ "qwen-voice-enrollment",+ {+ "action": "create",+ "preferred_name": "testvoice",+ "audio": {"data": "data:audio/mpeg;base64,AAEC"},+ "text": "Transcript",+ },+ ),+ (+ "cosyvoice-v3-plus",+ {"audio_url": "https://example.com/sample.mp3"},+ "voice-enrollment",+ {+ "action": "create_voice",+ "prefix": "testvoice",+ "url": "https://example.com/sample.mp3",+ },+ ),+ ],+ )+ for model, audio, enrollment, inputs in cases:+ for key in ("voice", "voice_id", "voice_name"):+ with self.subTest(model=model, response_key=key):+ self.post.reset_mock()+ self.post.return_value = httpx.Response(+ 200,+ json={"output": {key: "voice-created"}},+ )+ self.assertEqual(+ await self.dashscope.create_voice(+ parameters=self.dashscope.Parameters(+ target_model=model,+ prefix="testvoice",+ text="Transcript",+ ),+ filename="sample.mp3",+ **audio,+ ),+ "voice-created",+ )+ self.assertEqual(+ self.dashscope.get_enrollment_model(model),+ enrollment,+ )+ self.post.assert_awaited_once_with(+ "https://dashscope.aliyuncs.com/api/v1/services"+ "/audio/tts/customization",+ headers={+ "Authorization": "Bearer test",+ "Content-Type": "application/json",+ },+ json={+ "model": enrollment,+ "input": {"target_model": model, **inputs},+ },+ )++ async def test_dashscope_uses_credential_base_url(self) -> None:+ """Enrollment follows the credential host and proxy path prefix."""+ origins = (+ "https://dashscope.aliyuncs.com",+ "https://dashscope-intl.aliyuncs.com",+ "https://workspace.cn-beijing.maas.aliyuncs.com",+ "https://proxy.example.test:8443/gateway/dashscope",+ "http://localhost:8080/dashscope",+ )+ for origin in origins:+ for suffix in ("", "/compatible-mode/v1", "/api/v1"):+ for trailing in ("", "/"):+ base_url = origin + suffix + trailing+ with self.subTest(base_url=base_url):+ self.post.reset_mock()+ self.post.return_value = httpx.Response(+ 200,+ json={"output": {"voice_id": "voice-created"}},+ )+ self.dashscope = DashScopeVoiceCloningClient(+ DashScopeCredential(+ api_key="test",+ base_url=base_url,+ ),+ )+ self.assertEqual(+ await self._create("dashscope"),+ "voice-created",+ )+ self.post.assert_awaited_once_with(+ f"{origin}/api/v1/services"+ "/audio/tts/customization",+ headers={+ "Authorization": "Bearer test",+ "Content-Type": "application/json",+ },+ json={+ "model": "voice-enrollment",+ "input": {+ "action": "create_voice",+ "target_model": "cosyvoice-v3-plus",+ "prefix": "agentscope",+ "url": "https://example.com/sample.mp3",+ },+ },+ )++ async def test_invalid_dashscope_base_url_fails_before_http(self) -> None:+ """Reject relative URLs and unsupported schemes before any request."""+ for base_url in (+ "",+ "/api/v1",+ "https:///api/v1",+ "ftp://host/api/v1",+ ):+ with self.subTest(base_url=base_url):+ self.dashscope = DashScopeVoiceCloningClient(+ DashScopeCredential(api_key="test", base_url=base_url),+ )+ with self.assertRaises(ValueError):+ await self._create("dashscope")+ self.transport.assert_not_called()++ async def test_invalid_inputs_do_not_send_requests(self) -> None:+ """Missing metadata or ambiguous audio fails before networking."""+ for operation in ("consent", "openai", "dashscope"):+ method = {+ "consent": self.openai.create_consent,+ "openai": self.openai.create_voice,+ "dashscope": self.dashscope.create_voice,+ }[operation]+ base: dict[str, Any] = {+ "audio": b"sample",+ "filename": "sample.mp3",+ }+ invalid: tuple[dict[str, Any], ...]+ if operation == "dashscope":+ base.update(target_model="qwen-audio-3.1-tts-flash")+ invalid = (+ {"audio": None},+ {"audio": b""},+ {"filename": ""},+ {"audio_url": "https://example.com/sample.mp3"},+ {"audio": None, "audio_url": ""},+ {"target_model": ""},+ {"prefix": ""},+ )+ else:+ base.update(name="Test voice")+ required = "language" if operation == "consent" else "consent"+ base[required] = "en" if operation == "consent" else "cons-1"+ invalid = (+ {"audio": b""},+ {"filename": ""},+ {"name": ""},+ {required: ""},+ )+ for overrides in invalid:+ with self.subTest(operation=operation, overrides=overrides):+ with self.assertRaises(ValueError):+ values = {**base, **overrides}+ if operation == "consent":+ await method(**values)+ else:+ client = (+ self.openai+ if operation == "openai"+ else self.dashscope+ )+ options = {+ name: values.pop(name)+ for name in client.Parameters.model_fields+ if name in values+ }+ await method(+ **values,+ parameters=client.Parameters(**options),+ )+ self.transport.assert_not_called()++ async def test_provider_failures_are_sdk_errors(self) -> None:+ """Expose SDK errors without retries or framework coupling."""+ for operation in ("consent", "openai", "dashscope"):+ provider = "DashScope" if operation == "dashscope" else "OpenAI"+ action = (+ "consent upload" if operation == "consent" else "voice clone"+ )+ for code in (400, 403, 429, 500):+ with self.subTest(operation=operation, code=code):+ self.post.reset_mock()+ self.post.return_value = httpx.Response(+ code,+ text="provider failure",+ )+ with self.assertRaises(VoiceCloningError) as ctx:+ await self._create(operation)+ self.assertEqual(+ str(ctx.exception),+ f"{provider} {action} failed ({code}): "+ "provider failure",+ )+ self.post.assert_awaited_once()++ async def test_network_errors_are_sdk_errors(self) -> None:+ """Network failures retain their cause and do not retry creation."""+ for operation in ("consent", "openai", "dashscope"):+ for error in (httpx.ConnectError, httpx.ReadTimeout):+ with self.subTest(operation=operation, error=error):+ self.post.reset_mock()+ cause = error("offline")+ self.post.side_effect = cause+ with self.assertRaises(VoiceCloningError) as ctx:+ await self._create(operation)+ provider = (+ "DashScope" if operation == "dashscope" else "OpenAI"+ )+ self.assertEqual(+ str(ctx.exception),+ f"Network error calling {provider}: offline",+ )+ self.assertIs(ctx.exception.__cause__, cause)+ self.post.assert_awaited_once()++ async def test_dashscope_missing_voice_error_is_bounded(self) -> None:+ """A malformed success response cannot flood the API error detail."""+ result = {"output": {"unexpected": "a" * 2000}}+ self.post.return_value = httpx.Response(200, json=result)+ with self.assertRaises(VoiceCloningError) as ctx:+ await self._create("dashscope")+ self.assertEqual(+ str(ctx.exception),+ "DashScope returned success but no voice found in response: "+ + str(result)[:500],+ )++ async def test_invalid_success_payloads_are_sdk_errors(self) -> None:+ """Malformed JSON, unexpected structures and unusable IDs fail."""+ responses = [+ httpx.Response(200, content=body)+ for body in (b"<html>error</html>", b"", b"{", b"null", b"[]")+ ]+ responses.extend(+ httpx.Response(200, json=body)+ for body in (+ {},+ {"id": "", "output": {}},+ {"id": 1, "output": {"voice": 1}},+ {"id": [], "output": []},+ {"id": None, "output": None},+ )+ )+ for operation in ("consent", "openai", "dashscope"):+ for response in responses:+ with self.subTest(operation=operation, body=response.text):+ self.post.return_value = response+ with self.assertRaises(VoiceCloningError):+ await self._create(operation)++ async def test_unknown_filename_uses_wav_mime_type(self) -> None:+ """Preserve the existing MIME fallback for unrecognized filenames."""+ self.post.return_value = httpx.Response(200, json={"id": "voice-1"})+ self.assertEqual(+ await self.openai.create_voice(+ b"sample",+ parameters=self.openai.Parameters(+ name="Test voice",+ consent="cons-1",+ ),+ filename="sample.unknown-audio-extension",+ ),+ "voice-1",+ )+ self.assertEqual(+ self.post.call_args.kwargs["files"],+ {+ "audio_sample": (+ "sample.unknown-audio-extension",+ b"sample",+ "audio/wav",+ ),+ },+ )diff --git a/tests/voice_profile_test.py b/tests/voice_profile_test.pynew file mode 100644index 000000000..4b6f42fe3--- /dev/null+++ b/tests/voice_profile_test.py@@ -0,0 +1,1679 @@+# -*- coding: utf-8 -*-+# pylint: disable=protected-access+"""Unit tests for Voice Profile storage model and constants.++Covers:+ * VoiceProfileData and VoiceProfileRecord model creation.+ * ENGINE_TO_CREDENTIAL_TYPE mapping completeness.+ * Credential-derived voice cloning capabilities.+"""+import base64+import typing+from unittest import IsolatedAsyncioTestCase, TestCase+from unittest.mock import AsyncMock, patch++import httpx+from fastapi import HTTPException+from pydantic import BaseModel, ValidationError++from agentscope.app._router._voice_profile import (+ _decode_audio,+ _validate_voice_profile_data,+ clone_voice,+ list_available_engines,+ upload_openai_consent,+)+from agentscope.app._router._schema import (+ CloneVoiceRequest,+ OpenAIConsentRequest,+)+from agentscope.app._router._schema._voice_profile import (+ MAX_AUDIO_SIZE_BYTES,+ MAX_AUDIO_BASE64_LENGTH,+)+from agentscope.app._service._tts_model import (+ _validate_voice_binding,+ _config_error_detail,+ get_tts_model,+ validate_tts_model_config,+)+from agentscope.app.storage._model import (+ CredentialRecord,+ ENGINE_TO_CREDENTIAL_TYPE,+ TTSModelConfig,+ VoiceProfileData,+ VoiceProfileRecord,+)+from agentscope.app.storage._model._voice_profile import (+ _ENGINE_TYPE,+)+from agentscope.tts import (+ DashScopeCosyVoiceTTSModel,+ TTSModelCard,+ VoiceCloningError,+ VoiceCloningClientBase,+)+from agentscope.credential import (+ CredentialBase,+ CredentialFactory,+ DashScopeCredential,+ OpenAICredential,+)+++class _DemoVoiceCloningClient(VoiceCloningClientBase):+ """A third-party client used to verify provider-independent dispatch."""++ class Parameters(VoiceCloningClientBase.Parameters):+ """Creation options understood by the demo provider."""++ name: str++ async def create_voice(+ self,+ audio: bytes | None = None,+ *,+ filename: str = "voice.wav",+ audio_url: str | None = None,+ parameters: BaseModel | None = None,+ ) -> str:+ """Return a provider ID without a network request."""+ return "demo-voice-id"+++class _DemoVoiceCredential(CredentialBase): # pylint: disable=abstract-method+ """A separately registered credential supplying its own client."""++ type: typing.Literal["demo_voice_credential"] = "demo_voice_credential"++ @classmethod+ def get_voice_cloning_client_class(+ cls,+ ) -> typing.Type[VoiceCloningClientBase]:+ """Expose the demo client's voice creation capability."""+ return _DemoVoiceCloningClient+++class TestVoiceCloningClientDispatch(IsolatedAsyncioTestCase):+ """New providers use the common route without adding dispatch branches."""++ async def test_registered_provider_uses_common_route(self) -> None:+ """Credential registration and engine mapping select a third client."""+ access = AsyncMock()+ data = {+ "type": "demo_voice_credential",+ "id": "credential-demo",+ "name": "Demo credential",+ }+ access.resolve_credential.return_value = CredentialRecord(+ id="credential-demo",+ user_id="user-a",+ data=data,+ )+ with (+ patch.object(+ CredentialFactory,+ "_classes",+ list(CredentialFactory._classes),+ ),+ patch.object(CredentialFactory, "_adapter", None),+ patch.dict(+ ENGINE_TO_CREDENTIAL_TYPE,+ {"demo_engine": "demo_voice_credential"},+ ),+ patch.object(+ _DemoVoiceCloningClient,+ "create_voice",+ autospec=True,+ return_value="demo-voice-id",+ ) as create,+ ):+ CredentialFactory.register_credential(_DemoVoiceCredential)+ result = await clone_voice(+ CloneVoiceRequest(+ engine="demo_engine",+ credential_id="credential-demo",+ audio_base64="AAEC",+ audio_filename="sample.mp3",+ prefix="Demo voice",+ ),+ "user-a",+ access,+ )+ self.assertEqual(+ result.model_dump(),+ {+ "voice_id": "demo-voice-id",+ "credential_id": "credential-demo",+ },+ )+ create.assert_awaited_once()+ client = create.call_args.args[0]+ self.assertEqual(client.credential.model_dump(), data)+ create.assert_awaited_once_with(+ client,+ b"\x00\x01\x02",+ filename="sample.mp3",+ audio_url=None,+ parameters=_DemoVoiceCloningClient.Parameters(name="Demo voice"),+ )++ async def test_unsupported_client_is_rejected(self) -> None:+ """Unknown engines and credentials without clients do not dispatch."""+ access = AsyncMock()+ for engine in ("unknown", "gemini_tts"):+ with self.subTest(engine=engine):+ with self.assertRaises(HTTPException) as ctx:+ await clone_voice(+ CloneVoiceRequest(+ engine=engine,+ credential_id="credential-a",+ ),+ "user-a",+ access,+ )+ self.assertEqual(ctx.exception.status_code, 400)+ access.resolve_credential.assert_not_called()++ async def test_common_route_keeps_credential_authorization(self) -> None:+ """Shared and wrong-provider credentials cannot reach any SDK call."""+ for engine, provider in (+ ("openai_tts", "openai_credential"),+ ("cosyvoice", "dashscope_credential"),+ ):+ for owner, actual_type, expected_status in (+ ("user-b", provider, 403),+ ("user-a", "gemini_credential", 400),+ ):+ with self.subTest(engine=engine, owner=owner):+ access = AsyncMock()+ access.resolve_credential.return_value = CredentialRecord(+ id="credential-a",+ user_id=owner,+ data={"type": actual_type, "api_key": "test"},+ )+ with patch(+ "agentscope.tts._voice_utils.httpx.AsyncClient",+ ) as client:+ with self.assertRaises(HTTPException) as ctx:+ await clone_voice(+ CloneVoiceRequest(+ engine=engine,+ credential_id="credential-a",+ ),+ "user-a",+ access,+ )+ self.assertEqual(+ ctx.exception.status_code,+ expected_status,+ )+ client.assert_not_called()+++class TestVoiceProfileModel(TestCase):+ """Unit tests for VoiceProfileData and VoiceProfileRecord."""++ def test_create_voice_profile_data_minimal(self) -> None:+ """VoiceProfileData can be created with only name."""+ data = VoiceProfileData(name="Test Voice")+ self.assertEqual(+ data.model_dump(),+ {+ "name": "Test Voice",+ "engine": None,+ "model": None,+ "credential_id": None,+ "voice": None,+ "metadata": None,+ },+ )++ def test_create_voice_profile_data_full(self) -> None:+ """VoiceProfileData can be created with all fields."""+ data = VoiceProfileData(+ name="Clone Voice",+ engine="dashscope_tts",+ model="qwen3-tts-flash",+ credential_id="cred-abc-123",+ voice="cosyvoice-clone-abc123",+ metadata={"quality": "high"},+ )+ self.assertEqual(+ data.model_dump(),+ {+ "name": "Clone Voice",+ "engine": "dashscope_tts",+ "model": "qwen3-tts-flash",+ "credential_id": "cred-abc-123",+ "voice": "cosyvoice-clone-abc123",+ "metadata": {"quality": "high"},+ },+ )++ def test_create_voice_profile_record(self) -> None:+ """VoiceProfileRecord can be created with auto id."""+ data = VoiceProfileData(name="Test")+ record = VoiceProfileRecord(+ user_id="user-1",+ data=data,+ )+ self.assertEqual(record.user_id, "user-1")+ self.assertEqual(record.data.name, "Test")+ self.assertIsNotNone(record.id)+ self.assertIsNotNone(record.created_at)++ def test_stored_source_does_not_affect_profile_binding(self) -> None:+ """Existing records remain readable after removing the source label."""+ expected = {+ "name": "Voice A",+ "engine": "dashscope_tts",+ "model": "qwen3-tts-flash",+ "credential_id": "credential-a",+ "voice": "voice-a",+ "metadata": {"label": "sample"},+ }+ for source in ("api", "local", None):+ with self.subTest(source=source):+ data = VoiceProfileData.model_validate(+ {**expected, "source": source},+ )+ self.assertEqual(data.model_dump(), expected)+++def _model_card(+ voices: list[str],+ *,+ voice_cloning: bool = False,+) -> TTSModelCard:+ """Build a minimal model card with provider-declared preset voices."""+ return TTSModelCard(+ name="gpt-4o-mini-tts",+ label="OpenAI TTS",+ voice_cloning=voice_cloning,+ parameter_schema={+ "type": "object",+ "properties": {+ "voice": {+ "type": "string",+ "enum": voices,+ },+ },+ },+ parameters_overrides={},+ )+++def _custom_config(+ *,+ profile_id: str | None = "profile-a",+ credential_id: str = "credential-a",+ voice: str = "voice-a",+) -> TTSModelConfig:+ """Build a custom voice TTS config for authorization tests."""+ return TTSModelConfig(+ type="openai_credential",+ credential_id=credential_id,+ model="gpt-4o-mini-tts",+ voice_profile_id=profile_id,+ parameters={"voice": voice},+ )+++def _profile(+ *,+ user_id: str = "user-a",+ credential_id: str = "credential-a",+ voice: str = "voice-a",+) -> VoiceProfileRecord:+ """Build an owner-scoped custom voice profile."""+ return VoiceProfileRecord(+ id="profile-a",+ user_id=user_id,+ data=VoiceProfileData(+ name="Voice A",+ engine="openai_tts",+ model="gpt-4o-mini-tts",+ credential_id=credential_id,+ voice=voice,+ ),+ )+++class TestVoiceProfileTenantIsolation(IsolatedAsyncioTestCase):+ """Authorization tests for preset and custom voices."""++ async def test_omitted_voice_is_allowed_for_model_with_presets(+ self,+ ) -> None:+ """A normal preset-capable model may continue using its default."""+ storage = AsyncMock()+ config = _custom_config(profile_id=None)+ config.parameters = {}++ await _validate_voice_binding(+ user_id="user-a",+ config=config,+ credential_owner_id="user-b",+ storage=storage,+ card=_model_card(["alloy"], voice_cloning=True),+ )++ storage.get_voice_profile.assert_not_called()++ async def test_clone_only_model_requires_voice_profile(self) -> None:+ """A clone-only model cannot fall through to a class default voice."""+ storage = AsyncMock()+ config = _custom_config(profile_id=None)+ config.parameters = {}++ with self.assertRaises(HTTPException) as ctx:+ await _validate_voice_binding(+ user_id="user-a",+ config=config,+ credential_owner_id="user-a",+ storage=storage,+ card=_model_card([], voice_cloning=True),+ )++ self.assertEqual(ctx.exception.status_code, 400)+ self.assertIn("requires a cloned voice profile", ctx.exception.detail)+ storage.get_voice_profile.assert_not_called()++ async def test_clone_only_card_cannot_use_shared_class_default(+ self,+ ) -> None:+ """Clone-only cards cannot fall back to the shared default voice."""+ card = next(+ card+ for card in DashScopeCosyVoiceTTSModel.list_models()+ if card.name == "cosyvoice-v3.5-plus"+ )+ config = TTSModelConfig(+ type="dashscope_credential",+ credential_id="credential-a",+ model=card.name,+ parameters={},+ )++ with self.assertRaises(HTTPException) as ctx:+ await _validate_voice_binding(+ user_id="user-a",+ config=config,+ credential_owner_id="user-a",+ storage=AsyncMock(),+ card=card,+ )++ self.assertEqual(ctx.exception.status_code, 400)+ self.assertIn("requires a cloned voice profile", ctx.exception.detail)++ async def test_clone_only_model_rejects_unbound_explicit_voice(+ self,+ ) -> None:+ """Supplying a clone id directly cannot bypass profile ownership."""+ storage = AsyncMock()++ with self.assertRaises(HTTPException) as ctx:+ await _validate_voice_binding(+ user_id="user-a",+ config=_custom_config(profile_id=None, voice="voice-a"),+ credential_owner_id="user-b",+ storage=storage,+ card=_model_card([], voice_cloning=True),+ )++ self.assertEqual(ctx.exception.status_code, 400)+ self.assertIn("requires a cloned voice profile", ctx.exception.detail)+ storage.get_voice_profile.assert_not_called()++ async def test_owned_keys_accept_unlisted_and_existing_cloned_voices(+ self,+ ) -> None:+ """Direct SDK/API voice IDs need no App profile for owned keys."""+ for card in (+ None,+ _model_card(["alloy"]),+ _model_card([], voice_cloning=True),+ ):+ with self.subTest(card=card):+ storage = AsyncMock()+ await _validate_voice_binding(+ user_id="user-a",+ config=_custom_config(profile_id=None, voice="voice-a"),+ credential_owner_id="user-a",+ storage=storage,+ card=card,+ )+ storage.get_voice_profile.assert_not_called()+ with self.assertRaises(HTTPException):+ await _validate_voice_binding(+ user_id="user-a",+ config=_custom_config(+ profile_id=None,+ voice="voice-a",+ ),+ credential_owner_id="user-b",+ storage=storage,+ card=card,+ )++ async def test_preset_voice_does_not_require_profile(self) -> None:+ """Provider-declared preset voices remain usable as before."""+ storage = AsyncMock()+ await _validate_voice_binding(+ user_id="user-a",+ config=_custom_config(profile_id=None, voice="alloy"),+ credential_owner_id="user-b",+ storage=storage,+ card=_model_card(["alloy"]),+ )+ storage.get_voice_profile.assert_not_called()++ async def test_custom_voice_without_profile_is_rejected(self) -> None:+ """A caller cannot submit an arbitrary custom voice identifier."""+ with self.assertRaises(HTTPException) as ctx:+ await _validate_voice_binding(+ user_id="user-a",+ config=_custom_config(profile_id=None, voice="voice-b"),+ credential_owner_id="user-b",+ storage=AsyncMock(),+ card=_model_card(["alloy"]),+ )+ self.assertEqual(ctx.exception.status_code, 403)++ async def test_other_tenant_profile_is_hidden(self) -> None:+ """A profile id owned by user B is not resolvable for user A."""+ storage = AsyncMock()+ storage.get_voice_profile.return_value = None++ with self.assertRaises(HTTPException) as ctx:+ await _validate_voice_binding(+ user_id="user-a",+ config=_custom_config(profile_id="profile-b", voice="voice-b"),+ credential_owner_id="user-a",+ storage=storage,+ card=_model_card(["alloy"]),+ )++ self.assertEqual(ctx.exception.status_code, 404)+ storage.get_voice_profile.assert_awaited_once_with(+ "user-a",+ "profile-b",+ )++ async def test_shared_credential_is_rejected_for_custom_voice(+ self,+ ) -> None:+ """Sharing a credential does not implicitly share custom voices."""+ storage = AsyncMock()+ storage.get_voice_profile.return_value = _profile()++ with self.assertRaises(HTTPException) as ctx:+ await _validate_voice_binding(+ user_id="user-a",+ config=_custom_config(),+ credential_owner_id="user-b",+ storage=storage,+ card=_model_card(["alloy"]),+ )++ self.assertEqual(ctx.exception.status_code, 403)++ async def test_profile_binding_must_match_voice(self) -> None:+ """The voice id cannot be swapped after selecting an owned profile."""+ storage = AsyncMock()+ storage.get_voice_profile.return_value = _profile()++ with self.assertRaises(HTTPException) as ctx:+ await _validate_voice_binding(+ user_id="user-a",+ config=_custom_config(voice="voice-b"),+ credential_owner_id="user-a",+ storage=storage,+ card=_model_card(["alloy"]),+ )++ self.assertEqual(ctx.exception.status_code, 400)+ self.assertIn("voice", ctx.exception.detail)++ async def test_exact_owned_profile_binding_is_allowed(self) -> None:+ """An owned profile with an exact binding passes validation."""+ storage = AsyncMock()+ storage.get_voice_profile.return_value = _profile()++ await _validate_voice_binding(+ user_id="user-a",+ config=_custom_config(),+ credential_owner_id="user-a",+ storage=storage,+ card=_model_card(["alloy"]),+ )++ async def test_write_and_runtime_reject_empty_binding_fields(self) -> None:+ """CRUD and runtime use the same non-empty binding-field rule."""+ access = AsyncMock()+ incomplete_profile = _profile(voice="")++ with self.assertRaises(HTTPException) as write_ctx:+ await _validate_voice_profile_data(+ access,+ "user-a",+ incomplete_profile.data,+ )++ self.assertEqual(write_ctx.exception.status_code, 400)+ self.assertIn("voice", write_ctx.exception.detail)+ access.resolve_credential.assert_not_called()++ storage = AsyncMock()+ storage.get_voice_profile.return_value = incomplete_profile+ with self.assertRaises(HTTPException) as runtime_ctx:+ await _validate_voice_binding(+ user_id="user-a",+ config=_custom_config(voice=""),+ credential_owner_id="user-a",+ storage=storage,+ card=_model_card(["alloy"]),+ )++ self.assertEqual(runtime_ctx.exception.status_code, 400)+ self.assertIn("incomplete", runtime_ctx.exception.detail)+ self.assertIn("voice", runtime_ctx.exception.detail)++ async def test_profile_cannot_bind_shared_credential(self) -> None:+ """Profile CRUD rejects a credential owned by another tenant."""+ access = AsyncMock()+ access.resolve_credential.return_value = CredentialRecord(+ id="credential-b",+ user_id="user-b",+ data={+ "type": "openai_credential",+ "api_key": "secret",+ },+ )+ data = _profile(credential_id="credential-b").data++ with self.assertRaises(HTTPException) as ctx:+ await _validate_voice_profile_data(+ access,+ "user-a",+ data,+ )++ self.assertEqual(ctx.exception.status_code, 403)++ async def test_full_config_validation_accepts_owned_binding(self) -> None:+ """Persisted-session validation resolves the same tenant binding."""+ access = AsyncMock()+ access.resolve_credential.return_value = CredentialRecord(+ id="credential-a",+ user_id="user-a",+ data={+ "type": "openai_credential",+ "api_key": "secret",+ },+ )+ storage = AsyncMock()+ storage.get_voice_profile.return_value = _profile()++ await validate_tts_model_config(+ "user-a",+ _custom_config(),+ access,+ storage,+ )++ access.resolve_credential.assert_awaited_once_with(+ "user-a",+ "credential-a",+ )+ storage.get_voice_profile.assert_awaited_once_with(+ "user-a",+ "profile-a",+ )+++class TestVoiceProfileRuntime(IsolatedAsyncioTestCase):+ """Runtime follows current profiles with strict authorization checks."""++ def setUp(self) -> None:+ """Provide an owned credential and profile without cloud calls."""+ self.access = AsyncMock()+ self.access.resolve_credential.return_value = CredentialRecord(+ id="credential-a",+ user_id="user-a",+ data={"type": "openai_credential", "api_key": "test"},+ )+ self.storage = AsyncMock()+ self.storage.get_voice_profile.return_value = _profile()++ async def test_missing_profile_skips_tts_but_cannot_be_saved(self) -> None:+ """A deleted or invisible profile never synthesizes stale audio."""+ self.storage.get_voice_profile.return_value = None+ config = _custom_config()+ model = await get_tts_model(+ "user-a",+ config,+ self.access,+ self.storage,+ )+ self.assertIsNone(model)+ self.access.resolve_credential.assert_not_called()+ with self.assertRaises(HTTPException) as ctx:+ await validate_tts_model_config(+ "user-a",+ config,+ self.access,+ self.storage,+ )+ self.assertEqual(ctx.exception.status_code, 404)++ async def test_invalid_credentials_skip_runtime_but_reject_saves(+ self,+ ) -> None:+ """Deleted, revoked and invalid credentials never reach synthesis."""+ for code in (400, 403, 404):+ with self.subTest(code=code):+ self.access.resolve_credential.side_effect = HTTPException(+ code,+ )+ config = _custom_config()+ self.assertIsNone(+ await get_tts_model(+ "user-a",+ config,+ self.access,+ self.storage,+ ),+ )+ with self.assertRaises(HTTPException) as ctx:+ await validate_tts_model_config(+ "user-a",+ config,+ self.access,+ self.storage,+ )+ self.assertEqual(ctx.exception.status_code, code)++ async def test_invalid_parameters_skip_runtime_but_reject_saves(+ self,+ ) -> None:+ """Parameter validation is isolated at runtime and strict on save."""+ config = _custom_config()+ config.parameters["response_format"] = "invalid-format"+ self.assertIsNone(+ await get_tts_model(+ "user-a",+ config,+ self.access,+ self.storage,+ ),+ )+ with self.assertRaises(HTTPException) as ctx:+ await validate_tts_model_config(+ "user-a",+ config,+ self.access,+ self.storage,+ )+ self.assertEqual(ctx.exception.status_code, 400)++ async def test_profile_model_is_validated_before_save(self) -> None:+ """Known incompatible clones fail; presets and new deployments work."""+ for model, voice, rejected in (+ ("tts-1", "custom-voice-id", True),+ ("tts-1-hd", "custom-voice-id", True),+ ("tts-1", "alloy", False),+ ("gpt-4o-mini-tts", "custom-voice-id", False),+ ("custom-deployment", "custom-voice-id", False),+ ):+ with self.subTest(model=model, voice=voice):+ data = _profile().data+ data.model = model+ data.voice = voice+ if rejected:+ with self.assertRaises(HTTPException) as ctx:+ await _validate_voice_profile_data(+ self.access,+ "user-a",+ data,+ )+ self.assertEqual(ctx.exception.status_code, 400)+ self.storage.get_voice_profile.return_value.data = data+ self.assertIsNone(+ await get_tts_model(+ "user-a",+ _custom_config(),+ self.access,+ self.storage,+ ),+ )+ else:+ await _validate_voice_profile_data(+ self.access,+ "user-a",+ data,+ )++ async def test_owned_legacy_voices_work_without_profiles(self) -> None:+ """YAML voice removals and unknown models do not break owned keys."""+ for model, voice in (+ ("tts-1", "verse"),+ ("tts-1-hd", "ballad"),+ ("custom-deployment", "unlisted-voice"),+ ("gpt-4o-mini-tts", {"id": "custom-voice"}),+ ):+ with self.subTest(model=model, voice=voice):+ config = _custom_config(profile_id=None)+ config.model = model+ config.parameters = {"voice": voice}+ instance = await get_tts_model(+ "user-a",+ config,+ self.access,+ self.storage,+ )+ self.assertEqual(instance.parameters.voice, voice)+ await instance.client.close()+ self.storage.get_voice_profile.assert_not_called()++ async def test_stale_bindings_cannot_be_saved(self) -> None:+ """Runtime resolution does not weaken write-time binding checks."""+ for changes, mismatch in (+ ({"voice": "voice-new"}, "voice"),+ ({"model": "tts-1"}, "model"),+ ({"credential_id": "credential-new"}, "credential_id"),+ ({"engine": "cosyvoice"}, "provider type"),+ ):+ with self.subTest(changes=changes):+ profile = _profile()+ profile.data = profile.data.model_copy(update=changes)+ self.storage.get_voice_profile.return_value = profile+ config = _custom_config()+ before = config.model_dump()++ with self.assertRaises(HTTPException) as ctx:+ await validate_tts_model_config(+ "user-a",+ config,+ self.access,+ self.storage,+ )+ self.assertEqual(+ (ctx.exception.status_code, ctx.exception.detail),+ (+ 400,+ "TTS config does not match voice profile "+ f"'profile-a': {mismatch}.",+ ),+ )+ self.assertEqual(config.model_dump(), before)++ async def test_runtime_uses_latest_voice_and_credential(self) -> None:+ """Recloning and credential edits override the session snapshot."""+ for voice, credential_id in (+ ("voice-new", "credential-a"),+ ("voice-a", "credential-new"),+ ("voice-new", "credential-new"),+ ):+ with self.subTest(voice=voice, credential_id=credential_id):+ self.storage.get_voice_profile.return_value = _profile(+ voice=voice,+ credential_id=credential_id,+ )+ self.access.resolve_credential.reset_mock()+ self.access.resolve_credential.return_value.id = credential_id+ config = _custom_config()+ config.parameters["response_format"] = "wav"+ before = config.model_dump()+ model = await get_tts_model(+ "user-a",+ config,+ self.access,+ self.storage,+ )+ self.assertIsNotNone(model)+ self.access.resolve_credential.assert_awaited_once_with(+ "user-a",+ credential_id,+ )+ self.assertEqual(+ model.parameters.model_dump(),+ {+ "voice": {"id": voice},+ "response_format": "wav",+ "instructions": None,+ },+ )+ self.assertEqual(config.model_dump(), before)+ await model.client.close()++ async def test_runtime_uses_latest_model_and_provider(self) -> None:+ """Model or provider edits select the current synthesis adapter."""+ profile = _profile(voice="voice-new", credential_id="credential-new")+ profile.data.engine = "dashscope_tts"+ profile.data.model = "qwen-audio-3.1-tts-flash"+ self.storage.get_voice_profile.return_value = profile+ self.access.resolve_credential.return_value = CredentialRecord(+ id="credential-new",+ user_id="user-a",+ data={"type": "dashscope_credential", "api_key": "test"},+ )+ for provider, old_model in (+ ("dashscope_credential", "qwen3-tts-vc-2026-01-22"),+ ("openai_credential", "gpt-4o-mini-tts"),+ ):+ with self.subTest(provider=provider):+ config = _custom_config()+ config.type = provider+ config.model = old_model+ config.parameters["realtime"] = True+ before = config.model_dump()+ self.access.resolve_credential.reset_mock()+ model = await get_tts_model(+ "user-a",+ config,+ self.access,+ self.storage,+ )+ self.assertIsInstance(model, DashScopeCosyVoiceTTSModel)+ self.assertEqual(+ (model.model, model.parameters.model_dump()),+ (+ "qwen-audio-3.1-tts-flash",+ {"voice": "voice-new", "realtime": False},+ ),+ )+ self.access.resolve_credential.assert_awaited_once_with(+ "user-a",+ "credential-new",+ )+ self.assertEqual(config.model_dump(), before)++ async def test_incomplete_current_profile_skips_tts(self) -> None:+ """An incomplete profile cannot fall back to stale session values."""+ self.storage.get_voice_profile.return_value.data.voice = None+ self.assertIsNone(+ await get_tts_model(+ "user-a",+ _custom_config(),+ self.access,+ self.storage,+ ),+ )+ self.access.resolve_credential.assert_not_called()++ async def test_runtime_uses_one_owner_scoped_snapshot(self) -> None:+ """Runtime does not reread a profile after deriving its binding."""+ self.storage.get_voice_profile.side_effect = [+ _profile(),+ AssertionError("Unexpected second profile read"),+ ]+ model = await get_tts_model(+ "user-a",+ _custom_config(),+ self.access,+ self.storage,+ )+ self.assertIsNotNone(model)+ self.storage.get_voice_profile.assert_awaited_once_with(+ "user-a",+ "profile-a",+ )+ self.assertEqual(model.parameters.voice, {"id": "voice-a"})+ await model.client.close()++ async def test_validation_log_names_field_without_input(self) -> None:+ """Invalid parameter diagnostics identify fields but hide inputs."""+ config = _custom_config()+ config.parameters["response_format"] = "private-input"+ with patch("agentscope.app._service._tts_model.logger.warning") as log:+ self.assertIsNone(+ await get_tts_model(+ "user-a",+ config,+ self.access,+ self.storage,+ ),+ )+ self.assertEqual(+ log.call_args.args[-1],+ "response_format: literal_error",+ )++ async def test_short_parameters_leave_log_words_readable(self) -> None:+ """Ordinary voice, language and format values are not secrets."""+ config = _custom_config(profile_id=None)+ config.parameters = {+ "voice": "alloy",+ "language": "en",+ "response_format": "wav",+ }+ detail = "Credential endpoint cannot use alloy with en and wav."+ self.access.resolve_credential.side_effect = HTTPException(400, detail)+ with patch("agentscope.app._service._tts_model.logger.warning") as log:+ self.assertIsNone(+ await get_tts_model(+ "user-a",+ config,+ self.access,+ self.storage,+ ),+ )+ self.assertEqual(log.call_args.args[-1], f"HTTPException: {detail}")++ def test_credential_name_is_not_redacted(self) -> None:+ """Credential labels cannot replace ordinary error substrings."""+ credential = OpenAICredential(api_key="secret-key", name="en")+ self.assertEqual(+ _config_error_detail(ValueError("Invalid endpoint"), credential),+ "ValueError: Invalid endpoint",+ )++ def test_value_error_detail_is_redacted_and_bounded(self) -> None:+ """Constructor errors retain context without exposing known secrets."""+ credential = OpenAICredential(api_key="super-secret-key")+ error = ValueError(+ "Invalid endpoint https://host.test/?token=unknown-secret "+ "with super-secret-key and voice-a " + "x" * 600,+ )+ detail = _config_error_detail(error, credential)+ self.assertEqual(+ detail,+ (+ "ValueError: Invalid endpoint [URL] with [redacted] and "+ "voice-a " + "x" * 600+ )[:500],+ )++ async def test_profile_rename_keeps_tts_available(self) -> None:+ """Non-binding edits do not disable an otherwise valid voice."""+ self.storage.get_voice_profile.return_value.data.name = "Renamed"+ model = await get_tts_model(+ "user-a",+ _custom_config(),+ self.access,+ self.storage,+ )+ self.assertEqual(+ model.parameters.model_dump(),+ {+ "voice": {"id": "voice-a"},+ "response_format": "mp3",+ "instructions": None,+ },+ )+ await model.client.close()++ async def test_openai_voice_conversion_preserves_saved_config(+ self,+ ) -> None:+ """Only custom voices become objects after their binding is checked."""+ for voice, profile_id, expected in (+ ("voice_123", "profile-a", {"id": "voice_123"}),+ ("alloy", "profile-a", "alloy"),+ ("alloy", None, "alloy"),+ ("marin", "profile-a", "marin"),+ ("cedar", "profile-a", "cedar"),+ ("marin", None, "marin"),+ ("cedar", None, "cedar"),+ ):+ with self.subTest(voice=voice, profile_id=profile_id):+ config = _custom_config(voice=voice, profile_id=profile_id)+ before = config.model_dump()+ self.storage.get_voice_profile.return_value = _profile(+ voice=voice,+ )+ model = await get_tts_model(+ "user-a",+ config,+ self.access,+ self.storage,+ )+ self.assertEqual(+ model.parameters.model_dump(),+ {+ "voice": expected,+ "response_format": "mp3",+ "instructions": None,+ },+ )+ self.assertEqual(config.model_dump(), before)+ await model.client.close()++ async def test_unsupported_openai_custom_voice_model(self) -> None:+ """Legacy models cannot be saved with a custom voice binding."""+ config = _custom_config()+ config.model = "tts-1"+ self.storage.get_voice_profile.return_value.data.model = "tts-1"+ with self.assertRaises(HTTPException) as ctx:+ await validate_tts_model_config(+ "user-a",+ config,+ self.access,+ self.storage,+ )+ self.assertEqual(ctx.exception.status_code, 400)++ async def test_malformed_audio_is_rejected_before_http(self) -> None:+ """Both upload routes reject invalid base64 without a provider call."""+ with patch(+ "agentscope.tts._voice_utils.httpx.AsyncClient",+ ) as client:+ for audio in ("a", "!!!!", "中文", ""):+ for operation in ("consent", "clone"):+ with self.subTest(audio=audio, operation=operation):+ with self.assertRaises(HTTPException) as ctx:+ if operation == "consent":+ await upload_openai_consent(+ OpenAIConsentRequest(+ credential_id="credential-a",+ audio_base64=audio,+ ),+ "user-a",+ self.access,+ )+ else:+ await clone_voice(+ CloneVoiceRequest(+ engine="openai_tts",+ credential_id="credential-a",+ audio_base64=audio,+ consent="consent-1",+ ),+ "user-a",+ self.access,+ )+ self.assertEqual(ctx.exception.status_code, 400)+ client.assert_not_called()+ self.assertEqual(_decode_audio("AAEC"), b"\x00\x01\x02")++ async def test_clone_rejects_unsupported_synthesis_model(self) -> None:+ """An explicit OpenAI model must support custom speech."""+ with self.assertRaises(HTTPException) as ctx:+ await clone_voice(+ CloneVoiceRequest(+ engine="openai_tts",+ model="tts-1",+ credential_id="credential-a",+ audio_base64="AAEC",+ consent="consent-1",+ ),+ "user-a",+ self.access,+ )+ self.assertEqual(ctx.exception.status_code, 400)+ self.access.resolve_credential.assert_not_called()+++class TestOpenAIVoiceRequestConfig(IsolatedAsyncioTestCase):+ """Consent and voice creation share the synthesis connection settings."""++ async def test_uploads_use_credential_settings(self) -> None:+ """Default, custom and environment settings reach both endpoints."""+ cases = (+ ({}, {}, "https://api.openai.com/v1", {}),+ (+ {+ "base_url": "https://speech.example.test/proxy/v1/",+ "organization": "org-credential",+ },+ {+ "OPENAI_BASE_URL": "https://ignored.example.test/v1",+ "OPENAI_ORG_ID": "org-environment",+ },+ "https://speech.example.test/proxy/v1",+ {"OpenAI-Organization": "org-credential"},+ ),+ (+ {"base_url": None, "organization": None},+ {+ "OPENAI_BASE_URL": "https://environment.example.test/v1",+ "OPENAI_ORG_ID": "org-environment",+ "OPENAI_PROJECT_ID": "proj-environment",+ },+ "https://environment.example.test/v1",+ {+ "OpenAI-Organization": "org-environment",+ "OpenAI-Project": "proj-environment",+ },+ ),+ )+ for settings, environment, base_url, headers in cases:+ for operation in ("consent", "clone"):+ with self.subTest(settings=settings, operation=operation):+ access = AsyncMock()+ access.resolve_credential.return_value = CredentialRecord(+ id="credential-a",+ user_id="user-a",+ data={+ "type": "openai_credential",+ "api_key": "test",+ **settings,+ },+ )+ with (+ patch.dict("os.environ", environment, clear=True),+ patch(+ "agentscope.tts._voice_utils.httpx.AsyncClient",+ ) as client,+ ):+ post = AsyncMock(+ return_value=httpx.Response(+ 201,+ json={"id": "created-id"},+ ),+ )+ client.return_value.__aenter__.return_value.post = post+ if operation == "consent":+ result = await upload_openai_consent(+ OpenAIConsentRequest(+ credential_id="credential-a",+ audio_base64="AAEC",+ audio_filename="sample.mp3",+ language="zh",+ name="Test consent",+ ),+ "user-a",+ access,+ )+ endpoint = "voice_consents"+ data = {"name": "Test consent", "language": "zh"}+ file_field = "recording"+ expected = {"consent_id": "created-id"}+ else:+ result = await clone_voice(+ CloneVoiceRequest(+ engine="openai_tts",+ model="gpt-4o-mini-tts",+ credential_id="credential-a",+ audio_base64="AAEC",+ audio_filename="sample.mp3",+ consent="consent-1",+ prefix="Test voice",+ ),+ "user-a",+ access,+ )+ endpoint = "voices"+ data = {+ "name": "Test voice",+ "consent": "consent-1",+ }+ file_field = "audio_sample"+ expected = {+ "voice_id": "created-id",+ "credential_id": "credential-a",+ }+ post.assert_awaited_once_with(+ f"{base_url}/audio/{endpoint}",+ headers={"Authorization": "Bearer test", **headers},+ data=data,+ files={+ file_field: (+ "sample.mp3",+ b"\x00\x01\x02",+ "audio/mpeg",+ ),+ },+ )+ self.assertEqual(result.model_dump(), expected)+++class TestDashScopeVoiceCloneProtocol(IsolatedAsyncioTestCase):+ """Cloning requests use the protocol required by the target model."""++ async def test_clone_request_payloads(self) -> None:+ """Qwen Audio uploads use voice-enrollment without changing peers."""+ cases: list[tuple[str, str, str, dict[str, object]]] = [+ (+ "dashscope_tts",+ f"qwen-audio-{version}-tts-{tier}",+ "voice-enrollment",+ {+ "action": "create_voice",+ "prefix": "testvoice",+ "audio": "data:audio/mpeg;base64,AAEC",+ },+ )+ for version in ("3.0", "3.1")+ for tier in ("flash", "plus")+ ]+ cases.extend(+ [+ (+ "dashscope_tts",+ "qwen3-tts-vc-2026-01-22",+ "qwen-voice-enrollment",+ {+ "action": "create",+ "preferred_name": "testvoice",+ "audio": {"data": "data:audio/mpeg;base64,AAEC"},+ "text": "Sample transcript",+ },+ ),+ (+ "cosyvoice",+ "cosyvoice-v3-plus",+ "voice-enrollment",+ {+ "action": "create_voice",+ "prefix": "testvoice",+ "url": "https://example.com/sample.mp3",+ },+ ),+ ],+ )+ access = AsyncMock()+ access.resolve_credential.return_value = CredentialRecord(+ id="credential-a",+ user_id="user-a",+ data={+ "type": "dashscope_credential",+ "api_key": "test",+ "base_url": (+ "https://workspace.cn-beijing.maas.aliyuncs.com"+ "/compatible-mode/v1"+ ),+ },+ )+ for engine, model, enrollment, expected_input in cases:+ with self.subTest(model=model):+ with patch(+ "agentscope.tts._voice_utils.httpx.AsyncClient",+ ) as client:+ post = AsyncMock(+ return_value=httpx.Response(+ 200,+ json={"output": {"voice_id": "voice-1"}},+ ),+ )+ client.return_value.__aenter__.return_value.post = post+ result = await clone_voice(+ CloneVoiceRequest(+ engine=engine,+ model=model,+ credential_id="credential-a",+ audio_base64="AAEC"+ if engine != "cosyvoice"+ else None,+ audio_filename="sample.mp3",+ audio_url="https://example.com/sample.mp3"+ if engine == "cosyvoice"+ else None,+ text="Sample transcript",+ prefix="testvoice",+ ),+ "user-a",+ access,+ )+ post.assert_awaited_once_with(+ "https://workspace.cn-beijing.maas.aliyuncs.com"+ "/api/v1/services/audio/tts/customization",+ json={+ "model": enrollment,+ "input": {**expected_input, "target_model": model},+ },+ headers={+ "Authorization": "Bearer test",+ "Content-Type": "application/json",+ },+ )+ self.assertEqual(+ result.model_dump(),+ {"voice_id": "voice-1", "credential_id": "credential-a"},+ )+++class TestVoiceProfileUpstreamResponse(IsolatedAsyncioTestCase):+ """Success status codes still require a valid upstream JSON body."""++ async def _request(+ self,+ operation: str,+ response: httpx.Response,+ ) -> dict:+ """Call a voice endpoint with a mocked upstream response."""+ access = AsyncMock()+ access.resolve_credential.return_value = CredentialRecord(+ id="credential-a",+ user_id="user-a",+ data={+ "type": (+ "dashscope_credential"+ if operation == "dashscope"+ else "openai_credential"+ ),+ "api_key": "test",+ },+ )+ with patch(+ "agentscope.tts._voice_utils.httpx.AsyncClient",+ ) as client:+ client.return_value.__aenter__.return_value.post = AsyncMock(+ return_value=response,+ )+ if operation == "consent":+ result = await upload_openai_consent(+ OpenAIConsentRequest(+ credential_id="credential-a",+ audio_base64="AAEC",+ ),+ "user-a",+ access,+ )+ else:+ result = await clone_voice(+ CloneVoiceRequest(+ engine=(+ "cosyvoice"+ if operation == "dashscope"+ else "openai_tts"+ ),+ credential_id="credential-a",+ model="cosyvoice-v3-plus"+ if operation == "dashscope"+ else None,+ audio_url="https://example.com/sample.wav"+ if operation == "dashscope"+ else None,+ audio_base64="AAEC"+ if operation != "dashscope"+ else None,+ consent="consent-1",+ ),+ "user-a",+ access,+ )+ return result.model_dump()++ async def test_non_json_success_returns_bad_gateway(self) -> None:+ """HTML, empty, and malformed success bodies all become HTTP 502."""+ for operation in ("consent", "openai", "dashscope"):+ statuses = (200,) if operation == "dashscope" else (200, 201)+ for code in statuses:+ for body in (b"<html>proxy error</html>", b"", b"{"):+ with self.subTest(+ operation=operation,+ status=code,+ body=body,+ ):+ with self.assertRaises(HTTPException) as ctx:+ await self._request(+ operation,+ httpx.Response(code, content=body),+ )+ provider = (+ "DashScope"+ if operation == "dashscope"+ else "OpenAI"+ )+ self.assertEqual(+ (ctx.exception.status_code, ctx.exception.detail),+ (+ 502,+ f"{provider} returned an invalid JSON "+ "response.",+ ),+ )++ async def test_sdk_errors_keep_http_boundary(self) -> None:+ """SDK input and provider errors become HTTP 400 and 502."""+ for operation, method in (+ ("consent", "OpenAIVoiceCloningClient.create_consent"),+ ("openai", "OpenAIVoiceCloningClient.create_voice"),+ ("dashscope", "DashScopeVoiceCloningClient.create_voice"),+ ):+ for error, status_code in (+ (ValueError("invalid audio"), 400),+ (VoiceCloningError("upstream failure"), 502),+ ):+ with self.subTest(operation=operation, status=status_code):+ with patch(+ f"agentscope.tts.{method}",+ new_callable=AsyncMock,+ side_effect=error,+ ) as create:+ with self.assertRaises(HTTPException) as ctx:+ await self._request(+ operation,+ httpx.Response(200, json={}),+ )+ self.assertEqual(+ (ctx.exception.status_code, ctx.exception.detail),+ (status_code, str(error)),+ )+ self.assertIs(ctx.exception.__cause__, error)+ create.assert_awaited_once()++ async def test_valid_success_preserves_response(self) -> None:+ """Provider ids are still returned in the public response schema."""+ for operation, payload, expected in (+ ("consent", {"id": "consent-1"}, {"consent_id": "consent-1"}),+ (+ "openai",+ {"id": "voice-1"},+ {"voice_id": "voice-1", "credential_id": "credential-a"},+ ),+ (+ "dashscope",+ {"output": {"voice_id": "voice-1"}},+ {"voice_id": "voice-1", "credential_id": "credential-a"},+ ),+ ):+ with self.subTest(operation=operation):+ self.assertEqual(+ await self._request(+ operation,+ httpx.Response(200, json=payload),+ ),+ expected,+ )+++class TestEngineToCredentialMapping(TestCase):+ """Unit tests for ENGINE_TO_CREDENTIAL_TYPE mapping."""++ def test_api_engines_map_correctly(self) -> None:+ """All engines map to their respective credentials."""+ expected = {+ "cosyvoice": "dashscope_credential",+ "dashscope_tts": "dashscope_credential",+ "openai_tts": "openai_credential",+ "gemini_tts": "gemini_credential",+ }+ self.assertEqual(ENGINE_TO_CREDENTIAL_TYPE, expected)++ def test_all_engines_have_mapping(self) -> None:+ """Every _ENGINE_TYPE value has a credential mapping."""+ args = typing.get_args(_ENGINE_TYPE)+ for engine in args:+ self.assertIn(+ engine,+ ENGINE_TO_CREDENTIAL_TYPE,+ f"Missing mapping for engine '{engine}'",+ )+++class TestVoiceAudioLimits(TestCase):+ """Reject oversized uploads before provider requests or extra encoding."""++ def test_base64_and_decoded_size_limits(self) -> None:+ """Boundary-sized audio works; padding cannot hide an extra byte."""+ audio = b"a" * MAX_AUDIO_SIZE_BYTES+ encoded = base64.b64encode(audio).decode("ascii")+ for schema, extra in (+ (CloneVoiceRequest, {"engine": "openai_tts"}),+ (OpenAIConsentRequest, {}),+ ):+ with self.subTest(schema=schema):+ request = schema(+ credential_id="credential-a",+ audio_base64=encoded,+ **extra,+ )+ self.assertEqual(_decode_audio(request.audio_base64), audio)+ with self.assertRaises(ValidationError) as ctx:+ schema(+ credential_id="credential-a",+ audio_base64="a" * (MAX_AUDIO_BASE64_LENGTH + 1),+ **extra,+ )+ self.assertEqual(+ [+ (error["loc"], error["type"])+ for error in ctx.exception.errors()+ ],+ [(("audio_base64",), "string_too_long")],+ )+ oversized = base64.b64encode(audio + b"a").decode("ascii")+ self.assertLessEqual(len(oversized), MAX_AUDIO_BASE64_LENGTH)+ with self.assertRaises(HTTPException) as ctx:+ _decode_audio(oversized)+ self.assertEqual(ctx.exception.status_code, 413)+++class TestEngineCapabilities(IsolatedAsyncioTestCase):+ """Engine discovery follows the credential's SDK capability."""++ async def test_cloning_flag_tracks_credential_client(self) -> None:+ """Changing a credential client changes engine info immediately."""+ access = AsyncMock()+ access.list_resource.return_value = [+ CredentialRecord(+ id="credential-a",+ user_id="user-a",+ data={"type": "openai_credential", "name": "OpenAI"},+ ),+ ]+ card = _model_card(["alloy"], voice_cloning=True).model_copy(+ update={"name": "custom-deployment"},+ )+ for supported in (False, True):+ with self.subTest(supported=supported):+ with (+ patch.object(+ OpenAICredential,+ "get_voice_cloning_client_class",+ return_value=_DemoVoiceCloningClient+ if supported+ else None,+ ),+ patch.object(+ OpenAICredential,+ "list_tts_models",+ return_value=[card],+ ),+ ):+ response = await list_available_engines("user-a", access)+ self.assertEqual(+ response.model_dump(),+ {+ "engine_details": [+ {+ "name": "openai_tts",+ "credential_type": "openai_credential",+ "models": [+ {+ **card.model_dump(),+ "enrollment_model": None,+ },+ ],+ "voice_cloning": supported,+ "credentials": [+ {"id": "credential-a", "label": "OpenAI"},+ ],+ },+ ],+ },+ )++ async def test_dashscope_models_and_enrollment_metadata(self) -> None:+ """Expose SDK models with existing App grouping and owned keys only."""+ access = AsyncMock()+ access.list_resource.return_value = [+ CredentialRecord(+ id="shared",+ user_id="other",+ data={"type": "dashscope_credential", "name": "Shared"},+ ),+ CredentialRecord(+ id="owned",+ user_id="user-a",+ data={"type": "dashscope_credential", "name": "DashScope"},+ ),+ ]+ cases = (+ ("qwen3-tts-flash", True, "qwen-voice-enrollment"),+ ("qwen-audio-3.1-tts-flash", True, "voice-enrollment"),+ ("cosyvoice-v3-plus", True, "voice-enrollment"),+ ("qwen-preset-only", False, None),+ )+ cards = [+ _model_card([], voice_cloning=cloning).model_copy(+ update={"name": name},+ )+ for name, cloning, _ in cases+ ]+ with patch.object(+ DashScopeCredential,+ "list_tts_models",+ return_value=cards,+ ) as load_models:+ response = await list_available_engines("user-a", access)+ load_models.assert_called_once_with()+ expected_models = [+ {**card.model_dump(), "enrollment_model": enrollment}+ for card, (_, _, enrollment) in zip(cards, cases)+ ]+ common = {+ "credential_type": "dashscope_credential",+ "voice_cloning": True,+ "credentials": [{"id": "owned", "label": "DashScope"}],+ }+ self.assertEqual(+ response.model_dump(),+ {+ "engine_details": [+ {+ **common,+ "name": "cosyvoice",+ "models": [expected_models[2]],+ },+ {+ **common,+ "name": "dashscope_tts",+ "models": [+ expected_models[0],+ expected_models[1],+ expected_models[3],+ ],+ },+ ],+ },+ )++ # A later request reloads cards, including an empty updated registry.+ with patch.object(+ DashScopeCredential,+ "list_tts_models",+ return_value=[],+ ) as load_models:+ refreshed = await list_available_engines("user-a", access)+ load_models.assert_called_once_with()+ self.assertEqual(+ refreshed.model_dump(),+ {+ "engine_details": [+ {**common, "name": "cosyvoice", "models": []},+ {**common, "name": "dashscope_tts", "models": []},+ ],+ },+ )++ access.list_resource.return_value = access.list_resource.return_value[+ :1+ ]+ response = await list_available_engines("user-a", access)+ self.assertEqual(response.model_dump(), {"engine_details": []})