Skip to content

オートモードで移動が開始しない場合があるバグを修正 - #5309

Merged
TinyKitten merged 7 commits into
devfrom
fix/automode
Feb 17, 2026
Merged

TinyKitten merged 7 commits into
devfrom
fix/automode

Conversation

@TinyKitten

@TinyKitten TinyKitten commented Feb 17, 2026 •

Copy link
Copy Markdown
Member

Summary by CodeRabbit

リリースノート

  • テスト

    • テストを共通の状態モックへ移行し、開始位置、経路順序、通過駅/非停車駅、速度プロファイル、間隔更新など多様なシナリオを追加しました。
  • 改善

    • 現在駅ベースの開始位置解決を強化し、路線外や座標未設定時のフォールバックや順序反転に対する動作を安定化しました。
  • 破壊的変更

    • 位置更新の公開インターフェースが変更され、位置更新の呼び出し方法が変わっています。

@TinyKitten TinyKitten self-assigned this Feb 17, 2026
@github-actions github-actions Bot added the react label Feb 17, 2026
@coderabbitai

coderabbitai Bot commented Feb 17, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉


📝 Walkthrough

Walkthrough

useSimulationMode フックは開始位置決定を内部の resolveStartIndex に移し、位置更新を直接の setLocation 呼び出しから store.set(locationAtom, …) へ統一。テストは個別フックのスパイを廃止し、setupAtomMocks によるアトム駆動のモックへ移行した。

Changes

Cohort / File(s) Summary
Simulation Mode Hook Implementation
src/hooks/useSimulationMode.ts
開始地点解決を resolveStartIndex に集約し、useInRadiusStation 依存を除去。位置更新を store.set(locationAtom, …) に統一、セグメント進行・ガード・依存配列を更新。
Simulation Mode Test Suite
src/hooks/useSimulationMode.test.tsx
フックの直接スパイを廃止し setupAtomMocks を導入。mockPassStation / mockLocationObject 等のビルダ追加、store.set を用いた状態駆動の検証へ移行。各種シナリオ(start index, nearest, pass-station, 速度プロファイル, interval 更新等)を拡張。
Store & Atom test mocks / Test utilities
~/store/atoms/location, ~/store/atoms/station, ~/store/atoms/navigation, src/hooks/...setupAtomMocks*
テスト用モックを更新:locationAtom を toString() を持つオブジェクトに変更し setLocation を削除。駅/ナビ用アトムモックとモックストア(get/set)を追加、アトム戻り値の順序制御を行う setupAtomMocks を追加。

Sequence Diagram(s)

sequenceDiagram
    rect rgba(200,200,255,0.5)
    participant Test as テスト
    end
    rect rgba(200,255,200,0.5)
    participant Hook as useSimulationMode
    participant Stations as 駅リスト
    participant Speed as 速度プロファイル生成器
    participant Store as モックJotaiStore\n(locationAtom)
    end

    Test->>Hook: フックをマウント / シミュレーション開始
    Hook->>Stations: maybeReversedStations + currentStation を渡す
    Hook->>Stations: resolveStartIndex() を呼び出す
    Hook->>Speed: 速度プロファイルを要求
    Speed-->>Hook: speedProfile を返す
    Hook->>Store: store.set(locationAtom, { coords, bearing, ... })
    Store-->>Test: サブスクライバ通知 / テストが更新を検証
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

🐇 新しい線路で、アトムを跳ねる朝
resolveStartIndex が道を示すよ
モックで整えたテストの庭で
store.set がそっと位置を描く
ぴょん、と進もう、バグも逃がす ✨

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed プルリクエストのタイトルは「オートモードで移動が開始しない場合があるバグを修正」で、変更内容と完全に関連しており、修正されたバグの本質を明確に要約しています。
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Merge Conflict Detection ✅ Passed ✅ No merge conflicts detected when merging into dev

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

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/automode

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

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

261-277: 終端リセット時に childIndexRef も初期化すると安全です。
segmentIndexRef を 0 に戻す際に childIndexRef が残ると次セグメント開始が飛ぶ可能性があるため、同時リセットを検討してください。

