Repository navigation
英語のTTSエンジンをGoogle Cloud TTS APIからGemini TTS (Vertex AI)に移行しボイス選択UIを追加 - #5533
Conversation
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
📝 WalkthroughWalkthroughGemini(Vertex AI)を主要TTSエンジンに導入し、Google TTSをフォールバックに維持。PCM/WAV⇄MP3処理とMIMEベースのキャッシュ拡張、クライアント側の言語別音声名永続化とピッカーUI、GraphQL型からの nameIpa 削除、Node.js 要件を 22 に更新。 Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant User as ユーザー
participant App as モバイルアプリ
participant Fetcher as ttsSpeechFetcher
participant Func as Cloud Function (tts)
participant Gemini as Gemini (Vertex AI)
participant Google as Google TTS
participant Audio as Audio/Encoder
participant Storage as Cache/Cloud Storage
User->>App: 再生要求 (テキスト, 選択音声)
App->>AsyncStorage: 音声名を保存
App->>Fetcher: fetchSpeechAudio(text, jaVoice,enVoice)
Fetcher->>Func: onCall HTTP (text, voice names, token)
Func->>Storage: キャッシュ確認 (ja/en, MIME)
alt キャッシュヒット
Storage-->>Func: base64 音声 + MIME
else キャッシュミス
Func->>Gemini: 合成要求 (SSML/テキスト, voice)
alt Gemini 成功
Gemini-->>Func: base64 音声 + MIME
else
Func->>Google: Google TTS フォールバック
Google-->>Func: base64 MP3
end
Func->>Audio: 必要でエンコード (PCM/WAV→MP3)
Audio-->>Func: エンコード済音声 + MIME
Func->>Storage: キャッシュ保存 (ファイル、MIME、モデル情報)
end
Func-->>Fetcher: 音声パス/データ (拡張子は MIME 基準)
Fetcher-->>App: ローカルファイルパス返却
App->>Audio: 再生
Estimated code review effort🎯 4 (Complex) | ⏱️ ~75 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 5
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
functions/src/funcs/tts.ts (1)
126-137:⚠️ Potential issue | 🟠 Major
ssmlEnを型検査する前に触らないほうがいいです。
normalizeRomanText(req.data.ssmlEn)は非文字列入力でそのまま throw するので、ここはinvalid-argumentではなく 500 になります。typeof req.data.ssmlEn === 'string'を確認してから正規化したいです。修正例
- let ssmlEn = normalizeRomanText(req.data.ssmlEn); + if (!(typeof req.data.ssmlEn === 'string') || req.data.ssmlEn.length === 0) { + throw new HttpsError( + 'invalid-argument', + `The function must be called with one argument "ssmlEn" containing the message to add.` + ); + } + + let ssmlEn = normalizeRomanText(req.data.ssmlEn);🤖 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 126 - 137, Before calling normalizeRomanText, validate that req.data.ssmlEn is a string to avoid runtime throws converting non-strings (which turns the error into a 500); first check typeof req.data.ssmlEn === 'string' and if not throw the HttpsError('invalid-argument', ...) as currently used, then assign ssmlEn = normalizeRomanText(req.data.ssmlEn), then proceed with the existing phoneme check and applyLegacyIpaReplacements(ssmlEn) and subsequent empty-string check.src/hooks/useTTS.test.ts (1)
164-177:⚠️ Potential issue | 🟡 Minor順序検証は index 固定のままだとまだ flaky です。
呼び出し回数だけを緩めても、再レンダーで
['/tmp/tts-id_ja.wav', '/tmp/tts-id_ja.wav', '/tmp/tts-id_en.wav']のような並びになるとcalls[1]が落ちます。JAの最初の出現位置より後にENが現れることを見たほうが安定します。修正例
- await waitFor(() => { - expect(calls.length).toBeGreaterThanOrEqual(2); - }); - - expect(calls[1]).toBe('/tmp/tts-id_en.wav'); + await waitFor(() => { + const jaIndex = calls.indexOf('/tmp/tts-id_ja.wav'); + const enIndex = calls.indexOf('/tmp/tts-id_en.wav'); + expect(jaIndex).toBeGreaterThanOrEqual(0); + expect(enIndex).toBeGreaterThan(jaIndex); + });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/hooks/useTTS.test.ts` around lines 164 - 177, The test currently asserts fixed indexes on the calls array (calls[0], calls[1]) which is flaky; after triggering EN playback via jest.runAllTimers() assert that the first occurrence index of '/tmp/tts-id_en.wav' appears after the first occurrence index of '/tmp/tts-id_ja.wav' (e.g. use calls.findIndex or Array.prototype.indexOf to get positions) and keep the existing waitFor that ensures calls.length >= 2; this ensures EN appears after the initial JA call regardless of intermediate duplicates and references the calls array and the jest.runAllTimers() / EN_PLAYBACK_DELAY_MS flow.
🧹 Nitpick comments (4)
src/utils/ttsSpeechFetcher.test.ts (1)
12-18:beforeEachのclearAllMocksは冗長です。
afterEachでjest.clearAllMocks()を呼び出しているため、beforeEachでの呼び出しは冗長です。コーディングガイドラインではafterEachブロックでの呼び出しを推奨しています。♻️ 冗長な beforeEach の削除
describe('fetchSpeechAudio', () => { - beforeEach(() => { - jest.clearAllMocks(); - }); - afterEach(() => { jest.clearAllMocks(); });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/utils/ttsSpeechFetcher.test.ts` around lines 12 - 18, Remove the redundant beforeEach that calls jest.clearAllMocks(): keep the afterEach(() => { jest.clearAllMocks(); }) as the single teardown, delete the beforeEach block entirely so mocks are only cleared once per test via afterEach; ensure no other setup relies on the removed beforeEach and update any test-specific setup into separate beforeEach blocks if needed.functions/src/cli/find-tts-cache.ts (1)
198-201: フォールバックパスの拡張子を確認してください。
pathJa/pathEnが存在しない場合のフォールバックパスが.mp3固定になっています。Gemini TTS移行後、新しいキャッシュエントリは.wavで保存される可能性があります。レガシーエントリとの後方互換性のためであれば問題ありませんが、意図を明確にするためにコメントを追加することを推奨します。💡 コメント追加の提案
const storagePathJa = + // フォールバック: pathJa/pathEn がない古いドキュメント用(レガシーMP3形式) typeof data.pathJa === 'string' ? data.pathJa : `caches/tts/ja/${id}.mp3`; const storagePathEn = typeof data.pathEn === 'string' ? data.pathEn : `caches/tts/en/${id}.mp3`;🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@functions/src/cli/find-tts-cache.ts` around lines 198 - 201, The fallback storage paths for TTS caches (storagePathJa and storagePathEn) unconditionally use the .mp3 extension which may be incorrect for new Gemini TTS entries saved as .wav; update the logic in find-tts-cache.ts so that when data.pathJa/data.pathEn is absent you either derive the extension dynamically (e.g., prefer .wav when new-format entries are expected) or check both .mp3 and .wav fallback candidates, and add a short comment explaining the choice for backward compatibility; refer to the storagePathJa/storagePathEn variables and the data.pathJa/data.pathEn and id identifiers when making this change.functions/src/utils/normalize.ts (1)
38-40: 略語パターンをより正確に修正してください。
.Sta.、.Univ.、.Hp.の先頭のドット(.)は正規表現のワイルドカード(任意の1文字)として機能しており、意図しないマッチの原因となる可能性があります。例えば「Station.Sta.」は「Station Station」に変換されてしまいます。現在のデータ形式では「Tokyo Sta.」のように空白が含まれているため実際の問題は発生していませんが、より堅牢にするため、空白または単語境界パターンへの変更をお勧めします:
/.Sta\./gi→/\sSta\./gi(空白を明示的にマッチ)- または
/\bSta\./gi(単語境界を使用)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@functions/src/utils/normalize.ts` around lines 38 - 40, The regex patterns used in the .replace calls (.replace(/.Sta\./gi, ' Station'), .replace(/.Univ\./gi, ' University'), .replace(/.Hp\./gi, ' Hospital')) use an unescaped leading dot which acts as a wildcard; update those to match a whitespace or word boundary instead (e.g. use a \s or \b before Sta\. / Univ\. / Hp\.) so only intended abbreviations like " Sta." are replaced; locate these .replace calls in normalize.ts and change the three regexes accordingly, keeping the trailing escaped dot and flags (gi).src/components/TuningSettings.tsx (1)
99-111: voice 設定の永続化は 1 箇所に寄せたいです。
src/hooks/useTTS.tsでも同じキーを読んでいるので、初期化中のgetItem()が選択直後の state を後から上書きする race が残ります。復元/保存は atom 初期化か専用 hook に集約したほうが安全です。Also applies to: 198-205
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/components/TuningSettings.tsx` around lines 99 - 111, The effect in TuningSettings.tsx that reads AsyncStorage (the anonymous async IIFE using AsyncStorage.getItem for ASYNC_STORAGE_KEYS.TTS_JA_VOICE_NAME and TTS_EN_VOICE_NAME and calling setSettings) must be removed and persistence centralized: move restore/save logic into the atom initialization or a dedicated hook (e.g., the existing useTTS hook or a new useTTSPersistence hook) so only that module reads/writes AsyncStorage and updates the atom; update useTTS to read from and write to that single persistence layer (or initialize the atom from it) to eliminate the race where TuningSettings' effect can overwrite a recent selection.
🤖 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/package.json`:
- Around line 23-25: The package.json currently specifies the Node engine as
"node": "22" which conflicts with multiple docs that require Node 20; either
update all documentation (AGENTS.md, .github/copilot-instructions.md, README.md,
functions/README.md, docs/bump-version-on-canary-pr.md) to reflect Node 22, or
revert the engines entry to Node 20 by changing the "engines" object (the "node"
value) back to "20" so it matches the stated supported runtime for dependencies
like `@google-cloud/vertexai` and firebase-functions; make the change in the
package.json engines block and ensure any CI/runtime configs are adjusted to the
chosen version for consistency.
In `@functions/src/funcs/tts.ts`:
- Around line 241-244: The code currently defaults
jaAudio.mimeType/enAudio.mimeType to 'audio/pcm' which can corrupt real WAV/MP3
data; replace that fallback by calling the existing sniffAudioMimeType() on the
corresponding audio bytes (use jaAudioContent and enAudioContent) when
jaAudio.mimeType or enAudio.mimeType is missing, mirroring the same pattern used
in the cache-hit implementation around the cache handling logic (see the logic
used in the 191-198 cache-hit block) so both live-response and cache-response
branches use sniffAudioMimeType() to determine the correct MIME type.
In `@src/components/TuningSettings.tsx`:
- Around line 331-375: The UI shows "Kore" even when the saved voice is empty,
which falsely implies a selection; update the display in the
Pressable/Typhography blocks for both JA and EN to render a true placeholder
when settings.ttsJaVoiceName or settings.ttsEnVoiceName is falsy (e.g., show
"Select voice" or a translated placeholder) instead of the hardcoded 'Kore'.
Locate the Pressable usages that call showVoicePicker and the inner Typography
rendering settings.ttsJaVoiceName and settings.ttsEnVoiceName (handlers
handleJaVoiceNameChange and handleEnVoiceNameChange) and change the fallback
text to a placeholder style and string, keeping the existing color/font
conditional logic.
- Around line 170-195: The Android fallback in showVoicePicker uses Alert.alert
which only supports up to 3 buttons, causing many TTS_VOICE_NAMES to be
unavailable; replace the Alert.alert branch with an Android-specific selectable
UI (e.g., a modal/bottom-sheet or a platform ActionSheet library) that renders
all TTS_VOICE_NAMES as a scrollable list and calls onSelect(name) when tapped,
includes a cancel action, and preserves the current selection marker (e.g., `●
${name}`) so behavior matches the iOS ActionSheet implementation in
showVoicePicker.
In `@src/hooks/useTTS.ts`:
- Around line 83-95: The hydration logic in useEffect loads
ttsJaVoiceName/ttsEnVoiceName after mount, which can let the first
speechWithText() run with empty voices; move the AsyncStorage restore so saved
voices are available before the first utterance by either (A) reading
ASYNC_STORAGE_KEYS.TTS_JA_VOICE_NAME and TTS_EN_VOICE_NAME during atom/state
initialization (so setTuning(...) is seeded with persisted values), or (B)
expose a "voicesHydrated" flag from this hook (set true after the Promise.all)
and ensure callers of speechWithText() await that flag before speaking; update
useEffect/useTuning initialization and any callers of speechWithText()
accordingly to prevent a race.
---
Outside diff comments:
In `@functions/src/funcs/tts.ts`:
- Around line 126-137: Before calling normalizeRomanText, validate that
req.data.ssmlEn is a string to avoid runtime throws converting non-strings
(which turns the error into a 500); first check typeof req.data.ssmlEn ===
'string' and if not throw the HttpsError('invalid-argument', ...) as currently
used, then assign ssmlEn = normalizeRomanText(req.data.ssmlEn), then proceed
with the existing phoneme check and applyLegacyIpaReplacements(ssmlEn) and
subsequent empty-string check.
In `@src/hooks/useTTS.test.ts`:
- Around line 164-177: The test currently asserts fixed indexes on the calls
array (calls[0], calls[1]) which is flaky; after triggering EN playback via
jest.runAllTimers() assert that the first occurrence index of
'/tmp/tts-id_en.wav' appears after the first occurrence index of
'/tmp/tts-id_ja.wav' (e.g. use calls.findIndex or Array.prototype.indexOf to get
positions) and keep the existing waitFor that ensures calls.length >= 2; this
ensures EN appears after the initial JA call regardless of intermediate
duplicates and references the calls array and the jest.runAllTimers() /
EN_PLAYBACK_DELAY_MS flow.
---
Nitpick comments:
In `@functions/src/cli/find-tts-cache.ts`:
- Around line 198-201: The fallback storage paths for TTS caches (storagePathJa
and storagePathEn) unconditionally use the .mp3 extension which may be incorrect
for new Gemini TTS entries saved as .wav; update the logic in find-tts-cache.ts
so that when data.pathJa/data.pathEn is absent you either derive the extension
dynamically (e.g., prefer .wav when new-format entries are expected) or check
both .mp3 and .wav fallback candidates, and add a short comment explaining the
choice for backward compatibility; refer to the storagePathJa/storagePathEn
variables and the data.pathJa/data.pathEn and id identifiers when making this
change.
In `@functions/src/utils/normalize.ts`:
- Around line 38-40: The regex patterns used in the .replace calls
(.replace(/.Sta\./gi, ' Station'), .replace(/.Univ\./gi, ' University'),
.replace(/.Hp\./gi, ' Hospital')) use an unescaped leading dot which acts as a
wildcard; update those to match a whitespace or word boundary instead (e.g. use
a \s or \b before Sta\. / Univ\. / Hp\.) so only intended abbreviations like "
Sta." are replaced; locate these .replace calls in normalize.ts and change the
three regexes accordingly, keeping the trailing escaped dot and flags (gi).
In `@src/components/TuningSettings.tsx`:
- Around line 99-111: The effect in TuningSettings.tsx that reads AsyncStorage
(the anonymous async IIFE using AsyncStorage.getItem for
ASYNC_STORAGE_KEYS.TTS_JA_VOICE_NAME and TTS_EN_VOICE_NAME and calling
setSettings) must be removed and persistence centralized: move restore/save
logic into the atom initialization or a dedicated hook (e.g., the existing
useTTS hook or a new useTTSPersistence hook) so only that module reads/writes
AsyncStorage and updates the atom; update useTTS to read from and write to that
single persistence layer (or initialize the atom from it) to eliminate the race
where TuningSettings' effect can overwrite a recent selection.
In `@src/utils/ttsSpeechFetcher.test.ts`:
- Around line 12-18: Remove the redundant beforeEach that calls
jest.clearAllMocks(): keep the afterEach(() => { jest.clearAllMocks(); }) as the
single teardown, delete the beforeEach block entirely so mocks are only cleared
once per test via afterEach; ensure no other setup relies on the removed
beforeEach and update any test-specific setup into separate beforeEach blocks if
needed.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 744b1ad1-0efd-41bf-954c-063dbf60c01f
⛔ Files ignored due to path filters (1)
functions/package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (17)
assets/translations/en.jsonassets/translations/ja.jsonfunctions/package.jsonfunctions/src/cli/find-orphaned-tts.tsfunctions/src/cli/find-tts-cache.tsfunctions/src/funcs/tts.tsfunctions/src/funcs/ttsCachePubSub.tsfunctions/src/utils/legacyIpa.tsfunctions/src/utils/normalize.tssrc/components/TuningSettings.tsxsrc/constants/asyncStorage.tssrc/hooks/useTTS.test.tssrc/hooks/useTTS.tssrc/store/atoms/tuning.tssrc/utils/ssml.tssrc/utils/ttsSpeechFetcher.test.tssrc/utils/ttsSpeechFetcher.ts
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/hooks/useBusTTSText.ts (1)
91-100:⚠️ Potential issue | 🟠 Major英語バス案内の括弧除去がここだけ外れています。
useTTSText側は返却直前で括弧を落としていますが、この hook はboundForEn/nextStation/afterNextStation/allStopsに生のnameRomanを流すだけなので、Foo (Bar)がそのまま英語 TTS に残ります。nameRomanだけparenthesisRegexp.replace()済みで扱うか、enTextの返却直前で英語側だけ同じ正規化を入れたいです。Based on learnings: In LineBoard.tsx for bus lines, only the
nameRomanfield requires parentheses removal viaparenthesisRegexp.replace().Also applies to: 100-110, 129-137
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/hooks/useBusTTSText.ts` around lines 91 - 100, The English text still contains parentheses because boundForEn, nextStation, afterNextStation and allStops are built from raw nameRoman; run parenthesisRegexp.replace(...) on each nameRoman used here (when creating boundForEn in the useMemo, and when assigning nextStation/afterNextStation/allStops) so the parentheses are removed before passing to useTTSText, or alternatively apply the same parenthesisRegexp normalization to the enText just before return; update the references in this hook (boundForEn, nextStation, afterNextStation, allStops) to use the cleaned nameRoman so LineBoard.tsx’s nameRoman-specific parentheses removal is mirrored here.
🤖 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 159-163: Wrap the Firestore read for 'configs'->'tts' in a
try/catch so transient Firestore failures don't crash TTS: move the await
firestore.collection('configs').doc('tts').get() into a try block, on success
keep using ttsConfigDoc.data() as before, and on catch set ttsConfig = undefined
(or {}) and log a warning that includes the caught error; then keep computing
defaultJaVoice and defaultEnVoice from ttsConfig?.jaVoiceName || 'Aoede' and
ttsConfig?.enVoiceName || 'Kore' so the function falls back to the hardcoded
voices instead of throwing.
- Around line 70-119: synthesizeWithGemini currently passes raw SSML
(ssmlJa/ssmlEn) through to model.generateContent which can include unsupported
tags like <sub> and <phoneme>; before calling Vertex AI (in synthesizeWithGemini
and the other Gemini-TTS call sites in this file), detect SSML input and
sanitize or convert it to plain text/phonetic instructions (strip or translate
<sub>, <phoneme>, and other SSML tags into readable text or IPA/lexicon hints)
or route only already-plain text to generateContent; implement this by adding an
SSML sanitizer/translator used just prior to the call to model.generateContent
so the contents.parts[].text field is always valid plain text/phonetic
directives instead of raw SSML.
In `@functions/src/utils/encodeMp3.ts`:
- Around line 36-57: The spawn('ffmpeg', ...) call in encodePcmToMp3 will fail
at runtime because ffmpeg isn't provisioned; add an ffmpeg installer to
dependencies (e.g., add "ffmpeg-static" or "@ffmpeg-installer/ffmpeg" to
functions/package.json) and change encodePcmToMp3 to require/import the
installer and use its binary path (e.g., const ffmpegPath =
require('ffmpeg-static') or require('@ffmpeg-installer/ffmpeg').path) when
calling spawn(ffmpegPath, args) instead of spawn('ffmpeg', ...), keeping the
same args, stdin handling and error aggregation logic.
---
Outside diff comments:
In `@src/hooks/useBusTTSText.ts`:
- Around line 91-100: The English text still contains parentheses because
boundForEn, nextStation, afterNextStation and allStops are built from raw
nameRoman; run parenthesisRegexp.replace(...) on each nameRoman used here (when
creating boundForEn in the useMemo, and when assigning
nextStation/afterNextStation/allStops) so the parentheses are removed before
passing to useTTSText, or alternatively apply the same parenthesisRegexp
normalization to the enText just before return; update the references in this
hook (boundForEn, nextStation, afterNextStation, allStops) to use the cleaned
nameRoman so LineBoard.tsx’s nameRoman-specific parentheses removal is mirrored
here.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 1359d14a-92e7-43cd-a16f-b3de7109f0ff
📒 Files selected for processing (24)
.github/copilot-instructions.md.github/workflows/bump_version_on_canary_pr.yml.github/workflows/bump_version_on_release_pr.yml.github/workflows/test.yml.github/workflows/typecheck.ymlAGENTS.mdREADME.mddocs/bump-version-on-canary-pr.mdfunctions/src/funcs/tts.tsfunctions/src/utils/encodeMp3.tsfunctions/src/utils/normalize.tssrc/@types/graphql.d.tssrc/__fixtures__/line.tssrc/hooks/useBusTTSText.tssrc/hooks/useGetStationsWithTermination.test.tsxsrc/hooks/useRefreshStation.test.tsxsrc/hooks/useTTS.test.tssrc/hooks/useTTSText.tssrc/hooks/useTransferLinesFromStation.test.tsxsrc/lib/graphql/queries.tssrc/utils/__fixtures__/search.tssrc/utils/jr.tssrc/utils/ssml.tssrc/utils/test/factories.ts
💤 Files with no reviewable changes (10)
- src/utils/jr.ts
- src/hooks/useRefreshStation.test.tsx
- src/hooks/useTransferLinesFromStation.test.tsx
- src/utils/test/factories.ts
- src/fixtures/line.ts
- src/hooks/useGetStationsWithTermination.test.tsx
- src/utils/ssml.ts
- src/lib/graphql/queries.ts
- src/utils/fixtures/search.ts
- src/@types/graphql.d.ts
✅ Files skipped from review due to trivial changes (2)
- docs/bump-version-on-canary-pr.md
- .github/workflows/typecheck.yml
🚧 Files skipped from review as they are similar to previous changes (1)
- functions/src/utils/normalize.ts
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
functions/src/funcs/tts.ts (1)
268-281: 日本語音声合成のプロンプト言語について検討の余地があります。日本語音声合成用のプロンプトが英語で記述されています。Gemini TTSが英語プロンプトで日本語コンテンツを適切に処理できるか確認してください。日本語プロンプトの方が発音精度が向上する可能性があります。
🤖 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 268 - 281, The Japanese TTS call to synthesizeWithGemini is using an English prompt which may degrade pronunciation of Japanese station names; update the call that passes ssmlJa / jaVoiceName into synthesizeWithGemini to use a Japanese-language prompt (or choose the prompt based on the ssml locale) that instructs the model to read as a Japanese train announcement and pronounce station/line names accurately; ensure the prompt string replacement affects only the ssmlJa invocation (leave the ssmlEn invocation as-is) and keep references to synthesizeWithGemini, ssmlJa, jaVoiceName so the change is easy to locate.
🤖 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 91-101: Add a JSDoc to the Gemini TTS function (e.g.,
synthesizeWithGemini) describing its responsibility (text->audio), input/output
shapes, and note that `@google-cloud/vertexai` does not type `speechConfig` so the
current type assertion around vertexAI.getGenerativeModel({ model:
GEMINI_TTS_MODEL, generationConfig: { speechConfig: ... } }) is intentional;
improve error handling by removing raw JSON.stringify(result) and instead
log/throw a compact, relevant subset (e.g., result.status, result.usageMetadata,
any error fields) and explicitly check for missing audioData (throwing an error
like "Gemini TTS returned no audio data" including usage/metadata), referencing
the model variable, GEMINI_TTS_MODEL, vertexAI.getGenerativeModel,
synthesizeWithGemini, result, and audioData to locate the changes.
---
Nitpick comments:
In `@functions/src/funcs/tts.ts`:
- Around line 268-281: The Japanese TTS call to synthesizeWithGemini is using an
English prompt which may degrade pronunciation of Japanese station names; update
the call that passes ssmlJa / jaVoiceName into synthesizeWithGemini to use a
Japanese-language prompt (or choose the prompt based on the ssml locale) that
instructs the model to read as a Japanese train announcement and pronounce
station/line names accurately; ensure the prompt string replacement affects only
the ssmlJa invocation (leave the ssmlEn invocation as-is) and keep references to
synthesizeWithGemini, ssmlJa, jaVoiceName so the change is easy to locate.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 64a79d96-9f46-4e08-b3b5-9c3e579e3bdc
📒 Files selected for processing (2)
functions/src/funcs/tts.tssrc/hooks/useBusTTSText.ts
There was a problem hiding this comment.
🧹 Nitpick comments (1)
functions/src/funcs/tts.ts (1)
269-282: プロンプト文字列の定数化を検討してください。日本語・英語のプロンプト文字列が関数呼び出し内にインラインで記述されています。将来的なプロンプト調整やA/Bテストを容易にするため、ファイル上部で定数として定義することを推奨します。
♻️ 定数化の例
const GEMINI_TTS_MODEL = 'gemini-2.5-flash-tts'; const VERTEX_AI_LOCATION = 'us-central1'; + +const JA_TTS_PROMPT = + 'Read the following as a Japanese train announcement. The text contains Japanese railway station names and line names. Pronounce them accurately:'; +const EN_TTS_PROMPT = + 'Read the following at a natural, slightly fast pace like a train announcement. The text contains Japanese railway station names and line names in romanized form. Pronounce them accurately:';const [jaAudio, enAudio] = await Promise.all([ synthesizeWithGemini( projectId, ssmlJa, jaVoiceName, - 'Read the following as a Japanese train announcement. The text contains Japanese railway station names and line names. Pronounce them accurately:' + JA_TTS_PROMPT ), synthesizeWithGemini( projectId, ssmlEn, enVoiceName, - 'Read the following at a natural, slightly fast pace like a train announcement. The text contains Japanese railway station names and line names in romanized form. Pronounce them accurately:' + EN_TTS_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 269 - 282, The inline prompt strings passed to synthesizeWithGemini (for the Japanese and English calls using variables ssmlJa, jaVoiceName and ssmlEn, enVoiceName) should be extracted into file-level constants (e.g., PROMPT_TRAIN_ANNOUNCEMENT_JA and PROMPT_TRAIN_ANNOUNCEMENT_EN) so they’re easy to tweak or swap for A/B testing; define these constants near the top of the file and replace the inline literals in the Promise.all call with the new constant names, keeping the existing function signatures and variable usages unchanged.
🤖 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 269-282: The inline prompt strings passed to synthesizeWithGemini
(for the Japanese and English calls using variables ssmlJa, jaVoiceName and
ssmlEn, enVoiceName) should be extracted into file-level constants (e.g.,
PROMPT_TRAIN_ANNOUNCEMENT_JA and PROMPT_TRAIN_ANNOUNCEMENT_EN) so they’re easy
to tweak or swap for A/B testing; define these constants near the top of the
file and replace the inline literals in the Promise.all call with the new
constant names, keeping the existing function signatures and variable usages
unchanged.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 6a573716-e966-4911-8d28-6ba0f8f4b4f5
📒 Files selected for processing (2)
functions/src/funcs/tts.tssrc/components/TuningSettings.tsx
f5429db to
6cacba9
Compare
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
There was a problem hiding this comment.
🧹 Nitpick comments (1)
functions/src/funcs/tts.ts (1)
238-241:?? nullは冗長ですが動作に影響なし。
download()の戻り値がundefinedになることはないため、?? nullは省略可能です。ただし、意図を明確にするためにそのままでも問題ありません。♻️ 簡略化の例
- const jaBuffer = jaAudioData?.[0] ?? null; - const enBuffer = enAudioData?.[0] ?? null; - const jaAudioContent = jaBuffer?.toString('base64') ?? null; - const enAudioContent = enBuffer?.toString('base64') ?? null; + const jaBuffer = jaAudioData[0]; + const enBuffer = enAudioData[0]; + const jaAudioContent = jaBuffer.toString('base64'); + const enAudioContent = enBuffer.toString('base64');🤖 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 238 - 241, The code uses redundant "?? null" when assigning jaBuffer/enBuffer and jaAudioContent/enAudioContent; since the download() result is never undefined, remove the "?? null" fallbacks in the assignments around jaBuffer, enBuffer, jaAudioContent, and enAudioContent so values come directly from jaAudioData?.[0] and enAudioData?.[0] and their .toString('base64') results; update the four lines (the jaBuffer, enBuffer, jaAudioContent, enAudioContent assignments) accordingly to simplify the logic while preserving the same runtime behavior.
🤖 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 238-241: The code uses redundant "?? null" when assigning
jaBuffer/enBuffer and jaAudioContent/enAudioContent; since the download() result
is never undefined, remove the "?? null" fallbacks in the assignments around
jaBuffer, enBuffer, jaAudioContent, and enAudioContent so values come directly
from jaAudioData?.[0] and enAudioData?.[0] and their .toString('base64')
results; update the four lines (the jaBuffer, enBuffer, jaAudioContent,
enAudioContent assignments) accordingly to simplify the logic while preserving
the same runtime behavior.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 76ab263a-ad41-46de-a2ff-48c46a45333c
📒 Files selected for processing (1)
functions/src/funcs/tts.ts
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
@coderabbitai resume |
✅ Actions performedReviews resumed. |
|
@coderabbitai 残指摘を教えてください |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: Length of output: 116485
|
| # | ファイル | 行 | 内容 |
|---|---|---|---|
| 1 | functions/src/funcs/tts.ts |
126–137 | ssmlEn の型検査前に normalizeRomanText() を呼んでいるため、非文字列入力で invalid-argument でなく 500 になる可能性あり |
| 2 | src/hooks/useTTS.test.ts |
164–177 | 再レンダーで calls 配列が [ja, ja, en] になった場合に calls[1] が落ちる flaky なテスト |
| 3 | src/components/TuningSettings.tsx |
99–111 | TuningSettings と useTTS の両方で AsyncStorage を読んでいるため、選択直後に古い値で上書きされるレース |
| 4 | src/hooks/useBusTTSText.ts |
91–100 | 英語バス案内の nameRoman に括弧除去が適用されておらず、Foo (Bar) がそのまま英語 TTS に流れる |
🧹 Nitpick(未対応)
| # | ファイル | 行 | 内容 |
|---|---|---|---|
| 5 | src/utils/ttsSpeechFetcher.test.ts |
12–18 | beforeEach の jest.clearAllMocks() が afterEach と重複 |
| 6 | functions/src/cli/find-tts-cache.ts |
198–201 | フォールバックパスが .mp3 固定で、Gemini 移行後の新エントリと不整合になる可能性(コメント追加推奨) |
| 7 | functions/src/utils/normalize.ts |
38–40 | .Sta\. の先頭 . がワイルドカードとして機能しており、意図しないマッチが発生しうる |
| 8 | functions/src/funcs/tts.ts |
268–281 | 日本語 TTS 用プロンプトが英語で書かれている(発音精度に影響する可能性) |
| 9 | functions/src/funcs/tts.ts |
269–282 | プロンプト文字列がインラインのまま(定数化推奨) |
| 10 | functions/src/funcs/tts.ts |
238–241 | ?? null が冗長 |
#1(型検査前呼び出し)と #4(バス英語 TTS の括弧)は実行時エラーや音声品質に直結するため、優先度が高めです。
🧠 Learnings used
Learnt from: CR
Repo: TrainLCD/MobileApp PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2026-02-27T08:01:30.350Z
Learning: Provide code reviews and feedback in Japanese
Learnt from: TinyKitten
Repo: TrainLCD/MobileApp PR: 0
File: :0-0
Timestamp: 2025-08-11T21:13:39.083Z
Learning: TinyKitten prefers concise code reviews for the TrainLCD/MobileApp repository. Keep review comments brief and to the point.
Learnt from: TinyKitten
Repo: TrainLCD/MobileApp PR: 5102
File: .env:0-0
Timestamp: 2026-01-18T01:25:10.303Z
Learning: TrainLCD/MobileAppのレビューコメントでは、CodeRabbitの組み込みツール(dotenv-linter等)による指摘と、プロジェクト固有のコーディング規約による指摘を明確に区別して記載すること。組み込みツールの指摘であることを明示的に伝えること。
Learnt from: CR
Repo: TrainLCD/MobileApp PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2026-02-27T08:01:30.350Z
Learning: Conduct code interactions with GitHub Copilot in Japanese
Learnt from: TinyKitten
Repo: TrainLCD/MobileApp PR: 5464
File: android/app/src/main/java/me/tinykitten/trainlcd/MainApplication.kt:33-37
Timestamp: 2026-02-27T07:30:06.268Z
Learning: TinyKitten prefers not to modify code taken from official templates (e.g., Expo, React Native) to maintain alignment with upstream and ease future updates.
Learnt from: TinyKitten
Repo: TrainLCD/MobileApp PR: 4448
File: functions/src/funcs/tts.ts:214-232
Timestamp: 2025-08-11T20:23:23.071Z
Learning: PR `#4448` in TrainLCD/MobileApp is specifically about AI feedback summarization and labeling functionality, not about TTS (Text-to-Speech) improvements. The TTS code changes appear to be part of a modularization refactoring but are not the focus of this PR.
Learnt from: CR
Repo: TrainLCD/MobileApp PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2026-02-27T08:01:30.350Z
Learning: Write commit messages in Japanese (e.g., `テレメトリー送信機をリファクタリングしてnull状態を回避`)
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 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 241-260: The ja-JP voice is hardcoded and never reads the
Firestore config or request override; update the logic that sets jaVoiceName to
mirror the English flow: read ttsConfig?.jaVoiceName (from the fetched tts
config) into a defaultJaVoice, then set jaVoiceName to req.data.jaVoiceName if
present and a string, otherwise use defaultJaVoice (and apply the same fix for
the duplicate block referenced around lines 341-349). Ensure you modify the
variables named ttsConfig, defaultEnVoice/defaultJaVoice, enVoiceName, and
jaVoiceName so the cache key and synthesis use the selected Japanese voice.
- Around line 156-166: 現在、汎用の catch ブロックが全ての例外を HttpsError('internal', ...)
に再包装しており、synthesizeWithGoogleTts が投げる HttpsError('failed-precondition', ...)
や「GCP project ID is not set」の failed-precondition を隠蔽しています。該当する catch
ブロックを修正して、catch (error) { if (error instanceof HttpsError) throw error; throw
new HttpsError('internal', '...', { original: String(error) }); } のように
HttpsError インスタンスはそのまま再スローし、それ以外のみ internal に包むようにしてください(参照シンボル:
synthesizeWithGoogleTts、および catch ブロックで再包装している箇所)。
In `@src/components/TuningSettings.tsx`:
- Around line 175-195: The voice picker never exposes the "not specified" option
so users cannot reset ttsEnVoiceName to '', update showVoicePicker to add
translate('notSpecified') as an explicit choice on both platforms: for iOS
extend the options array built from TTS_VOICE_NAMES to include
translate('notSpecified') (before the cancel entry), adjust the index handling
in ActionSheetIOS.showActionSheetWithOptions to call onSelect('') when that
index is chosen; for Android include translate('notSpecified') when calling
setVoicePickerState (e.g., by passing a choices list containing TTS_VOICE_NAMES
plus translate('notSpecified')) and ensure the onSelect passed to
setVoicePickerState maps that label to ''. Apply the same addition for the other
occurrences referenced (lines ~344-345 and ~450-491) where showVoicePicker
behavior is mirrored.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 39a6fe26-4ebd-45fa-b3b0-8fec5d4d8c3a
📒 Files selected for processing (4)
functions/README.mdfunctions/src/funcs/tts.tsios/TrainLCD.xcodeproj/xcshareddata/xcschemes/CanaryTrainLCD.xcschemesrc/components/TuningSettings.tsx
✅ Files skipped from review due to trivial changes (1)
- functions/README.md
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/hooks/useBusTTSText.ts (1)
100-106:⚠️ Potential issue | 🟡 Minor
boundForEnがundefined文字列になる可能性があります104行目でテンプレート文字列を使用しているため、
directionalStopsが未定義の場合、その値がそのまま"undefined"という文字列になります。ここは空文字にフォールバックする必要があります。修正案
const boundForEn = useMemo( () => isLoopLine ? (loopLineBoundEn?.boundFor?.replaceAll('&', ' and ') ?? '') - : `${directionalStops?.map((s) => s?.nameRoman ?? '').join(' and ')}`, + : (directionalStops?.map((s) => s?.nameRoman ?? '').join(' and ') ?? + ''), [directionalStops, isLoopLine, loopLineBoundEn?.boundFor] );🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/hooks/useBusTTSText.ts` around lines 100 - 106, boundForEn can become the literal string "undefined" when directionalStops is undefined because the template string always coerces undefined to "undefined"; update the useMemo initialization for boundForEn (the function using useMemo, isLoopLine, directionalStops, and loopLineBoundEn?.boundFor) to explicitly fall back to an empty string when directionalStops is falsy (e.g. use a conditional: if isLoopLine use loopLineBoundEn?.boundFor replacement as before, else if directionalStops is present use directionalStops.map(...).join(' and ') otherwise return ''), ensuring the memo dependencies remain [directionalStops, isLoopLine, loopLineBoundEn?.boundFor].
🧹 Nitpick comments (2)
src/utils/ttsSpeechFetcher.ts (1)
98-99: キャッシュキーにjaVoiceNameが含まれていません。
buildCacheKeyはenVoiceNameのみを含んでいますが、将来的にjaVoiceNameがユーザー選択可能になった場合、異なる日本語ボイスで同じキャッシュが返される可能性があります。Based on learnings: 日本語ボイスは現在固定仕様のため、今は問題になりませんが、リリース確定時の対応で考慮が必要です。
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/utils/ttsSpeechFetcher.ts` around lines 98 - 99, buildCacheKey currently only encodes opts.enVoiceName so different jaVoiceName selections could collide; update the buildCacheKey implementation to include opts.jaVoiceName (e.g. append `${opts.jaVoiceName ?? ''}` into the key generation) so the cache key uniquely reflects both enVoiceName and jaVoiceName; ensure you reference the FetchSpeechOptions fields (jaVoiceName, enVoiceName, textJa, textEn) and preserve the existing separator/null-coalescing approach.src/utils/ttsSpeechFetcher.test.ts (1)
12-19:jest.clearAllMocks()がbeforeEachとafterEachの両方で呼ばれています。PR コメントでも指摘されていますが、
afterEachでjest.clearAllMocks()を呼んでいるため、beforeEachでの呼び出しは冗長です。♻️ 修正案
describe('fetchSpeechAudio', () => { beforeEach(() => { - jest.clearAllMocks(); clearFetchCache(); });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/utils/ttsSpeechFetcher.test.ts` around lines 12 - 19, Duplicate call to jest.clearAllMocks() exists in both beforeEach and afterEach; remove the redundant one in beforeEach. Edit the test setup so beforeEach only calls clearFetchCache() (leave clearFetchCache() intact) and keep jest.clearAllMocks() in afterEach; update the beforeEach block that currently contains jest.clearAllMocks() and clearFetchCache() to only call clearFetchCache().
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/hooks/useBusTTSText.ts`:
- Around line 138-145: allStops currently filters out the current station by
comparing s.id to station?.id which is unsafe because slicedStations are
normalized by groupId; change the filter to exclude any station whose groupId
matches station?.groupId (i.e., use s.groupId === station?.groupId) so that all
members of the same group are omitted; update the useMemo that defines allStops
(which references slicedStations, station, getIsPass) to perform the groupId
comparison instead of id to prevent the current station appearing via another id
in the same group.
---
Outside diff comments:
In `@src/hooks/useBusTTSText.ts`:
- Around line 100-106: boundForEn can become the literal string "undefined" when
directionalStops is undefined because the template string always coerces
undefined to "undefined"; update the useMemo initialization for boundForEn (the
function using useMemo, isLoopLine, directionalStops, and
loopLineBoundEn?.boundFor) to explicitly fall back to an empty string when
directionalStops is falsy (e.g. use a conditional: if isLoopLine use
loopLineBoundEn?.boundFor replacement as before, else if directionalStops is
present use directionalStops.map(...).join(' and ') otherwise return ''),
ensuring the memo dependencies remain [directionalStops, isLoopLine,
loopLineBoundEn?.boundFor].
---
Nitpick comments:
In `@src/utils/ttsSpeechFetcher.test.ts`:
- Around line 12-19: Duplicate call to jest.clearAllMocks() exists in both
beforeEach and afterEach; remove the redundant one in beforeEach. Edit the test
setup so beforeEach only calls clearFetchCache() (leave clearFetchCache()
intact) and keep jest.clearAllMocks() in afterEach; update the beforeEach block
that currently contains jest.clearAllMocks() and clearFetchCache() to only call
clearFetchCache().
In `@src/utils/ttsSpeechFetcher.ts`:
- Around line 98-99: buildCacheKey currently only encodes opts.enVoiceName so
different jaVoiceName selections could collide; update the buildCacheKey
implementation to include opts.jaVoiceName (e.g. append `${opts.jaVoiceName ??
''}` into the key generation) so the cache key uniquely reflects both
enVoiceName and jaVoiceName; ensure you reference the FetchSpeechOptions fields
(jaVoiceName, enVoiceName, textJa, textEn) and preserve the existing
separator/null-coalescing approach.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 850cf22b-5b7e-49fc-9e60-482caec445b2
📒 Files selected for processing (9)
functions/src/funcs/tts.tssrc/hooks/useBusTTSText.test.tsxsrc/hooks/useBusTTSText.tssrc/hooks/useTTS.test.tssrc/hooks/useTTS.tssrc/hooks/useTTSText.test.tsxsrc/hooks/useTTSText.tssrc/utils/ttsSpeechFetcher.test.tssrc/utils/ttsSpeechFetcher.ts
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
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)
src/hooks/useBusTTSText.ts (1)
118-133:⚠️ Potential issue | 🟠 Major
afterNextStationが無いケースで中間停留所案内が壊れます
afterNextStationIndexが-1のまま Line 132 のslice(nextStationIndex + 1, afterNextStationIndex)が走ると、実際は次の次の停留所が無い場面でもbetweenNextStationに余計な停留所が入ります。結果として「お乗り換えです」の案内が誤って読み上げられるので、src/hooks/useTTSText.tsと同じ境界チェックを入れたいです。💡 修正案
const betweenNextStation = useMemo( - () => slicedStations.slice(nextStationIndex + 1, afterNextStationIndex), + () => + nextStationIndex === -1 || + afterNextStationIndex === -1 || + afterNextStationIndex <= nextStationIndex + ? [] + : slicedStations.slice(nextStationIndex + 1, afterNextStationIndex), [afterNextStationIndex, nextStationIndex, slicedStations] );🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/hooks/useBusTTSText.ts` around lines 118 - 133, The slice for betweenNextStation can produce incorrect entries when afterNextStationIndex is -1; update the useMemo that computes betweenNextStation so it first checks the boundary (e.g., if afterNextStationIndex <= nextStationIndex or afterNextStationIndex === -1) and return an empty array in that case, otherwise return slicedStations.slice(nextStationIndex + 1, afterNextStationIndex); reference the variables afterNextStationIndex, nextStationIndex and the betweenNextStation useMemo when making the change.
🧹 Nitpick comments (2)
src/hooks/useBusTTSText.ts (1)
725-733: 括弧除去は返却直前ではなく英字名側に寄せた方が安全ですここで
jaText/nextJaTextまで一律にreplace(parenthesisRegexp, '')すると、日本語 SSML 側の ASCII 括弧まで落とします。括弧除去が必要なのは英字名だけなので、最低でも日本語側には適用せず、理想的にはnameRomanを組み立てる時点で正規化した方が副作用が少ないです。 Based on learnings: InLineBoard.tsxfor bus lines (TransportType.Bus), only thenameRomanfield requires parentheses removal viaparenthesisRegexp.replace(). Other language fields should remain unchanged in the mapping.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/hooks/useBusTTSText.ts` around lines 725 - 733, The current code trims and applies parenthesisRegexp replacement to both jaText/nextJaText and enText/nextEnText right before returning, which strips ASCII parentheses from Japanese SSML; instead, remove parentheses only for the romanized English names and not for Japanese text—move parenthesisRegexp.replace() to where nameRoman is composed (e.g. the mapping for TransportType.Bus in LineBoard.tsx) and stop applying it to jaText and nextJaText in useBusTTSText.ts so that jaText/nextJaText remain unmodified while enText/nextEnText (or specifically nameRoman) are normalized.src/hooks/useTTSText.ts (1)
25-35: 共有契約は hook 本体から切り出しておくと保守しやすいです
TTSTextResultはsrc/hooks/useBusTTSText.tsから型参照されていて、resolveTemplateTheme()も両 hook で重複しています。共通型と共通解決ロジックを中立モジュールに寄せると、hooks 間依存と更新漏れを減らせます。🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/hooks/useTTSText.ts` around lines 25 - 35, Extract the shared type and logic into a neutral module: move the TTSTextResult interface and the resolveTemplateTheme function out of useTTSText and into a new shared module (e.g., ttsShared) and export them; then update both useTTSText and useBusTTSText to import TTSTextResult and resolveTemplateTheme from that module so the hooks no longer duplicate the type or resolution logic and future changes are centralized.
🤖 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 `@src/hooks/useBusTTSText.ts`:
- Around line 118-133: The slice for betweenNextStation can produce incorrect
entries when afterNextStationIndex is -1; update the useMemo that computes
betweenNextStation so it first checks the boundary (e.g., if
afterNextStationIndex <= nextStationIndex or afterNextStationIndex === -1) and
return an empty array in that case, otherwise return
slicedStations.slice(nextStationIndex + 1, afterNextStationIndex); reference the
variables afterNextStationIndex, nextStationIndex and the betweenNextStation
useMemo when making the change.
---
Nitpick comments:
In `@src/hooks/useBusTTSText.ts`:
- Around line 725-733: The current code trims and applies parenthesisRegexp
replacement to both jaText/nextJaText and enText/nextEnText right before
returning, which strips ASCII parentheses from Japanese SSML; instead, remove
parentheses only for the romanized English names and not for Japanese text—move
parenthesisRegexp.replace() to where nameRoman is composed (e.g. the mapping for
TransportType.Bus in LineBoard.tsx) and stop applying it to jaText and
nextJaText in useBusTTSText.ts so that jaText/nextJaText remain unmodified while
enText/nextEnText (or specifically nameRoman) are normalized.
In `@src/hooks/useTTSText.ts`:
- Around line 25-35: Extract the shared type and logic into a neutral module:
move the TTSTextResult interface and the resolveTemplateTheme function out of
useTTSText and into a new shared module (e.g., ttsShared) and export them; then
update both useTTSText and useBusTTSText to import TTSTextResult and
resolveTemplateTheme from that module so the hooks no longer duplicate the type
or resolution logic and future changes are centralized.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 4ccb1abc-8e20-4e1d-b866-de19df9f4ebf
📒 Files selected for processing (2)
src/hooks/useBusTTSText.tssrc/hooks/useTTSText.ts
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
There was a problem hiding this comment.
🧹 Nitpick comments (2)
src/hooks/useBusTTSText.ts (2)
35-40:resolveTemplateThemeは共通化しておくと保守しやすいです。同じ実装が
src/hooks/useTTSText.tsにもあるので、テーマ追加時の片更新を避けるために共通ユーティリティへ出しておくとズレにくいです。🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/hooks/useBusTTSText.ts` around lines 35 - 40, The resolveTemplateTheme function is duplicated across useBusTTSText.ts and useTTSText.ts; extract it into a shared utility (e.g., a new helper module) and export it so both hooks import the same implementation, then remove the duplicate definitions in useBusTTSText and useTTSText and update their imports to use the shared resolveTemplateTheme; ensure the function signature and return type (AppTheme) remain unchanged and reference APP_THEME constants exactly as in the original implementation.
731-739: 括弧除去は文全体ではなく英語断片側に寄せたいです。返却直前に
jaText/nextJaTextまで同じ正規表現をかけると、将来 SSML や日本語名に括弧が入ったときも一律で削れてしまいます。今回の目的は英語読み上げ用の正規化なので、nameRomanを組み立てる箇所だけで落としておく方が意図も副作用も明確です。🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/hooks/useBusTTSText.ts` around lines 731 - 739, The code currently applies parenthesisRegexp trimming to both jaText/nextJaText and enText/nextEnText at return, which removes parentheses from Japanese text too; change it so only the English fragments are stripped: remove the replace(parenthesisRegexp, '') call from jaText and nextJaText in the returned object and ensure parentheses removal is performed earlier and locally where nameRoman is constructed (e.g., inside the code that builds nameRoman, using parenthesisRegexp on the Romanized name), leaving jaText/nextJaText untouched; update references to jaText, enText, nextJaText, nextEnText, nameRoman, and parenthesisRegexp accordingly.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@src/hooks/useBusTTSText.ts`:
- Around line 35-40: The resolveTemplateTheme function is duplicated across
useBusTTSText.ts and useTTSText.ts; extract it into a shared utility (e.g., a
new helper module) and export it so both hooks import the same implementation,
then remove the duplicate definitions in useBusTTSText and useTTSText and update
their imports to use the shared resolveTemplateTheme; ensure the function
signature and return type (AppTheme) remain unchanged and reference APP_THEME
constants exactly as in the original implementation.
- Around line 731-739: The code currently applies parenthesisRegexp trimming to
both jaText/nextJaText and enText/nextEnText at return, which removes
parentheses from Japanese text too; change it so only the English fragments are
stripped: remove the replace(parenthesisRegexp, '') call from jaText and
nextJaText in the returned object and ensure parentheses removal is performed
earlier and locally where nameRoman is constructed (e.g., inside the code that
builds nameRoman, using parenthesisRegexp on the Romanized name), leaving
jaText/nextJaText untouched; update references to jaText, enText, nextJaText,
nextEnText, nameRoman, and parenthesisRegexp accordingly.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 43ab8f07-9bc6-44a8-bc3c-769ebe1b4cfd
📒 Files selected for processing (2)
src/hooks/useBusTTSText.tssrc/hooks/useTTSText.ts
Summary
useTTS.test.tsの期待値を.mp3→.wavに更新createAudioPlayerの複数回呼び出しに対応し、calls.lengthの検証をtoBe(2)→toBeGreaterThanOrEqual(2)に緩和(JA→EN順序検証は維持)Test plan
npm test全テスト通過確認済み🤖 Generated with Claude Code
Summary by CodeRabbit
リリースノート
New Features
Chores
Breaking Changes