Skip to content

路線推定を利用した列車種別の誤指定検出機能を追加 - #5754

Merged
TinyKitten merged 3 commits into
devfrom
claude/fix-issue-5753-ZSC3o
Apr 3, 2026
Merged

TinyKitten merged 3 commits into
devfrom
claude/fix-issue-5753-ZSC3o

Conversation

@TinyKitten

@TinyKitten TinyKitten commented Apr 3, 2026 •

Copy link
Copy Markdown
Member

closes #5753

https://claude.ai/code/session_01RZhe3b5iSb3gpaLzht8wAv

Summary by CodeRabbit

  • 新機能
    • 選択した列車種別が実際の運行サービスと異なる可能性がある場合に、警告パネルで通知する機能を追加しました(推定結果と選択内容を比較)。
  • ローカライズ
    • 上記警告用の文言を日本語と英語の翻訳ファイルに追加しました。

@github-actions github-actions Bot added the react label Apr 3, 2026
@coderabbitai

coderabbitai Bot commented Apr 3, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

新しいフック useTrainTypeMismatchDetector を追加し、選択された列車種別と GPS ベースのルート推定結果を比較して不一致を検出、useWarningInfo に統合して警告用の翻訳文字列を追加しました。

Changes

Cohort / File(s) Summary
翻訳文字列
assets/translations/en.json, assets/translations/ja.json
英日両方に trainTypeMismatchWarning キーを追加。既存行の末尾にカンマを追加して JSON を整形。
フック実装
src/hooks/useTrainTypeMismatchDetector.ts
新規エクスポートのカスタムフック。navigationState の trainType と stationState の selectedBound を監視し、useRouteEstimation の候補と信頼度(>=0.7)を基に groupId を比較して不一致を boolean で返す。推定の開始/停止/リセット挙動を管理。
フック統合
src/hooks/index.ts, src/hooks/useWarningInfo.ts
useTrainTypeMismatchDetector をエクスポートに追加。useWarningInfo に組み込み、検出時に WARNING レベルで translate('trainTypeMismatchWarning') を返す早期リターンを追加。
テストスイート
src/hooks/useTrainTypeMismatchDetector.test.tsx
新規テストファイルを追加。Jotai と推定フック群をモックし、各種分岐(未選択、候補なし、信頼度境界、null groupId、status 切替、推定開始トリガー等)を網羅する非同期テスト群を実装。
sequenceDiagram
  participant UI as "UI / useWarningInfo"
  participant Hook as "useTrainTypeMismatchDetector"
  participant AtomNav as "Jotai:navigationState"
  participant AtomStation as "Jotai:stationState"
  participant Est as "useRouteEstimation"
  participant Control as "useRouteEstimationControl"

  UI->>Hook: フック呼び出し
  Hook->>AtomNav: trainType 読取
  Hook->>AtomStation: selectedBound 読取
  alt selectedBound.id && trainType
    Hook->>Control: startEstimation()
    Hook->>Est: candidates / status 取得
    Est-->>Hook: candidates, status
    alt status == "ready" && candidates[0].confidence >= 0.7 && trainType.groupId && candidate.groupId
      Hook-->>UI: isMismatch = (trainType.groupId != candidate.groupId)
    else
      Hook-->>UI: isMismatch = false
    end
  else selectedBound cleared
    Hook->>Control: stopEstimation()
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 ぴょんと飛び出す新しい目、
線路の声をそっと聞くよ
種別が違うと教えるよ、
そっと警告、安心の一歩、
旅路を見守る小さな耳。

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning PR説明がテンプレートで要求される情報をほぼ満たしていない。外部リンクのみで、本文の詳細な記述や変更内容の詳細、テストの実施状況が記載されていない。 テンプレートに従い、概要・変更内容・テスト実施状況・関連Issueを詳細に記述してください。外部リンク頼みではなく、PR本文に必要な情報を記載してください。
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed PRタイトルは路線推定を利用した列車種別の誤指定検出機能を追加する変更内容と完全に一致している。
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ 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-issue-5753-ZSC3o

Warning

Review ran into problems

🔥 Problems

Git: Failed to clone repository. Please run the @coderabbitai full review command to re-trigger a full review. If the issue persists, set path_filters to include or exclude specific files.


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

@TinyKitten

Copy link
Copy Markdown
Member Author

APIアクセスが定期的に発生するのが痛い

@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.

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/useWarningInfo.ts (1)

145-156: ⚠️ Potential issue | 🟠 Major

警告の優先順位を確認してください。

