Skip to content

逆走通知のバッテリー消費を抑えるため検知ロジックをatomに集約し通知重複防止とヒステリシスを強化 - #5934

Merged
TinyKitten merged 2 commits into
devfrom
claude/fix-battery-drain-alert-Hh4wG
May 11, 2026
Merged

TinyKitten merged 2 commits into
devfrom
claude/fix-battery-drain-alert-Hh4wG

Conversation

@TinyKitten

@TinyKitten TinyKitten commented May 11, 2026 •

Copy link
Copy Markdown
Member

概要

設定画面で逆走通知を ON にするとバッテリー消費が速くなる問題への対処。逆方向検知ロジックを atom に集約して二重計算を解消し、GPS ノイズによる通知の連続再発火を防ぐ。

変更の種類

  • バグ修正
  • 新機能
  • リファクタリング
  • ドキュメント
  • CI/CD
  • その他

変更内容

  • 逆方向検知結果用 atom src/store/atoms/wrongDirection.ts を新設し、検知結果を { isWrongDirection, isLoopLineWrongDirection } 形で一元管理。
  • useWrongDirectionDetector を atom 読み取り専用に縮退し、計算ロジック本体は useWrongDirectionDetectorEffect として切り出して Permitted.tsx で 1 度だけマウントするよう変更(従来は useRefreshStation と useWarningInfo の 2 箇所から呼ばれており、位置更新ごとに getDistance 計算と state 更新が二重に実行されていた)。
  • 検知ロジックに 10m のノイズトレランスを導入。小さな距離減少では wrongDirectionDetected を false に戻さず、完全リセットは arrived / selectedBound 変更 / 次駅変更 / 前提条件不成立時のみに限定。
  • useRefreshStation の逆走通知発火 effect で、重複防止 ref を boolean から 次駅 ID ベースに変更。isWrongDirection の一時的な false 復帰だけでは再発火させず、同一区間で通知が連続して鳴るのを防ぐ。
  • 上記挙動を検証する Jest テスト useWrongDirectionDetector.test.tsx を追加(ヒステリシス成立・小ノイズで判定が維持されること・到着でリセットされること・公開フックの初期値)。

回帰リスクと緩和

  • 逆走警告パネル (useWarningInfo) の表示は ON/OFF に関係なく従来通り動作する(atom 経由で同じ結果を購読)。
  • ヒステリシス強化により誤検知の解除条件が緩むが、arrived / selectedBound / 次駅変更 / GPS精度劣化のいずれかで完全リセットされるため、本来の「区間移行」場面での誤検知持ち越しは発生しない。
  • 通知のクールダウンを次駅 ID 紐付けに変更したため、同一区間で再通知したくなるユースケースは存在しない(次駅が変わるかブランチがクリアされれば再発火可能)。

テスト

  • npm run lint が通ること
  • npm test が通ること(1531 件、全パス)
  • npm run typecheck が通ること

関連Issue

スクリーンショット(任意)


Generated by Claude Code

Summary by CodeRabbit

  • New Features

    • 誤進行検出の処理をアプリ全体で共有する仕組みに統合し、検出状態を中央で管理して配信するように変更
  • バグ修正

    • 同一路線・駅区間での重複通知を抑制するロジックを導入
    • GPSの小さな揺らぎに影響されにくくし、誤検出の抑制精度を向上
    • 駅到着時に誤進行判定が確実にリセットされるよう修正
  • テスト

    • 誤進行検出のヒステリシスやリセット挙動を検証するテストを追加

Review Change Stack

@TinyKitten TinyKitten self-assigned this May 11, 2026
@coderabbitai

coderabbitai Bot commented May 11, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 902ec744-b852-4050-b6dc-136224a44381

📥 Commits

Reviewing files that changed from the base of the PR and between c42e1e4 and 2b79328.

📒 Files selected for processing (1)
  • src/hooks/useWrongDirectionDetector.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/hooks/useWrongDirectionDetector.ts

📝 Walkthrough

Walkthrough

GPSベースの逆方向検出がコンポーネント内状態からJotai atomへ移動。新しい effect フックが検出を実行して atom に書き込み、購読フックは atom を読み取る。アプリレイアウトで effect を一度起動し、通知ロジックは駅単位で重複を抑制する。

Changes

Wrong Direction Detection Refactoring

Layer / File(s) Summary
Shared State Atom
src/store/atoms/wrongDirection.ts
新規 wrongDirectionAtom が isWrongDirection と isLoopLineWrongDirection を保持する WrongDirectionState を提供。
Detection Effect Hook
src/hooks/useWrongDirectionDetector.ts
新規 useWrongDirectionDetectorEffect() が位置情報と駅情報を読み、距離差を累積するヒステリシスとノイズ許容を適用して検出結果を atom に書き込む。重複書き込みの抑制を含む。
Subscription Hook
src/hooks/useWrongDirectionDetector.ts
useWrongDirectionDetector() は atom を購読して WrongDirectionState を返すようにリファクタ。
App Layout Integration
src/components/Permitted.tsx
PermittedLayout で useWrongDirectionDetectorEffect() を呼び出し、トップレベルで検出を有効化。
Hook Export
src/hooks/index.ts
useWrongDirectionDetectorEffect を既存の useWrongDirectionDetector と共に再エクスポートするよう変更。
Per-Station Notification Tracking
src/hooks/useRefreshStation.ts
nextStationId を導出し lastNotifiedWrongDirectionStationIdRef で最後に通知した駅を追跡。通知は駅が変わるまで重複送信されないよう抑制。
Test Suite
src/hooks/useWrongDirectionDetector.test.tsx
ヒステリシス蓄積、GPSノイズ耐性、到着時リセット、effect 未実行時の購読フック挙動を確認する包括的な Jest テストを追加。