修正案
       if (!nextStopStation) {
         segmentIndexRef.current = 0;
+        childIndexRef.current = 0;
         segmentProgressDistanceRef.current = 0;
         const firstStation = maybeRevsersedStations[0];
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/hooks/useSimulationMode.ts` around lines 261 - 277, When resetting the
terminal condition in useSimulationMode (where segmentIndexRef.current and
segmentProgressDistanceRef.current are set to 0 and the location is set from
maybeRevsersedStations[0]), also reset childIndexRef.current to 0 to avoid
skipping the first child segment on the next segment start; update the same
block that references segmentIndexRef, segmentProgressDistanceRef,
maybeRevsersedStations, and store.set(locationAtom, ...) to include
childIndexRef.current = 0 so all segment-related refs are initialized together.
🤖 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/useSimulationMode.ts`:
- Around line 261-277: When resetting the terminal condition in
useSimulationMode (where segmentIndexRef.current and
segmentProgressDistanceRef.current are set to 0 and the location is set from
maybeRevsersedStations[0]), also reset childIndexRef.current to 0 to avoid
skipping the first child segment on the next segment start; update the same
block that references segmentIndexRef, segmentProgressDistanceRef,
maybeRevsersedStations, and store.set(locationAtom, ...) to include
childIndexRef.current = 0 so all segment-related refs are initialized together.

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

141-217: ⚠️ Potential issue | 🟠 Major

速度プロファイルが初期レンダー固定になり、後から駅が入ると空のまま。
resolveStartIndex を追加した現在の構成だと、stations が非同期で入るケースで speedProfilesRef が空のまま残り、移動が進まない恐れがあります。stations / direction 変化に追従して再生成してください。

🐛 修正案(依存配列を正しく更新)
-// biome-ignore lint/correctness/useExhaustiveDependencies: プロファイル生成は初回のみ
-useEffect(() => {
+useEffect(() => {
+  if (maybeRevsersedStations.length === 0) {
+    return;
+  }
   const speedProfiles = maybeRevsersedStations.map((cur, _, arr) => {
     const stationsWithoutPass = arr.filter((s) => !getIsPass(s));
@@
   segmentIndexRef.current = resolveStartIndex();
   speedProfilesRef.current = speedProfiles;
   childIndexRef.current = 0;
   segmentProgressDistanceRef.current = 0;
   dwellPendingRef.current = false;
-}, []);
+}, [maybeRevsersedStations, resolveStartIndex, isBus, currentLineType, maxSpeed]);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/hooks/useSimulationMode.ts` around lines 141 - 217, The effect that
builds speedProfiles (useEffect) runs only on mount so speedProfilesRef.current
stays empty when maybeRevsersedStations (stations/direction) arrive
asynchronously; update the effect to re-run whenever inputs change by including
maybeRevsersedStations and any other inputs used inside (e.g., isBus,
currentLineType, maxSpeed, resolveStartIndex) in the dependency array, and
ensure you recompute speedProfiles (the speedProfiles variable), set
speedProfilesRef.current, segmentIndexRef.current = resolveStartIndex(),
childIndexRef.current, segmentProgressDistanceRef.current and
dwellPendingRef.current each time the effect runs so the simulation follows
station/direction updates.
🤖 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/useSimulationMode.ts`:
- Around line 88-123: In resolveStartIndex, directIndex may point at a passing
station which later misaligns with stationsWithoutPass; change the logic so if
maybeRevsersedStations[directIndex] exists and
getIsPass(maybeRevsersedStations[directIndex]) is true, treat it as not found
and continue to the nearest-non-pass fallback; i.e., only return directIndex
when it exists and getIsPass(...) is false, otherwise run the existing
nearest-station-by-coordinate loop (which already skips passing stations) and
return nearestIndex or 0 as before. Ensure the check references
resolveStartIndex, maybeRevsersedStations, currentStation and getIsPass.

---

Outside diff comments:
In `@src/hooks/useSimulationMode.ts`:
- Around line 141-217: The effect that builds speedProfiles (useEffect) runs
only on mount so speedProfilesRef.current stays empty when
maybeRevsersedStations (stations/direction) arrive asynchronously; update the
effect to re-run whenever inputs change by including maybeRevsersedStations and
any other inputs used inside (e.g., isBus, currentLineType, maxSpeed,
resolveStartIndex) in the dependency array, and ensure you recompute
speedProfiles (the speedProfiles variable), set speedProfilesRef.current,
segmentIndexRef.current = resolveStartIndex(), childIndexRef.current,
segmentProgressDistanceRef.current and dwellPendingRef.current each time the
effect runs so the simulation follows station/direction updates.

Comment thread src/hooks/useSimulationMode.ts Resolved

@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 (2)
src/hooks/useSimulationMode.test.tsx (2)

106-128: setupAtomMocksのコール順序依存は脆弱性があります。

useAtomValueのモックがコール順序に依存しているため、フック内部の実装が変更されるとテストが壊れる可能性があります。コメント(line 115-116)で意図は説明されていますが、より堅牢なアプローチとしてatom参照で判定することを検討してください。

♻️ atom参照ベースのモック例
import stationState from '~/store/atoms/station';
import navigationState from '~/store/atoms/navigation';

// モック設定でatom参照を使用
jest.mock('~/store/atoms/station', () => ({
  __esModule: true,
  default: { toString: () => 'stationState' },
}));

jest.mock('~/store/atoms/navigation', () => ({
  __esModule: true,
  default: { toString: () => 'navigationState' },
}));

const setupAtomMocks = (stationStateValue: {...}, navigationStateValue: {...}) => {
  (useAtomValue as jest.Mock).mockImplementation((atom: any) => {
    if (atom.toString() === 'stationState') {
      return { station: stationStateValue.station ?? null, ... };
    }
    if (atom.toString() === 'navigationState') {
      return navigationStateValue;
    }
    return undefined;
  });
};
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/hooks/useSimulationMode.test.tsx` around lines 106 - 128, The current
setupAtomMocks relies on call order of useAtomValue which is fragile; change it
to inspect the atom reference instead: mock the station and navigation atom
modules to export identifiable objects (e.g., stationState and navigationState
with a custom toString() or a unique property) and replace the useAtomValue
mockImplementation in setupAtomMocks to switch on atom.toString() (or that
unique property) returning the station payload when the atom matches
stationState and the navigation payload when it matches navigationState,
returning undefined otherwise; keep the helper name setupAtomMocks and the
inputs the same so tests consume the same API.

655-691: 特殊路線タイプのテストアサーションが弱いです。

新幹線(BulletTrain)と特急(LimitedExpress)のテストでは、resultがtruthyかどうかのみを確認しています。useSimulationModeはvoidを返すため、このアサーションは実質的に何もテストしていません。

♻️ より意味のあるアサーションの提案
     it('新幹線の路線タイプでは最高速度が適用される', () => {
+      const stations = [
+        mockStation(1, 1, 35.681, 139.767),
+        mockStation(2, 2, 35.691, 139.777),
+      ];
+
       setupAtomMocks(
-        { stations: [], selectedDirection: 'OUTBOUND' },
-        { autoModeEnabled: false }
+        { station: stations[0], stations, selectedDirection: 'OUTBOUND' },
+        { autoModeEnabled: true }
       );

       jest
         .spyOn(useCurrentLineModule, 'useCurrentLine')
         .mockReturnValue({ id: 1, lineType: LineType.BulletTrain } as any);

-      const { result } = renderHook(() => useSimulationMode(), {
+      const generateSpy = jest.spyOn(
+        trainSpeedModule,
+        'generateTrainSpeedProfile'
+      );
+
+      renderHook(() => useSimulationMode(), {
         wrapper: ({ children }) => <Provider>{children}</Provider>,
       });

-      expect(result).toBeTruthy();
+      // 新幹線の最高速度が適用されていることを確認
+      expect(generateSpy).toHaveBeenCalled();
+      const callArgs = generateSpy.mock.calls[0]?.[0];
+      expect(callArgs?.maxSpeed).toBe(LINE_TYPE_MAX_SPEEDS_IN_M_S[LineType.BulletTrain]);
     });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/hooks/useSimulationMode.test.tsx` around lines 655 - 691, The tests for
BulletTrain and LimitedExpress only assert result is truthy but
useSimulationMode returns void; instead assert the side-effect the hook
performs: after mocking useCurrentLine (LineType.BulletTrain) and
useCurrentTrainType (TrainTypeKind.LimitedExpress) call useSimulationMode via
renderHook and then verify the simulation speed state was updated to the
expected max speed (e.g., read the relevant atom/state that setupAtomMocks
initializes or spy on the setter used by useSimulationMode); specifically update
the two test cases to replace expect(result).toBeTruthy() with assertions that
the simulation max speed (the atom/state changed by useSimulationMode) equals
the expected BulletTrain speed and LimitedExpress speed respectively, using the
Provider wrapper and any existing mock/spied setter created by setupAtomMocks.
🤖 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/useSimulationMode.test.tsx`:
- Around line 106-128: The current setupAtomMocks relies on call order of
useAtomValue which is fragile; change it to inspect the atom reference instead:
mock the station and navigation atom modules to export identifiable objects
(e.g., stationState and navigationState with a custom toString() or a unique
property) and replace the useAtomValue mockImplementation in setupAtomMocks to
switch on atom.toString() (or that unique property) returning the station
payload when the atom matches stationState and the navigation payload when it
matches navigationState, returning undefined otherwise; keep the helper name
setupAtomMocks and the inputs the same so tests consume the same API.
- Around line 655-691: The tests for BulletTrain and LimitedExpress only assert
result is truthy but useSimulationMode returns void; instead assert the
side-effect the hook performs: after mocking useCurrentLine
(LineType.BulletTrain) and useCurrentTrainType (TrainTypeKind.LimitedExpress)
call useSimulationMode via renderHook and then verify the simulation speed state
was updated to the expected max speed (e.g., read the relevant atom/state that
setupAtomMocks initializes or spy on the setter used by useSimulationMode);
specifically update the two test cases to replace expect(result).toBeTruthy()
with assertions that the simulation max speed (the atom/state changed by
useSimulationMode) equals the expected BulletTrain speed and LimitedExpress
speed respectively, using the Provider wrapper and any existing mock/spied
setter created by setupAtomMocks.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/hooks/useSimulationMode.test.tsx (1)

1-141: ⚠️ Potential issue | 🟡 Minor

biome-ignore-all は範囲が広すぎます
ファイル全体の無効化ではなく、必要箇所のみに限定してください。

修正案
-/** biome-ignore-all lint/suspicious/noExplicitAny: テストコードまで型安全にするのはつらい */
@@
-  (useAtomValue as jest.Mock).mockImplementation((atom: any) => {
+  (useAtomValue as jest.Mock).mockImplementation(
+    // biome-ignore lint/suspicious/noExplicitAny: テスト用の Atom 判定
+    (atom: any) => {

As per coding guidelines Use // biome-ignore only for true compatibility issues and include an inline reason.

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

In `@src/hooks/useSimulationMode.test.tsx` around lines 1 - 141, The file-wide
"biome-ignore-all lint/suspicious/noExplicitAny" is too broad; remove the
top-level carte-blanche comment and instead add narrow, inline ignores where the
any type is actually required (for example annotate only the problematic
declarations like the mock helpers mockStation, mockPassStation,
mockLocationObject or the setupAtomMocks signature). Replace the file-wide
comment with targeted comments such as "// biome-ignore-next-line
lint/suspicious/noExplicitAny: test helper uses dynamic mock types" immediately
above the specific lines (e.g., the mock function or useAtomValue jest.mock
implementation) so lint suppression is limited to the exact symbols causing the
issue (setupAtomMocks, mockStation, mockPassStation, mockLocationObject, and the
useAtomValue jest mock).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@src/hooks/useSimulationMode.test.tsx`:
- Around line 1-141: The file-wide "biome-ignore-all
lint/suspicious/noExplicitAny" is too broad; remove the top-level carte-blanche
comment and instead add narrow, inline ignores where the any type is actually
required (for example annotate only the problematic declarations like the mock
helpers mockStation, mockPassStation, mockLocationObject or the setupAtomMocks
signature). Replace the file-wide comment with targeted comments such as "//
biome-ignore-next-line lint/suspicious/noExplicitAny: test helper uses dynamic
mock types" immediately above the specific lines (e.g., the mock function or
useAtomValue jest.mock implementation) so lint suppression is limited to the
exact symbols causing the issue (setupAtomMocks, mockStation, mockPassStation,
mockLocationObject, and the useAtomValue jest mock).

@TinyKitten
TinyKitten merged commit 1d01300 into dev Feb 17, 2026
5 checks passed
@TinyKitten
TinyKitten deleted the fix/automode branch February 17, 2026 06:08
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.

1 participant