tkadkghdlf commited on
Commit
bc7b288
·
verified ·
1 Parent(s): e20f8a3

Sync DemoService 2150d5839c322d3d61bfde1129daca24c6886748

Browse files
api/auth-service/app/api/v1/endpoints/active_run.py CHANGED
@@ -62,9 +62,10 @@ def lock_user(db, user):
62
  db.execute(select(User.id).where(User.id == user.id).with_for_update()).first()
63
 
64
  @router.get("")
65
- def read_active(db: Session = Depends(get_db), user: User = Depends(get_current_user)):
66
  row = db.scalar(select(ActiveRun).where(ActiveRun.user_id == user.id, ActiveRun.ended == 0))
67
- return {"active": envelope(row)}
 
68
 
69
  @router.get("/environment-density")
70
  def environment_density(response: Response, db: Session = Depends(get_db),
 
62
  db.execute(select(User.id).where(User.id == user.id).with_for_update()).first()
63
 
64
  @router.get("")
65
+ def read_active(db: Session = Depends(get_db), user: User = Depends(get_current_user), session_id: str | None = None):
66
  row = db.scalar(select(ActiveRun).where(ActiveRun.user_id == user.id, ActiveRun.ended == 0))
67
+ previous = db.get(ActiveRun, (user.id, session_id)) if session_id else None
68
+ return {"active": envelope(row), "ended_session_id": previous.session_id if previous and previous.ended else None}
69
 
70
  @router.get("/environment-density")
71
  def environment_density(response: Response, db: Session = Depends(get_db),
api/auth-service/app/api/v1/endpoints/runs.py CHANGED
@@ -658,90 +658,41 @@ def get_recent_routes(
658
  db: Session = Depends(get_db),
659
  current_user: User = Depends(get_current_user),
660
  ):
661
- has_map_image_column = _routes_has_map_image_column(db)
662
-
663
- query = (
664
- """
665
- WITH ranked_runs AS (
666
- SELECT
667
- rs.id,
668
- rs.route_id,
669
- rs.distance_km,
670
- rs.user_rating,
671
- rs.finished_at,
672
- rs.started_at,
673
- COUNT(*) OVER (PARTITION BY rs.route_id)::int AS completed_count,
674
- ROW_NUMBER() OVER (
675
- PARTITION BY rs.route_id
676
- ORDER BY COALESCE(rs.finished_at, rs.started_at) DESC, rs.id DESC
677
- ) AS route_rank
678
- FROM run_sessions rs
679
- WHERE rs.user_id = :user_id
680
- AND rs.route_id IS NOT NULL
681
- )
682
- SELECT
683
- rr.id AS run_session_id,
684
- r.id AS route_id,
685
- COALESCE(NULLIF(TRIM(r.title), ''), 'Route') AS route_title,
686
- NULLIF(TRIM(r.animal_label), '') AS animal_label,
687
- COALESCE(rr.distance_km, 0) AS actual_distance_km,
688
- COALESCE(r.length_km, 0) AS route_length_km,
689
- COALESCE(NULLIF(TRIM(r.map_image_url), ''), '/icon.svg') AS map_image_url,
690
- r.center_lat AS center_lat,
691
- r.center_lng AS center_lng,
692
- r.polyline AS polyline,
693
- COALESCE(rr.finished_at, rr.started_at) AS completed_at,
694
- rr.completed_count AS completed_count,
695
- rr.user_rating AS user_rating
696
- FROM ranked_runs rr
697
- JOIN routes r ON r.id = rr.route_id
698
- WHERE rr.route_rank = 1
699
- ORDER BY COALESCE(rr.finished_at, rr.started_at) DESC, rr.id DESC
700
- LIMIT :limit
701
- """
702
- if has_map_image_column
703
- else """
704
- WITH ranked_runs AS (
705
  SELECT
706
- rs.id,
707
  rs.route_id,
708
- rs.distance_km,
 
 
 
 
 
 
 
 
 
709
  rs.user_rating,
710
- rs.finished_at,
711
- rs.started_at,
712
- COUNT(*) OVER (PARTITION BY rs.route_id)::int AS completed_count,
713
- ROW_NUMBER() OVER (
714
- PARTITION BY rs.route_id
715
- ORDER BY COALESCE(rs.finished_at, rs.started_at) DESC, rs.id DESC
716
- ) AS route_rank
 
717
  FROM run_sessions rs
 
 
718
  WHERE rs.user_id = :user_id
719
- AND rs.route_id IS NOT NULL
720
- )
721
- SELECT
722
- rr.id AS run_session_id,
723
- r.id AS route_id,
724
- COALESCE(NULLIF(TRIM(r.title), ''), 'Route') AS route_title,
725
- NULLIF(TRIM(r.animal_label), '') AS animal_label,
726
- COALESCE(rr.distance_km, 0) AS actual_distance_km,
727
- COALESCE(r.length_km, 0) AS route_length_km,
728
- '/icon.svg' AS map_image_url,
729
- r.center_lat AS center_lat,
730
- r.center_lng AS center_lng,
731
- r.polyline AS polyline,
732
- COALESCE(rr.finished_at, rr.started_at) AS completed_at,
733
- rr.completed_count AS completed_count,
734
- rr.user_rating AS user_rating
735
- FROM ranked_runs rr
736
- JOIN routes r ON r.id = rr.route_id
737
- WHERE rr.route_rank = 1
738
- ORDER BY COALESCE(rr.finished_at, rr.started_at) DESC, rr.id DESC
739
- LIMIT :limit
740
- """
741
- )
742
-
743
- rows = db.execute(
744
- text(query),
745
  {"user_id": current_user.id, "limit": limit},
746
  ).mappings().all()
747
 
@@ -749,7 +700,7 @@ def get_recent_routes(
749
  routes=[
750
  RecentRouteItem(
751
  run_session_id=int(row["run_session_id"]),
752
- route_id=int(row["route_id"]),
753
  route_title=str(row["route_title"]),
754
  animal_label=str(row["animal_label"]) if row["animal_label"] is not None else None,
755
  actual_distance_km=float(row["actual_distance_km"] or 0),
@@ -761,6 +712,14 @@ def get_recent_routes(
761
  completed_at=row["completed_at"],
762
  completed_count=int(row["completed_count"] or 0),
763
  user_rating=int(row["user_rating"]) if row["user_rating"] is not None else None,
 
 
 
 
 
 
 
 
764
  )
765
  for row in rows
766
  ]
 
658
  db: Session = Depends(get_db),
659
  current_user: User = Depends(get_current_user),
660
  ):
661
+ # History is per workout, not per distinct course. Include free runs and
662
+ # prefer the travelled trace over the planned course for completed records.
663
+ image = ("COALESCE(NULLIF(TRIM(r.map_image_url), ''), '/icon.svg')"
664
+ if _routes_has_map_image_column(db) else "'/icon.svg'")
665
+ rows = db.execute(
666
+ text(f"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
667
  SELECT
668
+ rs.id AS run_session_id,
669
  rs.route_id,
670
+ COALESCE(NULLIF(TRIM(r.title), ''), '자유 러닝') AS route_title,
671
+ NULLIF(TRIM(r.animal_label), '') AS animal_label,
672
+ COALESCE(rs.distance_km, 0) AS actual_distance_km,
673
+ COALESCE(r.length_km, rs.distance_km, 0) AS route_length_km,
674
+ {image} AS map_image_url,
675
+ COALESCE(actual.center_lat, r.center_lat) AS center_lat,
676
+ COALESCE(actual.center_lng, r.center_lng) AS center_lng,
677
+ COALESCE(actual.polyline, r.polyline) AS polyline,
678
+ COALESCE(rs.finished_at, rs.started_at) AS completed_at,
679
+ COUNT(*) OVER (PARTITION BY rs.route_id) AS completed_count,
680
  rs.user_rating,
681
+ rs.duration_sec,
682
+ rs.avg_pace_sec_per_km,
683
+ rs.calories,
684
+ rs.avg_bpm,
685
+ rs.achievement_pct,
686
+ rs.is_completed,
687
+ rs.source,
688
+ rs.place_text
689
  FROM run_sessions rs
690
+ LEFT JOIN routes r ON r.id = rs.route_id
691
+ LEFT JOIN run_session_actual_routes actual ON actual.run_session_id = rs.id
692
  WHERE rs.user_id = :user_id
693
+ ORDER BY COALESCE(rs.finished_at, rs.started_at) DESC, rs.id DESC
694
+ LIMIT :limit
695
+ """),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
696
  {"user_id": current_user.id, "limit": limit},
697
  ).mappings().all()
698
 
 
700
  routes=[
701
  RecentRouteItem(
702
  run_session_id=int(row["run_session_id"]),
703
+ route_id=int(row["route_id"]) if row["route_id"] is not None else None,
704
  route_title=str(row["route_title"]),
705
  animal_label=str(row["animal_label"]) if row["animal_label"] is not None else None,
706
  actual_distance_km=float(row["actual_distance_km"] or 0),
 
712
  completed_at=row["completed_at"],
713
  completed_count=int(row["completed_count"] or 0),
714
  user_rating=int(row["user_rating"]) if row["user_rating"] is not None else None,
715
+ duration_sec=int(row["duration_sec"] or 0),
716
+ avg_pace_sec_per_km=row["avg_pace_sec_per_km"],
717
+ calories=row["calories"],
718
+ avg_bpm=row["avg_bpm"],
719
+ achievement_pct=float(row["achievement_pct"] or 0),
720
+ is_completed=bool(row["is_completed"]),
721
+ source=row["source"] or "nearby",
722
+ place_text=row["place_text"],
723
  )
724
  for row in rows
725
  ]
api/auth-service/app/schemas/run.py CHANGED
@@ -199,7 +199,7 @@ class RunSessionRatingUpdate(BaseModel):
199
 
200
  class RecentRouteItem(BaseModel):
201
  run_session_id: int
202
- route_id: int
203
  route_title: str
204
  animal_label: str | None = None
205
  actual_distance_km: float
@@ -211,6 +211,14 @@ class RecentRouteItem(BaseModel):
211
  completed_at: datetime | None = None
212
  completed_count: int
213
  user_rating: int | None = None
 
 
 
 
 
 
 
 
214
 
215
 
216
  class RecentRoutesResponse(BaseModel):
 
199
 
200
  class RecentRouteItem(BaseModel):
201
  run_session_id: int
202
+ route_id: int | None = None
203
  route_title: str
204
  animal_label: str | None = None
205
  actual_distance_km: float
 
211
  completed_at: datetime | None = None
212
  completed_count: int
213
  user_rating: int | None = None
214
+ duration_sec: int = 0
215
+ avg_pace_sec_per_km: float | None = None
216
+ calories: int | None = None
217
+ avg_bpm: float | None = None
218
+ achievement_pct: float = 0
219
+ is_completed: bool = False
220
+ source: str = "nearby"
221
+ place_text: str | None = None
222
 
223
 
224
  class RecentRoutesResponse(BaseModel):
api/auth-service/tests/test_active_run.py CHANGED
@@ -52,6 +52,14 @@ class ActiveRunTests(unittest.TestCase):
52
  complete(mode, self.payload(mode, 3, session=mode), self.db, self.user)
53
  self.assertIsNone(read_active(self.db, self.user)["active"])
54
 
 
 
 
 
 
 
 
 
55
  def test_stale_write_and_terminal_resurrection_are_rejected(self):
56
  start(self.payload(revision=10), self.db, self.user)
57
  self.assertEqual(checkpoint("run-1", self.payload(revision=9), self.db, self.user)["checkpoint"]["revision"], 10)
 
52
  complete(mode, self.payload(mode, 3, session=mode), self.db, self.user)
53
  self.assertIsNone(read_active(self.db, self.user)["active"])
54
 
55
+ def test_recovery_distinguishes_unuploaded_and_ended_sessions(self):
56
+ self.assertIsNone(read_active(self.db, self.user, "unuploaded")["ended_session_id"])
57
+ start(self.payload(), self.db, self.user)
58
+ complete("run-1", self.payload(revision=2), self.db, self.user)
59
+ self.assertEqual(read_active(self.db, self.user, "run-1")["ended_session_id"], "run-1")
60
+ self.assertIsNone(read_active(self.db, self.other, "run-1")["ended_session_id"])
61
+ self.assertIsNone(read_active(self.db, self.user, "different-session")["ended_session_id"])
62
+
63
  def test_stale_write_and_terminal_resurrection_are_rejected(self):
64
  start(self.payload(revision=10), self.db, self.user)
65
  self.assertEqual(checkpoint("run-1", self.payload(revision=9), self.db, self.user)["checkpoint"]["revision"], 10)
api/auth-service/tests/test_recent_runs.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Recent workout history contract, using an isolated in-memory database."""
2
+ import json
3
+ import unittest
4
+ from types import SimpleNamespace
5
+ from unittest.mock import patch
6
+ from sqlalchemy import create_engine, text
7
+ from sqlalchemy.orm import Session
8
+ from app.api.v1.endpoints.runs import get_recent_routes
9
+
10
+
11
+ class RecentRunsTests(unittest.TestCase):
12
+ def setUp(self):
13
+ self.engine = create_engine("sqlite:///:memory:")
14
+ self.db = Session(self.engine)
15
+ statements = [
16
+ """CREATE TABLE routes (id INTEGER PRIMARY KEY, title TEXT, animal_label TEXT,
17
+ length_km REAL, map_image_url TEXT, center_lat REAL, center_lng REAL, polyline TEXT)""",
18
+ """CREATE TABLE run_sessions (id INTEGER PRIMARY KEY, user_id INTEGER, route_id INTEGER,
19
+ started_at TEXT, finished_at TEXT, distance_km REAL, user_rating INTEGER,
20
+ duration_sec INTEGER, avg_pace_sec_per_km REAL, calories INTEGER, avg_bpm REAL,
21
+ achievement_pct REAL, is_completed INTEGER, source TEXT, place_text TEXT)""",
22
+ """CREATE TABLE run_session_actual_routes (run_session_id INTEGER PRIMARY KEY,
23
+ center_lat REAL, center_lng REAL, polyline TEXT)""",
24
+ ]
25
+ for statement in statements:
26
+ self.db.execute(text(statement))
27
+ self.db.execute(text("INSERT INTO routes VALUES (7, '강변 루트', 'dog', 5, '/map.png', 37, 127, :line)"),
28
+ {"line": json.dumps([[37, 127], [37.1, 127]])})
29
+
30
+ def tearDown(self):
31
+ self.db.close()
32
+ self.engine.dispose()
33
+
34
+ def add_run(self, identity, date, route=7, user=1, distance=2.5, completed=1):
35
+ self.db.execute(text("""INSERT INTO run_sessions VALUES
36
+ (:id, :user, :route, :date, :date, :distance, 4, 900, 360, 180, 125, 50, :completed, 'manual', '서울')"""),
37
+ dict(id=identity, user=user, route=route, date=date, distance=distance, completed=completed))
38
+
39
+ def recent(self, limit=2, image_column=True):
40
+ with patch("app.api.v1.endpoints.runs._routes_has_map_image_column", return_value=image_column):
41
+ return get_recent_routes(limit, self.db, SimpleNamespace(id=1)).routes
42
+
43
+ def test_repeated_course_is_listed_per_workout_with_actual_metrics_and_trace(self):
44
+ self.add_run(1, "2026-11-01T10:00:00Z")
45
+ self.add_run(2, "2026-11-02T10:00:00Z", distance=0, completed=0)
46
+ self.add_run(3, "2026-11-03T10:00:00Z", user=2)
47
+ trace = [[37.5, 127.5], [37.51, 127.51]]
48
+ self.db.execute(text("INSERT INTO run_session_actual_routes VALUES (2, 37.5, 127.5, :line)"),
49
+ {"line": json.dumps(trace)})
50
+ rows = self.recent()
51
+ self.assertEqual([r.run_session_id for r in rows], [2, 1])
52
+ self.assertEqual(rows[0].polyline, trace)
53
+ self.assertEqual(rows[0].center_lat, 37.5)
54
+ self.assertEqual(rows[0].actual_distance_km, 0)
55
+ self.assertEqual(rows[0].duration_sec, 900)
56
+ self.assertEqual(rows[0].avg_pace_sec_per_km, 360)
57
+ self.assertEqual(rows[0].calories, 180)
58
+ self.assertEqual(rows[0].avg_bpm, 125)
59
+ self.assertEqual(rows[0].achievement_pct, 50)
60
+ self.assertFalse(rows[0].is_completed)
61
+ self.assertEqual(rows[0].completed_count, 2)
62
+
63
+ def test_free_run_without_geometry_is_visible_and_legacy_image_column_is_optional(self):
64
+ self.add_run(1, "2026-11-02T10:00:00Z", route=None)
65
+ self.add_run(2, "2026-11-01T10:00:00Z")
66
+ self.db.execute(text("ALTER TABLE routes DROP COLUMN map_image_url"))
67
+ row = self.recent(limit=1, image_column=False)[0]
68
+ self.assertIsNone(row.route_id)
69
+ self.assertEqual(row.route_title, "자유 러닝")
70
+ self.assertEqual(row.polyline, [])
71
+ self.assertEqual(row.map_image_url, "/icon.svg")
72
+
73
+
74
+ if __name__ == "__main__":
75
+ unittest.main()
main/app/_components/ActiveRunGuard.tsx CHANGED
@@ -16,9 +16,8 @@ import {
16
  import { hasUsableAccessToken } from "../_utils/sessionRestore";
17
 
18
  /**
19
- * Keeps an active run pinned to its run URL without ever replacing the visible UI
20
- * with a guard/loading page. Local state is checked synchronously; server
21
- * reconciliation happens in the background and only redirects when necessary.
22
  */
23
  export default function ActiveRunGuard({ children }: { children: ReactNode }) {
24
  const pathname = usePathname();
@@ -55,8 +54,9 @@ export default function ActiveRunGuard({ children }: { children: ReactNode }) {
55
  // Opening the bare app URL is an intentional request to enter the
56
  // app, not permission to jump straight into a previously active run.
57
  // Keep the checkpoint resumable, but let `/` continue to the lobby.
58
- if (pathname === "/") {
59
  sessionStorage.setItem(ACTIVE_RUN_REDIRECT_SUPPRESSION_KEY, runUrl);
 
60
  return false;
61
  }
62
  const shouldPromptAfterLogin =
 
16
  import { hasUsableAccessToken } from "../_utils/sessionRestore";
17
 
18
  /**
19
+ * Protects active run recovery while allowing the lobby to offer an explicit
20
+ * resume action. Server reconciliation runs in the background.
 
21
  */
22
  export default function ActiveRunGuard({ children }: { children: ReactNode }) {
23
  const pathname = usePathname();
 
54
  // Opening the bare app URL is an intentional request to enter the
55
  // app, not permission to jump straight into a previously active run.
56
  // Keep the checkpoint resumable, but let `/` continue to the lobby.
57
+ if (pathname === "/" || pathname === "/lobby") {
58
  sessionStorage.setItem(ACTIVE_RUN_REDIRECT_SUPPRESSION_KEY, runUrl);
59
+ if (pathname === "/lobby") sessionStorage.removeItem(ACTIVE_RUN_LOGIN_PROMPT_KEY);
60
  return false;
61
  }
62
  const shouldPromptAfterLogin =
main/app/_components/RecentRuns.tsx ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use client";
2
+
3
+ import { useEffect, useState } from "react";
4
+ import { useRouter } from "next/navigation";
5
+ import LeafletMap from "./LeafletMap";
6
+ import {
7
+ ACTIVE_RUN_EVENT, ACTIVE_RUN_REDIRECT_SUPPRESSION_KEY, readRun, runOwner,
8
+ type RunCheckpoint,
9
+ } from "../_utils/activeRun";
10
+ import { getStoredAccessToken, requestLogin, restoreSession, SESSION_CHANGED_EVENT } from "../_utils/sessionRestore";
11
+ import { formatRecentRunDuration, storeRecentRoutePreview, type RecentRoutePreview } from "../_utils/recentRoutePreview";
12
+
13
+ type Point = [number, number];
14
+ type RecentRun = {
15
+ run_session_id: number; route_id: number | null; route_title: string;
16
+ animal_label: string | null; actual_distance_km: number; route_length_km: number;
17
+ center_lat: number | null; center_lng: number | null; polyline: Point[];
18
+ completed_at: string | null; user_rating: number | null; duration_sec: number;
19
+ avg_pace_sec_per_km: number | null; calories: number | null; avg_bpm: number | null;
20
+ achievement_pct: number; is_completed: boolean; source: string; place_text: string | null;
21
+ };
22
+
23
+ function points(value: unknown): Point[] {
24
+ return Array.isArray(value) ? value.filter((point): point is Point =>
25
+ Array.isArray(point) && point.length === 2 &&
26
+ Number.isFinite(point[0]) && Math.abs(point[0]) <= 90 &&
27
+ Number.isFinite(point[1]) && Math.abs(point[1]) <= 180) : [];
28
+ }
29
+
30
+ function previewFor(run: RecentRun): RecentRoutePreview {
31
+ return {
32
+ runSessionId: run.run_session_id, routeId: run.route_id,
33
+ title: run.route_title || "러닝 기록", label: run.animal_label,
34
+ actualDistanceKm: run.actual_distance_km, routeDistanceKm: run.route_length_km,
35
+ center: Number.isFinite(run.center_lat) && Number.isFinite(run.center_lng)
36
+ ? [run.center_lat!, run.center_lng!] : null,
37
+ polyline: points(run.polyline), completedAt: run.completed_at, rating: run.user_rating,
38
+ durationSec: run.duration_sec, paceSecPerKm: run.avg_pace_sec_per_km,
39
+ calories: run.calories, bpm: run.avg_bpm, achievementPct: run.achievement_pct,
40
+ isCompleted: run.is_completed, source: run.source === "manual" ? "manual" : "nearby",
41
+ place: run.place_text ?? "",
42
+ };
43
+ }
44
+
45
+ function savedDate(value: string | null): string {
46
+ const date = value ? new Date(value) : null;
47
+ return date && Number.isFinite(date.getTime())
48
+ ? date.toLocaleDateString("ko-KR", { month: "2-digit", day: "2-digit" }) : "최근";
49
+ }
50
+
51
+ function RunMap({ route, center }: { route: Point[]; center?: Point | null }) {
52
+ return (
53
+ <div className="lobby-route-map pointer-events-none relative isolate h-[72px] overflow-hidden bg-[#EEF2F1]" aria-hidden="true">
54
+ {route.length > 1 ? (
55
+ <LeafletMap center={center ?? route[0]} route={route} interactive={false} className="h-full w-full" zoom={14} />
56
+ ) : (
57
+ <div className="flex h-full items-center justify-center text-xs font-medium text-[#63736A]">경로 기록 없음</div>
58
+ )}
59
+ </div>
60
+ );
61
+ }
62
+
63
+ export default function RecentRuns({ apiBase }: { apiBase: string }) {
64
+ const router = useRouter();
65
+ const [active, setActive] = useState<RunCheckpoint | null>(null);
66
+ const [history, setHistory] = useState<RecentRun[]>([]);
67
+ const [loading, setLoading] = useState(true);
68
+ const [resuming, setResuming] = useState(false);
69
+ const [error, setError] = useState<string | null>(null);
70
+ const [recoveryError, setRecoveryError] = useState<string | null>(null);
71
+ const [reload, setReload] = useState(0);
72
+
73
+ useEffect(() => {
74
+ let mounted = true;
75
+ let request = 0;
76
+ let visibleOwner = runOwner();
77
+ const readActive = () => {
78
+ try {
79
+ const stored = readRun();
80
+ setActive(stored && !stored.ended ? stored.checkpoint : null);
81
+ setRecoveryError(null);
82
+ } catch {
83
+ setActive(null);
84
+ setRecoveryError("진행 중인 러닝 정보를 읽지 못했습니다. 새로고침 후 다시 확인해 주세요.");
85
+ }
86
+ };
87
+ const load = async () => {
88
+ const id = ++request;
89
+ const owner = runOwner();
90
+ readActive();
91
+ if (owner !== visibleOwner) {
92
+ visibleOwner = owner;
93
+ setHistory([]);
94
+ }
95
+ const token = getStoredAccessToken();
96
+ if (!owner || !token) { setHistory([]); setLoading(false); return; }
97
+ setLoading(true);
98
+ try {
99
+ const response = await fetch(`${apiBase}/api/v1/auth/runs/recent-routes?limit=2`, {
100
+ headers: { Authorization: `Bearer ${token}` }, cache: "no-store",
101
+ });
102
+ if (!response.ok) throw new Error("history_unavailable");
103
+ const data = await response.json() as { routes?: RecentRun[] };
104
+ if (mounted && request === id && owner === runOwner()) {
105
+ setHistory(data.routes ?? []);
106
+ setError(null);
107
+ }
108
+ } catch {
109
+ if (mounted && request === id && owner === runOwner()) {
110
+ setError("최근 러닝 기록을 불러오지 못했습니다. 다시 시도해 주세요.");
111
+ }
112
+ } finally {
113
+ if (mounted && request === id) setLoading(false);
114
+ }
115
+ };
116
+ const refresh = () => { void load(); };
117
+ const onStorage = (event: StorageEvent) => {
118
+ if (!event.key || event.key === "access_token") refresh();
119
+ else readActive();
120
+ };
121
+ void load();
122
+ window.addEventListener(ACTIVE_RUN_EVENT, readActive);
123
+ window.addEventListener(SESSION_CHANGED_EVENT, refresh);
124
+ window.addEventListener("storage", onStorage);
125
+ window.addEventListener("focus", refresh);
126
+ window.addEventListener("online", refresh);
127
+ return () => {
128
+ mounted = false;
129
+ window.removeEventListener(ACTIVE_RUN_EVENT, readActive);
130
+ window.removeEventListener(SESSION_CHANGED_EVENT, refresh);
131
+ window.removeEventListener("storage", onStorage);
132
+ window.removeEventListener("focus", refresh);
133
+ window.removeEventListener("online", refresh);
134
+ };
135
+ }, [apiBase, reload]);
136
+
137
+ const authenticated = async (action: () => void) => {
138
+ try {
139
+ if (await restoreSession()) { action(); return; }
140
+ requestLogin();
141
+ } catch {
142
+ setError("로그인 상태나 연결을 확인한 뒤 다시 시도해 주세요.");
143
+ }
144
+ };
145
+
146
+ const resume = async () => {
147
+ if (!active || resuming) return;
148
+ setResuming(true);
149
+ setError(null);
150
+ const owner = runOwner();
151
+ await authenticated(() => {
152
+ const current = readRun();
153
+ if (owner !== runOwner() || !current || current.ended || current.checkpoint.sessionId !== active.sessionId) {
154
+ setError("이미 종료되었거나 변경된 러닝입니다. 최근 기록을 다시 확인해 주세요.");
155
+ setReload(value => value + 1);
156
+ return;
157
+ }
158
+ // Use the original URL/session. A new runKey would lose the checkpoint.
159
+ sessionStorage.removeItem(ACTIVE_RUN_REDIRECT_SUPPRESSION_KEY);
160
+ router.push(current.checkpoint.runUrl);
161
+ });
162
+ setResuming(false);
163
+ };
164
+
165
+ const openRecord = async (run: RecentRun) => {
166
+ setError(null);
167
+ const owner = runOwner();
168
+ await authenticated(() => {
169
+ if (owner !== runOwner()) { setReload(value => value + 1); return; }
170
+ try {
171
+ const key = storeRecentRoutePreview(previewFor(run));
172
+ if (!key) throw new Error("preview_unavailable");
173
+ router.push(`/route/recent-${run.run_session_id}?recentRouteKey=${encodeURIComponent(key)}`);
174
+ } catch {
175
+ setError("러닝 기록을 열지 못했습니다. 다시 시도해 주세요.");
176
+ }
177
+ });
178
+ };
179
+
180
+ const activeRoute = active ? points(active.actualRoute).length > 1
181
+ ? points(active.actualRoute) : points(active.routePayload.route) : [];
182
+ const activeTitle = active ? new URL(active.runUrl, "https://local.invalid").searchParams.get("routeTitle") ||
183
+ (active.routeId === "free-run" ? "자유 러닝" : "진행 중인 루트") : "";
184
+
185
+ return (
186
+ <section className="rounded-[18px] border border-white/75 bg-white/74 p-3 shadow-sm backdrop-blur-md lg:p-5" aria-labelledby="recent-runs-title">
187
+ <div className="flex items-center justify-between">
188
+ <h2 id="recent-runs-title" className="text-base font-bold text-[#111111]">최근 루트</h2>
189
+ <button type="button" onClick={() => void authenticated(() => router.push("/saved-routes"))}
190
+ className="rounded-full bg-[#fafafa] px-3 py-1.5 text-xs font-semibold text-[#525252]">저장 루트</button>
191
+ </div>
192
+
193
+ {active ? (
194
+ <button type="button" onClick={() => void resume()} disabled={resuming}
195
+ className="mt-3 w-full overflow-hidden rounded-2xl border border-[#22724D]/30 bg-[#F2F8F4] text-left shadow-sm disabled:opacity-60"
196
+ aria-label={`${activeTitle} 이어서 달리기`}>
197
+ <RunMap route={activeRoute} center={active.currentPosition} />
198
+ <div className="p-3">
199
+ <p className="text-xs font-bold text-[#22724D]">{active.mode === "simulation" ? "시뮬레이션 · " : ""}{active.isPaused ? "일시정지 중" : "진행 중인 러닝"}</p>
200
+ <p className="mt-1 truncate text-sm font-bold text-[#16211B]">{activeTitle}</p>
201
+ <p className="mt-1 text-xs font-semibold text-[#525252]">{active.distanceKm.toFixed(2)}km · {formatRecentRunDuration(active.elapsedSec)}</p>
202
+ <p className="mt-2 text-xs text-[#63736A]">저장된 지점부터 계속할 수 있어요.</p>
203
+ <p className="mt-2 text-sm font-bold text-[#22724D]">{resuming ? "러닝을 여는 중…" : "이어서 달리기 →"}</p>
204
+ </div>
205
+ </button>
206
+ ) : null}
207
+
208
+ <div className="mt-2 grid grid-cols-2 gap-2 lg:mt-3 lg:gap-3" aria-busy={loading}>
209
+ {loading && history.length === 0 ? [0, 1].map(index => (
210
+ <div key={index} className="h-36 animate-pulse rounded-2xl bg-[#EEF2F1]" aria-label="최근 기록을 불러오는 중" />
211
+ )) : history.map(run => (
212
+ <button type="button" key={run.run_session_id} onClick={() => void openRecord(run)}
213
+ className="min-w-0 isolate overflow-hidden rounded-2xl border border-black/10 bg-white/95 text-left shadow-sm"
214
+ aria-label={`${run.route_title} 러닝 기록 보기`}>
215
+ <RunMap route={points(run.polyline)} center={previewFor(run).center} />
216
+ <div className="p-2 sm:p-3">
217
+ <div className="flex items-center justify-between gap-1 text-[11px] text-[#63736A]">
218
+ <span className="font-bold text-[#22724D]">{run.is_completed ? "완주" : "종료"}</span>
219
+ <span>{savedDate(run.completed_at)}</span>
220
+ </div>
221
+ <p className="mt-1 truncate text-sm font-bold text-[#16211B]">{run.route_title || "러닝 기록"}</p>
222
+ <p className="mt-1 text-xs font-semibold text-[#525252]">{run.actual_distance_km.toFixed(2)}km · {formatRecentRunDuration(run.duration_sec)}</p>
223
+ <p className="mt-2 text-xs font-bold text-[#63736A]">기록 보기 →</p>
224
+ </div>
225
+ </button>
226
+ ))}
227
+ </div>
228
+ {!loading && history.length === 0 && !error ? <p className="py-5 text-center text-sm text-[#737373]">완료한 러닝 기록이 아직 없어요.</p> : null}
229
+ {recoveryError || error ? <div role="alert" className="mt-3 text-xs leading-5 text-[#b42323]">{recoveryError || error}
230
+ <button type="button" className="ml-2 font-bold underline" onClick={() => setReload(value => value + 1)}>다시 시도</button>
231
+ </div> : null}
232
+ </section>
233
+ );
234
+ }
main/app/_utils/activeRun.ts CHANGED
@@ -93,14 +93,19 @@ export async function reconcileRun(): Promise<StoredRun | null> {
93
  const owner = runOwner();
94
  if (!owner) return null;
95
  const before = readRun(owner);
96
- const result = await runRequest("");
97
  const local = readRun(owner);
98
  const remote = result.active as { checkpoint: RunCheckpoint; ended: boolean } | null;
99
  if (!remote) {
100
  // A start or checkpoint written while GET was in flight is newer evidence.
101
  if (local && (!before || local.checkpoint.sessionId !== before.checkpoint.sessionId
102
  || local.checkpoint.revision !== before.checkpoint.revision)) return local;
103
- if (local && !local.ended) storeRun(local.checkpoint, true, owner);
 
 
 
 
 
104
  return null;
105
  }
106
  if (!validCheckpoint(remote.checkpoint)) throw new Error("서버의 러닝 복구 정보를 확인하지 못했습니다.");
 
93
  const owner = runOwner();
94
  if (!owner) return null;
95
  const before = readRun(owner);
96
+ const result = await runRequest(before ? `?session_id=${encodeURIComponent(before.checkpoint.sessionId)}` : "");
97
  const local = readRun(owner);
98
  const remote = result.active as { checkpoint: RunCheckpoint; ended: boolean } | null;
99
  if (!remote) {
100
  // A start or checkpoint written while GET was in flight is newer evidence.
101
  if (local && (!before || local.checkpoint.sessionId !== before.checkpoint.sessionId
102
  || local.checkpoint.revision !== before.checkpoint.revision)) return local;
103
+ // A device can close before its first upload. Absence on the server is
104
+ // not a completion: only a matching terminal record can end local recovery.
105
+ if (local && !local.ended) {
106
+ if (result.ended_session_id !== local.checkpoint.sessionId) return local;
107
+ storeRun(local.checkpoint, true, owner);
108
+ }
109
  return null;
110
  }
111
  if (!validCheckpoint(remote.checkpoint)) throw new Error("서버의 러닝 복구 정보를 확인하지 못했습니다.");
main/app/_utils/recentRoutePreview.ts CHANGED
@@ -1,8 +1,11 @@
1
  "use client";
2
 
 
 
 
3
  export type RecentRoutePreview = {
4
  runSessionId: number;
5
- routeId: number;
6
  title: string;
7
  label: string | null;
8
  actualDistanceKm: number;
@@ -11,6 +14,14 @@ export type RecentRoutePreview = {
11
  polyline: [number, number][];
12
  completedAt: string | null;
13
  rating: number | null;
 
 
 
 
 
 
 
 
14
  };
15
 
16
  const PREFIX = "tranimal:recent-route-preview:";
@@ -20,10 +31,12 @@ function isPoint(value: unknown): value is [number, number] {
20
  }
21
 
22
  export function storeRecentRoutePreview(preview: RecentRoutePreview): string | null {
23
- if (typeof window === "undefined" || preview.polyline.length < 2) return null;
 
 
24
 
25
  const key = `${PREFIX}${preview.runSessionId}`;
26
- window.sessionStorage.setItem(key, JSON.stringify(preview));
27
  return key;
28
  }
29
 
@@ -31,10 +44,11 @@ export function readRecentRoutePreview(key: string | null): RecentRoutePreview |
31
  if (typeof window === "undefined" || !key?.startsWith(PREFIX)) return null;
32
 
33
  try {
34
- const parsed = JSON.parse(window.sessionStorage.getItem(key) ?? "") as Partial<RecentRoutePreview>;
35
  if (
 
36
  !Number.isFinite(parsed.runSessionId) ||
37
- !Number.isFinite(parsed.routeId) ||
38
  typeof parsed.title !== "string" ||
39
  !Array.isArray(parsed.polyline) ||
40
  !parsed.polyline.every(isPoint)
@@ -53,8 +67,60 @@ export function readRecentRoutePreview(key: string | null): RecentRoutePreview |
53
  polyline: parsed.polyline,
54
  completedAt: typeof parsed.completedAt === "string" ? parsed.completedAt : null,
55
  rating: Number.isFinite(parsed.rating) ? parsed.rating : null,
 
 
 
 
 
 
 
 
56
  };
57
  } catch {
58
  return null;
59
  }
60
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  "use client";
2
 
3
+ import { runOwner } from "./activeRun";
4
+ import { DEFAULT_MAP_CENTER, type CommunityPost } from "./communityPosts";
5
+
6
  export type RecentRoutePreview = {
7
  runSessionId: number;
8
+ routeId: number | null;
9
  title: string;
10
  label: string | null;
11
  actualDistanceKm: number;
 
14
  polyline: [number, number][];
15
  completedAt: string | null;
16
  rating: number | null;
17
+ durationSec?: number | null;
18
+ paceSecPerKm?: number | null;
19
+ calories?: number | null;
20
+ bpm?: number | null;
21
+ achievementPct?: number;
22
+ isCompleted?: boolean;
23
+ source?: "nearby" | "manual";
24
+ place?: string;
25
  };
26
 
27
  const PREFIX = "tranimal:recent-route-preview:";
 
31
  }
32
 
33
  export function storeRecentRoutePreview(preview: RecentRoutePreview): string | null {
34
+ if (typeof window === "undefined") return null;
35
+ const owner = runOwner();
36
+ if (!owner) return null;
37
 
38
  const key = `${PREFIX}${preview.runSessionId}`;
39
+ window.sessionStorage.setItem(key, JSON.stringify({ ...preview, owner }));
40
  return key;
41
  }
42
 
 
44
  if (typeof window === "undefined" || !key?.startsWith(PREFIX)) return null;
45
 
46
  try {
47
+ const parsed = JSON.parse(window.sessionStorage.getItem(key) ?? "") as Partial<RecentRoutePreview> & { owner?: string };
48
  if (
49
+ !runOwner() || parsed.owner !== runOwner() ||
50
  !Number.isFinite(parsed.runSessionId) ||
51
+ (parsed.routeId !== null && !Number.isFinite(parsed.routeId)) ||
52
  typeof parsed.title !== "string" ||
53
  !Array.isArray(parsed.polyline) ||
54
  !parsed.polyline.every(isPoint)
 
67
  polyline: parsed.polyline,
68
  completedAt: typeof parsed.completedAt === "string" ? parsed.completedAt : null,
69
  rating: Number.isFinite(parsed.rating) ? parsed.rating : null,
70
+ durationSec: metric(parsed.durationSec),
71
+ paceSecPerKm: metric(parsed.paceSecPerKm),
72
+ calories: metric(parsed.calories),
73
+ bpm: metric(parsed.bpm),
74
+ achievementPct: metric(parsed.achievementPct) ?? 0,
75
+ isCompleted: parsed.isCompleted ?? Boolean(parsed.completedAt),
76
+ source: parsed.source === "manual" ? "manual" : "nearby",
77
+ place: typeof parsed.place === "string" ? parsed.place : "",
78
  };
79
  } catch {
80
  return null;
81
  }
82
  }
83
+
84
+ function metric(value: unknown): number | null {
85
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;
86
+ }
87
+
88
+ export function formatRecentRunDuration(value: number | null | undefined): string {
89
+ const seconds = metric(value);
90
+ if (seconds === null) return "-";
91
+ const total = Math.floor(seconds);
92
+ const minutes = Math.floor(total / 60);
93
+ return minutes >= 60
94
+ ? `${Math.floor(minutes / 60)}:${String(minutes % 60).padStart(2, "0")}:${String(total % 60).padStart(2, "0")}`
95
+ : `${String(minutes).padStart(2, "0")}:${String(total % 60).padStart(2, "0")}`;
96
+ }
97
+
98
+ export function recentRouteToCommunityPost(preview: RecentRoutePreview): CommunityPost {
99
+ const duration = metric(preview.durationSec);
100
+ const pace = metric(preview.paceSecPerKm) ||
101
+ (duration && preview.actualDistanceKm > 0 ? duration / preview.actualDistanceKm : null);
102
+ const paceSeconds = pace ? Math.round(pace) : null;
103
+ return {
104
+ id: `recent-${preview.runSessionId}`,
105
+ routeId: preview.routeId === null ? "" : String(preview.routeId),
106
+ title: preview.title || "러닝 기록",
107
+ content: preview.isCompleted ? "완주한 러닝 기록입니다." : "종료한 러닝 기록입니다.",
108
+ nickname: "나",
109
+ createdAt: preview.completedAt ?? new Date().toISOString(),
110
+ stats: {
111
+ distance: Math.max(0, preview.actualDistanceKm).toFixed(2),
112
+ achievement: String(preview.achievementPct ?? 0),
113
+ time: formatRecentRunDuration(duration),
114
+ pace: paceSeconds === null ? "--'--''" : `${Math.floor(paceSeconds / 60)}'${String(paceSeconds % 60).padStart(2, "0")}''`,
115
+ calories: metric(preview.calories) === null ? "-" : `${Math.round(preview.calories!)} kcal`,
116
+ bpm: preview.bpm ? String(Math.round(preview.bpm)) : "-",
117
+ },
118
+ map: {
119
+ center: preview.center ?? preview.polyline[0] ?? DEFAULT_MAP_CENTER,
120
+ polyline: preview.polyline,
121
+ mode: preview.source === "manual" ? "manual" : "nearby",
122
+ address: preview.place || "내 러닝 기록",
123
+ },
124
+ likeCount: 0, likedByMe: false, viewCount: 0, comments: [],
125
+ };
126
+ }
main/app/lobby/page.tsx CHANGED
@@ -2,45 +2,17 @@
2
 
3
  import { useEffect, useState } from "react";
4
  import { useRouter } from "next/navigation";
5
- import LeafletMap from "../_components/LeafletMap";
6
  import MotionDialog from "../_components/MotionDialog";
7
  import { FLOW_KEYS, issueUiFlowPermit } from "../_utils/uiFlowGuard";
8
  import { requestNativeAppExit } from "../_utils/nativeWearBridge";
9
- import { prepareCoursePreview } from "../_utils/coursePreview";
10
  import { getAppPosition } from "../_utils/nativeLocation";
11
  import { readLocationConsent, storeLocationConsent } from "../_utils/locationConsent";
12
- import { storeRecentRoutePreview } from "../_utils/recentRoutePreview";
13
  import { clearStoredSession, requestLogin, restoreSession } from "../_utils/sessionRestore";
14
 
15
- // The lobby is a glanceable home screen. Show the latest pair side by side;
16
- // the complete route history remains available from the "전체" action.
17
- const RECENT_ROUTE_LIMIT = 2;
18
- const DEFAULT_CENTER: [number, number] = [37.5665, 126.978];
19
-
20
- type Point = [number, number];
21
  type WeatherCondition = "sunny" | "rainy" | "cloudy" | "snowy";
22
  type WeatherLoadStatus = "loading" | "ready" | "fallback";
23
 
24
- type RecentRoute = {
25
- run_session_id: number;
26
- route_id: number;
27
- route_title: string;
28
- animal_label: string | null;
29
- actual_distance_km: number;
30
- route_length_km: number;
31
- map_image_url: string;
32
- center_lat: number | null;
33
- center_lng: number | null;
34
- polyline: Point[];
35
- completed_at: string | null;
36
- completed_count: number;
37
- user_rating: number | null;
38
- };
39
-
40
- type RecentRoutesResponse = {
41
- routes: RecentRoute[];
42
- };
43
-
44
  type IconProps = {
45
  className?: string;
46
  };
@@ -320,78 +292,6 @@ function getCookieValue(name: string): string | null {
320
  );
321
  }
322
 
323
- function resolveMapImage(path: string): string {
324
- if (!path) {
325
- return "/icon.svg";
326
- }
327
-
328
- if (
329
- path.startsWith("/") ||
330
- path.startsWith("http://") ||
331
- path.startsWith("https://")
332
- ) {
333
- return path;
334
- }
335
-
336
- return `/${path}`;
337
- }
338
-
339
- function sanitizePoint(value: unknown): Point | null {
340
- if (!Array.isArray(value) || value.length !== 2) {
341
- return null;
342
- }
343
-
344
- const lat = Number(value[0]);
345
- const lng = Number(value[1]);
346
-
347
- if (!Number.isFinite(lat) || !Number.isFinite(lng)) {
348
- return null;
349
- }
350
-
351
- return [lat, lng];
352
- }
353
-
354
- function sanitizePolyline(value: unknown): Point[] {
355
- if (!Array.isArray(value)) {
356
- return [];
357
- }
358
-
359
- const points: Point[] = [];
360
-
361
- for (const point of value) {
362
- const parsed = sanitizePoint(point);
363
- if (parsed) {
364
- points.push(parsed);
365
- }
366
- }
367
-
368
- return points;
369
- }
370
-
371
- function formatCompletedAt(value: string | null): string {
372
- if (!value) {
373
- return "최근";
374
- }
375
-
376
- const parsed = new Date(value);
377
- if (!Number.isFinite(parsed.getTime())) {
378
- return "최근";
379
- }
380
-
381
- return parsed.toLocaleDateString("ko-KR", {
382
- month: "2-digit",
383
- day: "2-digit",
384
- });
385
- }
386
-
387
- function formatLabel(raw: string | null): string {
388
- if (!raw) {
389
- return "루트";
390
- }
391
-
392
- return raw.replace(/_/g, " ");
393
- }
394
-
395
  function ArrowRightIcon({ className = "" }: IconProps) {
396
  return (
397
  <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2.3" aria-hidden="true">
@@ -489,8 +389,6 @@ function WeatherIcon({
489
  export default function Page() {
490
  const router = useRouter();
491
  const [displayName, setDisplayName] = useState("러너");
492
- const [recentRoutes, setRecentRoutes] = useState<RecentRoute[]>([]);
493
- const [isRecentLoading, setIsRecentLoading] = useState(true);
494
  const [isExitDialogOpen, setIsExitDialogOpen] = useState(false);
495
  const [weatherState, setWeatherState] = useState<WeatherState>(INITIAL_WEATHER);
496
  const [weatherReloadKey, setWeatherReloadKey] = useState(0);
@@ -616,85 +514,16 @@ export default function Page() {
616
  }, [weatherReloadKey]);
617
 
618
  useEffect(() => {
619
- const token =
620
- localStorage.getItem("access_token") ?? getCookieValue("access_token");
621
-
622
- if (!token) {
623
- setIsRecentLoading(false);
624
- return;
625
- }
626
-
627
- let isMounted = true;
628
- const headers = { Authorization: `Bearer ${token}` };
629
-
630
- const load = async () => {
631
- try {
632
- const [meResponse, recentResponse] = await Promise.all([
633
- fetch(`${apiBase}/api/v1/auth/me`, { headers }),
634
- fetch(`${apiBase}/api/v1/auth/runs/recent-routes?limit=${RECENT_ROUTE_LIMIT}`, {
635
- headers,
636
- cache: "no-store",
637
- }),
638
- ]);
639
-
640
- if (!isMounted) {
641
- return;
642
- }
643
-
644
- if (meResponse.ok) {
645
- const meData = (await meResponse.json()) as {
646
- first_name?: string;
647
- email?: string;
648
- };
649
- const name =
650
- meData?.first_name?.trim() ||
651
- meData?.email?.split("@")[0] ||
652
- "러너";
653
- setDisplayName(name);
654
- }
655
-
656
- if (recentResponse.ok) {
657
- const recentData = (await recentResponse.json()) as RecentRoutesResponse;
658
- const normalized = (recentData.routes ?? []).map((route) => ({
659
- ...route,
660
- polyline: sanitizePolyline(route.polyline),
661
- actual_distance_km:
662
- typeof route.actual_distance_km === "number" &&
663
- Number.isFinite(route.actual_distance_km)
664
- ? route.actual_distance_km
665
- : 0,
666
- route_length_km:
667
- typeof route.route_length_km === "number" &&
668
- Number.isFinite(route.route_length_km)
669
- ? route.route_length_km
670
- : 0,
671
- user_rating:
672
- typeof route.user_rating === "number"
673
- ? Math.max(0, Math.min(5, Math.round(route.user_rating)))
674
- : null,
675
- }));
676
- setRecentRoutes(normalized);
677
- } else {
678
- setRecentRoutes([]);
679
- }
680
- } catch {
681
- if (!isMounted) {
682
- return;
683
- }
684
- setDisplayName("러너");
685
- setRecentRoutes([]);
686
- } finally {
687
- if (isMounted) {
688
- setIsRecentLoading(false);
689
- }
690
- }
691
- };
692
-
693
- void load();
694
-
695
- return () => {
696
- isMounted = false;
697
- };
698
  }, [apiBase]);
699
 
700
  useEffect(() => {
@@ -757,51 +586,6 @@ export default function Page() {
757
  void requireLogin(startFreeRun);
758
  };
759
 
760
- const startRecentRoute = (route: RecentRoute) => {
761
- if (typeof window === "undefined" || route.polyline.length < 2) {
762
- return;
763
- }
764
-
765
- const isCompletedRoute = route.completed_at !== null || route.completed_count > 0;
766
- if (isCompletedRoute) {
767
- const previewKey = storeRecentRoutePreview({
768
- runSessionId: route.run_session_id,
769
- routeId: route.route_id,
770
- title: route.route_title || "러닝 루트",
771
- label: route.animal_label,
772
- actualDistanceKm: route.actual_distance_km,
773
- routeDistanceKm: route.route_length_km,
774
- center: Number.isFinite(route.center_lat) && Number.isFinite(route.center_lng)
775
- ? [route.center_lat as number, route.center_lng as number]
776
- : null,
777
- polyline: route.polyline,
778
- completedAt: route.completed_at,
779
- rating: route.user_rating,
780
- });
781
- if (previewKey) {
782
- router.push(`/route/recent-${route.run_session_id}?recentRouteKey=${encodeURIComponent(previewKey)}`);
783
- }
784
- return;
785
- }
786
-
787
- router.push(prepareCoursePreview({
788
- id: `recent-${route.route_id}`,
789
- title: route.route_title || "러닝 루트",
790
- place: route.route_title || "러닝 루트",
791
- distanceKm: route.route_length_km,
792
- center: Number.isFinite(route.center_lat) && Number.isFinite(route.center_lng)
793
- ? [route.center_lat as number, route.center_lng as number]
794
- : route.polyline[0],
795
- route: route.polyline,
796
- label: route.animal_label ?? undefined,
797
- source: "최근 러닝 코스",
798
- }));
799
- };
800
-
801
- const handleStartRecentRoute = (route: RecentRoute) => {
802
- void requireLogin(() => startRecentRoute(route));
803
- };
804
-
805
  const handleConfirmAppExit = () => {
806
  setExitRequestError(null);
807
  if (requestNativeAppExit()) {
@@ -907,100 +691,7 @@ export default function Page() {
907
  </div>
908
  </section>
909
 
910
- <section className="rounded-[18px] border border-white/75 bg-white/74 p-3 shadow-sm backdrop-blur-md lg:p-5">
911
- <div className="flex items-center justify-between">
912
- <h2 className="text-base font-bold text-[#111111]">최근 루트</h2>
913
- <button
914
- type="button"
915
- onClick={() => void requireLogin(() => router.push("/saved-routes"))}
916
- className="flex items-center gap-1 rounded-full bg-[#fafafa] px-3 py-1.5 text-xs font-semibold text-[#525252] transition hover:bg-[#f5f5f5] active:scale-[0.98]"
917
- >
918
- 전체
919
- </button>
920
- </div>
921
-
922
- <div className="mt-2 grid grid-cols-2 gap-2 lg:mt-3 lg:gap-3">
923
- {isRecentLoading &&
924
- Array.from({ length: RECENT_ROUTE_LIMIT }).map((_, index) => (
925
- <article
926
- key={`recent-loading-${index}`}
927
- className="isolate overflow-hidden rounded-2xl border border-black/10 bg-white/95 shadow-sm [clip-path:inset(0_round_16px)]"
928
- >
929
- <div className="h-14 w-full rounded-t-2xl animate-pulse bg-[#EEF2F1] sm:h-[72px]" />
930
- <div className="space-y-2 rounded-b-2xl bg-white/95 p-2 sm:p-3">
931
- <div className="h-3 w-20 animate-pulse rounded bg-[#EEF2F1]" />
932
- <div className="h-3 w-28 animate-pulse rounded bg-[#EEF2F1]" />
933
- </div>
934
- </article>
935
- ))}
936
-
937
- {!isRecentLoading &&
938
- recentRoutes.map((route) => {
939
- const isCompletedRoute = route.completed_at !== null || route.completed_count > 0;
940
- const hasCenter =
941
- Number.isFinite(route.center_lat) &&
942
- Number.isFinite(route.center_lng);
943
- const hasPolyline = route.polyline.length > 1;
944
- const mapCenter: Point = hasCenter
945
- ? [route.center_lat as number, route.center_lng as number]
946
- : hasPolyline
947
- ? route.polyline[0]
948
- : DEFAULT_CENTER;
949
-
950
- return (
951
- <button
952
- type="button"
953
- key={`recent-route-${route.run_session_id}`}
954
- onClick={() => handleStartRecentRoute(route)}
955
- className="isolate overflow-hidden rounded-2xl border border-black/10 bg-white/95 text-left shadow-sm transition hover:shadow-md focus:outline-none focus:ring-2 focus:ring-black/20 active:scale-[0.99] [clip-path:inset(0_round_16px)]"
956
- aria-label={isCompletedRoute ? `${route.route_title} 완료한 루트 보기` : `${route.route_title} 다시 달리기`}
957
- >
958
- <div className="relative h-14 w-full overflow-hidden rounded-t-2xl bg-[#f5f5f5] max-[700px]:h-12 sm:h-[72px]">
959
- {hasPolyline ? (
960
- <LeafletMap
961
- center={mapCenter}
962
- route={route.polyline}
963
- className="lobby-route-map pointer-events-none h-full w-full"
964
- zoom={14}
965
- />
966
- ) : (
967
- <img
968
- src={resolveMapImage(route.map_image_url)}
969
- alt={route.route_title}
970
- className="h-full w-full object-cover"
971
- onError={(event) => {
972
- const target = event.currentTarget;
973
- target.onerror = null;
974
- target.src = "/icon.svg";
975
- }}
976
- />
977
- )}
978
-
979
- <div className="absolute inset-0 z-[500] bg-gradient-to-t from-black/55 via-transparent to-transparent" />
980
- <div className="absolute bottom-2 left-2 right-2 z-[500] truncate text-xs font-bold text-white">
981
- {route.route_title}
982
- </div>
983
- </div>
984
-
985
- <div className="flex min-h-[34px] items-center justify-between gap-1.5 rounded-b-2xl border-t border-black/5 bg-white/95 px-2 py-1.5 max-[700px]:min-h-[30px] max-[700px]:py-1 sm:px-3">
986
- <span className="min-w-0 truncate text-xs font-bold text-[#111111] sm:text-sm">
987
- {formatLabel(route.animal_label)}
988
- </span>
989
- <span className="shrink-0 text-xs font-bold text-[#737373]">
990
- {formatCompletedAt(route.completed_at)}
991
- </span>
992
- </div>
993
- </button>
994
- );
995
- })}
996
-
997
- {!isRecentLoading && recentRoutes.length === 0 && (
998
- <div className="rounded-xl border border-dashed border-black/15 bg-[#FAFCFB] px-4 py-8 text-center text-sm font-bold text-[#737373]">
999
- 기록 없음
1000
- </div>
1001
- )}
1002
- </div>
1003
- </section>
1004
  </div>
1005
  </section>
1006
 
 
2
 
3
  import { useEffect, useState } from "react";
4
  import { useRouter } from "next/navigation";
5
+ import RecentRuns from "../_components/RecentRuns";
6
  import MotionDialog from "../_components/MotionDialog";
7
  import { FLOW_KEYS, issueUiFlowPermit } from "../_utils/uiFlowGuard";
8
  import { requestNativeAppExit } from "../_utils/nativeWearBridge";
 
9
  import { getAppPosition } from "../_utils/nativeLocation";
10
  import { readLocationConsent, storeLocationConsent } from "../_utils/locationConsent";
 
11
  import { clearStoredSession, requestLogin, restoreSession } from "../_utils/sessionRestore";
12
 
 
 
 
 
 
 
13
  type WeatherCondition = "sunny" | "rainy" | "cloudy" | "snowy";
14
  type WeatherLoadStatus = "loading" | "ready" | "fallback";
15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  type IconProps = {
17
  className?: string;
18
  };
 
292
  );
293
  }
294
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
295
  function ArrowRightIcon({ className = "" }: IconProps) {
296
  return (
297
  <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2.3" aria-hidden="true">
 
389
  export default function Page() {
390
  const router = useRouter();
391
  const [displayName, setDisplayName] = useState("러너");
 
 
392
  const [isExitDialogOpen, setIsExitDialogOpen] = useState(false);
393
  const [weatherState, setWeatherState] = useState<WeatherState>(INITIAL_WEATHER);
394
  const [weatherReloadKey, setWeatherReloadKey] = useState(0);
 
514
  }, [weatherReloadKey]);
515
 
516
  useEffect(() => {
517
+ const token = localStorage.getItem("access_token") ?? getCookieValue("access_token");
518
+ if (!token) return;
519
+ let mounted = true;
520
+ void fetch(`${apiBase}/api/v1/auth/me`, { headers: { Authorization: `Bearer ${token}` } })
521
+ .then(async response => {
522
+ if (!response.ok) return;
523
+ const me = await response.json() as { first_name?: string; email?: string };
524
+ if (mounted) setDisplayName(me.first_name?.trim() || me.email?.split("@")[0] || "러너");
525
+ }).catch(() => {});
526
+ return () => { mounted = false; };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
527
  }, [apiBase]);
528
 
529
  useEffect(() => {
 
586
  void requireLogin(startFreeRun);
587
  };
588
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
589
  const handleConfirmAppExit = () => {
590
  setExitRequestError(null);
591
  if (requestNativeAppExit()) {
 
691
  </div>
692
  </section>
693
 
694
+ <RecentRuns apiBase={apiBase} />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
695
  </div>
696
  </section>
697
 
main/app/route/[id]/page.tsx CHANGED
@@ -19,7 +19,7 @@ import {
19
  } from "../../_utils/communityApi";
20
  import { loadSharedRoutePost, invalidateCommunityRouteData } from "../../_utils/communityRouteData";
21
  import CommunityRouteLoading from "../../_components/CommunityRouteLoading";
22
- import { readRecentRoutePreview } from "../../_utils/recentRoutePreview";
23
  import { prepareCoursePreview } from "../../_utils/coursePreview";
24
 
25
  const LeafletMap = dynamic(() => import("../../_components/LeafletMap"), {
@@ -51,36 +51,7 @@ export default function Page() {
51
 
52
  const recentRoute = readRecentRoutePreview(recentRouteKey);
53
  if (recentRoute) {
54
- const completedAt = recentRoute.completedAt ?? new Date().toISOString();
55
- const distance = recentRoute.actualDistanceKm > 0
56
- ? recentRoute.actualDistanceKm
57
- : recentRoute.routeDistanceKm;
58
- setPosts([{
59
- id: `recent-${recentRoute.runSessionId}`,
60
- routeId: String(recentRoute.routeId),
61
- title: recentRoute.title || "완료한 러닝 루트",
62
- content: "완료한 러닝 기록입니다.",
63
- nickname: "나",
64
- createdAt: completedAt,
65
- stats: {
66
- distance: `${Math.max(0, distance).toFixed(2)}`,
67
- achievement: "100",
68
- pace: "--'--''",
69
- calories: "-",
70
- time: "-",
71
- bpm: "-",
72
- },
73
- map: {
74
- center: recentRoute.center ?? recentRoute.polyline[0] ?? DEFAULT_MAP_CENTER,
75
- polyline: recentRoute.polyline,
76
- mode: "nearby",
77
- address: "완료한 러닝 기록",
78
- },
79
- likeCount: 0,
80
- likedByMe: false,
81
- viewCount: 0,
82
- comments: [],
83
- }]);
84
  setIsCompletedHistory(true);
85
  setLoadError(null);
86
  setLoadedRouteId(routeId);
@@ -303,7 +274,7 @@ export default function Page() {
303
 
304
  const placeLabel =
305
  isCompletedHistory
306
- ? "완료한 러닝 기록"
307
  : route.map?.mode === "manual"
308
  ? route.map.address || "설정한 지역"
309
  : "내 주변 러닝 코스";
@@ -343,7 +314,7 @@ export default function Page() {
343
  <p className="mt-3 text-sm font-medium text-[#63736A]">{placeLabel}</p>
344
  <p className="mt-4 text-sm text-[#666]">
345
  {isCompletedHistory
346
- ? `완료일: ${formatRelativeKoreanTime(route.createdAt)}`
347
  : `작성자: ${route.nickname} · 작성일: ${formatRelativeKoreanTime(route.createdAt)}`}
348
  </p>
349
  </div>
@@ -401,12 +372,14 @@ export default function Page() {
401
 
402
  <section className="rts-card rts-card-flush">
403
  <div className="h-[320px] w-full bg-[#f5f5f5]">
404
- <LeafletMap
 
 
405
  center={route.map?.center ?? DEFAULT_MAP_CENTER}
406
  route={route.map?.polyline}
407
  className="h-full w-full"
408
  zoom={14}
409
- />
410
  </div>
411
  </section>
412
 
@@ -420,10 +393,8 @@ export default function Page() {
420
  ["페이스", route.stats.pace],
421
  ["칼로리", route.stats.calories],
422
  ["BPM", route.stats.bpm],
423
- ["난이도", difficulty],
424
  ["완주율", achievementText],
425
- ["좋아요", String(likes)],
426
- ["조회수", String(views)],
427
  ].map(([label, value]) => (
428
  <div key={label} className="min-w-0 py-1">
429
  <p className="text-xs font-semibold text-[#737373]">{label}</p>
 
19
  } from "../../_utils/communityApi";
20
  import { loadSharedRoutePost, invalidateCommunityRouteData } from "../../_utils/communityRouteData";
21
  import CommunityRouteLoading from "../../_components/CommunityRouteLoading";
22
+ import { readRecentRoutePreview, recentRouteToCommunityPost } from "../../_utils/recentRoutePreview";
23
  import { prepareCoursePreview } from "../../_utils/coursePreview";
24
 
25
  const LeafletMap = dynamic(() => import("../../_components/LeafletMap"), {
 
51
 
52
  const recentRoute = readRecentRoutePreview(recentRouteKey);
53
  if (recentRoute) {
54
+ setPosts([recentRouteToCommunityPost(recentRoute)]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  setIsCompletedHistory(true);
56
  setLoadError(null);
57
  setLoadedRouteId(routeId);
 
274
 
275
  const placeLabel =
276
  isCompletedHistory
277
+ ? route.map?.address || "내 러닝 기록"
278
  : route.map?.mode === "manual"
279
  ? route.map.address || "설정한 지역"
280
  : "내 주변 러닝 코스";
 
314
  <p className="mt-3 text-sm font-medium text-[#63736A]">{placeLabel}</p>
315
  <p className="mt-4 text-sm text-[#666]">
316
  {isCompletedHistory
317
+ ? `러닝일: ${formatRelativeKoreanTime(route.createdAt)}`
318
  : `작성자: ${route.nickname} · 작성일: ${formatRelativeKoreanTime(route.createdAt)}`}
319
  </p>
320
  </div>
 
372
 
373
  <section className="rts-card rts-card-flush">
374
  <div className="h-[320px] w-full bg-[#f5f5f5]">
375
+ {isCompletedHistory && !route.map?.polyline?.length ? (
376
+ <div className="flex h-full items-center justify-center text-sm text-[#737373]">저장된 경로가 없습니다.</div>
377
+ ) : <LeafletMap
378
  center={route.map?.center ?? DEFAULT_MAP_CENTER}
379
  route={route.map?.polyline}
380
  className="h-full w-full"
381
  zoom={14}
382
+ />}
383
  </div>
384
  </section>
385
 
 
393
  ["페이스", route.stats.pace],
394
  ["칼로리", route.stats.calories],
395
  ["BPM", route.stats.bpm],
 
396
  ["완주율", achievementText],
397
+ ...(!isCompletedHistory ? [["난이도", difficulty], ["좋아요", String(likes)], ["조회수", String(views)]] : []),
 
398
  ].map(([label, value]) => (
399
  <div key={label} className="min-w-0 py-1">
400
  <p className="text-xs font-semibold text-[#737373]">{label}</p>
main/app/run/[id]/page.tsx CHANGED
@@ -2123,7 +2123,7 @@ function RunPageContent({ params }: { params: { id: string } }) {
2123
  aria-haspopup="dialog"
2124
  aria-controls="run-music-player"
2125
  >
2126
- <span aria-hidden="true" className="font-sans text-2xl font-bold leading-none">♫</span>
2127
  <span className="text-[11px] font-bold">음악</span>
2128
  </button>
2129
  </div>
@@ -2183,6 +2183,7 @@ function RunPageContent({ params }: { params: { id: string } }) {
2183
  keepMounted
2184
  slide
2185
  swipeToDismiss
 
2186
  onDismiss={() => setIsMusicPanelOpen(false)}
2187
  ariaLabelledBy="run-music-title"
2188
  panelClassName="relative max-h-[calc(100dvh-2rem)] w-[calc(100%-2rem)] max-w-md overflow-y-auto rounded-[28px] bg-white p-5 shadow-2xl"
 
2123
  aria-haspopup="dialog"
2124
  aria-controls="run-music-player"
2125
  >
2126
+ <span aria-hidden="true" className="translate-y-[2px] font-sans text-2xl font-bold leading-none">♫</span>
2127
  <span className="text-[11px] font-bold">음악</span>
2128
  </button>
2129
  </div>
 
2183
  keepMounted
2184
  slide
2185
  swipeToDismiss
2186
+ dismissOnBackdrop
2187
  onDismiss={() => setIsMusicPanelOpen(false)}
2188
  ariaLabelledBy="run-music-title"
2189
  panelClassName="relative max-h-[calc(100dvh-2rem)] w-[calc(100%-2rem)] max-w-md overflow-y-auto rounded-[28px] bg-white p-5 shadow-2xl"
main/tests/activeRun.cjs CHANGED
@@ -54,6 +54,10 @@ function setup(handler) {
54
  assert.equal((await s.api.reconcileRun()).checkpoint.elapsedSec,45);
55
  s = setup(async () => ({active:null}));
56
  s.api.storeRun(cp());
 
 
 
 
57
  assert.equal(await s.api.reconcileRun(),null);
58
  assert.equal(s.api.readRun().ended,true);
59
 
 
54
  assert.equal((await s.api.reconcileRun()).checkpoint.elapsedSec,45);
55
  s = setup(async () => ({active:null}));
56
  s.api.storeRun(cp());
57
+ assert.equal((await s.api.reconcileRun()).checkpoint.sessionId,'one');
58
+ assert.equal(s.api.readRun().ended,false,'server absence cannot erase an unuploaded checkpoint');
59
+ s = setup(async () => ({active:null,ended_session_id:'one'}));
60
+ s.api.storeRun(cp());
61
  assert.equal(await s.api.reconcileRun(),null);
62
  assert.equal(s.api.readRun().ended,true);
63
 
main/tests/uiContinuity.cjs CHANGED
@@ -13,7 +13,7 @@ assert.match(activeRunGuard, /MotionDialog[\s\S]*?진행 중이던 러닝이 있
13
 
14
  const sessionGuard = read('app/_components/SessionGuard.tsx');
15
  assert.doesNotMatch(sessionGuard, /이전 계정으로 로그인하고 있습니다/);
16
- assert.match(sessionGuard, /return <>{children}<\/>;/, 'session restore must run behind the visible app shell');
17
 
18
  const layout = read('app/layout.tsx');
19
  assert.doesNotMatch(layout, /러닝 세션 확인 중/);
@@ -60,8 +60,10 @@ assert.match(login, /ACTIVE_RUN_LOGIN_PROMPT_KEY/,
60
  'a successful login must request an interrupted-run prompt');
61
 
62
  const lobby = read('app/lobby/page.tsx');
 
63
  const routeDetail = read('app/route/[id]/page.tsx');
64
- assert.match(lobby, /storeRecentRoutePreview/,
 
65
  'completed recent routes must open a detail preview instead of being disabled');
66
  assert.doesNotMatch(lobby, /disabled=\{isCompletedRoute\}/,
67
  'completed recent route cards must remain tappable');
 
13
 
14
  const sessionGuard = read('app/_components/SessionGuard.tsx');
15
  assert.doesNotMatch(sessionGuard, /이전 계정으로 로그인하고 있습니다/);
16
+ assert.match(sessionGuard, /return \([\s\S]*?\{children\}/, 'session restore must run behind the visible app shell');
17
 
18
  const layout = read('app/layout.tsx');
19
  assert.doesNotMatch(layout, /러닝 세션 확인 중/);
 
60
  'a successful login must request an interrupted-run prompt');
61
 
62
  const lobby = read('app/lobby/page.tsx');
63
+ const recentRuns = read('app/_components/RecentRuns.tsx');
64
  const routeDetail = read('app/route/[id]/page.tsx');
65
+ assert.match(lobby, /<RecentRuns /);
66
+ assert.match(recentRuns, /storeRecentRoutePreview/,
67
  'completed recent routes must open a detail preview instead of being disabled');
68
  assert.doesNotMatch(lobby, /disabled=\{isCompletedRoute\}/,
69
  'completed recent route cards must remain tappable');
tools/test-recent-runs.cjs ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Exercise actual recovery, history-card actions and private-detail mapping.
2
+ const assert = require('node:assert/strict');
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+ const vm = require('node:vm');
6
+ const ts = require('../main/node_modules/typescript');
7
+ const root = path.resolve(__dirname, '../main/app');
8
+ const flush = async () => { for (let i = 0; i < 30; i++) await Promise.resolve(); };
9
+ const plain = value => JSON.parse(JSON.stringify(value));
10
+
11
+ function fixture() {
12
+ const storage = () => {
13
+ const values = new Map();
14
+ return { getItem: key => values.get(key) ?? null, setItem: (key, value) => values.set(key, String(value)), removeItem: key => values.delete(key) };
15
+ };
16
+ const localStorage = storage(), sessionStorage = storage();
17
+ const login = owner => localStorage.setItem('access_token', `e30.${Buffer.from(JSON.stringify({ sub: owner })).toString('base64url')}.fixture`);
18
+ login('1');
19
+ const window = Object.assign(new EventTarget(), { localStorage, sessionStorage });
20
+ const states = [], effects = [], dependencies = [], cleanups = [], navigations = [], requests = [];
21
+ let cursor = 0, fetcher = async () => ({ ok: true, status: 200, json: async () => ({ routes: [] }) });
22
+ const react = {
23
+ useState(initial) {
24
+ const key = cursor++;
25
+ if (!(key in states)) states[key] = typeof initial === 'function' ? initial() : initial;
26
+ return [states[key], next => { states[key] = typeof next === 'function' ? next(states[key]) : next; }];
27
+ },
28
+ useEffect(effect, deps) {
29
+ const key = cursor++;
30
+ if (!dependencies[key] || deps.some((value, i) => !Object.is(value, dependencies[key][i]))) {
31
+ dependencies[key] = deps;
32
+ effects.push(() => { cleanups[key]?.(); cleanups[key] = effect(); });
33
+ }
34
+ },
35
+ };
36
+ const modules = new Map();
37
+ function load(relative) {
38
+ const filename = path.resolve(root, relative);
39
+ if (modules.has(filename)) return modules.get(filename);
40
+ const exports = {}; modules.set(filename, exports);
41
+ const requireFixture = name => {
42
+ if (name === 'react') return react;
43
+ if (name === 'react/jsx-runtime') return { jsx: (type, props) => ({ type, props }), jsxs: (type, props) => ({ type, props }) };
44
+ if (name === 'next/navigation') return { useRouter: () => ({ push: url => navigations.push(url) }) };
45
+ if (name.endsWith('/LeafletMap')) return { __esModule: true, default: 'LeafletMap' };
46
+ if (name.endsWith('/sessionRestore')) return {
47
+ restoreSession: async () => true, getStoredAccessToken: () => localStorage.getItem('access_token'),
48
+ requestLogin() {}, SESSION_CHANGED_EVENT: 'session-changed',
49
+ };
50
+ const target = path.resolve(path.dirname(filename), name);
51
+ return load(path.relative(root, target + (fs.existsSync(target + '.ts') ? '.ts' : '.tsx')));
52
+ };
53
+ const code = ts.transpileModule(fs.readFileSync(filename, 'utf8'), {
54
+ compilerOptions: { module: ts.ModuleKind.CommonJS, jsx: ts.JsxEmit.ReactJSX, target: ts.ScriptTarget.ES2020, esModuleInterop: true },
55
+ }).outputText;
56
+ vm.runInNewContext(`(function(require,exports){${code}\n})`, {
57
+ window, localStorage, sessionStorage, Event, URL, URLSearchParams, AbortController, setTimeout, clearTimeout,
58
+ atob: value => Buffer.from(value, 'base64').toString('utf8'), crypto: { randomUUID: () => 'writer' },
59
+ fetch: async (...args) => { requests.push(args); return fetcher(...args); }, process: { env: {} },
60
+ }, { filename })(requireFixture, exports);
61
+ return exports;
62
+ }
63
+ const component = load('_components/RecentRuns.tsx').default;
64
+ return {
65
+ load, window, login, navigations, requests, sessionStorage, localStorage,
66
+ fetchWith: next => { fetcher = next; },
67
+ render() { cursor = 0; const tree = component({ apiBase: '' }); effects.splice(0).forEach(effect => effect()); return tree; },
68
+ dispose() { cleanups.forEach(cleanup => cleanup?.()); },
69
+ };
70
+ }
71
+
72
+ function nodes(tree, predicate) {
73
+ if (!tree || typeof tree !== 'object') return [];
74
+ if (Array.isArray(tree)) return tree.flatMap(child => nodes(child, predicate));
75
+ return [...(predicate(tree) ? [tree] : []), ...nodes(tree.props?.children, predicate)];
76
+ }
77
+ const button = (tree, label) => nodes(tree, node => node.type === 'button' && node.props['aria-label']?.includes(label))[0];
78
+ const checkpoint = changes => ({
79
+ sessionId: 'running-1', routeId: 'free-run', runUrl: '/run/free-run?runKey=running-1&flowToken=original',
80
+ mode: 'real', revision: 3, savedAt: Date.now(), elapsedSec: 123, distanceKm: 0.4, isPaused: true,
81
+ simulationCursor: 0, actualRoute: [[37.5, 127], [37.501, 127]], currentPosition: [37.501, 127], routePayload: {}, guidance: {}, ...changes,
82
+ });
83
+
84
+ (async () => {
85
+ const f = fixture(), recovery = f.load('_utils/activeRun.ts');
86
+ const cp = checkpoint();
87
+ recovery.storeRun(cp);
88
+ f.fetchWith(async () => ({ ok: true, status: 200, json: async () => ({ active: null, ended_session_id: null }) }));
89
+ assert.equal((await recovery.reconcileRun()).checkpoint.sessionId, cp.sessionId, 'server absence preserves a locally saved, unuploaded run');
90
+ assert.ok(f.requests[0][0].includes('session_id=running-1'));
91
+ f.fetchWith(async () => ({ ok: true, status: 200, json: async () => ({ routes: [] }) }));
92
+ f.render(); await flush();
93
+ const resume = button(f.render(), '이어서 달리기');
94
+ assert.ok(resume, 'active card is visible alongside completed history');
95
+ await resume.props.onClick(); await flush();
96
+ assert.equal(f.navigations[0], cp.runUrl, 'resume preserves original runKey, flowToken and checkpoint');
97
+ assert.equal(recovery.readRun().checkpoint.elapsedSec, 123);
98
+ assert.equal(f.requests.filter(([, init]) => init?.method === 'POST').length, 0, 'lobby never creates or resets a session');
99
+
100
+ f.fetchWith(async () => ({ ok: true, status: 200, json: async () => ({ active: null, ended_session_id: cp.sessionId }) }));
101
+ assert.equal(await recovery.reconcileRun(), null);
102
+ assert.equal(recovery.readRun().ended, true);
103
+ assert.equal(button(f.render(), '이어서 달리기'), undefined, 'terminal session is not resumable');
104
+ recovery.storeRun(cp);
105
+ assert.equal(recovery.readRun().ended, true, 'old data cannot resurrect an ended session');
106
+ f.dispose();
107
+ console.log('PASS recovery preserves an unuploaded checkpoint, resumes the same session, and respects server termination');
108
+
109
+ const h = fixture();
110
+ const completed = {
111
+ run_session_id: 8, route_id: null, route_title: '자유 러닝', animal_label: null,
112
+ actual_distance_km: 0, route_length_km: 5, center_lat: null, center_lng: null, polyline: [],
113
+ completed_at: '2026-11-09T10:00:00Z', user_rating: null, duration_sec: 123,
114
+ avg_pace_sec_per_km: null, calories: 12, avg_bpm: 130, achievement_pct: 0,
115
+ is_completed: true, source: 'nearby', place_text: '서울',
116
+ };
117
+ h.fetchWith(async () => ({ ok: true, status: 200, json: async () => ({ routes: [completed] }) }));
118
+ h.render(); await flush();
119
+ const record = button(h.render(), '러닝 기록 보기');
120
+ assert.ok(record, 'a free run without GPS geometry can still open its metrics');
121
+ record.props.onClick(); await flush();
122
+ const destination = new URL(h.navigations[0], 'https://fixture.invalid');
123
+ const previews = h.load('_utils/recentRoutePreview.ts');
124
+ const preview = previews.readRecentRoutePreview(destination.searchParams.get('recentRouteKey'));
125
+ const post = previews.recentRouteToCommunityPost(preview);
126
+ assert.equal(destination.pathname, '/route/recent-8');
127
+ assert.equal(post.stats.distance, '0.00', 'zero actual distance must never fall back to planned distance');
128
+ assert.equal(post.stats.time, '02:03');
129
+ assert.equal(post.stats.achievement, '0', 'free run has no invented 100% target achievement');
130
+ assert.equal(post.stats.calories, '12 kcal');
131
+ assert.equal(post.stats.bpm, '130');
132
+ assert.equal(post.map.address, '서울');
133
+ assert.deepEqual(plain(post.map.polyline), []);
134
+ const traced = previews.recentRouteToCommunityPost({ ...preview, actualDistanceKm: 2, durationSec: 720, polyline: [[37, 127], [37.1, 127]], isCompleted: false });
135
+ assert.equal(traced.stats.pace, "6'00''");
136
+ assert.equal(traced.stats.time, '12:00');
137
+ assert.ok(traced.content.includes('종료'));
138
+ h.login('2'); h.window.dispatchEvent(new Event('session-changed')); await flush();
139
+ assert.equal(previews.readRecentRoutePreview(destination.searchParams.get('recentRouteKey')), null, 'another account cannot open this private preview');
140
+ h.dispose();
141
+ console.log('PASS completed/free-run cards open private details with actual metrics, even without geometry');
142
+
143
+ const race = fixture(); let resolve;
144
+ race.fetchWith(() => new Promise(done => { resolve = done; }));
145
+ race.render();
146
+ race.login('2');
147
+ resolve({ ok: true, status: 200, json: async () => ({ routes: [completed] }) }); await flush();
148
+ assert.equal(button(race.render(), '러닝 기록 보기'), undefined, 'in-flight history from another account is discarded');
149
+ race.dispose();
150
+ console.log('PASS account change during an API response does not expose previous history');
151
+ })().catch(error => { console.error(error); process.exitCode = 1; });