Sequence Diagram(s)

sequenceDiagram
  participant locationAtom as locationAtom
  participant detector as useWrongDirectionDetectorEffect
  participant wrongAtom as wrongDirectionAtom
  participant refresher as useRefreshStation

  locationAtom->>detector: location updates
  detector->>detector: compute distance delta & hysteresis
  detector->>wrongAtom: writeState({isWrongDirection, isLoopLineWrongDirection})
  wrongAtom->>refresher: subscriber reads flags
  refresher->>refresher: compare nextStationId with lastNotifiedWrongDirectionStationIdRef
  refresher->>refresher: send notification if not already notified
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 ぼくの耳で聞いたGPSの歌、

距離を数えて、ノイズを忘れ、
アトムで伝えて、道を正す、
駅ごとに知らせを止めて、
小さな跳ねる足で祝おう!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed タイトルは逆走通知のバッテリー消費削減、検知ロジック集約、通知重複防止、ヒステリシス強化という変更内容を正確に要約しており、プルリクエストの主要な目的を明確に表現している。
Description check ✅ Passed 説明はテンプレートのすべての必須セクション(概要、変更の種類、変更内容、テスト結果)を完備し、詳細な実装内容、回帰リスク緩和、テスト検証結果を記載している。
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/fix-battery-drain-alert-Hh4wG

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions github-actions Bot added the react label May 11, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/hooks/useWrongDirectionDetector.ts (1)

82-88: ⚡ Quick win

resetDetectionState の依存配列から isLoopLine を除外することを推奨

resetDetectionState が isLoopLine に依存しているため、ループ路線の判定が変わると selectedBoundId 変更用の useEffect(Line 98-102)が再実行され、検知状態が意図せずリセットされる可能性があります。

writeState(false, isLoopLine) は detected=false の場合、isLoopLine の値に関係なく両フラグが false になるため、ここでは isLoopLine は不要です。

♻️ 修正案
  const resetDetectionState = useCallback(() => {
    prevDistanceRef.current = null;
    consecutiveIncreaseCountRef.current = 0;
    cumulativeIncreaseRef.current = 0;
    notifiedForStationIdRef.current = undefined;
-   writeState(false, isLoopLine);
-  }, [isLoopLine, writeState]);
+   writeState(false, false);
+  }, [writeState]);
🤖 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/useWrongDirectionDetector.ts` around lines 82 - 88, The
resetDetectionState callback depends on isLoopLine unnecessarily causing resets
when loop-route status changes; update the resetDetectionState definition to
remove isLoopLine from its dependency array and call writeState with only the
detected value (e.g., writeState(false)) or otherwise compute the necessary
flags without reading isLoopLine, so that resetting detection no longer
re-triggers when isLoopLine toggles; adjust the dependency array to [writeState]
and keep the body setting prevDistanceRef, consecutiveIncreaseCountRef,
cumulativeIncreaseRef, and notifiedForStationIdRef as before.
🤖 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/useWrongDirectionDetector.ts`:
- Around line 82-88: The resetDetectionState callback depends on isLoopLine
unnecessarily causing resets when loop-route status changes; update the
resetDetectionState definition to remove isLoopLine from its dependency array
and call writeState with only the detected value (e.g., writeState(false)) or
otherwise compute the necessary flags without reading isLoopLine, so that
resetting detection no longer re-triggers when isLoopLine toggles; adjust the
dependency array to [writeState] and keep the body setting prevDistanceRef,
consecutiveIncreaseCountRef, cumulativeIncreaseRef, and notifiedForStationIdRef
as before.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 7cbdde2c-ea12-431c-a2fc-ea453eb1f7dd

📥 Commits

Reviewing files that changed from the base of the PR and between 997ca43 and c42e1e4.

📒 Files selected for processing (6)
  • src/components/Permitted.tsx
  • src/hooks/index.ts
  • src/hooks/useRefreshStation.ts
  • src/hooks/useWrongDirectionDetector.test.tsx
  • src/hooks/useWrongDirectionDetector.ts
  • src/store/atoms/wrongDirection.ts

@TinyKitten
TinyKitten merged commit 04660d2 into dev May 11, 2026
5 checks passed
@TinyKitten
TinyKitten deleted the claude/fix-battery-drain-alert-Hh4wG branch May 11, 2026 07:03
TinyKitten added a commit that referenced this pull request Sep 14, 2026
`cumulativeIncreaseRef` は正の増加だけを足し込む一方、
`WRONG_DIRECTION_NOISE_TOLERANCE` (10m) 以内の減少は無視して累積を維持していた。
この非対称性により、静止していてもGPSの揺れだけで累積が単調に伸び、
`WRONG_DIRECTION_MIN_DISTANCE` (300m) に到達しうる (#6967)。

累積を「最接近点 (`nearestDistanceRef`) からの正味距離」で測るよう変更する。
無視した小さな減少も起点の更新を通じて距離へ反映されるため、静止中の揺れでは
正味距離が伸びない。連続カウンタ側のヒステリシス (#5934 の意図) はそのまま残す。


Claude-Session: https://claude.ai/code/session_01W43wAgGXf7Sank3yirTJD2

Co-authored-by: Claude Opus 5 <[email protected]>
@TinyKitten TinyKitten mentioned this pull request Sep 14, 2026
5 of 9 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants