Repository navigation
TrainLCDをFirebaseからCloudflareへ全面移行 - #6238
Conversation
Co-Authored-By: Claude Opus 4.8 <[email protected]>
…エンド) Co-Authored-By: Claude Opus 4.8 <[email protected]>
匿名認証をインストールID+Worker発行JWTに、Firestore/Storage/RemoteConfigをWorkerエンドポイントに置換し、@react-native-firebaseを撤去。 Co-Authored-By: Claude Opus 4.8 <[email protected]>
firebase.jsonとandroid gradleのgoogle-services参照、LicensesのFirebaseエントリを削除。ネイティブ再生成とプロジェクト撤去の手順をdocsに追加。 Co-Authored-By: Claude Opus 4.8 <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
find-tts-cache/find-orphaned-tts を Cloudflare REST(KV)+S3(R2) で再実装。fewshot.example.jsonl と利用手順を追加。 Co-Authored-By: Claude Opus 4.8 <[email protected]>
旧Cloud Functions用の*_TTS_API_URL/*_FEEDBACK_API_URL(と未使用のLOCAL)を廃し、workerUrl()で/tts・/postFeedbackを生成する。 Co-Authored-By: Claude Opus 4.8 <[email protected]>
SESSION_JWT_SECRET未設定を明示し、fetchハンドラ全体をtry/catchでログ+JSON500化。 Co-Authored-By: Claude Opus 4.8 <[email protected]>
DISCORD_REVIEW_WEBHOOK_URL/GOOGLE_SA_KEY 未設定は通知オフ扱いとし、毎時Cronのエラーログを抑止。 Co-Authored-By: Claude Opus 4.8 <[email protected]>
stdinパイプ(Windowsで値が届かず空secretになる)を廃し、Nodeで生成した一時JSONをwrangler secret bulkに渡す方式に。put-secrets.ps1とbuild-secrets-json.mjsを追加、GOOGLE_SA_KEY_FILEは.secrets.env行でも指定可。 Co-Authored-By: Claude Opus 4.8 <[email protected]>
Queuesの128KB上限に音声が収まらずPayload Too Largeになるため、tts-cacheキューを撤去し/ttsハンドラからwriteTtsCacheでR2+KVへ直接保存する。 Co-Authored-By: Claude Opus 4.8 <[email protected]>
few-shotはfeedbackトリアージ専用でTTSと無関係なため、設定用KV(config:fewshot)へ移し、変数をFEW_SHOT_KV_KEYに変更。 Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughFirebase Cloud Functions・Firestore・Storage・Auth・Remote Config・Pub/Sub への依存をすべて除去し、バックエンドを Cloudflare Workers(KV/R2/Queues/Workers AI/Azure Speech)へ完全移行した。アプリ側は installId ベースのセッション JWT 認証と Worker URL を使う形に統一されている。 ChangesFirebase → Cloudflare Workers 全面移行
Sequence Diagram(s)sequenceDiagram
participant App as モバイルアプリ
participant Worker as Cloudflare Worker
participant KV as KV Namespace
participant R2 as R2 Bucket
participant Azure as Azure Speech
participant Queue as Cloudflare Queue
participant AI as Workers AI
rect rgba(59, 130, 246, 0.5)
note over App,Worker: セッション確立
App->>Worker: POST /auth/token { installId }
Worker-->>App: { token, expiresIn }
end
rect rgba(34, 197, 94, 0.5)
note over App,Azure: TTS 取得
App->>Worker: POST /tts (Bearer, ssmlJa, ssmlEn)
Worker->>KV: get voice:{id}
alt キャッシュヒット
KV-->>Worker: pathJa, pathEn
Worker->>R2: get audio files
R2-->>Worker: バイナリ
else キャッシュミス
Worker->>Azure: synthesizeSpeech x2
Azure-->>Worker: SynthesizedAudio
Worker->>R2: put (waitUntil)
Worker->>KV: put voice:{id} (waitUntil)
end
Worker-->>App: { jaAudio, enAudio }
end
rect rgba(168, 85, 247, 0.5)
note over App,AI: フィードバック送信〜トリアージ
App->>Worker: POST /postFeedback (Bearer, report)
Worker->>Queue: send FeedbackQueueMessage
Worker-->>App: { ok, queued }
Queue->>Worker: queue consumer
Worker->>AI: runTriage(few-shot + description)
AI-->>Worker: AIReport
end
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Possibly related PRs
Poem
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
|
There was a problem hiding this comment.
Actionable comments posted: 15
Note
Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/hooks/useAnonymousUser.ts (1)
8-25:⚠️ Potential issue | 🔴 Critical | ⚡ Quick win
useRefの更新では再レンダリングされないため、常にnullを返す可能性が高い
useRefの.currentを更新しても React は再レンダリングをトリガーしません。getInstallId()が完了してuserRef.current = { uid }を設定しても、呼び出し側コンポーネントは再レンダリングされず、初回のnullのまま使い続けます。
useStateを使用するか、コメントにある通りuseCachedAnonymousUserの使用を強制する設計に変更すべきです。🐛 useState を使用した修正案
-import { useEffect, useRef } from 'react'; +import { useEffect, useState } from 'react'; import { getInstallId } from '../lib/installId'; import type { AppUser } from '../store/atoms/auth'; /** * Jotaiが使えない環境の時にもユーザーを持ちたい場合に使います。基本的に `useCachedAnonymousUser` を使ってください。 */ export const useAnonymousUser = (): AppUser | null => { - const userRef = useRef<AppUser | null>(null); + const [user, setUser] = useState<AppUser | null>(null); useEffect(() => { let active = true; getInstallId() .then((uid) => { if (active) { - userRef.current = { uid }; + setUser({ uid }); } }) .catch(() => undefined); return () => { active = false; }; }, []); - return userRef.current; + return user; };🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/hooks/useAnonymousUser.ts` around lines 8 - 25, The useAnonymousUser hook uses useRef which does not trigger re-renders when its value is updated, causing the hook to always return null even after getInstallId() completes successfully. Replace useRef with useState to properly trigger re-renders when the anonymous user data is fetched. Change useRef<AppUser | null>(null) to useState<AppUser | null>(null), update the .then() callback to call the state setter instead of assigning to userRef.current, and return the state value instead of userRef.current at the end of the hook.
🟡 Minor comments (10)
functions/src/utils/ttsVoice.test.ts-10-14 (1)
10-14:⚠️ Potential issue | 🟡 Minor | ⚡ Quick win
en-US-Neuralの拒否ケースを回帰テストに追加してください。
isAzureVoiceNameの境界条件として、Neuralのみ(語幹なし)を明示的にfalse固定しておくと、Line 9 の正規表現回帰を防げます。🔧 追加入力例
it('rejects non-Azure voice ids', () => { expect(isAzureVoiceName('ja-JP-Standard-B')).toBe(false); expect(isAzureVoiceName('en-US-Chirp3-HD-Aoede')).toBe(false); + expect(isAzureVoiceName('en-US-Neural')).toBe(false); expect(isAzureVoiceName('')).toBe(false); });🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@functions/src/utils/ttsVoice.test.ts` around lines 10 - 14, The test for isAzureVoiceName is missing a boundary condition test case for the string 'en-US-Neural' which should be rejected. Add an expect statement in the 'rejects non-Azure voice ids' test block to explicitly verify that isAzureVoiceName('en-US-Neural') returns false, ensuring the regex pattern at Line 9 correctly handles the case where Neural appears without a stem suffix.functions/src/routes/tts.ts-70-75 (1)
70-75:⚠️ Potential issue | 🟡 Minor | ⚡ Quick win
requireStringのエラーメッセージが引数実態と一致していません。Line 74-75 の
"containing the message to add"は/ttsのssmlJa/ssmlEn契約と不一致で、クライアント側の調査を難しくします。対象パラメータ名に合わせた文言へ更新してください。🔧 修正案
if (typeof value !== 'string' || value.length === 0) { throw new CallableError( 'invalid-argument', - `The function must be called with one argument "${name}" containing the message to add.` + `The function must be called with one argument "${name}" containing a non-empty SSML string.` ); }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@functions/src/routes/tts.ts` around lines 70 - 75, The error message in the `requireString` function (lines 74-75) contains hardcoded text "containing the message to add" which does not match the actual contract for TTS parameters like `ssmlJa` and `ssmlEn` that contain SSML content, not generic messages. Update the error message to be more generic and parameter-agnostic by removing the assumption about what the parameter contains. Instead, make the message reference the parameter name (already available via the `name` argument) and describe the general requirement that it must be a non-empty string, without prescribing what type of content it should contain.src/lib/installId.ts-10-25 (1)
10-25:⚠️ Potential issue | 🟡 Minor | ⚡ Quick win初回呼び出し時の競合状態によりIDが重複生成される可能性
getInstallId()が複数箇所から同時に呼ばれた場合、両方がcachedInstallId === nullかつstored === nullの状態でrandomUUID()を実行し、異なる ID を生成・保存する可能性があります。最初のsetItemAsyncが完了する前に 2 回目の呼び出しがgetItemAsyncを実行すると発生します。また、
SecureStoreの操作は keychain エラーで例外を投げる可能性がありますが、エラーハンドリングがありません。🛡️ 競合防止とエラーハンドリングの追加案
let cachedInstallId: string | null = null; +let pendingPromise: Promise<string> | null = null; -export const getInstallId = async (): Promise<string> => { +export const getInstallId = (): Promise<string> => { if (cachedInstallId) { - return cachedInstallId; + return Promise.resolve(cachedInstallId); } + if (pendingPromise) { + return pendingPromise; + } - const stored = await SecureStore.getItemAsync(INSTALL_ID_KEY); - if (stored) { - cachedInstallId = stored; - return stored; - } - - const generated = Crypto.randomUUID(); - await SecureStore.setItemAsync(INSTALL_ID_KEY, generated); - cachedInstallId = generated; - return generated; + pendingPromise = (async () => { + try { + const stored = await SecureStore.getItemAsync(INSTALL_ID_KEY); + if (stored) { + cachedInstallId = stored; + return stored; + } + const generated = Crypto.randomUUID(); + await SecureStore.setItemAsync(INSTALL_ID_KEY, generated); + cachedInstallId = generated; + return generated; + } finally { + pendingPromise = null; + } + })(); + return pendingPromise; };🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/lib/installId.ts` around lines 10 - 25, The getInstallId function has a race condition where multiple simultaneous calls can generate different IDs if they all execute the randomUUID() before any complete the setItemAsync call, and it lacks error handling for SecureStore operations that may throw keychain exceptions. Add a Promise-based locking mechanism to ensure only one concurrent execution of the ID generation logic (by tracking a pending promise and reusing it across concurrent calls), and wrap the SecureStore.getItemAsync and SecureStore.setItemAsync calls in try-catch blocks to properly handle potential keychain errors.functions/src/routes/uploadImage.ts-38-41 (1)
38-41:⚠️ Potential issue | 🟡 Minor | ⚡ Quick win不正な base64 入力時のエラーハンドリング
base64ToBytesは不正な base64 文字列を受け取ると予期しない結果やエラーを引き起こす可能性があります。デコード失敗時に明確なエラーを返すことを推奨します。🛡️ 修正案
- const bytes = base64ToBytes(imageBase64); + let bytes: Uint8Array; + try { + bytes = base64ToBytes(imageBase64); + } catch { + throw new CallableError('invalid-argument', 'invalid base64 encoding'); + } if (bytes.byteLength > MAX_IMAGE_BYTES) {🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@functions/src/routes/uploadImage.ts` around lines 38 - 41, The base64ToBytes function call at line 38 in uploadImage.ts does not handle invalid base64 input, which could cause unexpected errors or results. Wrap the base64ToBytes(imageBase64) call in a try-catch block to catch any decoding errors, and throw a CallableError with error code 'invalid-argument' and a clear message indicating that the image data is not valid base64 when decoding fails.functions/src/consumers/feedbackTriage.test.ts-1-3 (1)
1-3:⚠️ Potential issue | 🟡 Minor | ⚡ Quick win
afterEachでjest.clearAllMocks()を追加してください。このテストではモックのリセットフックがなく、ガイドライン要件を満たしていません。
💡 修正案
import { coerceReport, looksLikeSpam } from './feedbackTriage'; + +afterEach(() => { + jest.clearAllMocks(); +});As per coding guidelines,
テストの afterEach で jest.clearAllMocks() を呼び出してください。🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@functions/src/consumers/feedbackTriage.test.ts` around lines 1 - 3, Add an `afterEach` hook to the describe block in feedbackTriage.test.ts that calls `jest.clearAllMocks()` to ensure all mocks are properly reset between test cases. This hook should be placed after the imports and before or after the test cases to comply with testing guidelines and prevent mock state from leaking between tests.Source: Coding guidelines
functions/src/consumers/feedbackTriage.ts-497-498 (1)
497-498:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winDiscord 通知文言にタイポがあります。
届きまさしたは届きましたに修正した方がよいです(両方のメッセージ)。💡 修正案
- ? `**🙏アプリから新しいフィードバックが届きまさした‼🙏**\n\`\`\`${description}\`\`\`` - : `**😭アプリからクラッシュレポートが届きまさした‼😭**\n**${description}**\n\`\`\`${stacktrace + ? `**🙏アプリから新しいフィードバックが届きました‼🙏**\n\`\`\`${description}\`\`\`` + : `**😭アプリからクラッシュレポートが届きました‼😭**\n**${description}**\n\`\`\`${stacktrace ?.split('\n')🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@functions/src/consumers/feedbackTriage.ts` around lines 497 - 498, Fix the Japanese typo in the Discord notification messages in the feedbackTriage.ts file. In the ternary operator that constructs the notification message, replace "届きまさした" with "届きました" in both the feedback message (the first part of the ternary) and the crash report message (the second part of the ternary) to correct the grammatical error in both Discord notification strings.functions/README.md-21-22 (1)
21-22:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winREADME 内で few-shot の保存先が矛盾しています。
Line 21-22 では few-shot を R2 扱いにしていますが、Line 106-108 では
CONFIG_KV(config:fewshot)を参照しています。どちらかに統一しないとセットアップで誤設定が起きます。Also applies to: 106-108
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@functions/README.md` around lines 21 - 22, The README contains contradictory information about where few-shot data is stored. In functions/README.md lines 21-22, few-shot data is listed as being stored in R2, but in functions/README.md lines 106-108, the documentation references CONFIG_KV with config:fewshot, indicating KV storage instead. Resolve this contradiction by ensuring both sections consistently describe the same storage location for few-shot data. Determine the actual storage mechanism used in the codebase and update both locations to match that single source of truth.docs/cloudflare-migration-plan.md-49-50 (1)
49-50:⚠️ Potential issue | 🟡 Minor | ⚡ Quick win移行計画の記述が現行アーキテクチャとずれています(TTS キャッシュ経路 / few-shot 保存先)。
この計画書では
/ttsの Queue 投函・tts-cacheconsumer・few-shot の R2 保管が前提になっていますが、今回の移行結果は「TTS は/ttsから R2+KV へ直接保存」「few-shot はCONFIG_KV」です。運用手順の誤誘導を避けるため、ここを最新版に同期してください。Also applies to: 73-75, 110-112
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/cloudflare-migration-plan.md` around lines 49 - 50, The migration plan document in docs/cloudflare-migration-plan.md contains outdated architecture descriptions across multiple sections. The current implementation stores TTS cache directly in R2+KV from the `/tts` endpoint (not via Queue with a tts-cache consumer) and stores few-shot prompts in CONFIG_KV (not R2). Update the table entries at lines 49-50 (the `/tts` and `/postFeedback` rows) to reflect that TTS is saved directly to R2+KV without Queue involvement, and update the corresponding descriptions at lines 73-75 and lines 110-112 to align with the actual current architecture regarding TTS caching and few-shot storage locations to prevent operational confusion.docs/cloudflare-migration-phase3-checklist.md-38-51 (1)
38-51:⚠️ Potential issue | 🟡 Minor | ⚡ Quick win移行後アーキテクチャと手順の記述が一部ずれています。
Line 38 の
tts-cache-devキュー作成と、Line 50 の「R2 に配置」という説明は、同ファイル内のコマンド実体(CONFIG_KV への few-shot投入)および今回の移行方針と不整合です。feedback-triageキュー中心の記述へ修正し、few-shot は KV 配置で統一してください。🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/cloudflare-migration-phase3-checklist.md` around lines 38 - 51, The queue creation command and few-shot deployment description in the checklist are misaligned with the actual implementation and migration policy. In the wrangler queues create command, ensure the documentation focuses on the feedback-triage queue as the primary queue rather than tts-cache-dev. Additionally, update the comment describing few-shot placement to correctly state that few-shot is being placed in KV (CONFIG_KV binding) via the wrangler kv key put command, not in R2 as currently described. Align all documentation references to match the actual command implementations shown in the diff.functions/src/scheduled/appStoreReviews.test.ts-3-57 (1)
3-57:⚠️ Potential issue | 🟡 Minor | ⚡ Quick win
afterEachでjest.clearAllMocks()を追加してください。このファイルは現在モック未使用ですが、将来のモック追加時にテスト間汚染を防ぐため、共通で
afterEach(() => jest.clearAllMocks())を入れておくべきです。As per coding guidelines: 「テストの
afterEachでjest.clearAllMocks()を呼び出してください」。🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@functions/src/scheduled/appStoreReviews.test.ts` around lines 3 - 57, The test suite for parseAppStoreJson currently lacks an afterEach hook to clear mocks, which can cause test pollution when mocks are added in the future. Add an afterEach hook inside the describe('parseAppStoreJson') block that calls jest.clearAllMocks() to ensure mocks are properly cleared between test runs, following the coding guidelines for test cleanup.Source: Coding guidelines
🧹 Nitpick comments (4)
functions/src/routes/auth.ts (1)
35-38: 💤 Low valueエラーメッセージで内部設定名を露出
SESSION_JWT_SECRETというシークレット名を含むエラーメッセージを返しています。運用上のデバッグには便利ですが、攻撃者にシステム構成のヒントを与える可能性があります。本番環境では汎用的なメッセージに変更することを検討してください。
return new Response( - JSON.stringify({ error: 'server misconfigured: SESSION_JWT_SECRET' }), + JSON.stringify({ error: 'server configuration error' }), { status: 500, headers: JSON_HEADERS } );🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@functions/src/routes/auth.ts` around lines 35 - 38, The error response in the SESSION_JWT_SECRET validation block is exposing the internal secret name in the error message, which reveals system configuration details to potential attackers. Replace the error message in the JSON response from the current message that includes "SESSION_JWT_SECRET" with a generic, non-revealing message such as "Internal server error" or "Authentication service unavailable" that provides no hints about the internal configuration while maintaining the same HTTP status code 500 and headers.functions/src/lib/crypto.ts (1)
40-48: 💤 Low value長さが異なる場合の早期リターンはタイミング情報を漏洩する可能性あり
timingSafeEqualは長さが異なる場合に即座にfalseを返すため、長さの違いがタイミングで推測可能です。現在の用途(JWT 署名比較)では署名長が固定のため実害はありませんが、汎用ユーティリティとして公開する場合は注意が必要です。ドキュメントコメントに用途の制限を明記することを推奨します。
-/** タイミング安全な文字列比較。 */ +/** タイミング安全な文字列比較(同一長の文字列向け。長さが異なる場合は即座に false を返す)。 */🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@functions/src/lib/crypto.ts` around lines 40 - 48, The timingSafeEqual function has a documentation comment that does not clarify an important limitation regarding timing side-channel vulnerabilities. The early length check in the function (if a.length !== b.length return false) leaks timing information about whether the input strings have different lengths, which could be exploited in contexts where this function is used with variable-length inputs. Update the JSDoc comment for the timingSafeEqual function to document this constraint explicitly, noting that the function should only be used when comparing strings of equal or predictable lengths (such as fixed-length JWT signatures), and that it is not safe for comparing arbitrary-length strings where length differences might reveal sensitive information.functions/src/scheduled/googlePlayReviews.test.ts (1)
22-66: 🏗️ Heavy lift
runGooglePlayReviewJobの統合テストを追加して、通知/state 更新契約を固定してください。現状は純粋関数の単体テストのみで、ジョブ本体の「DRY_RUN 時に state を進めない」「Webhook 失敗時の state 挙動」「ページネーションと dedupe」の互換性が未検証です。
fetch・KV・token 取得をモックした統合テストをこのファイルに追加するのが安全です。As per coding guidelines:
**/*.{test,spec}.{ts,tsx,js,jsx,py,java,go,cs}: Test agents in isolation and with integration tests to ensure correctness and compatibility.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@functions/src/scheduled/googlePlayReviews.test.ts` around lines 22 - 66, The test file currently contains only unit tests for the pure function toPlayReviews but lacks integration tests for the main runGooglePlayReviewJob function. Add integration tests for runGooglePlayReviewJob that mock external dependencies (fetch calls, KV storage operations, and token acquisition) to verify the actual job behavior including state management during DRY_RUN mode, state updates after successful webhook calls, error handling when webhooks fail, and the compatibility of pagination and deduplication logic. These integration tests should be added to the same test file alongside the existing unit tests.Source: Coding guidelines
functions/src/scheduled/appStoreReviews.test.ts (1)
3-57: 🏗️ Heavy liftジョブ本体の統合シナリオも追加して回帰検知を強化してください。
今回の主変更は
runAppStoreReviewJobの KV 状態遷移・DryRun・Webhookスキップ動作なので、fetch/KV をモックした統合寄りテスト(同時刻ID、投稿失敗時state更新抑止など)を追加すると安全です。As per coding guidelines: 「Test agents in isolation and with integration tests to ensure correctness and compatibility」。
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@functions/src/scheduled/appStoreReviews.test.ts` around lines 3 - 57, The current test file focuses only on the parseAppStoreJson utility function. Add integration test scenarios for the runAppStoreReviewJob function to strengthen regression detection by testing the actual job behavior with mocked fetch and KV dependencies. Create test cases that cover KV state transitions, DryRun mode behavior, Webhook skipping logic, simultaneous review IDs, and state update suppression when posting fails. This ensures the main job logic (not just the parsing utility) is properly validated for correctness and compatibility.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@functions/scripts/build-secrets-json.mjs`:
- Around line 30-49: The catch block in the readFileSync error handling is
silently ignoring all exceptions, including permission errors, invalid paths,
and I/O failures, which allows the process to continue with missing secrets.
Modify the catch block to inspect the error code property: only suppress the
error if the code is ENOENT (file not found), and rethrow any other error so
that unexpected failures are properly surfaced instead of being silently ignored
during secret value loading.
In `@functions/scripts/put-secrets.sh`:
- Around line 22-29: The argument parsing in the put-secrets.sh script (around
the WENV and wargs assignment section) currently ignores unknown options and
missing values for --env, risking unintended deployments to the default dev
environment. Add strict argument validation that explicitly checks for unknown
options before the WENV assignment logic and immediately exits with an error
message if any unrecognized arguments are found. Also add validation to ensure
that when --env is provided, it must be followed by a non-empty value, and exit
with an error if the value is missing.
In `@functions/src/cli/find-tts-cache.ts`:
- Around line 107-120: The code in the find-tts-cache.ts file is parsing JSON
records from KV storage and adding them directly to the matches array without
validating that the required id field exists and is a non-empty string. This
causes problems later when the code tries to use rec.id for file operations.
After successfully parsing the JSON into rec (after the JSON.parse call), add a
validation check to ensure rec.id exists and is a non-empty string. Skip the
record (use continue) if this validation fails, so only valid records with a
present and non-empty id field are added to the matches array.
In `@functions/src/consumers/feedbackTriage.ts`:
- Around line 341-342: The try-catch block wrapping the fetch call in
feedbackTriage.ts (around lines 341-342, and also at lines 417-420 and 540-542)
is suppressing exceptions silently, causing the queue handler in index.ts to
acknowledge the message as successfully processed even when the GitHub API call
fails. This results in lost messages that should be retried. Remove the
exception suppression by either re-throwing the caught error or ensuring that
when GitHub API operations fail, the error propagates up to the queue handler so
the message is not acknowledged and can be retried. Apply this same fix to all
affected locations where GitHub API calls are wrapped in try-catch blocks
without proper error propagation.
- Around line 136-145: The `getBool('isSpam')` call uses an un-normalized key
while the `map` object stores all data with normalized keys, causing a mismatch
that prevents the spam flag from being properly detected. Update the
`getBool('isSpam')` call to use the normalized key format (likely 'is_spam' in
snake_case to match the normalization convention used for other map keys like
'title' and 'summary') so that the spam classification from the model output is
correctly read and the triage logic functions as intended.
In `@functions/src/lib/google/accessToken.ts`:
- Around line 81-89: The code uses TypeScript's `as` type assertion to cast the
OAuth response without validating the actual structure, allowing invalid
payloads to be cached if required fields are missing or have incorrect types.
This causes cascading failures in subsequent API calls that rely on the cached
token. Add runtime validation after parsing the response with res.json() to
verify that json.access_token exists and is a string, and json.expires_in exists
and is a number. Throw an error or handle the validation failure appropriately
if these checks fail, before the tokenCache.set() call occurs.
In `@functions/src/lib/reviewState.ts`:
- Around line 7-16: The loadReviewState function lacks schema validation for the
ReviewState object retrieved from KV storage, which can cause downstream
failures when lastIds is stored in an invalid format. After retrieving the json
value from kv.get in the loadReviewState function, normalize and validate the
returned object to ensure lastIds is always an array (or undefined/empty if
missing). This normalization should happen at the read boundary before returning
the ReviewState to prevent exceptions or incorrect behavior in downstream code
that expects lastIds to be an array when used with new Set(state.lastIds ?? []).
In `@functions/src/routes/config.ts`:
- Around line 28-46: The handleMaintenanceConfig and handleRemoteConfig
functions lack error handling for KV store retrieval operations. When
env.CONFIG_KV.get(..., 'json') encounters corrupted JSON or fails, the exception
propagates causing a 500 error instead of gracefully degrading. Wrap both KV.get
calls in try/catch blocks and treat any caught exceptions as undefined, allowing
the code to fall back to default values (the existing logic already handles
undefined stored values appropriately).
In `@functions/src/routes/tts.ts`:
- Around line 89-139: The current validation only checks the byte length of
stripped SSML text (after stripSsml removes tags), which allows raw SSML with
excessive tags and attributes to bypass the byte limit. Add byte length
validation for the raw ssmlJa and ssmlEn strings (after normalization) using the
utf8ByteLength function, before the existing stripped text validation. Insert
these raw byte length checks immediately after the strippedJa and strippedEn
variables are assigned from stripSsml, similar to the existing pattern used for
jaTextBytes and enTextBytes, to ensure both the raw SSML and visible text
respect the TEXT_BYTE_LIMIT constraint.
In `@functions/src/scheduled/appStoreReviews.ts`:
- Around line 166-169: The filter order in the newcomers variable assignment has
a logic issue where items with timestamps equal to lastUpdated are being
excluded even if they have new IDs not in lastIds, defeating the purpose of
tracking lastIds for duplicate detection at the same timestamp. Modify the first
filter condition on dayjs(x.updated) to include items that are either strictly
after lastUpdated (using isAfter) OR have the same timestamp as lastUpdated and
are not in lastIds (using isSame combined with !lastIds.has(x.id)), ensuring
that new items at the same timestamp are not permanently lost.
- Around line 201-204: The state is being saved unconditionally after calling
postToDiscord, even when the Discord posting fails. Since postToDiscord only
logs errors but continues execution on non-2xx responses, failed notifications
still advance the state, causing reviews to be skipped in future runs. Wrap the
saveReviewState call (where lastUpdated and lastIds are persisted) in a
conditional check that only executes when the postToDiscord operation succeeds.
Ensure that if Discord posting fails, the state is not updated so that failed
reviews can be retried in the next job execution.
In `@functions/src/scheduled/googlePlayReviews.ts`:
- Around line 126-130: The `fetch` call to the Discord webhook URL lacks a
timeout mechanism, which could cause the scheduled function to hang indefinitely
if the webhook endpoint is slow or unresponsive. Add an
`AbortSignal.timeout(...)` to the fetch options to set a reasonable timeout
duration (for example, a few seconds). This signal should be added as a new
property in the options object passed to fetch, ensuring that long-running
webhook calls are automatically aborted and the scheduled job can complete or
fail gracefully.
- Around line 212-238: The state is being saved unconditionally after the
DRY_RUN check, which means lastUpdated and lastIds are persisted even when posts
were skipped in DRY_RUN mode or when posting to Discord failed. Move the
state-saving logic (the saveReviewState call and all the preceding state
calculation logic starting with "if (all.length)") from being executed
unconditionally to being executed only when the post was actually successful.
This should be inside the else block where postToDiscord is called, ensuring
state is updated only after confirmed successful notification delivery.
In `@functions/src/utils/ttsVoice.ts`:
- Around line 9-12: The AZURE_VOICE_PATTERN regex in the isAzureVoiceName
function uses [A-Za-z0-9]* which allows zero or more characters before "Neural",
permitting invalid voice names like "en-US-Neural" to pass validation and
subsequently causing Azure synthesis failures. Change the quantifier from * to +
in the AZURE_VOICE_PATTERN to require at least one alphanumeric character before
"Neural", ensuring only properly formatted voice names are accepted.
In `@src/hooks/useFeedback.ts`:
- Around line 89-110: The screenshot upload code in the `if (screenShotBase64)`
block can throw exceptions (from the fetch call or uploadRes.json() parsing)
that propagate to the outer catch handler and prevent the main feedback
submission from completing. Since image upload is auxiliary functionality, wrap
the entire screenshot upload block (the fetch request and json parsing) in a
local try/catch to catch any exceptions locally, log them as warnings, and allow
the feedback submission to continue regardless of whether the image upload
succeeds or fails.
---
Outside diff comments:
In `@src/hooks/useAnonymousUser.ts`:
- Around line 8-25: The useAnonymousUser hook uses useRef which does not trigger
re-renders when its value is updated, causing the hook to always return null
even after getInstallId() completes successfully. Replace useRef with useState
to properly trigger re-renders when the anonymous user data is fetched. Change
useRef<AppUser | null>(null) to useState<AppUser | null>(null), update the
.then() callback to call the state setter instead of assigning to
userRef.current, and return the state value instead of userRef.current at the
end of the hook.
---
Minor comments:
In `@docs/cloudflare-migration-phase3-checklist.md`:
- Around line 38-51: The queue creation command and few-shot deployment
description in the checklist are misaligned with the actual implementation and
migration policy. In the wrangler queues create command, ensure the
documentation focuses on the feedback-triage queue as the primary queue rather
than tts-cache-dev. Additionally, update the comment describing few-shot
placement to correctly state that few-shot is being placed in KV (CONFIG_KV
binding) via the wrangler kv key put command, not in R2 as currently described.
Align all documentation references to match the actual command implementations
shown in the diff.
In `@docs/cloudflare-migration-plan.md`:
- Around line 49-50: The migration plan document in
docs/cloudflare-migration-plan.md contains outdated architecture descriptions
across multiple sections. The current implementation stores TTS cache directly
in R2+KV from the `/tts` endpoint (not via Queue with a tts-cache consumer) and
stores few-shot prompts in CONFIG_KV (not R2). Update the table entries at lines
49-50 (the `/tts` and `/postFeedback` rows) to reflect that TTS is saved
directly to R2+KV without Queue involvement, and update the corresponding
descriptions at lines 73-75 and lines 110-112 to align with the actual current
architecture regarding TTS caching and few-shot storage locations to prevent
operational confusion.
In `@functions/README.md`:
- Around line 21-22: The README contains contradictory information about where
few-shot data is stored. In functions/README.md lines 21-22, few-shot data is
listed as being stored in R2, but in functions/README.md lines 106-108, the
documentation references CONFIG_KV with config:fewshot, indicating KV storage
instead. Resolve this contradiction by ensuring both sections consistently
describe the same storage location for few-shot data. Determine the actual
storage mechanism used in the codebase and update both locations to match that
single source of truth.
In `@functions/src/consumers/feedbackTriage.test.ts`:
- Around line 1-3: Add an `afterEach` hook to the describe block in
feedbackTriage.test.ts that calls `jest.clearAllMocks()` to ensure all mocks are
properly reset between test cases. This hook should be placed after the imports
and before or after the test cases to comply with testing guidelines and prevent
mock state from leaking between tests.
In `@functions/src/consumers/feedbackTriage.ts`:
- Around line 497-498: Fix the Japanese typo in the Discord notification
messages in the feedbackTriage.ts file. In the ternary operator that constructs
the notification message, replace "届きまさした" with "届きました" in both the feedback
message (the first part of the ternary) and the crash report message (the second
part of the ternary) to correct the grammatical error in both Discord
notification strings.
In `@functions/src/routes/tts.ts`:
- Around line 70-75: The error message in the `requireString` function (lines
74-75) contains hardcoded text "containing the message to add" which does not
match the actual contract for TTS parameters like `ssmlJa` and `ssmlEn` that
contain SSML content, not generic messages. Update the error message to be more
generic and parameter-agnostic by removing the assumption about what the
parameter contains. Instead, make the message reference the parameter name
(already available via the `name` argument) and describe the general requirement
that it must be a non-empty string, without prescribing what type of content it
should contain.
In `@functions/src/routes/uploadImage.ts`:
- Around line 38-41: The base64ToBytes function call at line 38 in
uploadImage.ts does not handle invalid base64 input, which could cause
unexpected errors or results. Wrap the base64ToBytes(imageBase64) call in a
try-catch block to catch any decoding errors, and throw a CallableError with
error code 'invalid-argument' and a clear message indicating that the image data
is not valid base64 when decoding fails.
In `@functions/src/scheduled/appStoreReviews.test.ts`:
- Around line 3-57: The test suite for parseAppStoreJson currently lacks an
afterEach hook to clear mocks, which can cause test pollution when mocks are
added in the future. Add an afterEach hook inside the
describe('parseAppStoreJson') block that calls jest.clearAllMocks() to ensure
mocks are properly cleared between test runs, following the coding guidelines
for test cleanup.
In `@functions/src/utils/ttsVoice.test.ts`:
- Around line 10-14: The test for isAzureVoiceName is missing a boundary
condition test case for the string 'en-US-Neural' which should be rejected. Add
an expect statement in the 'rejects non-Azure voice ids' test block to
explicitly verify that isAzureVoiceName('en-US-Neural') returns false, ensuring
the regex pattern at Line 9 correctly handles the case where Neural appears
without a stem suffix.
In `@src/lib/installId.ts`:
- Around line 10-25: The getInstallId function has a race condition where
multiple simultaneous calls can generate different IDs if they all execute the
randomUUID() before any complete the setItemAsync call, and it lacks error
handling for SecureStore operations that may throw keychain exceptions. Add a
Promise-based locking mechanism to ensure only one concurrent execution of the
ID generation logic (by tracking a pending promise and reusing it across
concurrent calls), and wrap the SecureStore.getItemAsync and
SecureStore.setItemAsync calls in try-catch blocks to properly handle potential
keychain errors.
---
Nitpick comments:
In `@functions/src/lib/crypto.ts`:
- Around line 40-48: The timingSafeEqual function has a documentation comment
that does not clarify an important limitation regarding timing side-channel
vulnerabilities. The early length check in the function (if a.length !==
b.length return false) leaks timing information about whether the input strings
have different lengths, which could be exploited in contexts where this function
is used with variable-length inputs. Update the JSDoc comment for the
timingSafeEqual function to document this constraint explicitly, noting that the
function should only be used when comparing strings of equal or predictable
lengths (such as fixed-length JWT signatures), and that it is not safe for
comparing arbitrary-length strings where length differences might reveal
sensitive information.
In `@functions/src/routes/auth.ts`:
- Around line 35-38: The error response in the SESSION_JWT_SECRET validation
block is exposing the internal secret name in the error message, which reveals
system configuration details to potential attackers. Replace the error message
in the JSON response from the current message that includes "SESSION_JWT_SECRET"
with a generic, non-revealing message such as "Internal server error" or
"Authentication service unavailable" that provides no hints about the internal
configuration while maintaining the same HTTP status code 500 and headers.
In `@functions/src/scheduled/appStoreReviews.test.ts`:
- Around line 3-57: The current test file focuses only on the parseAppStoreJson
utility function. Add integration test scenarios for the runAppStoreReviewJob
function to strengthen regression detection by testing the actual job behavior
with mocked fetch and KV dependencies. Create test cases that cover KV state
transitions, DryRun mode behavior, Webhook skipping logic, simultaneous review
IDs, and state update suppression when posting fails. This ensures the main job
logic (not just the parsing utility) is properly validated for correctness and
compatibility.
In `@functions/src/scheduled/googlePlayReviews.test.ts`:
- Around line 22-66: The test file currently contains only unit tests for the
pure function toPlayReviews but lacks integration tests for the main
runGooglePlayReviewJob function. Add integration tests for
runGooglePlayReviewJob that mock external dependencies (fetch calls, KV storage
operations, and token acquisition) to verify the actual job behavior including
state management during DRY_RUN mode, state updates after successful webhook
calls, error handling when webhooks fail, and the compatibility of pagination
and deduplication logic. These integration tests should be added to the same
test file alongside the existing unit tests.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: d107ab2b-8a10-48ed-b510-5dd4eaa4dbe4
⛔ Files ignored due to path filters (2)
functions/package-lock.jsonis excluded by!**/package-lock.jsonpackage-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (70)
.env.exampleAGENTS.mdandroid/app/build.gradleandroid/build.gradleapp.config.tsdocs/cloudflare-migration-phase3-checklist.mddocs/cloudflare-migration-plan.mdfirebase.jsonfunctions/.gitignorefunctions/.secrets.env.examplefunctions/README.mdfunctions/fewshot.example.jsonlfunctions/jest.config.jsfunctions/package.jsonfunctions/scripts/build-secrets-json.mjsfunctions/scripts/put-secrets.ps1functions/scripts/put-secrets.shfunctions/src/cli/find-orphaned-tts.tsfunctions/src/cli/find-tts-cache.tsfunctions/src/cli/lib/cloudflare.tsfunctions/src/consumers/feedbackTriage.test.tsfunctions/src/consumers/feedbackTriage.tsfunctions/src/funcs/enqueueFeedback.tsfunctions/src/funcs/tts.tsfunctions/src/funcs/ttsCachePubSub.tsfunctions/src/index.tsfunctions/src/lib/auth/session.tsfunctions/src/lib/azure/tts.tsfunctions/src/lib/callable.tsfunctions/src/lib/crypto.tsfunctions/src/lib/google/accessToken.tsfunctions/src/lib/reviewState.tsfunctions/src/lib/ttsCache.tsfunctions/src/routes/auth.tsfunctions/src/routes/config.tsfunctions/src/routes/feedback.tsfunctions/src/routes/tts.tsfunctions/src/routes/uploadImage.tsfunctions/src/scheduled/appStoreReviews.test.tsfunctions/src/scheduled/appStoreReviews.tsfunctions/src/scheduled/googlePlayReviews.test.tsfunctions/src/scheduled/googlePlayReviews.tsfunctions/src/types.tsfunctions/src/utils/ssml.tsfunctions/src/utils/ttsVoice.test.tsfunctions/src/utils/ttsVoice.tsfunctions/src/workers/__tests__/appStoreReviewNotifier.test.tsfunctions/src/workers/__tests__/googlePlayReviews.test.tsfunctions/src/workers/feedback.tsfunctions/src/workers/googlePlayReviews.tsfunctions/tsconfig.build.jsonfunctions/tsconfig.jsonfunctions/wrangler.jsoncjest.setup.jspackage.jsonsrc/@types/react-native-dotenv.d.tssrc/constants/location.tssrc/hooks/useAnonymousUser.tssrc/hooks/useCachedAnonymousUser.tssrc/hooks/useFeedback.tssrc/hooks/useTTS.test.tssrc/hooks/useTTS.tssrc/hooks/useUnderMaintenance.tssrc/lib/installId.tssrc/lib/remoteConfig.test.tssrc/lib/remoteConfig.tssrc/lib/session.tssrc/lib/workerApi.tssrc/screens/Licenses.tsxsrc/store/atoms/auth.ts
💤 Files with no reviewable changes (12)
- functions/src/workers/googlePlayReviews.ts
- functions/src/workers/feedback.ts
- functions/src/funcs/enqueueFeedback.ts
- android/build.gradle
- functions/src/workers/tests/googlePlayReviews.test.ts
- functions/src/funcs/tts.ts
- functions/src/workers/tests/appStoreReviewNotifier.test.ts
- firebase.json
- functions/src/funcs/ttsCachePubSub.ts
- android/app/build.gradle
- functions/tsconfig.build.json
- src/screens/Licenses.tsx
| const getBool = (...keys: string[]) => | ||
| keys.some((k) => { | ||
| const v = map.get(k); | ||
| return v === true || v === 'true'; | ||
| }); | ||
|
|
||
| let title = getStr('title'); | ||
| let summary = getStr('summary'); | ||
| const isSpam = getBool('isSpam'); | ||
| const rawLabels = map.get('labels'); |
There was a problem hiding this comment.
isSpam の読み取りがキー正規化と不整合です。
map 側は正規化キーで保持しているのに、getBool('isSpam') が未正規化キーを参照しており、モデル出力の isSpam を取りこぼします。スパム誤判定で triage が崩れます。
💡 修正案
- const getBool = (...keys: string[]) =>
+ const getBool = (...keys: string[]) =>
keys.some((k) => {
- const v = map.get(k);
+ const v = map.get(norm(k));
return v === true || v === 'true';
});
@@
- const isSpam = getBool('isSpam');
+ const isSpam = getBool('isSpam', 'is_spam');🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@functions/src/consumers/feedbackTriage.ts` around lines 136 - 145, The
`getBool('isSpam')` call uses an un-normalized key while the `map` object stores
all data with normalized keys, causing a mismatch that prevents the spam flag
from being properly detected. Update the `getBool('isSpam')` call to use the
normalized key format (likely 'is_spam' in snake_case to match the normalization
convention used for other map keys like 'title' and 'summary') so that the spam
classification from the model output is correctly read and the triage logic
functions as intended.
| try { | ||
| const res = await fetch( |
There was a problem hiding this comment.
GitHub 作成失敗が再試行されずに ACK される経路があります。
ここで例外を握りつぶすため、functions/src/index.ts の queue ハンドラでは成功扱いで message.ack() されます。GitHub API 失敗時にメッセージが失われます。
💡 修正案(失敗時のみ再試行へ)
+ let issueCreated = false;
try {
@@
if (res.status !== 201) {
console.error(await res.json());
throw new Error(`GitHub API failed with status ${res.status}`);
}
+ issueCreated = true;
@@
} catch (err) {
console.error(err);
+ if (!issueCreated) throw err;
}Also applies to: 417-420, 540-542
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@functions/src/consumers/feedbackTriage.ts` around lines 341 - 342, The
try-catch block wrapping the fetch call in feedbackTriage.ts (around lines
341-342, and also at lines 417-420 and 540-542) is suppressing exceptions
silently, causing the queue handler in index.ts to acknowledge the message as
successfully processed even when the GitHub API call fails. This results in lost
messages that should be retried. Remove the exception suppression by either
re-throwing the caught error or ensuring that when GitHub API operations fail,
the error propagates up to the queue handler so the message is not acknowledged
and can be retried. Apply this same fix to all affected locations where GitHub
API calls are wrapped in try-catch blocks without proper error propagation.
出力フォーマット既定を高音質化(48kHz/192kbit)し、mstts:express-asとprosodyをenvで付与可能に。HDボイス名(コロン含む)の検証も許可。 Co-Authored-By: Claude Opus 4.8 <[email protected]>
There was a problem hiding this comment.
🧹 Nitpick comments (2)
functions/src/lib/azure/tts.ts (2)
31-59: ⚡ Quick winSSML パラメータの入力バリデーションを推奨します。
voiceName,languageCode,optsの各フィールドが検証なしで SSML に直接埋め込まれています。現在の呼び出し側(/ttsルート)では環境変数やバリデーション済みの値を使用していますが、ライブラリ関数としては防御的であるべきです。特殊文字(<,>,",&)のエスケープまたは許可文字セットの検証を追加することで、将来的な SSML インジェクションリスクを軽減できます。🛡️ 入力バリデーション例
+/** SSML 属性値として安全な文字列かチェック(XML 特殊文字を含まない) */ +const isValidSsmlAttr = (value: string): boolean => { + return !/[<>"&]/.test(value); +}; + const buildAzureSsml = ( inner: string, languageCode: string, voiceName: string, opts: TtsOptions ): string => { + if (!isValidSsmlAttr(languageCode) || !isValidSsmlAttr(voiceName)) { + throw new Error('Invalid characters in languageCode or voiceName'); + } + if (opts.style && !isValidSsmlAttr(opts.style)) { + throw new Error('Invalid characters in style'); + } let content = inner;🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@functions/src/lib/azure/tts.ts` around lines 31 - 59, The buildAzureSsml function directly embeds parameters (voiceName, languageCode, opts.style, opts.styleDegree, opts.rate, opts.pitch, and inner content) into SSML XML without any validation or escaping, creating a potential SSML injection vulnerability. Add input validation or escaping for special XML characters (specifically <, >, ", and &) to all user-provided parameters before they are embedded into the XML string. This should include escaping the inner content and any option fields that could contain special characters to ensure they are safely rendered as SSML.
1-100: 🏗️ Heavy liftユニットテストの追加を推奨します。
この Azure TTS 実装は新規追加の重要なライブラリ関数ですが、対応するテストファイルが見当たりません。以下のテストケースを含む
functions/src/lib/azure/tts.test.tsの追加を検討してください:
extractSpeakInnerのエッジケース(ネストしたタグ、属性付き<speak>、マッチしない入力)buildAzureSsmlの各オプション組み合わせ(rate のみ、pitch のみ、style + styleDegree、すべて組み合わせ)synthesizeSpeechのエラーハンドリング(モック fetch で非 200 レスポンス、タイムアウト、ネットワークエラー)既存の
functions/jest.config.jsでテストインフラは整っているため、テストケース作成のみで品質保証を強化できます。🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@functions/src/lib/azure/tts.ts` around lines 1 - 100, Create a new test file at functions/src/lib/azure/tts.test.ts to add unit test coverage for the three main functions in tts.ts. For extractSpeakInner, write tests covering edge cases such as SSML with nested tags, speak tags with various attributes, and inputs that don't match the expected pattern. For buildAzureSsml, write tests for each option combination: applying rate only, applying pitch only, applying style with styleDegree, and applying all options together to verify the correct SSML wrapping. For synthesizeSpeech, write tests that mock the fetch call to simulate error scenarios: a non-200 HTTP response with detail text, an AbortSignal timeout, and network failures. Ensure all tests verify both successful cases and error handling paths using the existing Jest infrastructure.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@functions/src/lib/azure/tts.ts`:
- Around line 31-59: The buildAzureSsml function directly embeds parameters
(voiceName, languageCode, opts.style, opts.styleDegree, opts.rate, opts.pitch,
and inner content) into SSML XML without any validation or escaping, creating a
potential SSML injection vulnerability. Add input validation or escaping for
special XML characters (specifically <, >, ", and &) to all user-provided
parameters before they are embedded into the XML string. This should include
escaping the inner content and any option fields that could contain special
characters to ensure they are safely rendered as SSML.
- Around line 1-100: Create a new test file at
functions/src/lib/azure/tts.test.ts to add unit test coverage for the three main
functions in tts.ts. For extractSpeakInner, write tests covering edge cases such
as SSML with nested tags, speak tags with various attributes, and inputs that
don't match the expected pattern. For buildAzureSsml, write tests for each
option combination: applying rate only, applying pitch only, applying style with
styleDegree, and applying all options together to verify the correct SSML
wrapping. For synthesizeSpeech, write tests that mock the fetch call to simulate
error scenarios: a non-200 HTTP response with detail text, an AbortSignal
timeout, and network failures. Ensure all tests verify both successful cases and
error handling paths using the existing Jest infrastructure.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: c8713ab3-4a56-4739-a304-b71d91fae8fe
📒 Files selected for processing (5)
functions/src/lib/azure/tts.tsfunctions/src/routes/tts.tsfunctions/src/types.tsfunctions/src/utils/ttsVoice.tsfunctions/wrangler.jsonc
🚧 Files skipped from review as they are similar to previous changes (4)
- functions/src/types.ts
- functions/wrangler.jsonc
- functions/src/utils/ttsVoice.ts
- functions/src/routes/tts.ts
queue失敗時の再試行・KV/OAuth応答検証・通知state更新の成功条件化・引数/例外の厳密化・画像アップロード隔離など。 Co-Authored-By: Claude Opus 4.8 <[email protected]>
c3e8d4f to
9db44d8
Compare
nameIpaをGraphQLクエリで取得しreplaceJapaneseTextをphoneme優先に拡張。Google TTS向けのやまのて線カナ表記を漢字へ戻す。 Co-Authored-By: Claude Opus 4.8 <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[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 current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/hooks/tts/formatters.ts`:
- Around line 68-72: The `nameIpa` variable is being used directly in the
phoneme element without going through the same parenthesis removal normalization
that is applied to `name` and `nameKatakana`, causing sponsor names to be read
aloud in IPA data when they should be omitted. Apply the same parenthesis
removal normalization to `nameIpa` before using it in the escapeXmlAttr call
within the phoneme tag, ensuring consistent behavior across all name variants
regardless of whether IPA data is available.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 57cafd49-6932-4c4c-9c55-33e49d29cf11
📒 Files selected for processing (6)
functions/wrangler.jsoncsrc/hooks/tts/formatters.test.tssrc/hooks/tts/formatters.tssrc/hooks/useTTSText.tssrc/lib/graphql/queries.tssrc/utils/phoneme.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- functions/wrangler.jsonc
CodeRabbit指摘: スポンサー名等のカッコ書きがIPA経路で読み上げられるのを防ぐためstripParensForTTSを適用。 Co-Authored-By: Claude Opus 4.8 <[email protected]>
7d36fa8 to
44db8d0
Compare
Azureがja-JPのIPA語末撥音(ん)を再生しきれず「〜せ」で切れるため、日本語はnameKatakanaのsub aliasに戻す。英語IPAと山手線の漢字化は維持。 Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
@CodeRabbit review |
✅ Action performedReview finished.
|
coderabbit自体のチェックは通っているため。
概要
Firebase(Cloud Functions・Auth・Firestore・Storage・Remote Config)を Cloudflare(Workers・KV・R2・Queues・Workers AI)へ全面移行しました。TTS 合成は Azure Speech に切り替えています。バックエンド(
functions/)、アプリの脱 Firebase、旧ネイティブ設定の撤去までを含みます。変更の種類
変更内容
functions/を Firebase Cloud Functions から単一の Cloudflare Worker(fetch/queue/scheduled)へ全面置換。TTS=Azure Speech、フィードバックトリアージ=Workers AI、キャッシュ/設定=KV、音声/画像=R2、フィードバックキュー=Queues、レビュー通知=Cron。認証は Worker 発行のセッション JWT(HS256)。/config/maintenance・/config/remote・/feedback/upload-imageに置換し、@react-native-firebase/*を撤去(expo-secure-store追加)。TTS/フィードバック送信は callable 互換を維持しつつ Worker ベース URL から派生。firebase.json・Android gradle の google-services 参照・Licenses の Firebase 記載を削除(ネイティブ再生成expo prebuild --cleanは別途必要)。/ttsから R2+KV へ直接書き込み。few-shot は CONFIG_KV へ移動。nameIpa)を導入してイントネーションを改善し、山手線のカナ表記ハックを撤去。put-secrets.sh/put-secrets.ps1)、メンテ CLI(R2+KV 版)、移行プラン・手順 docs を追加。テスト
npm run lintが通ることnpm testが通ることnpm run typecheckが通ること関連Issue
スクリーンショット(任意)
Summary by CodeRabbit
リリースノート
Refactor
New Features
Bug Fixes