PRINTFILM: AI short-video marketing and AI short-drama creation platform
feat(voice): 暂停角色音色生成并保留已有音色使用
yi4efa6603206d
diff --git a/backend/app/api/capabilities.py b/backend/app/api/capabilities.pynew file mode 100644index 0000000..269aa99--- /dev/null+++ b/backend/app/api/capabilities.py@@ -0,0 +1,13 @@+"""Public feature availability without authentication or database access."""++from fastapi import APIRouter++from app.config import get_settings+++router = APIRouter(prefix="/capabilities", tags=["capabilities"])+++async def capabilities() -> dict[str, bool]:+ return {"drama_voice_generation_enabled": get_settings().drama_voice_generation_enabled}diff --git a/backend/app/api/drama/generation.py b/backend/app/api/drama/generation.pyindex 8e2dded..8ac8758 100644--- a/backend/app/api/drama/generation.py+++ b/backend/app/api/drama/generation.py@@ -24,6 +24,7 @@ from app.services.billing import record_llm_chat_line, run_billed_ephemeralfrom app.services.billing.http import http_exception_for_value_errorfrom app.services.drama.jobs import dispatch_asset_image_job, dispatch_asset_video_jobfrom app.services.drama.voice_prompt import suggest_voice_prompt_for_character+from app.services.drama.voice_generation_policy import ensure_voice_generation_enabledrouter = APIRouter()logger = logging.getLogger("app.drama.generation")@@ -175,6 +176,7 @@ async def suggest_voice_prompt(user: User = Depends(get_current_user),) -> dict:"""根据角色设定 AI 生成音色描述提示词。"""+ ensure_voice_generation_enabled()project = await get_owned_drama_project(db, body.project_id, user, with_script=True)asset = await db.get(DramaAsset, body.asset_id)if not asset or asset.project_id != project.id:@@ -236,6 +238,7 @@ async def generate_voice(user: User = Depends(get_current_user),) -> dict:"""按提示词合成 voice 资产参考音频(漫剧独立音色库,非科普 /api/voices)。"""+ ensure_voice_generation_enabled()project = await get_owned_drama_project(db, body.project_id, user, with_script=True)prompt = (body.voice_prompt or "").strip()if not prompt:diff --git a/backend/app/config.py b/backend/app/config.pyindex 74e7ea1..e34d1f0 100644--- a/backend/app/config.py+++ b/backend/app/config.py@@ -66,6 +66,8 @@ class Settings(BaseSettings):drama_user_video_job_limit: int = 12# 单个分镜视频最大尝试次数;超过后直接失败,避免长时间卡在同一镜drama_fragment_max_attempts: int = 3+ # 角色新音色设计暂未开放;已有音色和普通项目配音继续可用。+ drama_voice_generation_enabled: bool = False# 科普 full:Seedance 视频内置口播+环境音,后期不再叠外部 TTSkepu_seedance_native_audio: bool = True# 仅当 native_audio=false 时生效:Seedance 只要操作音效,口播改后期 TTS(默认开)diff --git a/backend/app/main.py b/backend/app/main.pyindex dcff355..841f7bf 100644--- a/backend/app/main.py+++ b/backend/app/main.py@@ -8,7 +8,7 @@ from fastapi.staticfiles import StaticFilesfrom sqlalchemy import select, textfrom sqlalchemy.ext.asyncio import AsyncEngine-from app.api import auth, billing, creation, projects, tasks, templates, tools+from app.api import auth, billing, capabilities, creation, projects, tasks, templates, toolsfrom app.api import teams, team_billing, team_content, team_edit_locksfrom app.api.admin import router as admin_routerfrom app.api.drama import router as drama_router@@ -107,6 +107,7 @@ static_dir.mkdir(parents=True, exist_ok=True)app.mount("/static", StaticFiles(directory=str(static_dir)), name="static")app.include_router(auth.router, prefix="/api")+app.include_router(capabilities.router, prefix="/api")app.include_router(templates.router, prefix="/api")app.include_router(projects.router, prefix="/api")app.include_router(creation.router, prefix="/api")diff --git a/backend/app/services/billing/ephemeral.py b/backend/app/services/billing/ephemeral.pyindex 88dc693..ee9320a 100644--- a/backend/app/services/billing/ephemeral.py+++ b/backend/app/services/billing/ephemeral.py@@ -17,6 +17,7 @@ from sqlalchemy import selectfrom app.config import get_settingsfrom app.services.billing.context import billing_scopefrom app.services.billing.settlement import freeze_for_task, settle_task+from app.services.drama.voice_generation_policy import ensure_voice_generation_task_enabledfrom app.services.tasks.handlers import get_task_handlerfrom app.services.tasks.inline import hold_inline_lease, start_inline_leasefrom app.services.tasks.queues import task_queue@@ -41,6 +42,7 @@ async def create_ephemeral_task_row(episode_id: int | None = None,) -> TaskRun:"""创建并立即执行的轻量任务行(不经过调度器排队)。"""+ ensure_voice_generation_task_enabled(domain, task_type)payload = {key: value for key, value in (payload or {}).items() if not key.startswith("_team_")}if drama_project_id is not None:from app.services.tasks.team_scope import prepare_background_taskdiff --git a/backend/app/services/drama/voice_generation_policy.py b/backend/app/services/drama/voice_generation_policy.pynew file mode 100644index 0000000..3c712ee--- /dev/null+++ b/backend/app/services/drama/voice_generation_policy.py@@ -0,0 +1,18 @@+"""Admission switch for new character voice design; running work is unaffected."""++from fastapi import HTTPException++from app.config import get_settings+++VOICE_GENERATION_TASK_TYPES = frozenset({"voice_prompt", "voice_synthesis"})+++def ensure_voice_generation_enabled() -> None:+ if not get_settings().drama_voice_generation_enabled:+ raise HTTPException(status_code=409, detail="音色生成功能暂未开放")+++def ensure_voice_generation_task_enabled(domain: str, task_type: str) -> None:+ if domain == "drama" and task_type in VOICE_GENERATION_TASK_TYPES:+ ensure_voice_generation_enabled()diff --git a/backend/app/services/tasks/service.py b/backend/app/services/tasks/service.pyindex 3c3aebf..626e4a1 100644--- a/backend/app/services/tasks/service.py+++ b/backend/app/services/tasks/service.py@@ -18,6 +18,7 @@ from app.schemas_tasks import TaskCreateRequest, TaskEventCreate, TaskStepCreatefrom app.services.tasks.handlers import get_task_handlerfrom app.services.tasks.queues import task_queuefrom app.services.tasks.execution_policy import is_direct_llm_task, llm_task_condition+from app.services.drama.voice_generation_policy import ensure_voice_generation_task_enabledlogger = logging.getLogger("app.tasks.service")@@ -124,6 +125,7 @@ async def create_task(commit: bool = True,) -> TaskRun:"""创建任务;文字 LLM 提交后立即执行,媒体任务留给调度器。"""+ ensure_voice_generation_task_enabled(body.domain, body.task_type)if body.payload is not None:body.payload = {key: value for key, value in body.payload.items() if not key.startswith("_team_")}if body.drama_project_id is not None:diff --git a/backend/tests/test_generation_task_registration.py b/backend/tests/test_generation_task_registration.pyindex b057346..236c850 100644--- a/backend/tests/test_generation_task_registration.py+++ b/backend/tests/test_generation_task_registration.py@@ -12,6 +12,13 @@ from app.models_tasks import TaskRunfrom app.services.billing import ephemeral+def voice_generation_enabled(monkeypatch):+ from app.config import get_settings++ monkeypatch.setattr(get_settings(), "drama_voice_generation_enabled", True)++def inline_runtime(monkeypatch):task = TaskRun(id=42, status="pending", payload={})db = SimpleNamespace(flush=AsyncMock(), commit=AsyncMock(), refresh=AsyncMock())@@ -52,7 +59,7 @@ async def test_inline_failure_remains_after_callers_rollback(monkeypatch):@pytest.mark.asyncio-async def test_unbilled_generation_tracks_output_without_new_charges(monkeypatch):+async def test_unbilled_generation_tracks_output_without_new_charges(monkeypatch, voice_generation_enabled):db, task = inline_runtime(monkeypatch)_, result = await ephemeral.run_billed_ephemeral(db, SimpleNamespace(id=1), domain="drama", task_type="voice_synthesis",@@ -94,7 +101,9 @@ async def test_generated_text_is_saved_in_task_result(monkeypatch):@pytest.mark.asyncio@pytest.mark.parametrize("fail", [False, True])-async def test_personal_voice_generation_has_one_durable_task_without_charging(db_session, monkeypatch, fail):+async def test_personal_voice_generation_has_one_durable_task_without_charging(+ db_session, monkeypatch, fail, voice_generation_enabled,+):from app.api.drama import generationfrom app.models_drama import DramaAsset, DramaProjectfrom app.schemas_drama import DramaVoiceGenerateRequestdiff --git a/backend/tests/test_team_voice_billing.py b/backend/tests/test_team_voice_billing.pyindex e11029f..6699d41 100644--- a/backend/tests/test_team_voice_billing.py+++ b/backend/tests/test_team_voice_billing.py@@ -9,6 +9,13 @@ from app.schemas_drama import DramaVoiceGenerateRequestfrom app.api.drama import generation[email protected](autouse=True)+def enable_voice_generation(monkeypatch):+ from app.config import get_settings++ monkeypatch.setattr(get_settings(), "drama_voice_generation_enabled", True)++@pytest.mark.asyncio@pytest.mark.parametrize("team_id", [None, 91])async def test_voice_endpoint_registers_all_tasks_and_bills_only_team(monkeypatch, team_id):diff --git a/backend/tests/test_voice_generation_feature.py b/backend/tests/test_voice_generation_feature.pynew file mode 100644index 0000000..cb06493--- /dev/null+++ b/backend/tests/test_voice_generation_feature.py@@ -0,0 +1,135 @@+"""Temporarily closed voice design must reject new work before any side effects."""++from types import SimpleNamespace+from unittest.mock import AsyncMock, Mock++import httpx+import pytest+from fastapi import FastAPI, HTTPException++from app.api.drama import generation+from app.config import Settings, get_settings+from app.database import get_db+from app.deps import get_current_user+from app.models import User+from app.models_drama import DramaAsset, DramaProject+from app.schemas_tasks import TaskCreateRequest+from app.services.billing import ephemeral+from app.services.tasks import service+++UNAVAILABLE = "音色生成功能暂未开放"+++def voice_api(monkeypatch):+ settings = get_settings()+ monkeypatch.setitem(settings.__dict__, "drama_voice_generation_enabled", False)+ user = User(id=2)+ project = DramaProject(id=17, user_id=user.id, team_id=None)+ asset = DramaAsset(id=8, project_id=17, type="voice", asset_type="audio",+ name="已有音色", url="/static/existing.mp3", params={})+ db = SimpleNamespace(get=AsyncMock(return_value=asset), add=Mock(), flush=AsyncMock(),+ commit=AsyncMock(), refresh=AsyncMock(), rollback=AsyncMock())+ db.add.side_effect = lambda value: setattr(value, "id", 8)+ lookup = AsyncMock(return_value=project)+ monkeypatch.setattr(generation, "get_owned_drama_project", lookup)+ prompt = AsyncMock(return_value=("沉稳的声音", "Cherry", "试听句"))+ synthesize = AsyncMock(return_value=asset)+ monkeypatch.setattr(generation, "suggest_voice_prompt_for_character", prompt)+ monkeypatch.setattr(generation, "generate_voice_asset_audio", synthesize)++ async def register(_db, _user, **kwargs):+ if kwargs["task_type"] == "voice_prompt":+ return SimpleNamespace(id=1), ("沉稳的声音", "Cherry", "试听句")+ return SimpleNamespace(id=1), asset++ billing = AsyncMock(side_effect=register)+ monkeypatch.setattr(generation, "run_billed_ephemeral", billing)+ app = FastAPI()+ app.include_router(generation.router, prefix="/api/drama")+ app.dependency_overrides[get_db] = lambda: db+ app.dependency_overrides[get_current_user] = lambda: user+ return SimpleNamespace(app=app, settings=settings, project=project, asset=asset, db=db,+ lookup=lookup, prompt=prompt, synthesize=synthesize, billing=billing)+++def test_voice_generation_defaults_to_closed(monkeypatch):+ monkeypatch.delenv("DRAMA_VOICE_GENERATION_ENABLED", raising=False)+ assert Settings(_env_file=None, debug=False).drama_voice_generation_enabled is False++[email protected]("team_id", [None, 91])[email protected]("path,payload", [+ ("voice_prompt", {"asset_id": 8}),+ ("voice", {"asset_id": 8, "voice_prompt": "沉稳的声音"}),+ ("voice", {"voice_prompt": "新的声音"}),+])+async def test_closed_voice_endpoints_reject_before_assets_tasks_billing_or_upstream(+ voice_api, team_id, path, payload,+):+ api = voice_api+ api.project.team_id = team_id+ if path == "voice_prompt":+ api.asset.type = "character"+ async with httpx.AsyncClient(transport=httpx.ASGITransport(api.app), base_url="http://test") as client:+ response = await client.post(f"/api/drama/generation/{path}", json={"project_id": 17, **payload})+ assert response.status_code == 409+ assert response.json() == {"detail": UNAVAILABLE}+ api.lookup.assert_not_awaited()+ api.db.get.assert_not_awaited()+ api.db.add.assert_not_called()+ api.db.flush.assert_not_awaited()+ api.db.commit.assert_not_awaited()+ api.billing.assert_not_awaited()+ api.prompt.assert_not_awaited()+ api.synthesize.assert_not_awaited()+ assert api.asset.params == {} and api.asset.url == "/static/existing.mp3"++[email protected]("task_type", ["voice_prompt", "voice_synthesis"])[email protected]("entry", ["queued", "inline"])+async def test_closed_voice_generation_cannot_bypass_api_via_task_admission(voice_api, monkeypatch, task_type, entry):+ scope = AsyncMock(side_effect=AssertionError("closed requests must not reach task admission"))+ monkeypatch.setattr(service, "_validate_task_scope", scope)+ with pytest.raises(HTTPException) as error:+ if entry == "queued":+ await service.create_task(voice_api.db, User(id=2), TaskCreateRequest(domain="drama", task_type=task_type))+ else:+ await ephemeral.create_ephemeral_task_row(voice_api.db, User(id=2), domain="drama", task_type=task_type)+ assert error.value.status_code == 409 and error.value.detail == UNAVAILABLE+ scope.assert_not_awaited()+ voice_api.db.add.assert_not_called()+ voice_api.db.commit.assert_not_awaited()++[email protected]("enabled", [False, True])+async def test_public_capabilities_exposes_voice_switch_without_authentication_or_database(monkeypatch, enabled):+ from app.main import app++ monkeypatch.setitem(get_settings().__dict__, "drama_voice_generation_enabled", enabled)+ database = Mock(side_effect=AssertionError("public capabilities must not open a database session"))+ monkeypatch.setitem(app.dependency_overrides, get_db, database)+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app), base_url="http://test") as client:+ response = await client.get("/api/capabilities")+ assert response.status_code == 200+ assert response.json() == {"drama_voice_generation_enabled": enabled}+ database.assert_not_called()+++async def test_voice_request_already_admitted_can_finish_after_switch_closes(voice_api, monkeypatch):+ api = voice_api+ monkeypatch.setitem(api.settings.__dict__, "drama_voice_generation_enabled", True)++ async def register(_db, _user, **kwargs):+ monkeypatch.setitem(api.settings.__dict__, "drama_voice_generation_enabled", False)+ return SimpleNamespace(id=1), await kwargs["executor"]()++ api.billing.side_effect = register+ async with httpx.AsyncClient(transport=httpx.ASGITransport(api.app), base_url="http://test") as client:+ response = await client.post("/api/drama/generation/voice", json={+ "project_id": 17, "asset_id": 8, "voice_prompt": "沉稳的声音",+ })+ assert response.status_code == 200+ assert response.json()["asset"]["url"] == "/static/existing.mp3"+ api.synthesize.assert_awaited_once()diff --git a/frontend/src/api/drama.ts b/frontend/src/api/drama.tsindex b152b74..de0b299 100644--- a/frontend/src/api/drama.ts+++ b/frontend/src/api/drama.ts@@ -1,5 +1,6 @@import { throwApiError } from '../lib/apiError'import { API_BASE, createJsonRequester } from './client'+import { ensureCharacterVoiceGenerationEnabled } from './publicCapabilities'import { withDramaEditLock, recordDramaResponse } from '../features/teams/editLocks'import { teamsApi } from './teams'import { projectTeam } from '../features/teams/editLocks'@@ -574,7 +575,7 @@ export const dramaApi = {body: JSON.stringify(body),}),- generateVoice: (body: {+ generateVoice: async (body: {project_id: numberasset_id?: numbername?: string@@ -582,17 +583,21 @@ export const dramaApi = {sample_text?: stringspeaker?: stringcharacter_asset_id?: number- }) =>- request<DramaVoiceGenerateResult>('/api/drama/generation/voice', {+ }) => {+ await ensureCharacterVoiceGenerationEnabled()+ return request<DramaVoiceGenerateResult>('/api/drama/generation/voice', {method: 'POST',body: JSON.stringify(body),- }),+ })+ },- suggestVoicePrompt: (body: { project_id: number; asset_id: number }) =>- request<DramaVoicePromptResult>('/api/drama/generation/voice_prompt', {+ suggestVoicePrompt: async (body: { project_id: number; asset_id: number }) => {+ await ensureCharacterVoiceGenerationEnabled()+ return request<DramaVoicePromptResult>('/api/drama/generation/voice_prompt', {method: 'POST',body: JSON.stringify(body),- }),+ })+ },getCanvas: (projectId: number) =>request<{ project_id: number; nodes: unknown[]; edges: unknown[] }>(diff --git a/frontend/src/api/publicCapabilities.ts b/frontend/src/api/publicCapabilities.tsnew file mode 100644index 0000000..06c8cc1--- /dev/null+++ b/frontend/src/api/publicCapabilities.ts@@ -0,0 +1,13 @@+import { createJsonRequester } from './client'+import { requireCharacterVoiceGeneration, type PublicCapabilities } from '../lib/publicCapabilities'++const request = createJsonRequester(() => { throw new Error('无法读取功能状态') })++export function getPublicCapabilities(): Promise<PublicCapabilities> {+ return request('/api/capabilities')+}++/** Check the server again at action time; a previously opened form is not authorization. */+export function ensureCharacterVoiceGenerationEnabled(): Promise<void> {+ return requireCharacterVoiceGeneration(getPublicCapabilities)+}diff --git a/frontend/src/hooks/usePublicCapabilities.ts b/frontend/src/hooks/usePublicCapabilities.tsnew file mode 100644index 0000000..1cccff7--- /dev/null+++ b/frontend/src/hooks/usePublicCapabilities.ts@@ -0,0 +1,35 @@+import { useEffect, useState } from 'react'+import { getPublicCapabilities } from '../api/publicCapabilities'+import { characterVoiceGenerationEnabled } from '../lib/publicCapabilities'++let enabled = false+let inflight: Promise<void> | null = null+const listeners = new Set<(value: boolean) => void>()++function refresh(): Promise<void> {+ if (!inflight) {+ inflight = getPublicCapabilities().then(characterVoiceGenerationEnabled).catch(() => false).then(value => {+ enabled = value+ listeners.forEach(receive => receive(value))+ }).finally(() => { inflight = null })+ }+ return inflight+}++/** Existing bindings remain available; only new AI voice creation follows this capability. */+export function useCharacterVoiceGenerationEnabled(): boolean {+ const [allowed, setAllowed] = useState(enabled)+ useEffect(() => {+ listeners.add(setAllowed)+ void refresh()+ const update = () => { void refresh() }+ const timer = window.setInterval(update, 60_000)+ window.addEventListener('focus', update)+ return () => {+ listeners.delete(setAllowed)+ window.clearInterval(timer)+ window.removeEventListener('focus', update)+ }+ }, [])+ return allowed+}diff --git a/frontend/src/lib/characterVoiceGenerate.ts b/frontend/src/lib/characterVoiceGenerate.tsindex a824d49..a31a387 100644--- a/frontend/src/lib/characterVoiceGenerate.ts+++ b/frontend/src/lib/characterVoiceGenerate.ts@@ -1,6 +1,7 @@/** 按角色设定 AI 生成音色并绑定到 voiceAudio(无弹窗,供卡片一键生成) */import { dramaApi, type DramaAsset } from '../api/drama'import { buildBoundParams } from '../pages/drama/CharacterVoiceBindModal'+import { ensureCharacterVoiceGenerationEnabled } from '../api/publicCapabilities'export type CharacterVoiceGenerateResult = {character: DramaAsset@@ -12,6 +13,7 @@ export async function generateAndBindCharacterVoice(projectId: number,asset: DramaAsset,): Promise<CharacterVoiceGenerateResult> {+ await ensureCharacterVoiceGenerationEnabled()const promptResult = await dramaApi.suggestVoicePrompt({project_id: projectId,asset_id: asset.id,diff --git a/frontend/src/lib/publicCapabilities.ts b/frontend/src/lib/publicCapabilities.tsnew file mode 100644index 0000000..7d42549--- /dev/null+++ b/frontend/src/lib/publicCapabilities.ts@@ -0,0 +1,14 @@+export type PublicCapabilities = { drama_voice_generation_enabled: boolean }++export const VOICE_GENERATION_DISABLED_MESSAGE = '音色生成暂时停用,可选择已有音色或上传音频。'++export function characterVoiceGenerationEnabled(value: unknown): boolean {+ return value !== null && typeof value === 'object' &&+ 'drama_voice_generation_enabled' in value && value.drama_voice_generation_enabled === true+}++/** Failed or older capability responses must never enable a paid generation call. */+export async function requireCharacterVoiceGeneration(load: () => Promise<unknown>): Promise<void> {+ const capabilities = await load().catch(() => null)+ if (!characterVoiceGenerationEnabled(capabilities)) throw new Error(VOICE_GENERATION_DISABLED_MESSAGE)+}diff --git a/frontend/src/pages/drama/AssetsStep.tsx b/frontend/src/pages/drama/AssetsStep.tsxindex 6c816f0..e059184 100644--- a/frontend/src/pages/drama/AssetsStep.tsx+++ b/frontend/src/pages/drama/AssetsStep.tsx@@ -33,6 +33,8 @@ import { pageCountOf } from '../../lib/pagination'import { readVisualPrompt } from '../../lib/dramaVisualPrompt'import { filterDramaLibraryAssets } from '../../lib/dramaLibraryAssets'import { DRAMA_VOICE_BINDING_ENABLED } from '../../lib/dramaVoiceBinding'+import { useCharacterVoiceGenerationEnabled } from '../../hooks/usePublicCapabilities'+import { VOICE_GENERATION_DISABLED_MESSAGE } from '../../lib/publicCapabilities'import {dramaAssetImageGenButtonLabel,dramaAssetNeedsImageGeneration,@@ -70,6 +72,7 @@ function needsImageGeneration(asset: DramaAsset): boolean {// 渲染资产库步骤export function AssetsStep({ projectId, onError }: AssetsStepProps) {+ const voiceGenerationEnabled = useCharacterVoiceGenerationEnabled()/** assets 项目资产* tab 当前分类@@ -368,6 +371,7 @@ export function AssetsStep({ projectId, onError }: AssetsStepProps) {// 一键 AI 生成音色并绑定(各角色独立 busy,互不阻塞)async function handleGenerateCharacterVoice(asset: DramaAsset) {+ if (!voiceGenerationEnabled) { onError(VOICE_GENERATION_DISABLED_MESSAGE); return }if (characterVoiceBusyIds.has(asset.id) || batchVoiceBusy) returnsetCharacterVoiceBusyIds((prev) => new Set(prev).add(asset.id))try {@@ -387,6 +391,7 @@ export function AssetsStep({ projectId, onError }: AssetsStepProps) {// 批量按角色设定生成音色async function batchGenerateCharacterVoices() {+ if (!voiceGenerationEnabled) { onError(VOICE_GENERATION_DISABLED_MESSAGE); return }if (batchVoiceBusy || selectedCharacterAssets.length === 0) returnconst ok = await dialog.confirm({title: '批量生成音色',@@ -471,6 +476,7 @@ export function AssetsStep({ projectId, onError }: AssetsStepProps) {// 按提示词合成 voice 资产试听async function handleSynthVoice(asset: DramaAsset) {+ if (!voiceGenerationEnabled) { onError(VOICE_GENERATION_DISABLED_MESSAGE); return }const prompt = (voicePromptDrafts[asset.id] ?? readVoicePrompt(asset)).trim()if (!prompt) {onError('请先填写音色描述')@@ -748,7 +754,7 @@ export function AssetsStep({ projectId, onError }: AssetsStepProps) {</button>) : null}- {DRAMA_VOICE_BINDING_ENABLED && tab === 'character' ? (+ {DRAMA_VOICE_BINDING_ENABLED && voiceGenerationEnabled && tab === 'character' ? (<buttontype="button"className="pf-btn pf-btn-lime"@@ -811,7 +817,7 @@ export function AssetsStep({ projectId, onError }: AssetsStepProps) {)}}}- onSynth={() => void handleSynthVoice(asset)}+ onSynth={voiceGenerationEnabled ? () => void handleSynthVoice(asset) : undefined}onDelete={() => void handleDeleteVoice(asset)}onError={onError}/>@@ -833,7 +839,7 @@ export function AssetsStep({ projectId, onError }: AssetsStepProps) {onOpen={() => setDetailAsset(asset)}actions={<>{mediaSrc && <button type="button" className="pf-btn pf-btn-sm" onClick={() => setPreviewAsset(asset)}>查看大图</button>}- {tab === 'character' && isCharacter ? (+ {voiceGenerationEnabled && tab === 'character' && isCharacter ? (<labelclassName="drama-voice-multi-select"style={{ display: 'inline-flex', gap: 8, alignItems: 'center', marginRight: 8, cursor: 'pointer' }}@@ -870,7 +876,7 @@ export function AssetsStep({ projectId, onError }: AssetsStepProps) {label={voice.label}onError={onError}/>- ) : (+ ) : voiceGenerationEnabled ? (<buttontype="button"className="pf-btn pf-btn-sm pf-btn-lime"@@ -883,7 +889,7 @@ export function AssetsStep({ projectId, onError }: AssetsStepProps) {>{characterVoiceBusyIds.has(asset.id) ? '生成中…' : '生成音色'}</button>- )+ ) : null) : null}<buttontype="button"diff --git a/frontend/src/pages/drama/CharacterVoiceBindModal.tsx b/frontend/src/pages/drama/CharacterVoiceBindModal.tsxindex 65b3231..274ceea 100644--- a/frontend/src/pages/drama/CharacterVoiceBindModal.tsx+++ b/frontend/src/pages/drama/CharacterVoiceBindModal.tsx@@ -3,6 +3,8 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { dramaApi, resolveDramaMediaUrl, type DramaAsset } from '../../api/drama'import Modal from '../../components/ui/Modal'import { AssetCard, AssetEmpty, AssetGrid, AssetTypeFilter } from '../../components/assets/AssetLibrary'+import { useCharacterVoiceGenerationEnabled } from '../../hooks/usePublicCapabilities'+import { VOICE_GENERATION_DISABLED_MESSAGE } from '../../lib/publicCapabilities'const AUDIO_ACCEPT = 'audio/mpeg,audio/mp3,audio/wav,audio/x-wav,audio/mp4,audio/m4a,.mp3,.wav,.m4a'@@ -115,6 +117,7 @@ export function CharacterVoiceBindModal({onBound,onError,}: Props) {+ const voiceGenerationEnabled = useCharacterVoiceGenerationEnabled()/** voiceAssets 项目内 voice/audio 资产* selectedId 选中音色@@ -142,6 +145,7 @@ export function CharacterVoiceBindModal({// 根据角色设定 AI 生成音色描述const fetchVoicePrompt = useCallback(async (force = false) => {+ if (!voiceGenerationEnabled) returnif (promptBusy) returnif (!force && newPrompt.trim()) returnsetPromptBusy(true)@@ -158,7 +162,7 @@ export function CharacterVoiceBindModal({setPromptBusy(false)}},- [asset.id, newPrompt, onError, projectId, promptBusy],+ [asset.id, newPrompt, onError, projectId, promptBusy, voiceGenerationEnabled],)useEffect(() => {@@ -190,10 +194,14 @@ export function CharacterVoiceBindModal({// 进入「AI 合成」时自动生成音色描述useEffect(() => {- if (!open || mode !== 'create' || promptRequestedRef.current) return+ if (!open || !voiceGenerationEnabled || mode !== 'create' || promptRequestedRef.current) returnpromptRequestedRef.current = truevoid fetchVoicePrompt(true)- }, [open, mode, fetchVoicePrompt])+ }, [open, mode, fetchVoicePrompt, voiceGenerationEnabled])++ useEffect(() => {+ if (!voiceGenerationEnabled && mode === 'create') setMode('pick')+ }, [voiceGenerationEnabled, mode])if (!open) return null@@ -234,6 +242,7 @@ export function CharacterVoiceBindModal({// 按提示词新建并合成 voice 资产async function handleCreateAndSynth() {+ if (!voiceGenerationEnabled) { onError(VOICE_GENERATION_DISABLED_MESSAGE); return }const prompt = newPrompt.trim()if (!prompt || synthBusy) returnsetSynthBusy(true)@@ -259,6 +268,7 @@ export function CharacterVoiceBindModal({// 对已有 voice 资产重新合成async function handleResynth(voice: DramaAsset) {+ if (!voiceGenerationEnabled) { onError(VOICE_GENERATION_DISABLED_MESSAGE); return }const prompt = readVoicePrompt(voice)if (!prompt || synthBusy) returnsetSynthBusy(true)@@ -358,8 +368,8 @@ export function CharacterVoiceBindModal({}><p className="drama-muted">- 给「{asset.name || '角色'}」配上说话声音。选一段试听、上传录音,或用 AI- 合成都可以。之后生成带对白的镜头时,会尽量按这段声音来念。+ 给「{asset.name || '角色'}」配上说话声音。选择已有音色或上传录音{voiceGenerationEnabled ? ',也可用 AI 合成' : ''}。+ 之后生成带对白的镜头时,会尽量按这段声音来念。</p><p className="drama-muted" style={{ marginTop: -6, fontSize: 12 }}>画布里也可以把「音频」节点连到角色,效果一样。@@ -367,7 +377,7 @@ export function CharacterVoiceBindModal({<div className="pf-library-toolbar"><AssetTypeFilter- options={[{ value: 'pick', label: '选择已有' }, { value: 'upload', label: '上传音频' }, { value: 'create', label: 'AI 合成' }] as const}+ options={[{ value: 'pick', label: '选择已有' }, { value: 'upload', label: '上传音频' }, ...(voiceGenerationEnabled ? [{ value: 'create' as const, label: 'AI 合成' }] : [])] as const}value={mode}disabled={anyBusy}ariaLabel="音色来源"@@ -378,7 +388,7 @@ export function CharacterVoiceBindModal({{mode === 'pick' ? (<AssetGrid picker>{voiceAssets.length === 0 ? (- <AssetEmpty>还没有可用音色,请先「上传音频」或「AI 合成」。</AssetEmpty>+ <AssetEmpty>还没有可用音色,请先「上传音频」{voiceGenerationEnabled ? '或「AI 合成」' : ''}。</AssetEmpty>) : (voiceAssets.map((voice) => {const hasAudio = Boolean(voice.url)@@ -396,7 +406,7 @@ export function CharacterVoiceBindModal({subtitle={statusLabel}footer="项目音色"onOpen={() => setSelectedId(voice.id)}- actions={hasAudio && canResynth ? <>+ actions={voiceGenerationEnabled && hasAudio && canResynth ? <><buttontype="button"className="pf-btn pf-btn-sm"@@ -438,7 +448,7 @@ export function CharacterVoiceBindModal({{uploadBusy ? '上传中…' : '选择音频文件'}</button></div>- ) : (+ ) : voiceGenerationEnabled ? (<div className="drama-voice-create-form"><label className="drama-field"><span>音色名称</span>@@ -487,7 +497,7 @@ export function CharacterVoiceBindModal({{synthBusy ? '合成中…' : '合成试听'}</button></div>- )}+ ) : null}{previewUrl ? (<audio className="drama-voice-audio" controls src={previewUrl} />diff --git a/frontend/src/pages/drama/DramaVoiceAssetCard.tsx b/frontend/src/pages/drama/DramaVoiceAssetCard.tsxindex 5764697..02e01d1 100644--- a/frontend/src/pages/drama/DramaVoiceAssetCard.tsx+++ b/frontend/src/pages/drama/DramaVoiceAssetCard.tsx@@ -10,7 +10,7 @@ type Props = {synthBusy: booleanonPromptChange: (value: string) => voidonPromptBlur: () => void- onSynth: () => void+ onSynth?: () => voidonDelete: () => voidonError: (message: string) => void}@@ -39,9 +39,9 @@ export function DramaVoiceAssetCard({status={synthBusy ? '合成中' : hasAudio ? '已合成' : '待合成'}actions={<>{hasAudio && <CharacterVoicePreviewButton url={asset.url || ''} label={asset.name || undefined} variant="button" size="sm" onError={onError} />}- <button type="button" className="pf-btn pf-btn-lime pf-btn-sm" disabled={synthBusy || !promptValue.trim()} onClick={onSynth}>+ {onSynth && <button type="button" className="pf-btn pf-btn-lime pf-btn-sm" disabled={synthBusy || !promptValue.trim()} onClick={onSynth}>{synthBusy ? '合成中…' : hasAudio ? '重新合成' : '按提示词合成'}- </button>+ </button>}<button type="button" className="pf-btn pf-btn-sm drama-btn-danger-text" aria-label={`删除 ${asset.name || '音色'}`} disabled={synthBusy} onClick={onDelete}><Trash2 size={14} />删除</button></>}>diff --git a/frontend/src/pages/drama/EpisodeEditAssetPanel.tsx b/frontend/src/pages/drama/EpisodeEditAssetPanel.tsxindex b485b14..244886f 100644--- a/frontend/src/pages/drama/EpisodeEditAssetPanel.tsx+++ b/frontend/src/pages/drama/EpisodeEditAssetPanel.tsx@@ -3,6 +3,7 @@ import { type DramaAsset } from '../../api/drama'import { AssetCard, AssetEmpty, AssetGrid, AssetTypeFilter } from '../../components/assets/AssetLibrary'import { CharacterVoicePreviewButton } from '../../components/drama/CharacterVoicePreviewButton'import { readAssetVoiceBinding } from './CharacterVoiceBindModal'+import { useCharacterVoiceGenerationEnabled } from '../../hooks/usePublicCapabilities'import {ASSET_TABS,normalizeAssetTab,@@ -64,6 +65,7 @@ export function EpisodeEditAssetPanel({onCreateAsset,onImportAsset,}: Props) {+ const voiceGenerationEnabled = useCharacterVoiceGenerationEnabled()return (<aside className="drama-ep-assets"><div className="drama-ep-assets-top">@@ -163,7 +165,7 @@ export function EpisodeEditAssetPanel({插入</button>)}- {isCharacter && onGenerateVoice ? (+ {isCharacter ? (voice ? (<CharacterVoicePreviewButtonurl={voice.url}@@ -172,7 +174,7 @@ export function EpisodeEditAssetPanel({className="drama-ep-asset-voice-btn is-bound"onError={onVoiceError}/>- ) : (+ ) : voiceGenerationEnabled && onGenerateVoice ? (<buttontype="button"className="drama-ep-asset-voice-btn"@@ -181,7 +183,7 @@ export function EpisodeEditAssetPanel({>{voiceGenerating ? '生成中…' : '生成音色'}</button>- )+ ) : null) : null}</>}/>diff --git a/frontend/src/pages/drama/canvas/nodes/CanvasNodeUploadBar.tsx b/frontend/src/pages/drama/canvas/nodes/CanvasNodeUploadBar.tsxindex 8e98680..ad30918 100644--- a/frontend/src/pages/drama/canvas/nodes/CanvasNodeUploadBar.tsx+++ b/frontend/src/pages/drama/canvas/nodes/CanvasNodeUploadBar.tsx@@ -5,6 +5,8 @@ import { dramaApi, type DramaAsset } from '../../../../api/drama'import { CharacterVoicePreviewButton } from '../../../../components/drama/CharacterVoicePreviewButton'import { generateAndBindCharacterVoice } from '../../../../lib/characterVoiceGenerate'import { DRAMA_VOICE_BINDING_ENABLED } from '../../../../lib/dramaVoiceBinding'+import { useCharacterVoiceGenerationEnabled } from '../../../../hooks/usePublicCapabilities'+import { VOICE_GENERATION_DISABLED_MESSAGE } from '../../../../lib/publicCapabilities'import { CharacterVoiceBindModal } from '../../CharacterVoiceBindModal'import { useCanvasStore } from '../CanvasStore'import { CANVAS_UPLOADABLE_KINDS, type CanvasNodeKind } from '../canvasTypes'@@ -33,6 +35,7 @@ export function CanvasNodeUploadBar({voiceLabel,voiceUrl,}: CanvasNodeUploadBarProps) {+ const voiceGenerationEnabled = useCharacterVoiceGenerationEnabled()/** uploading 本地上传中* pickerOpen 资产库弹窗@@ -124,6 +127,7 @@ export function CanvasNodeUploadBar({/** 一键 AI 生成音色并绑定到角色节点 */async function handleGenerateVoice() {+ if (!voiceGenerationEnabled) { setErrorMessage(VOICE_GENERATION_DISABLED_MESSAGE); return }if (voiceLoading) returnsetVoiceLoading(true)try {@@ -196,7 +200,7 @@ export function CanvasNodeUploadBar({</>) : (<>- <button+ {voiceGenerationEnabled && <buttontype="button"className="fc-toolbar-chip"disabled={toolbarBusy}@@ -209,7 +213,7 @@ export function CanvasNodeUploadBar({<AudioLines size={14} strokeWidth={1.8} />)}{voiceLoading ? '生成中…' : '生成音色'}- </button>+ </button>}<buttontype="button"className="fc-toolbar-chip"diff --git a/frontend/tests/character-voice-capabilities.test.mjs b/frontend/tests/character-voice-capabilities.test.mjsnew file mode 100644index 0000000..25d30f6--- /dev/null+++ b/frontend/tests/character-voice-capabilities.test.mjs@@ -0,0 +1,25 @@+import assert from 'node:assert/strict'+import test from 'node:test'+import { characterVoiceGenerationEnabled, requireCharacterVoiceGeneration } from '../src/lib/publicCapabilities.ts'++test('new voice generation requires the explicit server capability, independent of existing voice binding', () => {+ for (const value of [null, undefined, {}, { drama_voice_generation_enabled: false }, { drama_voice_generation_enabled: 'true' }, { drama_voice_binding_enabled: true }]) {+ assert.equal(characterVoiceGenerationEnabled(value), false)+ }+ assert.equal(characterVoiceGenerationEnabled({ drama_voice_generation_enabled: true }), true)+})++test('disabled or unavailable capability rejects before any prompt, synthesis, or binding work', async () => {+ let generated = 0+ for (const load of [async () => ({}), async () => ({ drama_voice_generation_enabled: false }), async () => { throw new Error('network unavailable') }]) {+ await assert.rejects(async () => {+ await requireCharacterVoiceGeneration(load)+ generated += 1+ }, /音色生成暂时停用/)+ }+ assert.equal(generated, 0)+})++test('explicitly enabled capability permits generation without altering unrelated capabilities', async () => {+ await requireCharacterVoiceGeneration(async () => ({ drama_voice_generation_enabled: true, ordinary_tts_enabled: false }))+})