Repository navigation
TTS日本語・英語プロンプトをチューニング設定から編集可能にする - #5594
Conversation
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
📝 WalkthroughWalkthroughTTSに日本語/英語のプロンプトを追加する変更。フロントエンド(UI、状態、AsyncStorage、定数、キャッシュキー)とクラウド関数(アクセストークン取得、プロンプトを含む合成呼び出し、キャッシュハッシュ v9→v10)にプロンプトが組み込まれています。 Changes
シーケンス図sequenceDiagram
participant UI as TuningSettings UI
participant Hook as useTTS Hook
participant Fetcher as ttsSpeechFetcher
participant CloudFunc as Cloud Function (tts.ts)
participant Firestore as Firestore
participant Gemini as Gemini API
UI->>Hook: プロンプト/ボイス名を設定
Hook->>Fetcher: fetchSpeechAudio(jaPrompt,enPrompt,jaVoice,enVoice,...)
Fetcher->>Fetcher: キャッシュキー生成(voice + prompt を含む)
alt キャッシュヒット
Fetcher-->>Hook: キャッシュ音声を返却
else キャッシュミス
Fetcher->>CloudFunc: TTSリクエスト(accessToken不要→CloudFuncがgetAccessToken, ペイロードにprompt含む)
CloudFunc->>Firestore: getTtsConfig (TTLキャッシュ確認)
CloudFunc->>CloudFunc: getAccessToken
CloudFunc->>Gemini: synthesize (Authorization + prompt)
Gemini-->>CloudFunc: 音声データ
CloudFunc-->>Fetcher: 合成音声返却(キャッシュ保存)
Fetcher-->>Hook: 音声データ返却
end
Hook-->>UI: 再生/状態更新
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
詩
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches
🧪 Generate unit tests (beta)
📝 Coding Plan
Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@functions/src/funcs/tts.ts`:
- Around line 247-252: The current prompt selection treats whitespace-only
strings as valid and doesn't prevent overly long prompts; update the logic that
sets jaPrompt and enPrompt (using req.data.jaPrompt, req.data.enPrompt,
JA_TTS_PROMPT, EN_TTS_PROMPT) to treat trimmed empty strings as absent (use
trim() before falling back to defaults) and add preflight byte-length checks
(use Buffer.byteLength) against Gemini-TTS limits (each SynthesisInput.text and
SynthesisInput.prompt <= 4000 bytes, combined <= 8000 bytes) and if any limit is
exceeded return an error with code 'invalid-argument' (before calling the Gemini
API) so the service never forwards invalid input and avoids later internal
errors.
In `@src/utils/ttsSpeechFetcher.ts`:
- Around line 101-102: Normalize all input fields used in the cache key by
treating strings that are only whitespace as empty: create a normalization step
for opts.textJa, opts.textEn, opts.jaVoiceName, opts.enVoiceName, opts.jaPrompt,
and opts.enPrompt (e.g. use (val ?? '').trim() === '' ? '' : val.trim()) and use
those normalized values when building the cache key string in the code that
constructs `${opts.textJa}\0${opts.textEn}...` (and apply the same normalization
at the other occurrence referenced around lines 137-138); this ensures
whitespace-only inputs fall back to the server default and the cache key is
consistently normalized.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 3d5e46b1-e75e-4cde-b18f-7d2c1cb9b8bf
📒 Files selected for processing (10)
assets/translations/en.jsonassets/translations/ja.jsonfunctions/src/funcs/tts.tssrc/components/TuningSettings.tsxsrc/constants/asyncStorage.tssrc/constants/index.tssrc/constants/tts.tssrc/hooks/useTTS.tssrc/store/atoms/tuning.tssrc/utils/ttsSpeechFetcher.ts
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
There was a problem hiding this comment.
♻️ Duplicate comments (1)
functions/src/funcs/tts.ts (1)
254-284:⚠️ Potential issue | 🟠 Major
text単体のバイト上限チェックが不足しています。Line 256/257 で
textバイト数を計算していますが、現在の検証はprompt単体とtext+prompt合計のみです。textが 4000 バイトを超えていても合計が 8000 以下なら通過してしまい、外部APIでINVALID_ARGUMENTになる経路が残ります。jaTextBytes/enTextBytesの単体上限チェックを追加してください。修正イメージ
const PROMPT_BYTE_LIMIT = 4000; + const TEXT_BYTE_LIMIT = 4000; const COMBINED_BYTE_LIMIT = 8000; const jaTextBytes = Buffer.byteLength(stripSsml(ssmlJa), 'utf8'); const enTextBytes = Buffer.byteLength(stripSsml(ssmlEn), 'utf8'); const jaPromptBytes = Buffer.byteLength(jaPrompt, 'utf8'); const enPromptBytes = Buffer.byteLength(enPrompt, 'utf8'); + if (jaTextBytes > TEXT_BYTE_LIMIT) { + throw new HttpsError( + 'invalid-argument', + `ssmlJa(text) exceeds ${TEXT_BYTE_LIMIT} byte limit (${jaTextBytes} bytes)`, + ); + } + if (enTextBytes > TEXT_BYTE_LIMIT) { + throw new HttpsError( + 'invalid-argument', + `ssmlEn(text) exceeds ${TEXT_BYTE_LIMIT} byte limit (${enTextBytes} bytes)`, + ); + } if (jaPromptBytes > PROMPT_BYTE_LIMIT) { throw new HttpsError( 'invalid-argument', `jaPrompt exceeds ${PROMPT_BYTE_LIMIT} byte limit (${jaPromptBytes} bytes)` );Google Cloud Text-to-Speech (Gemini-TTS) の SynthesisInput で、text と prompt の最新バイト上限(各フィールド上限・合計上限)を公式ドキュメントで確認してください。🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@functions/src/funcs/tts.ts` around lines 254 - 284, The code currently checks prompt sizes and combined text+prompt sizes but misses enforcing a per-text byte limit; add checks after computing jaTextBytes and enTextBytes to throw an HttpsError when jaTextBytes > PROMPT_BYTE_LIMIT or enTextBytes > PROMPT_BYTE_LIMIT (use the same PROMPT_BYTE_LIMIT constant), mirroring the existing enPrompt/jaPrompt error pattern and including the actual byte counts in the message; locate and update the block that defines PROMPT_BYTE_LIMIT, COMBINED_BYTE_LIMIT and the variables jaTextBytes, enTextBytes, jaPromptBytes, enPromptBytes to insert these two new validations (same HttpsError type and descriptive messages).
🧹 Nitpick comments (1)
src/utils/ttsSpeechFetcher.ts (1)
140-151:normalizeOptionalの二重呼び出しを削減できます。各フィールドで条件チェックと値の両方に
normalizeOptionalを呼び出しています。関数自体は軽量ですが、正規化済みの値を一度だけ計算することで、コードの意図がより明確になります。♻️ 修正案
+ const normalizedJaVoiceName = normalizeOptional(jaVoiceName); + const normalizedEnVoiceName = normalizeOptional(enVoiceName); + const normalizedJaPrompt = normalizeOptional(jaPrompt); + const normalizedEnPrompt = normalizeOptional(enPrompt); + const reqBody = { data: { ssmlJa: `<speak>${textJa.trim()}</speak>`, ssmlEn: `<speak>${textEn.trim()}</speak>`, - ...(normalizeOptional(jaVoiceName) - ? { jaVoiceName: normalizeOptional(jaVoiceName) } - : {}), - ...(normalizeOptional(enVoiceName) - ? { enVoiceName: normalizeOptional(enVoiceName) } - : {}), - ...(normalizeOptional(jaPrompt) - ? { jaPrompt: normalizeOptional(jaPrompt) } - : {}), - ...(normalizeOptional(enPrompt) - ? { enPrompt: normalizeOptional(enPrompt) } - : {}), + ...(normalizedJaVoiceName && { jaVoiceName: normalizedJaVoiceName }), + ...(normalizedEnVoiceName && { enVoiceName: normalizedEnVoiceName }), + ...(normalizedJaPrompt && { jaPrompt: normalizedJaPrompt }), + ...(normalizedEnPrompt && { enPrompt: normalizedEnPrompt }), }, };🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/utils/ttsSpeechFetcher.ts` around lines 140 - 151, Compute each normalized value once and reuse it instead of calling normalizeOptional twice per field: create local constants (e.g., normalizedJaVoiceName, normalizedEnVoiceName, normalizedJaPrompt, normalizedEnPrompt) by calling normalizeOptional(...) once for each input, then use those constants in the conditional spreads (e.g., ...(normalizedJaVoiceName ? { jaVoiceName: normalizedJaVoiceName } : {})). Update the code paths that currently call normalizeOptional(jaVoiceName), normalizeOptional(enVoiceName), normalizeOptional(jaPrompt), and normalizeOptional(enPrompt) to use the new normalized variables.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Duplicate comments:
In `@functions/src/funcs/tts.ts`:
- Around line 254-284: The code currently checks prompt sizes and combined
text+prompt sizes but misses enforcing a per-text byte limit; add checks after
computing jaTextBytes and enTextBytes to throw an HttpsError when jaTextBytes >
PROMPT_BYTE_LIMIT or enTextBytes > PROMPT_BYTE_LIMIT (use the same
PROMPT_BYTE_LIMIT constant), mirroring the existing enPrompt/jaPrompt error
pattern and including the actual byte counts in the message; locate and update
the block that defines PROMPT_BYTE_LIMIT, COMBINED_BYTE_LIMIT and the variables
jaTextBytes, enTextBytes, jaPromptBytes, enPromptBytes to insert these two new
validations (same HttpsError type and descriptive messages).
---
Nitpick comments:
In `@src/utils/ttsSpeechFetcher.ts`:
- Around line 140-151: Compute each normalized value once and reuse it instead
of calling normalizeOptional twice per field: create local constants (e.g.,
normalizedJaVoiceName, normalizedEnVoiceName, normalizedJaPrompt,
normalizedEnPrompt) by calling normalizeOptional(...) once for each input, then
use those constants in the conditional spreads (e.g., ...(normalizedJaVoiceName
? { jaVoiceName: normalizedJaVoiceName } : {})). Update the code paths that
currently call normalizeOptional(jaVoiceName), normalizeOptional(enVoiceName),
normalizeOptional(jaPrompt), and normalizeOptional(enPrompt) to use the new
normalized variables.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 8395bb5f-dd16-475b-9ecc-24e74c29396e
📒 Files selected for processing (2)
functions/src/funcs/tts.tssrc/utils/ttsSpeechFetcher.ts
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@functions/src/funcs/tts.ts`:
- Around line 254-257: After computing jaTextBytes/enTextBytes via
stripSsml(ssmlJa)/stripSsml(ssmlEn), add a validation that the stripped text
contains at least one visible character (e.g., check strippedText.trim().length
> 0) for both languages and reject/handle inputs that are empty after stripping
(instead of letting them flow to the external API and become "internal"); update
the logic around PROMPT_BYTE_LIMIT/COMBINED_BYTE_LIMIT and the handling that
leads to the internal branch to short-circuit when stripped text is empty so
inputs like "<speak><break/></speak>" are caught early (refer to stripSsml,
ssmlJa, ssmlEn, PROMPT_BYTE_LIMIT, COMBINED_BYTE_LIMIT and the code path that
sets internal).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 87838a08-5581-450b-bb46-a6f4c2ceac28
📒 Files selected for processing (2)
functions/src/funcs/tts.tssrc/utils/ttsSpeechFetcher.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/utils/ttsSpeechFetcher.ts
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
functions/src/funcs/tts.ts (1)
237-245:⚠️ Potential issue | 🟡 Minor音声名も
trim()/ type guard してから採用したいです。
req.data.*VoiceName = ' 'や Firestore 側の非文字列値でも、今の真偽値判定だとそのまま Gemini へ流れます。そこで 4xx になっても最後はinternalに丸められるので、空白-only はフォールバック、非文字列はデフォルトへ寄せた方が安全です。💡 修正イメージ
+const resolveVoiceName = (value: unknown, fallback: string): string => { + if (typeof value !== 'string') { + return fallback; + } + const trimmed = value.trim(); + return trimmed || fallback; +}; + ... - const defaultJaVoice = ttsConfig?.jaVoiceName || DEFAULT_TTS_VOICE_NAME; - const defaultEnVoice = ttsConfig?.enVoiceName || DEFAULT_TTS_VOICE_NAME; + const defaultJaVoice = resolveVoiceName( + ttsConfig?.jaVoiceName, + DEFAULT_TTS_VOICE_NAME + ); + const defaultEnVoice = resolveVoiceName( + ttsConfig?.enVoiceName, + DEFAULT_TTS_VOICE_NAME + ); - const jaVoiceName = - (typeof req.data.jaVoiceName === 'string' && req.data.jaVoiceName) || - defaultJaVoice; - const enVoiceName = - (typeof req.data.enVoiceName === 'string' && req.data.enVoiceName) || - defaultEnVoice; + const jaVoiceName = resolveVoiceName(req.data.jaVoiceName, defaultJaVoice); + const enVoiceName = resolveVoiceName(req.data.enVoiceName, defaultEnVoice);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@functions/src/funcs/tts.ts` around lines 237 - 245, Update the voice-name selection to first type-guard and trim the incoming values before using them: for defaultJaVoice/defaultEnVoice keep using ttsConfig?.jaVoiceName || DEFAULT_TTS_VOICE_NAME and ttsConfig?.enVoiceName || DEFAULT_TTS_VOICE_NAME, but compute jaVoiceName and enVoiceName by checking typeof req.data.jaVoiceName === 'string' then const v = req.data.jaVoiceName.trim(); use v if v !== '' otherwise fall back to defaultJaVoice; if not a string immediately use defaultJaVoice; apply the same logic for enVoiceName (referencing jaVoiceName, enVoiceName, ttsConfig, DEFAULT_TTS_VOICE_NAME, and req.data.*VoiceName).
🧹 Nitpick comments (1)
functions/src/funcs/tts.ts (1)
31-40: TTL切れ直後の取得失敗で前回設定まで捨てています。ここは Firestore の一時障害でも
getTtsConfig()が throw し、呼び出し側がAoedeデフォルトへ落ちます。前回取得できていたttsConfigCacheがあるなら、再取得失敗時はそれを返した方が音声設定がぶれません。💡 修正イメージ
const getTtsConfig = async (): Promise< FirebaseFirestore.DocumentData | undefined > => { if (ttsConfigCache && Date.now() - ttsConfigCache.fetchedAt < TTS_CONFIG_CACHE_TTL_MS) { return ttsConfigCache.data; } - const doc = await firestore.collection('configs').doc('tts').get(); - const data = doc.data(); - ttsConfigCache = { data, fetchedAt: Date.now() }; - return data; + try { + const doc = await firestore.collection('configs').doc('tts').get(); + const data = doc.data(); + ttsConfigCache = { data, fetchedAt: Date.now() }; + return data; + } catch (error) { + if (ttsConfigCache) { + console.warn('Failed to refresh TTS config. Using stale cache.', error); + return ttsConfigCache.data; + } + throw error; + } };🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@functions/src/funcs/tts.ts` around lines 31 - 40, The getTtsConfig function currently throws on Firestore fetch failures right after TTL expiry and overwrites the cache; wrap the firestore.collection('configs').doc('tts').get() call in a try/catch, only update ttsConfigCache when the fetch succeeds (set ttsConfigCache = { data, fetchedAt: Date.now() }), and on catch return the existing ttsConfigCache.data if ttsConfigCache is defined; if no cache exists, rethrow the error so callers can handle the failure. Use the existing symbols getTtsConfig, ttsConfigCache, and TTS_CONFIG_CACHE_TTL_MS to locate and change the logic.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Outside diff comments:
In `@functions/src/funcs/tts.ts`:
- Around line 237-245: Update the voice-name selection to first type-guard and
trim the incoming values before using them: for defaultJaVoice/defaultEnVoice
keep using ttsConfig?.jaVoiceName || DEFAULT_TTS_VOICE_NAME and
ttsConfig?.enVoiceName || DEFAULT_TTS_VOICE_NAME, but compute jaVoiceName and
enVoiceName by checking typeof req.data.jaVoiceName === 'string' then const v =
req.data.jaVoiceName.trim(); use v if v !== '' otherwise fall back to
defaultJaVoice; if not a string immediately use defaultJaVoice; apply the same
logic for enVoiceName (referencing jaVoiceName, enVoiceName, ttsConfig,
DEFAULT_TTS_VOICE_NAME, and req.data.*VoiceName).
---
Nitpick comments:
In `@functions/src/funcs/tts.ts`:
- Around line 31-40: The getTtsConfig function currently throws on Firestore
fetch failures right after TTL expiry and overwrites the cache; wrap the
firestore.collection('configs').doc('tts').get() call in a try/catch, only
update ttsConfigCache when the fetch succeeds (set ttsConfigCache = { data,
fetchedAt: Date.now() }), and on catch return the existing ttsConfigCache.data
if ttsConfigCache is defined; if no cache exists, rethrow the error so callers
can handle the failure. Use the existing symbols getTtsConfig, ttsConfigCache,
and TTS_CONFIG_CACHE_TTL_MS to locate and change the logic.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: a5965ca5-654a-4e0b-892e-074b70c48ecc
📒 Files selected for processing (1)
functions/src/funcs/tts.ts
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
@coderabbitai resume |
✅ Actions performedReviews resumed. |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
functions/src/funcs/tts.ts (1)
23-29:DEFAULT_TTS_VOICE_NAMEがクライアント側と重複しています。
src/constants/tts.tsにも同じ定数DEFAULT_TTS_VOICE_NAME = 'Aoede'が定義されています。サーバー/クライアントで別々に管理する意図であれば、コメントでその旨を明記しておくとメンテナンス時の混乱を防げます。🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@functions/src/funcs/tts.ts` around lines 23 - 29, DEFAULT_TTS_VOICE_NAME is duplicated in this file and in the client constants (same value 'Aoede'); either remove the local declaration and import DEFAULT_TTS_VOICE_NAME from the shared constant module (replace this file's DEFAULT_TTS_VOICE_NAME usage with the imported symbol) or, if the server must intentionally keep a separate value, add a clear comment above DEFAULT_TTS_VOICE_NAME explaining why it is duplicated and that it must be changed independently; reference the symbol DEFAULT_TTS_VOICE_NAME (and nearby TTS_CONFIG_CACHE_TTL_MS/ttsConfigCache if adjusting imports) to locate the change.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@functions/src/funcs/tts.ts`:
- Around line 23-29: DEFAULT_TTS_VOICE_NAME is duplicated in this file and in
the client constants (same value 'Aoede'); either remove the local declaration
and import DEFAULT_TTS_VOICE_NAME from the shared constant module (replace this
file's DEFAULT_TTS_VOICE_NAME usage with the imported symbol) or, if the server
must intentionally keep a separate value, add a clear comment above
DEFAULT_TTS_VOICE_NAME explaining why it is duplicated and that it must be
changed independently; reference the symbol DEFAULT_TTS_VOICE_NAME (and nearby
TTS_CONFIG_CACHE_TTL_MS/ttsConfigCache if adjusting imports) to locate the
change.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: c56351a7-7329-4a0c-ab59-49aabf3e1789
📒 Files selected for processing (1)
functions/src/funcs/tts.ts
Summary
AoedeをDEFAULT_TTS_VOICE_NAME定数に集約Test plan
🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Improvements
Validation