isTrainTypeMismatch(WARNING レベル)が badAccuracy(URGENT レベル)よりも先に評価されています。両方の条件が同時に true の場合、より緊急度の高い GPS 精度の警告が表示されず、列車種別の不一致警告が優先されます。

GPS 精度の問題はナビゲーション全体の信頼性に影響するため、badAccuracy のチェックを先に配置することを検討してください。

🔧 優先順位の修正案
     if (isLoopLineWrongDirection) {
       return {
         level: WARNING_PANEL_LEVEL.WARNING,
         text: translate('wrongDirectionLoopLineWarning'),
       };
     }
+    if (badAccuracy) {
+      return {
+        level: WARNING_PANEL_LEVEL.URGENT,
+        text: translate('badAccuracy'),
+      };
+    }
     if (isTrainTypeMismatch) {
       return {
         level: WARNING_PANEL_LEVEL.WARNING,
         text: translate('trainTypeMismatchWarning'),
       };
     }
-    if (badAccuracy) {
-      return {
-        level: WARNING_PANEL_LEVEL.URGENT,
-        text: translate('badAccuracy'),
-      };
-    }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/hooks/useWarningInfo.ts` around lines 145 - 156, The current ordering in
useWarningInfo.ts evaluates isTrainTypeMismatch before badAccuracy, causing
WARNING-level train type alerts to suppress URGENT GPS accuracy alerts when both
are true; swap the checks so badAccuracy is evaluated first (returning level:
WARNING_PANEL_LEVEL.URGENT, text: translate('badAccuracy')) before the
isTrainTypeMismatch block, ensuring URGENT accuracy warnings take precedence
over WARNING train-type mismatch messages.
🧹 Nitpick comments (1)
src/hooks/useTrainTypeMismatchDetector.test.tsx (1)

285-303: 境界値テストの追加を検討してください。

信頼度 0.5 で「低すぎる」ケースをテストしていますが、実際の閾値は MIN_MISMATCH_CONFIDENCE = 0.7 です。境界値として 0.69(false を期待)と 0.7(true を期待)のテストケースを追加すると、閾値ロジックがより厳密に検証されます。

🧪 境界値テストの追加案
it('returns false when confidence is just below threshold (0.69)', async () => {
  mockUseAtomValue.mockImplementation((atom: unknown) => {
    if (atom === require('../store/atoms/navigation').default) {
      return { trainType: createTrainType(100) };
    }
    if (atom === require('../store/atoms/station').default) {
      return { selectedBound: { id: 1 } };
    }
    return {};
  });

  mockCandidates = [createCandidate(200, 0.69)];
  mockStatus = 'ready';

  const { getByTestId } = render(<TestComponent />);
  await waitFor(() => {
    expect(getByTestId('result').props.children).toBe('ok');
  });
});

it('detects mismatch when confidence is at threshold (0.7)', async () => {
  mockUseAtomValue.mockImplementation((atom: unknown) => {
    if (atom === require('../store/atoms/navigation').default) {
      return { trainType: createTrainType(100) };
    }
    if (atom === require('../store/atoms/station').default) {
      return { selectedBound: { id: 1 } };
    }
    return {};
  });

  mockCandidates = [createCandidate(200, 0.7)];
  mockStatus = 'ready';

  const { getByTestId } = render(<TestComponent />);
  await waitFor(() => {
    expect(getByTestId('result').props.children).toBe('mismatch');
  });
});
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/hooks/useTrainTypeMismatchDetector.test.tsx` around lines 285 - 303, Add
two boundary tests around MIN_MISMATCH_CONFIDENCE to ensure threshold behavior:
update the test file to include one case where mockCandidates =
[createCandidate(200, 0.69)] and mockStatus = 'ready' and assert TestComponent
returns 'ok' (no mismatch), and another where mockCandidates =
[createCandidate(200, 0.7)] with mockStatus = 'ready' and assert TestComponent
returns 'mismatch'; reuse the same mockUseAtomValue setup (checking navigation
and station atoms) and the existing render/waitFor pattern so the tests exercise
the MIN_MISMATCH_CONFIDENCE logic used by the detector.
🤖 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/useTrainTypeMismatchDetector.ts`:
- Around line 41-49: The current logic in useTrainTypeMismatchDetector calls
stopEstimation() and startEstimation() but those only flip state and do not
clear bufferRef, so old location data remains; update the code to call the
reset() routine (which clears bufferRef.current) when the bound/direction
changes instead of—or in addition to—calling stopEstimation()/startEstimation();
to do this either export reset() from useRouteEstimation or expose it via
useRouteEstimationControl and invoke reset() (or explicitly clear
bufferRef.current) in the bound-change branch in useTrainTypeMismatchDetector to
ensure the buffer is cleared before restarting estimation.

---

Outside diff comments:
In `@src/hooks/useWarningInfo.ts`:
- Around line 145-156: The current ordering in useWarningInfo.ts evaluates
isTrainTypeMismatch before badAccuracy, causing WARNING-level train type alerts
to suppress URGENT GPS accuracy alerts when both are true; swap the checks so
badAccuracy is evaluated first (returning level: WARNING_PANEL_LEVEL.URGENT,
text: translate('badAccuracy')) before the isTrainTypeMismatch block, ensuring
URGENT accuracy warnings take precedence over WARNING train-type mismatch
messages.

---

Nitpick comments:
In `@src/hooks/useTrainTypeMismatchDetector.test.tsx`:
- Around line 285-303: Add two boundary tests around MIN_MISMATCH_CONFIDENCE to
ensure threshold behavior: update the test file to include one case where
mockCandidates = [createCandidate(200, 0.69)] and mockStatus = 'ready' and
assert TestComponent returns 'ok' (no mismatch), and another where
mockCandidates = [createCandidate(200, 0.7)] with mockStatus = 'ready' and
assert TestComponent returns 'mismatch'; reuse the same mockUseAtomValue setup
(checking navigation and station atoms) and the existing render/waitFor pattern
so the tests exercise the MIN_MISMATCH_CONFIDENCE logic used by the detector.
🪄 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: c8089d53-8b25-4642-b2ba-482bc5f33e50

📥 Commits

Reviewing files that changed from the base of the PR and between d40e75c and 8efa29b.

📒 Files selected for processing (6)
  • assets/translations/en.json
  • assets/translations/ja.json
  • src/hooks/index.ts
  • src/hooks/useTrainTypeMismatchDetector.test.tsx
  • src/hooks/useTrainTypeMismatchDetector.ts
  • src/hooks/useWarningInfo.ts

@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/useTrainTypeMismatchDetector.test.tsx (1)

201-206: jest.clearAllMocks() は afterEach ブロックで呼び出すべき

コーディングガイドラインでは、jest.clearAllMocks() は afterEach ブロックで呼び出すことが推奨されています。beforeEach でも動作しますが、テスト後のクリーンアップというセマンティクスに合わせるため afterEach を使用してください。

♻️ 修正案
   beforeEach(() => {
-    jest.clearAllMocks();
     mockCandidates = [];
     mockStatus = 'idle';
     mockIsEstimating = false;
   });
+
+  afterEach(() => {
+    jest.clearAllMocks();
+  });

As per coding guidelines: "Call jest.clearAllMocks() in afterEach blocks"

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/hooks/useTrainTypeMismatchDetector.test.tsx` around lines 201 - 206, Move
the jest.clearAllMocks() call out of the beforeEach block and into an afterEach
block: remove jest.clearAllMocks() from the existing beforeEach (which should
continue to initialize mockCandidates, mockStatus, mockIsEstimating) and add a
new afterEach that calls jest.clearAllMocks(); this aligns with the testing
guideline to perform mock cleanup in afterEach and keeps the initialization
logic inside beforeEach.
🤖 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/useTrainTypeMismatchDetector.test.tsx`:
- Around line 201-206: Move the jest.clearAllMocks() call out of the beforeEach
block and into an afterEach block: remove jest.clearAllMocks() from the existing
beforeEach (which should continue to initialize mockCandidates, mockStatus,
mockIsEstimating) and add a new afterEach that calls jest.clearAllMocks(); this
aligns with the testing guideline to perform mock cleanup in afterEach and keeps
the initialization logic inside beforeEach.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 8643c217-3efe-42a1-979c-26e04d394380

📥 Commits

Reviewing files that changed from the base of the PR and between 8efa29b and 359ace0.

📒 Files selected for processing (3)
  • src/hooks/useTrainTypeMismatchDetector.test.tsx
  • src/hooks/useTrainTypeMismatchDetector.ts
  • src/hooks/useWarningInfo.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/hooks/useWarningInfo.ts
  • src/hooks/useTrainTypeMismatchDetector.ts

@TinyKitten
TinyKitten merged commit 775ade1 into dev Apr 3, 2026
5 checks passed
@TinyKitten
TinyKitten deleted the claude/fix-issue-5753-ZSC3o branch April 3, 2026 09:36
@TinyKitten TinyKitten self-assigned this Apr 4, 2026
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