Repository navigation
テレメトリにインタラクションイベント送信を実装しアプリ起動時にapp_launchを送信 - #6391
Conversation
Co-Authored-By: Claude Fable 5 <[email protected]>
📝 WalkthroughWalkthroughテレメトリのセッションIDをプロセス共有に変更し、インタラクションイベントのGraphQL送信機能と Changesテレメトリイベント
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant Hook as useTelemetrySender
participant Fetch as global.fetch
participant API as GraphQL API
Hook->>Hook: telemetryEnabledを確認
Hook->>Fetch: app_launchを含むGraphQL POST
Fetch->>API: sendInteractionEvent mutation
API-->>Fetch: レスポンス
Fetch-->>Hook: 送信結果
Hook->>Hook: 失敗時に再送フラグをリセット
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
src/hooks/useTelemetrySender.ts (2)
93-108: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winモジュールレベル状態によりテストが実行順に依存する設計リスク
telemetrySessionId/hasAppLaunchEventBeenSentをモジュールスコープで共有する設計自体はプロセス単位の意図と合致していますが、テスト側(useTelemetrySender.appLaunch.test.tsx96-98行目)で「このdescribe内のテストは記述順に依存する」と明記されている通り、テスト間で状態がリセットされず順序依存になっています。将来的にテストランナーがランダム実行やshard分割を行うと壊れる可能性があります。テスト用にリセット関数をエクスポートするなど、テスト分離性を高めることを推奨します。♻️ 提案例
let telemetrySessionId: string | null = null; const getOrCreateSessionId = (): string => { if (telemetrySessionId == null) { telemetrySessionId = Crypto.randomUUID(); } return telemetrySessionId; }; let hasAppLaunchEventBeenSent = false; + +// テスト専用: モジュールレベル状態をリセットし、テスト間の順序依存を避ける +export const __resetTelemetrySenderStateForTests = () => { + telemetrySessionId = null; + hasAppLaunchEventBeenSent = 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 `@src/hooks/useTelemetrySender.ts` around lines 93 - 108, モジュールスコープのtelemetrySessionIdとhasAppLaunchEventBeenSentがテスト間で共有され、実行順序に依存している。getOrCreateSessionId周辺にテストから利用できるリセット手段を追加して両状態を初期値へ戻せるようにし、app_launch関連テストが各ケース開始時にそれを呼び出して独立実行できるよう更新する。
236-306: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy lift
sendInteractionEvent/sendLog/sendTelemetryの定型処理が3重に重複fetch呼び出し、
response.okチェック、JSON parseのtry/catch、zodによるレスポンス検証、errors配列のwarn、外側のtry/catchによるerror loggingという同一パターンが3つの関数(236-306行目, 308-380行目, 382-491行目)で丸ごと複製されています。共通のGraphQL送信ヘルパーへ抽出すれば、今後のエンドポイント変更やエラーハンドリング修正を一箇所で済ませられます。♻️ 提案(概略)
async function postTelemetryMutation<TResponse>( baseUrl: string, token: string, query: string, input: unknown, responseSchema: z.ZodType<TResponse>, label: string ): Promise<TResponse | null> { try { const response = await fetch(`${baseUrl}/graphql`, { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}`, }, body: JSON.stringify({ query, variables: { input } }), }); if (!response.ok) { console.error(`HTTP error: ${response.status} ${response.statusText}`); return null; } let json: unknown; try { json = await response.json(); } catch { console.error('Failed to parse response JSON'); return null; } const result = responseSchema.safeParse(json); if (!result.success) { console.error(`Invalid ${label} response:`, result.error, json); return null; } return result.data; } catch (error) { console.error(`Failed to send ${label}:`, error); return null; } }
sendInteractionEvent/sendLog/sendTelemetryはこのヘルパーを呼び、戻り値に対して各自のerrors/warning判定のみ行う形に簡略化できます。同様にSendLocationResponse/SendLogEventResponse/SendInteractionEventResponseの.refine(...)ラッパー(71-87行目, 188-203行目など)も共通のファクトリ関数化が可能です。🤖 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/useTelemetrySender.ts` around lines 236 - 306, Extract the duplicated GraphQL request, HTTP/status handling, JSON parsing, response-schema validation, and outer error logging from sendInteractionEvent, sendLog, and sendTelemetry into one shared postTelemetryMutation helper. Have each sender call the helper with its query, input, response schema, and label, then retain only its endpoint-specific errors or warnings handling. Do not change the existing payload construction or sender-specific behavior.
🤖 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/useTelemetrySender.appLaunch.test.tsx`:
- Around line 11-95: Extract the shared telemetry test setup from the jest.mock
declarations, wrapper, and mockFetch setup in
useTelemetrySender.appLaunch.test.tsx and
useTelemetrySender.interaction.test.tsx into a reusable helper under
src/utils/test/. Export the common mock configuration and TelemetryTestWrapper,
then update both test files to import and reuse them while preserving their
existing test-specific helpers and behavior.
In `@src/hooks/useTelemetrySender.ts`:
- Around line 501-512: Update sendInteractionEvent so every validation, HTTP,
JSON parsing, and fetch failure path returns false, while successful
transmission returns true. In the useEffect guarded by isTelemetryEnabled,
baseUrl, and hasAppLaunchEventBeenSent, await the result before treating
app_launch as sent and reset hasAppLaunchEventBeenSent on failure so a later
attempt can retry.
---
Nitpick comments:
In `@src/hooks/useTelemetrySender.ts`:
- Around line 93-108:
モジュールスコープのtelemetrySessionIdとhasAppLaunchEventBeenSentがテスト間で共有され、実行順序に依存している。getOrCreateSessionId周辺にテストから利用できるリセット手段を追加して両状態を初期値へ戻せるようにし、app_launch関連テストが各ケース開始時にそれを呼び出して独立実行できるよう更新する。
- Around line 236-306: Extract the duplicated GraphQL request, HTTP/status
handling, JSON parsing, response-schema validation, and outer error logging from
sendInteractionEvent, sendLog, and sendTelemetry into one shared
postTelemetryMutation helper. Have each sender call the helper with its query,
input, response schema, and label, then retain only its endpoint-specific errors
or warnings handling. Do not change the existing payload construction or
sender-specific behavior.
🪄 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: 470be181-daaa-43af-8587-6a1653827555
📒 Files selected for processing (3)
src/hooks/useTelemetrySender.appLaunch.test.tsxsrc/hooks/useTelemetrySender.interaction.test.tsxsrc/hooks/useTelemetrySender.ts
There was a problem hiding this comment.
🧹 Nitpick comments (4)
src/hooks/useTelemetrySender.ts (2)
93-108: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winモジュールレベルの共有状態によりテスト分離性が低下する。
telemetrySessionIdとhasAppLaunchEventBeenSentはプロセス全体で共有する設計意図は理解できますが、リセット手段が一切ないため、テスト側で「記述順に依存する」という運用が必須になっています(実際にuseTelemetrySender.appLaunch.test.tsxの NOTE コメントで明示されている通りです)。加えてuseTelemetrySender.interaction.test.tsxでも同じモジュールフラグが最初のテストの mount 時に一度だけ副作用として app_launch を送信してしまい、以降のテストでは送信されないという非対称な挙動が暗黙的に発生しています。また
hasAppLaunchEventBeenSent = trueはsendInteractionEventの呼び出し結果を待たずに同期的にセットされるため、初回のネットワーク送信が失敗した場合、プロセスの残り寿命の間app_launchイベントは二度と送信されません(fire-and-forget の代償として「最大1回」ではなく「0~1回」になる)。テスト用にモジュール状態をリセットできる内部エクスポート(例:
__resetTelemetrySessionForTests)を用意すると、テストの実行順依存を解消しやすくなります。♻️ テスト用リセットフックの追加例
let telemetrySessionId: string | null = null; + +// テスト専用: モジュールレベルの状態をリセットする +export const __resetTelemetrySessionForTests = () => { + telemetrySessionId = null; + hasAppLaunchEventBeenSent = 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 `@src/hooks/useTelemetrySender.ts` around lines 93 - 108, モジュール共有状態をテストからリセットできる内部エクスポートを追加してください。useTelemetrySender.ts の telemetrySessionId と hasAppLaunchEventBeenSent の両方を初期値へ戻す __resetTelemetrySessionForTests 相当の関数を実装し、テストごとに呼び出せるようにして実行順依存を解消してください。Source: Coding guidelines
236-306: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
sendLog/sendTelemetryとのGraphQL送信ロジックの重複。
sendInteractionEventは fetch → HTTPエラー処理 → JSONパース → Zod検証 → errors配列の警告、という一連の処理をsendLog(Lines 308-380)・sendTelemetry(Lines 382-491)とほぼ同一の形で3重に実装しています。共通のGraphQLミューテーション送信ヘルパー(baseUrl/token/query/variables/レスポンススキーマを受け取る)へ抽出すると、今後の4番目のイベント種別追加時の重複をさらに防げます。♻️ 共通ヘルパー抽出のイメージ
async function postGraphQLMutation<T>( baseUrl: string, token: string, query: string, variables: Record<string, unknown>, responseSchema: z.ZodType<T> ): Promise<T | null> { // fetch + HTTPエラー + JSON parse + zod validate をここに集約 }🤖 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/useTelemetrySender.ts` around lines 236 - 306, Extract the duplicated GraphQL request flow from sendInteractionEvent, sendLog, and sendTelemetry into one shared postGraphQLMutation helper accepting baseUrl, token, query, variables, and the response schema. Centralize fetch, HTTP-status handling, JSON parsing, and Zod validation there, while preserving each caller’s existing API errors warning and failure behavior.src/hooks/useTelemetrySender.interaction.test.tsx (1)
133-167: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winマウント時の自動
app_launch送信が本テストの意図と混在している。各テストで
useTelemetrySender(false, 'https://example.com', 'test-token')をレンダーすると、isTelemetryEnabled: trueかつbaseUrlあり・モジュールフラグ未設定の初回テスト(このテスト)でマウント時に自動でapp_launchイベントも送信されます。findInteractionCall(eventName)でフィルタしているため現状のアサーションは壊れませんが、toHaveBeenCalledTimes系のアサーションを将来追加すると、このファイル内のどのテストが最初に実行されたかによって呼び出し回数が変わり、意図しないフレーキーな失敗を招く可能性があります。useTelemetrySender.ts側でモジュール状態のリセット手段を用意し、beforeEachでリセットしておくと安全です。🤖 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/useTelemetrySender.interaction.test.tsx` around lines 133 - 167, Provide a reset mechanism for the module-level telemetry state in useTelemetrySender, then invoke it from beforeEach in the interaction tests. Ensure each test starts with clean state so the mount-time automatic app_launch event does not depend on prior test execution order or affect call-count assertions.src/hooks/useTelemetrySender.appLaunch.test.tsx (1)
11-56: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winテストセットアップの重複コード。
このファイルの
jest.mock群・wrapper・mockFetchの初期化ロジック(Lines 11-120)はuseTelemetrySender.interaction.test.tsxの同範囲とほぼ完全に一致しています。ガイドラインの通り、共有ヘルパーをsrc/utils/test/に切り出して重複を排除することをお勧めします。As per coding guidelines,
**/*.test.{ts,tsx}: "Reuse helper utilities fromsrc/utils/test/to avoid duplicate setup code in tests."🤖 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/useTelemetrySender.appLaunch.test.tsx` around lines 11 - 56, Extract the duplicated Jest mocks, wrapper setup, and mockFetch initialization shared by the app-launch and interaction tests into reusable helpers under src/utils/test/. Update useTelemetrySender.appLaunch.test.tsx and useTelemetrySender.interaction.test.tsx to import and use those helpers, preserving their existing test behavior and per-test configuration.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.
Nitpick comments:
In `@src/hooks/useTelemetrySender.appLaunch.test.tsx`:
- Around line 11-56: Extract the duplicated Jest mocks, wrapper setup, and
mockFetch initialization shared by the app-launch and interaction tests into
reusable helpers under src/utils/test/. Update
useTelemetrySender.appLaunch.test.tsx and
useTelemetrySender.interaction.test.tsx to import and use those helpers,
preserving their existing test behavior and per-test configuration.
In `@src/hooks/useTelemetrySender.interaction.test.tsx`:
- Around line 133-167: Provide a reset mechanism for the module-level telemetry
state in useTelemetrySender, then invoke it from beforeEach in the interaction
tests. Ensure each test starts with clean state so the mount-time automatic
app_launch event does not depend on prior test execution order or affect
call-count assertions.
In `@src/hooks/useTelemetrySender.ts`:
- Around line 93-108:
モジュール共有状態をテストからリセットできる内部エクスポートを追加してください。useTelemetrySender.ts の
telemetrySessionId と hasAppLaunchEventBeenSent の両方を初期値へ戻す
__resetTelemetrySessionForTests 相当の関数を実装し、テストごとに呼び出せるようにして実行順依存を解消してください。
- Around line 236-306: Extract the duplicated GraphQL request flow from
sendInteractionEvent, sendLog, and sendTelemetry into one shared
postGraphQLMutation helper accepting baseUrl, token, query, variables, and the
response schema. Centralize fetch, HTTP-status handling, JSON parsing, and Zod
validation there, while preserving each caller’s existing API errors warning and
failure behavior.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 470be181-daaa-43af-8587-6a1653827555
📒 Files selected for processing (3)
src/hooks/useTelemetrySender.appLaunch.test.tsxsrc/hooks/useTelemetrySender.interaction.test.tsxsrc/hooks/useTelemetrySender.ts
Co-Authored-By: Claude Fable 5 <[email protected]>
Fixes Applied SuccessfullyFixed 5 file(s) based on 2 CodeRabbit feedback item(s). Applied fixes:
Files modified:
Validation: Commit: The latest autofix changes are on the |
There was a problem hiding this comment.
🧹 Nitpick comments (2)
src/hooks/useTelemetrySender.appLaunch.test.tsx (1)
16-18: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winモジュールレベル状態への依存によるテスト順序依存を解消することを推奨します。
コメントで明示されている通り、
hasAppLaunchEventBeenSentとtelemetrySessionIdがuseTelemetrySender.tsのモジュールスコープで共有されるため、このdescribe内のテストは記述順に強く依存しています。将来テストが追加・並び替えされた場合に静かに壊れるリスクがあります。
useTelemetrySender.ts側にテスト専用のリセット関数を追加し、beforeEachで呼び出すことで順序依存を排除できます。♻️ 提案例
// src/hooks/useTelemetrySender.ts (テスト専用エクスポート) export const __resetTelemetryStateForTests = () => { telemetrySessionId = null; hasAppLaunchEventBeenSent = false; };+import { __resetTelemetryStateForTests } from '~/hooks/useTelemetrySender'; + describe('useTelemetrySender (app_launch event)', () => { beforeEach(() => { + __resetTelemetryStateForTests(); mockFetch = setupTelemetrySenderMocks();🤖 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/useTelemetrySender.appLaunch.test.tsx` around lines 16 - 18, Eliminate test-order dependence in the app_launch tests by adding a test-only reset function near the module-level state in useTelemetrySender.ts that clears hasAppLaunchEventBeenSent and telemetrySessionId, then invoke it from beforeEach in the useTelemetrySender (app_launch event) describe block.src/utils/test/telemetrySenderTestSetup.tsx (1)
106-117: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
telemetrySenderTestSetup.tsxのuseAtomValueモックを atom ごとに分けてください
locationAtom/arrivedAtom/approachingAtomに同じ truthy 値を返しているため、useTelemetrySenderのstateは実質arrivedに固定されます。今のenabledテストはarrivedを期待しているので通りますが、moving/approaching/passingを扱うケースを増やすならmockImplementationで分岐させたほうが安全です。🤖 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/utils/test/telemetrySenderTestSetup.tsx` around lines 106 - 117, Update the useAtomValue mock in telemetrySenderTestSetup.tsx to use mockImplementation and return values based on the requested atom: keep the location payload for locationAtom, and return independent values for arrivedAtom and approachingAtom. Preserve the existing enabled test expectations while allowing moving, approaching, and passing states to be configured without every atom receiving the same truthy object.
🤖 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 `@src/hooks/useTelemetrySender.appLaunch.test.tsx`:
- Around line 16-18: Eliminate test-order dependence in the app_launch tests by
adding a test-only reset function near the module-level state in
useTelemetrySender.ts that clears hasAppLaunchEventBeenSent and
telemetrySessionId, then invoke it from beforeEach in the useTelemetrySender
(app_launch event) describe block.
In `@src/utils/test/telemetrySenderTestSetup.tsx`:
- Around line 106-117: Update the useAtomValue mock in
telemetrySenderTestSetup.tsx to use mockImplementation and return values based
on the requested atom: keep the location payload for locationAtom, and return
independent values for arrivedAtom and approachingAtom. Preserve the existing
enabled test expectations while allowing moving, approaching, and passing states
to be configured without every atom receiving the same truthy object.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 82012c81-21e1-495e-8213-1f389dc7dff0
📒 Files selected for processing (5)
src/hooks/useTelemetrySender.appLaunch.test.tsxsrc/hooks/useTelemetrySender.enabled.test.tsxsrc/hooks/useTelemetrySender.interaction.test.tsxsrc/hooks/useTelemetrySender.tssrc/utils/test/telemetrySenderTestSetup.tsx
🚧 Files skipped from review as they are similar to previous changes (2)
- src/hooks/useTelemetrySender.interaction.test.tsx
- src/hooks/useTelemetrySender.ts
概要
実験的テレメトリ基盤の GraphQL
sendInteractionEventmutation に対応し、インタラクションイベントを送信できる仕組みをuseTelemetrySenderに追加しました。現時点でアプリが実際に送信するのはアプリ起動時のapp_launchイベントのみです。変更の種類
変更内容
useTelemetrySenderにsendInteractionEvent(eventName, properties?)を追加(テレメトリ基盤の GraphQLInteractionEventInputに対応。properties はフラットな map のみ許容)app_launchインタラクションイベントを自動送信sendInteractionEventのペイロード構造・エラーハンドリングとapp_launchの一度きり送信を検証する単体テストを追加テスト
npm run lintが通ることnpm testが通ることnpm run typecheckが通ること関連Issue
スクリーンショット(任意)
Summary by CodeRabbit