Spaces:
Runtime error
Runtime error
Sync DemoService 2150d5839c322d3d61bfde1129daca24c6886748
Browse filesFiles changed (15)
- api/auth-service/app/api/v1/endpoints/active_run.py+3-2
- api/auth-service/app/api/v1/endpoints/runs.py+39-80
- api/auth-service/app/schemas/run.py+9-1
- api/auth-service/tests/test_active_run.py+8
- api/auth-service/tests/test_recent_runs.pyAdded+75
- main/app/_components/ActiveRunGuard.tsx+4-4
- main/app/_components/RecentRuns.tsxAdded+234
- main/app/_utils/activeRun.ts+7-2
- main/app/_utils/recentRoutePreview.ts+71-5
- main/app/lobby/page.tsx+12-321
- main/app/route/[id]/page.tsx+9-38
- main/app/run/[id]/page.tsx+2-1
- main/tests/activeRun.cjs+4
- main/tests/uiContinuity.cjs+4-2
- tools/test-recent-runs.cjsAdded+151
61 unmodified lines62636465666768697061 unmodified linesdb.execute(select(User.id).where(User.id == user.id).with_for_update()).first()@router.get("")def read_active(db: Session = Depends(get_db), user: User = Depends(get_current_user)):row = db.scalar(select(ActiveRun).where(ActiveRun.user_id == user.id, ActiveRun.ended == 0))return {"active": envelope(row)}@router.get("/environment-density")def environment_density(response: Response, db: Session = Depends(get_db),61 unmodified lines6263646566676869707161 unmodified linesdb.execute(select(User.id).where(User.id == user.id).with_for_update()).first()@router.get("")def read_active(db: Session = Depends(get_db), user: User = Depends(get_current_user), session_id: str | None = None):row = db.scalar(select(ActiveRun).where(ActiveRun.user_id == user.id, ActiveRun.ended == 0))previous = db.get(ActiveRun, (user.id, session_id)) if session_id else Nonereturn {"active": envelope(row), "ended_session_id": previous.session_id if previous and previous.ended else None}@router.get("/environment-density")def environment_density(response: Response, db: Session = Depends(get_db),
657 unmodified lines6586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467471 unmodified line7497507517527537547555 unmodified lines761762763764765766657 unmodified linesdb: Session = Depends(get_db),current_user: User = Depends(get_current_user),):has_map_image_column = _routes_has_map_image_column(db)query = ("""WITH ranked_runs AS (SELECTrs.id,rs.route_id,rs.distance_km,rs.user_rating,rs.finished_at,rs.started_at,COUNT(*) OVER (PARTITION BY rs.route_id)::int AS completed_count,ROW_NUMBER() OVER (PARTITION BY rs.route_idORDER BY COALESCE(rs.finished_at, rs.started_at) DESC, rs.id DESC) AS route_rankFROM run_sessions rsWHERE rs.user_id = :user_idAND rs.route_id IS NOT NULL)SELECTrr.id AS run_session_id,r.id AS route_id,COALESCE(NULLIF(TRIM(r.title), ''), 'Route') AS route_title,NULLIF(TRIM(r.animal_label), '') AS animal_label,COALESCE(rr.distance_km, 0) AS actual_distance_km,COALESCE(r.length_km, 0) AS route_length_km,COALESCE(NULLIF(TRIM(r.map_image_url), ''), '/icon.svg') AS map_image_url,r.center_lat AS center_lat,r.center_lng AS center_lng,r.polyline AS polyline,COALESCE(rr.finished_at, rr.started_at) AS completed_at,rr.completed_count AS completed_count,rr.user_rating AS user_ratingFROM ranked_runs rrJOIN routes r ON r.id = rr.route_idWHERE rr.route_rank = 1ORDER BY COALESCE(rr.finished_at, rr.started_at) DESC, rr.id DESCLIMIT :limit"""if has_map_image_columnelse """WITH ranked_runs AS (SELECTrs.id,rs.route_id,rs.distance_km,rs.user_rating,rs.finished_at,rs.started_at,COUNT(*) OVER (PARTITION BY rs.route_id)::int AS completed_count,ROW_NUMBER() OVER (PARTITION BY rs.route_idORDER BY COALESCE(rs.finished_at, rs.started_at) DESC, rs.id DESC) AS route_rankFROM run_sessions rsWHERE rs.user_id = :user_idAND rs.route_id IS NOT NULL)SELECTrr.id AS run_session_id,r.id AS route_id,COALESCE(NULLIF(TRIM(r.title), ''), 'Route') AS route_title,NULLIF(TRIM(r.animal_label), '') AS animal_label,COALESCE(rr.distance_km, 0) AS actual_distance_km,COALESCE(r.length_km, 0) AS route_length_km,'/icon.svg' AS map_image_url,r.center_lat AS center_lat,r.center_lng AS center_lng,r.polyline AS polyline,COALESCE(rr.finished_at, rr.started_at) AS completed_at,rr.completed_count AS completed_count,rr.user_rating AS user_ratingFROM ranked_runs rrJOIN routes r ON r.id = rr.route_idWHERE rr.route_rank = 1ORDER BY COALESCE(rr.finished_at, rr.started_at) DESC, rr.id DESCLIMIT :limit""")rows = db.execute(text(query),{"user_id": current_user.id, "limit": limit},).mappings().all()1 unmodified lineroutes=[RecentRouteItem(run_session_id=int(row["run_session_id"]),route_id=int(row["route_id"]),route_title=str(row["route_title"]),animal_label=str(row["animal_label"]) if row["animal_label"] is not None else None,actual_distance_km=float(row["actual_distance_km"] or 0),5 unmodified linescompleted_at=row["completed_at"],completed_count=int(row["completed_count"] or 0),user_rating=int(row["user_rating"]) if row["user_rating"] is not None else None,)for row in rows]657 unmodified lines6586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976981 unmodified line7007017027037047057065 unmodified lines712713714715716717718719720721722723724725657 unmodified linesdb: Session = Depends(get_db),current_user: User = Depends(get_current_user),):# History is per workout, not per distinct course. Include free runs and# prefer the travelled trace over the planned course for completed records.image = ("COALESCE(NULLIF(TRIM(r.map_image_url), ''), '/icon.svg')"if _routes_has_map_image_column(db) else "'/icon.svg'")rows = db.execute(text(f"""SELECTrs.id AS run_session_id,rs.route_id,COALESCE(NULLIF(TRIM(r.title), ''), '자유 러닝') AS route_title,NULLIF(TRIM(r.animal_label), '') AS animal_label,COALESCE(rs.distance_km, 0) AS actual_distance_km,COALESCE(r.length_km, rs.distance_km, 0) AS route_length_km,{image} AS map_image_url,COALESCE(actual.center_lat, r.center_lat) AS center_lat,COALESCE(actual.center_lng, r.center_lng) AS center_lng,COALESCE(actual.polyline, r.polyline) AS polyline,COALESCE(rs.finished_at, rs.started_at) AS completed_at,COUNT(*) OVER (PARTITION BY rs.route_id) AS completed_count,rs.user_rating,rs.duration_sec,rs.avg_pace_sec_per_km,rs.calories,rs.avg_bpm,rs.achievement_pct,rs.is_completed,rs.source,rs.place_textFROM run_sessions rsLEFT JOIN routes r ON r.id = rs.route_idLEFT JOIN run_session_actual_routes actual ON actual.run_session_id = rs.idWHERE rs.user_id = :user_idORDER BY COALESCE(rs.finished_at, rs.started_at) DESC, rs.id DESCLIMIT :limit"""),{"user_id": current_user.id, "limit": limit},).mappings().all()1 unmodified lineroutes=[RecentRouteItem(run_session_id=int(row["run_session_id"]),route_id=int(row["route_id"]) if row["route_id"] is not None else None,route_title=str(row["route_title"]),animal_label=str(row["animal_label"]) if row["animal_label"] is not None else None,actual_distance_km=float(row["actual_distance_km"] or 0),5 unmodified linescompleted_at=row["completed_at"],completed_count=int(row["completed_count"] or 0),user_rating=int(row["user_rating"]) if row["user_rating"] is not None else None,duration_sec=int(row["duration_sec"] or 0),avg_pace_sec_per_km=row["avg_pace_sec_per_km"],calories=row["calories"],avg_bpm=row["avg_bpm"],achievement_pct=float(row["achievement_pct"] or 0),is_completed=bool(row["is_completed"]),source=row["source"] or "nearby",place_text=row["place_text"],)for row in rows]
198 unmodified lines1992002012022032042055 unmodified lines211212213214215216198 unmodified linesclass RecentRouteItem(BaseModel):run_session_id: introute_id: introute_title: stranimal_label: str | None = Noneactual_distance_km: float5 unmodified linescompleted_at: datetime | None = Nonecompleted_count: intuser_rating: int | None = Noneclass RecentRoutesResponse(BaseModel):198 unmodified lines1992002012022032042055 unmodified lines211212213214215216217218219220221222223224198 unmodified linesclass RecentRouteItem(BaseModel):run_session_id: introute_id: int | None = Noneroute_title: stranimal_label: str | None = Noneactual_distance_km: float5 unmodified linescompleted_at: datetime | None = Nonecompleted_count: intuser_rating: int | None = Noneduration_sec: int = 0avg_pace_sec_per_km: float | None = Nonecalories: int | None = Noneavg_bpm: float | None = Noneachievement_pct: float = 0is_completed: bool = Falsesource: str = "nearby"place_text: str | None = Noneclass RecentRoutesResponse(BaseModel):
51 unmodified lines52535455565751 unmodified linescomplete(mode, self.payload(mode, 3, session=mode), self.db, self.user)self.assertIsNone(read_active(self.db, self.user)["active"])def test_stale_write_and_terminal_resurrection_are_rejected(self):start(self.payload(revision=10), self.db, self.user)self.assertEqual(checkpoint("run-1", self.payload(revision=9), self.db, self.user)["checkpoint"]["revision"], 10)51 unmodified lines525354555657585960616263646551 unmodified linescomplete(mode, self.payload(mode, 3, session=mode), self.db, self.user)self.assertIsNone(read_active(self.db, self.user)["active"])def test_recovery_distinguishes_unuploaded_and_ended_sessions(self):self.assertIsNone(read_active(self.db, self.user, "unuploaded")["ended_session_id"])start(self.payload(), self.db, self.user)complete("run-1", self.payload(revision=2), self.db, self.user)self.assertEqual(read_active(self.db, self.user, "run-1")["ended_session_id"], "run-1")self.assertIsNone(read_active(self.db, self.other, "run-1")["ended_session_id"])self.assertIsNone(read_active(self.db, self.user, "different-session")["ended_session_id"])def test_stale_write_and_terminal_resurrection_are_rejected(self):start(self.payload(revision=10), self.db, self.user)self.assertEqual(checkpoint("run-1", self.payload(revision=9), self.db, self.user)["checkpoint"]["revision"], 10)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475"""Recent workout history contract, using an isolated in-memory database."""import jsonimport unittestfrom types import SimpleNamespacefrom unittest.mock import patchfrom sqlalchemy import create_engine, textfrom sqlalchemy.orm import Sessionfrom app.api.v1.endpoints.runs import get_recent_routes
class RecentRunsTests(unittest.TestCase): def setUp(self): self.engine = create_engine("sqlite:///:memory:") self.db = Session(self.engine) statements = [ """CREATE TABLE routes (id INTEGER PRIMARY KEY, title TEXT, animal_label TEXT, length_km REAL, map_image_url TEXT, center_lat REAL, center_lng REAL, polyline TEXT)""", """CREATE TABLE run_sessions (id INTEGER PRIMARY KEY, user_id INTEGER, route_id INTEGER, started_at TEXT, finished_at TEXT, distance_km REAL, user_rating INTEGER, duration_sec INTEGER, avg_pace_sec_per_km REAL, calories INTEGER, avg_bpm REAL, achievement_pct REAL, is_completed INTEGER, source TEXT, place_text TEXT)""", """CREATE TABLE run_session_actual_routes (run_session_id INTEGER PRIMARY KEY, center_lat REAL, center_lng REAL, polyline TEXT)""", ] for statement in statements: self.db.execute(text(statement)) self.db.execute(text("INSERT INTO routes VALUES (7, '강변 루트', 'dog', 5, '/map.png', 37, 127, :line)"), {"line": json.dumps([[37, 127], [37.1, 127]])})
def tearDown(self): self.db.close() self.engine.dispose()
def add_run(self, identity, date, route=7, user=1, distance=2.5, completed=1): self.db.execute(text("""INSERT INTO run_sessions VALUES (:id, :user, :route, :date, :date, :distance, 4, 900, 360, 180, 125, 50, :completed, 'manual', '서울')"""), dict(id=identity, user=user, route=route, date=date, distance=distance, completed=completed))
def recent(self, limit=2, image_column=True): with patch("app.api.v1.endpoints.runs._routes_has_map_image_column", return_value=image_column): return get_recent_routes(limit, self.db, SimpleNamespace(id=1)).routes
def test_repeated_course_is_listed_per_workout_with_actual_metrics_and_trace(self): self.add_run(1, "2026-11-01T10:00:00Z") self.add_run(2, "2026-11-02T10:00:00Z", distance=0, completed=0) self.add_run(3, "2026-11-03T10:00:00Z", user=2) trace = [[37.5, 127.5], [37.51, 127.51]] self.db.execute(text("INSERT INTO run_session_actual_routes VALUES (2, 37.5, 127.5, :line)"), {"line": json.dumps(trace)}) rows = self.recent() self.assertEqual([r.run_session_id for r in rows], [2, 1]) self.assertEqual(rows[0].polyline, trace) self.assertEqual(rows[0].center_lat, 37.5) self.assertEqual(rows[0].actual_distance_km, 0) self.assertEqual(rows[0].duration_sec, 900) self.assertEqual(rows[0].avg_pace_sec_per_km, 360) self.assertEqual(rows[0].calories, 180) self.assertEqual(rows[0].avg_bpm, 125) self.assertEqual(rows[0].achievement_pct, 50) self.assertFalse(rows[0].is_completed) self.assertEqual(rows[0].completed_count, 2)
def test_free_run_without_geometry_is_visible_and_legacy_image_column_is_optional(self): self.add_run(1, "2026-11-02T10:00:00Z", route=None) self.add_run(2, "2026-11-01T10:00:00Z") self.db.execute(text("ALTER TABLE routes DROP COLUMN map_image_url")) row = self.recent(limit=1, image_column=False)[0] self.assertIsNone(row.route_id) self.assertEqual(row.route_title, "자유 러닝") self.assertEqual(row.polyline, []) self.assertEqual(row.map_image_url, "/icon.svg")
if __name__ == "__main__": unittest.main()15 unmodified lines16171819202122232430 unmodified lines555657585960616215 unmodified linesimport { hasUsableAccessToken } from "../_utils/sessionRestore";/*** Keeps an active run pinned to its run URL without ever replacing the visible UI* with a guard/loading page. Local state is checked synchronously; server* reconciliation happens in the background and only redirects when necessary.*/export default function ActiveRunGuard({ children }: { children: ReactNode }) {const pathname = usePathname();30 unmodified lines// Opening the bare app URL is an intentional request to enter the// app, not permission to jump straight into a previously active run.// Keep the checkpoint resumable, but let `/` continue to the lobby.if (pathname === "/") {sessionStorage.setItem(ACTIVE_RUN_REDIRECT_SUPPRESSION_KEY, runUrl);return false;}const shouldPromptAfterLogin =15 unmodified lines161718192021222330 unmodified lines54555657585960616215 unmodified linesimport { hasUsableAccessToken } from "../_utils/sessionRestore";/*** Protects active run recovery while allowing the lobby to offer an explicit* resume action. Server reconciliation runs in the background.*/export default function ActiveRunGuard({ children }: { children: ReactNode }) {const pathname = usePathname();30 unmodified lines// Opening the bare app URL is an intentional request to enter the// app, not permission to jump straight into a previously active run.// Keep the checkpoint resumable, but let `/` continue to the lobby.if (pathname === "/" || pathname === "/lobby") {sessionStorage.setItem(ACTIVE_RUN_REDIRECT_SUPPRESSION_KEY, runUrl);if (pathname === "/lobby") sessionStorage.removeItem(ACTIVE_RUN_LOGIN_PROMPT_KEY);return false;}const shouldPromptAfterLogin =
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234"use client";
import { useEffect, useState } from "react";import { useRouter } from "next/navigation";import LeafletMap from "./LeafletMap";import { ACTIVE_RUN_EVENT, ACTIVE_RUN_REDIRECT_SUPPRESSION_KEY, readRun, runOwner, type RunCheckpoint,} from "../_utils/activeRun";import { getStoredAccessToken, requestLogin, restoreSession, SESSION_CHANGED_EVENT } from "../_utils/sessionRestore";import { formatRecentRunDuration, storeRecentRoutePreview, type RecentRoutePreview } from "../_utils/recentRoutePreview";
type Point = [number, number];type RecentRun = { run_session_id: number; route_id: number | null; route_title: string; animal_label: string | null; actual_distance_km: number; route_length_km: number; center_lat: number | null; center_lng: number | null; polyline: Point[]; completed_at: string | null; user_rating: number | null; duration_sec: number; avg_pace_sec_per_km: number | null; calories: number | null; avg_bpm: number | null; achievement_pct: number; is_completed: boolean; source: string; place_text: string | null;};
function points(value: unknown): Point[] { return Array.isArray(value) ? value.filter((point): point is Point => Array.isArray(point) && point.length === 2 && Number.isFinite(point[0]) && Math.abs(point[0]) <= 90 && Number.isFinite(point[1]) && Math.abs(point[1]) <= 180) : [];}
function previewFor(run: RecentRun): RecentRoutePreview { return { runSessionId: run.run_session_id, routeId: run.route_id, title: run.route_title || "러닝 기록", label: run.animal_label, actualDistanceKm: run.actual_distance_km, routeDistanceKm: run.route_length_km, center: Number.isFinite(run.center_lat) && Number.isFinite(run.center_lng) ? [run.center_lat!, run.center_lng!] : null, polyline: points(run.polyline), completedAt: run.completed_at, rating: run.user_rating, durationSec: run.duration_sec, paceSecPerKm: run.avg_pace_sec_per_km, calories: run.calories, bpm: run.avg_bpm, achievementPct: run.achievement_pct, isCompleted: run.is_completed, source: run.source === "manual" ? "manual" : "nearby", place: run.place_text ?? "", };}
function savedDate(value: string | null): string { const date = value ? new Date(value) : null; return date && Number.isFinite(date.getTime()) ? date.toLocaleDateString("ko-KR", { month: "2-digit", day: "2-digit" }) : "최근";}
function RunMap({ route, center }: { route: Point[]; center?: Point | null }) { return ( <div className="lobby-route-map pointer-events-none relative isolate h-[72px] overflow-hidden bg-[#EEF2F1]" aria-hidden="true"> {route.length > 1 ? ( <LeafletMap center={center ?? route[0]} route={route} interactive={false} className="h-full w-full" zoom={14} /> ) : ( <div className="flex h-full items-center justify-center text-xs font-medium text-[#63736A]">경로 기록 없음</div> )} </div> );}
export default function RecentRuns({ apiBase }: { apiBase: string }) { const router = useRouter(); const [active, setActive] = useState<RunCheckpoint | null>(null); const [history, setHistory] = useState<RecentRun[]>([]); const [loading, setLoading] = useState(true); const [resuming, setResuming] = useState(false); const [error, setError] = useState<string | null>(null); const [recoveryError, setRecoveryError] = useState<string | null>(null); const [reload, setReload] = useState(0);
useEffect(() => { let mounted = true; let request = 0; let visibleOwner = runOwner(); const readActive = () => { try { const stored = readRun(); setActive(stored && !stored.ended ? stored.checkpoint : null); setRecoveryError(null); } catch { setActive(null); setRecoveryError("진행 중인 러닝 정보를 읽지 못했습니다. 새로고침 후 다시 확인해 주세요."); } }; const load = async () => { const id = ++request; const owner = runOwner(); readActive(); if (owner !== visibleOwner) { visibleOwner = owner; setHistory([]); } const token = getStoredAccessToken(); if (!owner || !token) { setHistory([]); setLoading(false); return; } setLoading(true); try { const response = await fetch(`${apiBase}/api/v1/auth/runs/recent-routes?limit=2`, { headers: { Authorization: `Bearer ${token}` }, cache: "no-store", }); if (!response.ok) throw new Error("history_unavailable"); const data = await response.json() as { routes?: RecentRun[] }; if (mounted && request === id && owner === runOwner()) { setHistory(data.routes ?? []); setError(null); } } catch { if (mounted && request === id && owner === runOwner()) { setError("최근 러닝 기록을 불러오지 못했습니다. 다시 시도해 주세요."); } } finally { if (mounted && request === id) setLoading(false); } }; const refresh = () => { void load(); }; const onStorage = (event: StorageEvent) => { if (!event.key || event.key === "access_token") refresh(); else readActive(); }; void load(); window.addEventListener(ACTIVE_RUN_EVENT, readActive); window.addEventListener(SESSION_CHANGED_EVENT, refresh); window.addEventListener("storage", onStorage); window.addEventListener("focus", refresh); window.addEventListener("online", refresh); return () => { mounted = false; window.removeEventListener(ACTIVE_RUN_EVENT, readActive); window.removeEventListener(SESSION_CHANGED_EVENT, refresh); window.removeEventListener("storage", onStorage); window.removeEventListener("focus", refresh); window.removeEventListener("online", refresh); }; }, [apiBase, reload]);
const authenticated = async (action: () => void) => { try { if (await restoreSession()) { action(); return; } requestLogin(); } catch { setError("로그인 상태나 연결을 확인한 뒤 다시 시도해 주세요."); } };
const resume = async () => { if (!active || resuming) return; setResuming(true); setError(null); const owner = runOwner(); await authenticated(() => { const current = readRun(); if (owner !== runOwner() || !current || current.ended || current.checkpoint.sessionId !== active.sessionId) { setError("이미 종료되었거나 변경된 러닝입니다. 최근 기록을 다시 확인해 주세요."); setReload(value => value + 1); return; } // Use the original URL/session. A new runKey would lose the checkpoint. sessionStorage.removeItem(ACTIVE_RUN_REDIRECT_SUPPRESSION_KEY); router.push(current.checkpoint.runUrl); }); setResuming(false); };
const openRecord = async (run: RecentRun) => { setError(null); const owner = runOwner(); await authenticated(() => { if (owner !== runOwner()) { setReload(value => value + 1); return; } try { const key = storeRecentRoutePreview(previewFor(run)); if (!key) throw new Error("preview_unavailable"); router.push(`/route/recent-${run.run_session_id}?recentRouteKey=${encodeURIComponent(key)}`); } catch { setError("러닝 기록을 열지 못했습니다. 다시 시도해 주세요."); } }); };
const activeRoute = active ? points(active.actualRoute).length > 1 ? points(active.actualRoute) : points(active.routePayload.route) : []; const activeTitle = active ? new URL(active.runUrl, "https://local.invalid").searchParams.get("routeTitle") || (active.routeId === "free-run" ? "자유 러닝" : "진행 중인 루트") : "";
return ( <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"> <div className="flex items-center justify-between"> <h2 id="recent-runs-title" className="text-base font-bold text-[#111111]">최근 루트</h2> <button type="button" onClick={() => void authenticated(() => router.push("/saved-routes"))} className="rounded-full bg-[#fafafa] px-3 py-1.5 text-xs font-semibold text-[#525252]">저장 루트</button> </div>
{active ? ( <button type="button" onClick={() => void resume()} disabled={resuming} className="mt-3 w-full overflow-hidden rounded-2xl border border-[#22724D]/30 bg-[#F2F8F4] text-left shadow-sm disabled:opacity-60" aria-label={`${activeTitle} 이어서 달리기`}> <RunMap route={activeRoute} center={active.currentPosition} /> <div className="p-3"> <p className="text-xs font-bold text-[#22724D]">{active.mode === "simulation" ? "시뮬레이션 · " : ""}{active.isPaused ? "일시정지 중" : "진행 중인 러닝"}</p> <p className="mt-1 truncate text-sm font-bold text-[#16211B]">{activeTitle}</p> <p className="mt-1 text-xs font-semibold text-[#525252]">{active.distanceKm.toFixed(2)}km · {formatRecentRunDuration(active.elapsedSec)}</p> <p className="mt-2 text-xs text-[#63736A]">저장된 지점부터 계속할 수 있어요.</p> <p className="mt-2 text-sm font-bold text-[#22724D]">{resuming ? "러닝을 여는 중…" : "이어서 달리기 →"}</p> </div> </button> ) : null}
<div className="mt-2 grid grid-cols-2 gap-2 lg:mt-3 lg:gap-3" aria-busy={loading}> {loading && history.length === 0 ? [0, 1].map(index => ( <div key={index} className="h-36 animate-pulse rounded-2xl bg-[#EEF2F1]" aria-label="최근 기록을 불러오는 중" /> )) : history.map(run => ( <button type="button" key={run.run_session_id} onClick={() => void openRecord(run)} className="min-w-0 isolate overflow-hidden rounded-2xl border border-black/10 bg-white/95 text-left shadow-sm" aria-label={`${run.route_title} 러닝 기록 보기`}> <RunMap route={points(run.polyline)} center={previewFor(run).center} /> <div className="p-2 sm:p-3"> <div className="flex items-center justify-between gap-1 text-[11px] text-[#63736A]"> <span className="font-bold text-[#22724D]">{run.is_completed ? "완주" : "종료"}</span> <span>{savedDate(run.completed_at)}</span> </div> <p className="mt-1 truncate text-sm font-bold text-[#16211B]">{run.route_title || "러닝 기록"}</p> <p className="mt-1 text-xs font-semibold text-[#525252]">{run.actual_distance_km.toFixed(2)}km · {formatRecentRunDuration(run.duration_sec)}</p> <p className="mt-2 text-xs font-bold text-[#63736A]">기록 보기 →</p> </div> </button> ))} </div> {!loading && history.length === 0 && !error ? <p className="py-5 text-center text-sm text-[#737373]">완료한 러닝 기록이 아직 없어요.</p> : null} {recoveryError || error ? <div role="alert" className="mt-3 text-xs leading-5 text-[#b42323]">{recoveryError || error} <button type="button" className="ml-2 font-bold underline" onClick={() => setReload(value => value + 1)}>다시 시도</button> </div> : null} </section> );}92 unmodified lines9394959697989910010110210310410510692 unmodified linesconst owner = runOwner();if (!owner) return null;const before = readRun(owner);const result = await runRequest("");const local = readRun(owner);const remote = result.active as { checkpoint: RunCheckpoint; ended: boolean } | null;if (!remote) {// A start or checkpoint written while GET was in flight is newer evidence.if (local && (!before || local.checkpoint.sessionId !== before.checkpoint.sessionId|| local.checkpoint.revision !== before.checkpoint.revision)) return local;if (local && !local.ended) storeRun(local.checkpoint, true, owner);return null;}if (!validCheckpoint(remote.checkpoint)) throw new Error("서버의 러닝 복구 정보를 확인하지 못했습니다.");92 unmodified lines9394959697989910010110210310410510610710810911011192 unmodified linesconst owner = runOwner();if (!owner) return null;const before = readRun(owner);const result = await runRequest(before ? `?session_id=${encodeURIComponent(before.checkpoint.sessionId)}` : "");const local = readRun(owner);const remote = result.active as { checkpoint: RunCheckpoint; ended: boolean } | null;if (!remote) {// A start or checkpoint written while GET was in flight is newer evidence.if (local && (!before || local.checkpoint.sessionId !== before.checkpoint.sessionId|| local.checkpoint.revision !== before.checkpoint.revision)) return local;// A device can close before its first upload. Absence on the server is// not a completion: only a matching terminal record can end local recovery.if (local && !local.ended) {if (result.ended_session_id !== local.checkpoint.sessionId) return local;storeRun(local.checkpoint, true, owner);}return null;}if (!validCheckpoint(remote.checkpoint)) throw new Error("서버의 러닝 복구 정보를 확인하지 못했습니다.");
123456782 unmodified lines1112131415163 unmodified lines202122232425262728291 unmodified line3132333435363738394012 unmodified lines5354555657585960"use client";export type RecentRoutePreview = {runSessionId: number;routeId: number;title: string;label: string | null;actualDistanceKm: number;2 unmodified linespolyline: [number, number][];completedAt: string | null;rating: number | null;};const PREFIX = "tranimal:recent-route-preview:";3 unmodified lines}export function storeRecentRoutePreview(preview: RecentRoutePreview): string | null {if (typeof window === "undefined" || preview.polyline.length < 2) return null;const key = `${PREFIX}${preview.runSessionId}`;window.sessionStorage.setItem(key, JSON.stringify(preview));return key;}1 unmodified lineif (typeof window === "undefined" || !key?.startsWith(PREFIX)) return null;try {const parsed = JSON.parse(window.sessionStorage.getItem(key) ?? "") as Partial<RecentRoutePreview>;if (!Number.isFinite(parsed.runSessionId) ||!Number.isFinite(parsed.routeId) ||typeof parsed.title !== "string" ||!Array.isArray(parsed.polyline) ||!parsed.polyline.every(isPoint)12 unmodified linespolyline: parsed.polyline,completedAt: typeof parsed.completedAt === "string" ? parsed.completedAt : null,rating: Number.isFinite(parsed.rating) ? parsed.rating : null,};} catch {return null;}}12345678910112 unmodified lines14151617181920212223242526273 unmodified lines3132333435363738394041421 unmodified line444546474849505152535412 unmodified lines676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126"use client";import { runOwner } from "./activeRun";import { DEFAULT_MAP_CENTER, type CommunityPost } from "./communityPosts";export type RecentRoutePreview = {runSessionId: number;routeId: number | null;title: string;label: string | null;actualDistanceKm: number;2 unmodified linespolyline: [number, number][];completedAt: string | null;rating: number | null;durationSec?: number | null;paceSecPerKm?: number | null;calories?: number | null;bpm?: number | null;achievementPct?: number;isCompleted?: boolean;source?: "nearby" | "manual";place?: string;};const PREFIX = "tranimal:recent-route-preview:";3 unmodified lines}export function storeRecentRoutePreview(preview: RecentRoutePreview): string | null {if (typeof window === "undefined") return null;const owner = runOwner();if (!owner) return null;const key = `${PREFIX}${preview.runSessionId}`;window.sessionStorage.setItem(key, JSON.stringify({ ...preview, owner }));return key;}1 unmodified lineif (typeof window === "undefined" || !key?.startsWith(PREFIX)) return null;try {const parsed = JSON.parse(window.sessionStorage.getItem(key) ?? "") as Partial<RecentRoutePreview> & { owner?: string };if (!runOwner() || parsed.owner !== runOwner() ||!Number.isFinite(parsed.runSessionId) ||(parsed.routeId !== null && !Number.isFinite(parsed.routeId)) ||typeof parsed.title !== "string" ||!Array.isArray(parsed.polyline) ||!parsed.polyline.every(isPoint)12 unmodified linespolyline: parsed.polyline,completedAt: typeof parsed.completedAt === "string" ? parsed.completedAt : null,rating: Number.isFinite(parsed.rating) ? parsed.rating : null,durationSec: metric(parsed.durationSec),paceSecPerKm: metric(parsed.paceSecPerKm),calories: metric(parsed.calories),bpm: metric(parsed.bpm),achievementPct: metric(parsed.achievementPct) ?? 0,isCompleted: parsed.isCompleted ?? Boolean(parsed.completedAt),source: parsed.source === "manual" ? "manual" : "nearby",place: typeof parsed.place === "string" ? parsed.place : "",};} catch {return null;}}function metric(value: unknown): number | null {return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;}export function formatRecentRunDuration(value: number | null | undefined): string {const seconds = metric(value);if (seconds === null) return "-";const total = Math.floor(seconds);const minutes = Math.floor(total / 60);return minutes >= 60? `${Math.floor(minutes / 60)}:${String(minutes % 60).padStart(2, "0")}:${String(total % 60).padStart(2, "0")}`: `${String(minutes).padStart(2, "0")}:${String(total % 60).padStart(2, "0")}`;}export function recentRouteToCommunityPost(preview: RecentRoutePreview): CommunityPost {const duration = metric(preview.durationSec);const pace = metric(preview.paceSecPerKm) ||(duration && preview.actualDistanceKm > 0 ? duration / preview.actualDistanceKm : null);const paceSeconds = pace ? Math.round(pace) : null;return {id: `recent-${preview.runSessionId}`,routeId: preview.routeId === null ? "" : String(preview.routeId),title: preview.title || "러닝 기록",content: preview.isCompleted ? "완주한 러닝 기록입니다." : "종료한 러닝 기록입니다.",nickname: "나",createdAt: preview.completedAt ?? new Date().toISOString(),stats: {distance: Math.max(0, preview.actualDistanceKm).toFixed(2),achievement: String(preview.achievementPct ?? 0),time: formatRecentRunDuration(duration),pace: paceSeconds === null ? "--'--''" : `${Math.floor(paceSeconds / 60)}'${String(paceSeconds % 60).padStart(2, "0")}''`,calories: metric(preview.calories) === null ? "-" : `${Math.round(preview.calories!)} kcal`,bpm: preview.bpm ? String(Math.round(preview.bpm)) : "-",},map: {center: preview.center ?? preview.polyline[0] ?? DEFAULT_MAP_CENTER,polyline: preview.polyline,mode: preview.source === "manual" ? "manual" : "nearby",address: preview.place || "내 러닝 기록",},likeCount: 0, likedByMe: false, viewCount: 0, comments: [],};}
1 unmodified line2345678910111213141516171819202122232425262728293031323334353637383940414243444546273 unmodified lines32032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639791 unmodified lines489490491492493494495496119 unmodified lines61661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970056 unmodified lines75775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680799 unmodified lines90790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061 unmodified lineimport { useEffect, useState } from "react";import { useRouter } from "next/navigation";import LeafletMap from "../_components/LeafletMap";import MotionDialog from "../_components/MotionDialog";import { FLOW_KEYS, issueUiFlowPermit } from "../_utils/uiFlowGuard";import { requestNativeAppExit } from "../_utils/nativeWearBridge";import { prepareCoursePreview } from "../_utils/coursePreview";import { getAppPosition } from "../_utils/nativeLocation";import { readLocationConsent, storeLocationConsent } from "../_utils/locationConsent";import { storeRecentRoutePreview } from "../_utils/recentRoutePreview";import { clearStoredSession, requestLogin, restoreSession } from "../_utils/sessionRestore";// The lobby is a glanceable home screen. Show the latest pair side by side;// the complete route history remains available from the "전체" action.const RECENT_ROUTE_LIMIT = 2;const DEFAULT_CENTER: [number, number] = [37.5665, 126.978];type Point = [number, number];type WeatherCondition = "sunny" | "rainy" | "cloudy" | "snowy";type WeatherLoadStatus = "loading" | "ready" | "fallback";type RecentRoute = {run_session_id: number;route_id: number;route_title: string;animal_label: string | null;actual_distance_km: number;route_length_km: number;map_image_url: string;center_lat: number | null;center_lng: number | null;polyline: Point[];completed_at: string | null;completed_count: number;user_rating: number | null;};type RecentRoutesResponse = {routes: RecentRoute[];};type IconProps = {className?: string;};273 unmodified lines);}function resolveMapImage(path: string): string {if (!path) {return "/icon.svg";}if (path.startsWith("/") ||path.startsWith("http://") ||path.startsWith("https://")) {return path;}return `/${path}`;}function sanitizePoint(value: unknown): Point | null {if (!Array.isArray(value) || value.length !== 2) {return null;}const lat = Number(value[0]);const lng = Number(value[1]);if (!Number.isFinite(lat) || !Number.isFinite(lng)) {return null;}return [lat, lng];}function sanitizePolyline(value: unknown): Point[] {if (!Array.isArray(value)) {return [];}const points: Point[] = [];for (const point of value) {const parsed = sanitizePoint(point);if (parsed) {points.push(parsed);}}return points;}function formatCompletedAt(value: string | null): string {if (!value) {return "최근";}const parsed = new Date(value);if (!Number.isFinite(parsed.getTime())) {return "최근";}return parsed.toLocaleDateString("ko-KR", {month: "2-digit",day: "2-digit",});}function formatLabel(raw: string | null): string {if (!raw) {return "루트";}return raw.replace(/_/g, " ");}function ArrowRightIcon({ className = "" }: IconProps) {return (<svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2.3" aria-hidden="true">91 unmodified linesexport default function Page() {const router = useRouter();const [displayName, setDisplayName] = useState("러너");const [recentRoutes, setRecentRoutes] = useState<RecentRoute[]>([]);const [isRecentLoading, setIsRecentLoading] = useState(true);const [isExitDialogOpen, setIsExitDialogOpen] = useState(false);const [weatherState, setWeatherState] = useState<WeatherState>(INITIAL_WEATHER);const [weatherReloadKey, setWeatherReloadKey] = useState(0);119 unmodified lines}, [weatherReloadKey]);useEffect(() => {const token =localStorage.getItem("access_token") ?? getCookieValue("access_token");if (!token) {setIsRecentLoading(false);return;}let isMounted = true;const headers = { Authorization: `Bearer ${token}` };const load = async () => {try {const [meResponse, recentResponse] = await Promise.all([fetch(`${apiBase}/api/v1/auth/me`, { headers }),fetch(`${apiBase}/api/v1/auth/runs/recent-routes?limit=${RECENT_ROUTE_LIMIT}`, {headers,cache: "no-store",}),]);if (!isMounted) {return;}if (meResponse.ok) {const meData = (await meResponse.json()) as {first_name?: string;email?: string;};const name =meData?.first_name?.trim() ||meData?.email?.split("@")[0] ||"러너";setDisplayName(name);}if (recentResponse.ok) {const recentData = (await recentResponse.json()) as RecentRoutesResponse;const normalized = (recentData.routes ?? []).map((route) => ({...route,polyline: sanitizePolyline(route.polyline),actual_distance_km:typeof route.actual_distance_km === "number" &&Number.isFinite(route.actual_distance_km)? route.actual_distance_km: 0,route_length_km:typeof route.route_length_km === "number" &&Number.isFinite(route.route_length_km)? route.route_length_km: 0,user_rating:typeof route.user_rating === "number"? Math.max(0, Math.min(5, Math.round(route.user_rating))): null,}));setRecentRoutes(normalized);} else {setRecentRoutes([]);}} catch {if (!isMounted) {return;}setDisplayName("러너");setRecentRoutes([]);} finally {if (isMounted) {setIsRecentLoading(false);}}};void load();return () => {isMounted = false;};}, [apiBase]);useEffect(() => {56 unmodified linesvoid requireLogin(startFreeRun);};const startRecentRoute = (route: RecentRoute) => {if (typeof window === "undefined" || route.polyline.length < 2) {return;}const isCompletedRoute = route.completed_at !== null || route.completed_count > 0;if (isCompletedRoute) {const previewKey = storeRecentRoutePreview({runSessionId: route.run_session_id,routeId: route.route_id,title: route.route_title || "러닝 루트",label: route.animal_label,actualDistanceKm: route.actual_distance_km,routeDistanceKm: route.route_length_km,center: Number.isFinite(route.center_lat) && Number.isFinite(route.center_lng)? [route.center_lat as number, route.center_lng as number]: null,polyline: route.polyline,completedAt: route.completed_at,rating: route.user_rating,});if (previewKey) {router.push(`/route/recent-${route.run_session_id}?recentRouteKey=${encodeURIComponent(previewKey)}`);}return;}router.push(prepareCoursePreview({id: `recent-${route.route_id}`,title: route.route_title || "러닝 루트",place: route.route_title || "러닝 루트",distanceKm: route.route_length_km,center: Number.isFinite(route.center_lat) && Number.isFinite(route.center_lng)? [route.center_lat as number, route.center_lng as number]: route.polyline[0],route: route.polyline,label: route.animal_label ?? undefined,source: "최근 러닝 코스",}));};const handleStartRecentRoute = (route: RecentRoute) => {void requireLogin(() => startRecentRoute(route));};const handleConfirmAppExit = () => {setExitRequestError(null);if (requestNativeAppExit()) {99 unmodified lines</div></section><section className="rounded-[18px] border border-white/75 bg-white/74 p-3 shadow-sm backdrop-blur-md lg:p-5"><div className="flex items-center justify-between"><h2 className="text-base font-bold text-[#111111]">최근 루트</h2><buttontype="button"onClick={() => void requireLogin(() => router.push("/saved-routes"))}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]">전체</button></div><div className="mt-2 grid grid-cols-2 gap-2 lg:mt-3 lg:gap-3">{isRecentLoading &&Array.from({ length: RECENT_ROUTE_LIMIT }).map((_, index) => (<articlekey={`recent-loading-${index}`}className="isolate overflow-hidden rounded-2xl border border-black/10 bg-white/95 shadow-sm [clip-path:inset(0_round_16px)]"><div className="h-14 w-full rounded-t-2xl animate-pulse bg-[#EEF2F1] sm:h-[72px]" /><div className="space-y-2 rounded-b-2xl bg-white/95 p-2 sm:p-3"><div className="h-3 w-20 animate-pulse rounded bg-[#EEF2F1]" /><div className="h-3 w-28 animate-pulse rounded bg-[#EEF2F1]" /></div></article>))}{!isRecentLoading &&recentRoutes.map((route) => {const isCompletedRoute = route.completed_at !== null || route.completed_count > 0;const hasCenter =Number.isFinite(route.center_lat) &&Number.isFinite(route.center_lng);const hasPolyline = route.polyline.length > 1;const mapCenter: Point = hasCenter? [route.center_lat as number, route.center_lng as number]: hasPolyline? route.polyline[0]: DEFAULT_CENTER;return (<buttontype="button"key={`recent-route-${route.run_session_id}`}onClick={() => handleStartRecentRoute(route)}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)]"aria-label={isCompletedRoute ? `${route.route_title} 완료한 루트 보기` : `${route.route_title} 다시 달리기`}><div className="relative h-14 w-full overflow-hidden rounded-t-2xl bg-[#f5f5f5] max-[700px]:h-12 sm:h-[72px]">{hasPolyline ? (<LeafletMapcenter={mapCenter}route={route.polyline}className="lobby-route-map pointer-events-none h-full w-full"zoom={14}/>) : (<imgsrc={resolveMapImage(route.map_image_url)}alt={route.route_title}className="h-full w-full object-cover"onError={(event) => {const target = event.currentTarget;target.onerror = null;target.src = "/icon.svg";}}/>)}<div className="absolute inset-0 z-[500] bg-gradient-to-t from-black/55 via-transparent to-transparent" /><div className="absolute bottom-2 left-2 right-2 z-[500] truncate text-xs font-bold text-white">{route.route_title}</div></div><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"><span className="min-w-0 truncate text-xs font-bold text-[#111111] sm:text-sm">{formatLabel(route.animal_label)}</span><span className="shrink-0 text-xs font-bold text-[#737373]">{formatCompletedAt(route.completed_at)}</span></div></button>);})}{!isRecentLoading && recentRoutes.length === 0 && (<div className="rounded-xl border border-dashed border-black/15 bg-[#FAFCFB] px-4 py-8 text-center text-sm font-bold text-[#737373]">기록 없음</div>)}</div></section></div></section>1 unmodified line23456789101112131415161718273 unmodified lines29229329429529629791 unmodified lines389390391392393394119 unmodified lines51451551651751851952052152252352452552652752852956 unmodified lines58658758858959059199 unmodified lines6916926936946956966971 unmodified lineimport { useEffect, useState } from "react";import { useRouter } from "next/navigation";import RecentRuns from "../_components/RecentRuns";import MotionDialog from "../_components/MotionDialog";import { FLOW_KEYS, issueUiFlowPermit } from "../_utils/uiFlowGuard";import { requestNativeAppExit } from "../_utils/nativeWearBridge";import { getAppPosition } from "../_utils/nativeLocation";import { readLocationConsent, storeLocationConsent } from "../_utils/locationConsent";import { clearStoredSession, requestLogin, restoreSession } from "../_utils/sessionRestore";type WeatherCondition = "sunny" | "rainy" | "cloudy" | "snowy";type WeatherLoadStatus = "loading" | "ready" | "fallback";type IconProps = {className?: string;};273 unmodified lines);}function ArrowRightIcon({ className = "" }: IconProps) {return (<svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2.3" aria-hidden="true">91 unmodified linesexport default function Page() {const router = useRouter();const [displayName, setDisplayName] = useState("러너");const [isExitDialogOpen, setIsExitDialogOpen] = useState(false);const [weatherState, setWeatherState] = useState<WeatherState>(INITIAL_WEATHER);const [weatherReloadKey, setWeatherReloadKey] = useState(0);119 unmodified lines}, [weatherReloadKey]);useEffect(() => {const token = localStorage.getItem("access_token") ?? getCookieValue("access_token");if (!token) return;let mounted = true;void fetch(`${apiBase}/api/v1/auth/me`, { headers: { Authorization: `Bearer ${token}` } }).then(async response => {if (!response.ok) return;const me = await response.json() as { first_name?: string; email?: string };if (mounted) setDisplayName(me.first_name?.trim() || me.email?.split("@")[0] || "러너");}).catch(() => {});return () => { mounted = false; };}, [apiBase]);useEffect(() => {56 unmodified linesvoid requireLogin(startFreeRun);};const handleConfirmAppExit = () => {setExitRequestError(null);if (requestNativeAppExit()) {99 unmodified lines</div></section><RecentRuns apiBase={apiBase} /></div></section>
18 unmodified lines1920212223242525 unmodified lines515253545556575859606162636465666768697071727374757677787980818283848586216 unmodified lines30330430530630730830933 unmodified lines34334434534634734834951 unmodified lines4014024034044054064074084094104114127 unmodified lines42042142242342442542642742842918 unmodified lines} from "../../_utils/communityApi";import { loadSharedRoutePost, invalidateCommunityRouteData } from "../../_utils/communityRouteData";import CommunityRouteLoading from "../../_components/CommunityRouteLoading";import { readRecentRoutePreview } from "../../_utils/recentRoutePreview";import { prepareCoursePreview } from "../../_utils/coursePreview";const LeafletMap = dynamic(() => import("../../_components/LeafletMap"), {25 unmodified linesconst recentRoute = readRecentRoutePreview(recentRouteKey);if (recentRoute) {const completedAt = recentRoute.completedAt ?? new Date().toISOString();const distance = recentRoute.actualDistanceKm > 0? recentRoute.actualDistanceKm: recentRoute.routeDistanceKm;setPosts([{id: `recent-${recentRoute.runSessionId}`,routeId: String(recentRoute.routeId),title: recentRoute.title || "완료한 러닝 루트",content: "완료한 러닝 기록입니다.",nickname: "나",createdAt: completedAt,stats: {distance: `${Math.max(0, distance).toFixed(2)}`,achievement: "100",pace: "--'--''",calories: "-",time: "-",bpm: "-",},map: {center: recentRoute.center ?? recentRoute.polyline[0] ?? DEFAULT_MAP_CENTER,polyline: recentRoute.polyline,mode: "nearby",address: "완료한 러닝 기록",},likeCount: 0,likedByMe: false,viewCount: 0,comments: [],}]);setIsCompletedHistory(true);setLoadError(null);setLoadedRouteId(routeId);216 unmodified linesconst placeLabel =isCompletedHistory? "완료한 러닝 기록": route.map?.mode === "manual"? route.map.address || "설정한 지역": "내 주변 러닝 코스";33 unmodified lines<p className="mt-3 text-sm font-medium text-[#63736A]">{placeLabel}</p><p className="mt-4 text-sm text-[#666]">{isCompletedHistory? `완료일: ${formatRelativeKoreanTime(route.createdAt)}`: `작성자: ${route.nickname} · 작성일: ${formatRelativeKoreanTime(route.createdAt)}`}</p></div>51 unmodified lines<section className="rts-card rts-card-flush"><div className="h-[320px] w-full bg-[#f5f5f5]"><LeafletMapcenter={route.map?.center ?? DEFAULT_MAP_CENTER}route={route.map?.polyline}className="h-full w-full"zoom={14}/></div></section>7 unmodified lines["페이스", route.stats.pace],["칼로리", route.stats.calories],["BPM", route.stats.bpm],["난이도", difficulty],["완주율", achievementText],["좋아요", String(likes)],["조회수", String(views)],].map(([label, value]) => (<div key={label} className="min-w-0 py-1"><p className="text-xs font-semibold text-[#737373]">{label}</p>18 unmodified lines1920212223242525 unmodified lines51525354555657216 unmodified lines27427527627727827928033 unmodified lines31431531631731831932051 unmodified lines3723733743753763773783793803813823833843857 unmodified lines39339439539639739839940018 unmodified lines} from "../../_utils/communityApi";import { loadSharedRoutePost, invalidateCommunityRouteData } from "../../_utils/communityRouteData";import CommunityRouteLoading from "../../_components/CommunityRouteLoading";import { readRecentRoutePreview, recentRouteToCommunityPost } from "../../_utils/recentRoutePreview";import { prepareCoursePreview } from "../../_utils/coursePreview";const LeafletMap = dynamic(() => import("../../_components/LeafletMap"), {25 unmodified linesconst recentRoute = readRecentRoutePreview(recentRouteKey);if (recentRoute) {setPosts([recentRouteToCommunityPost(recentRoute)]);setIsCompletedHistory(true);setLoadError(null);setLoadedRouteId(routeId);216 unmodified linesconst placeLabel =isCompletedHistory? route.map?.address || "내 러닝 기록": route.map?.mode === "manual"? route.map.address || "설정한 지역": "내 주변 러닝 코스";33 unmodified lines<p className="mt-3 text-sm font-medium text-[#63736A]">{placeLabel}</p><p className="mt-4 text-sm text-[#666]">{isCompletedHistory? `러닝일: ${formatRelativeKoreanTime(route.createdAt)}`: `작성자: ${route.nickname} · 작성일: ${formatRelativeKoreanTime(route.createdAt)}`}</p></div>51 unmodified lines<section className="rts-card rts-card-flush"><div className="h-[320px] w-full bg-[#f5f5f5]">{isCompletedHistory && !route.map?.polyline?.length ? (<div className="flex h-full items-center justify-center text-sm text-[#737373]">저장된 경로가 없습니다.</div>) : <LeafletMapcenter={route.map?.center ?? DEFAULT_MAP_CENTER}route={route.map?.polyline}className="h-full w-full"zoom={14}/>}</div></section>7 unmodified lines["페이스", route.stats.pace],["칼로리", route.stats.calories],["BPM", route.stats.bpm],["완주율", achievementText],...(!isCompletedHistory ? [["난이도", difficulty], ["좋아요", String(likes)], ["조회수", String(views)]] : []),].map(([label, value]) => (<div key={label} className="min-w-0 py-1"><p className="text-xs font-semibold text-[#737373]">{label}</p>
2122 unmodified lines212321242125212621272128212953 unmodified lines2183218421852186218721882122 unmodified linesaria-haspopup="dialog"aria-controls="run-music-player"><span aria-hidden="true" className="font-sans text-2xl font-bold leading-none">♫</span><span className="text-[11px] font-bold">음악</span></button></div>53 unmodified lineskeepMountedslideswipeToDismissonDismiss={() => setIsMusicPanelOpen(false)}ariaLabelledBy="run-music-title"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"2122 unmodified lines212321242125212621272128212953 unmodified lines21832184218521862187218821892122 unmodified linesaria-haspopup="dialog"aria-controls="run-music-player"><span aria-hidden="true" className="translate-y-[2px] font-sans text-2xl font-bold leading-none">♫</span><span className="text-[11px] font-bold">음악</span></button></div>53 unmodified lineskeepMountedslideswipeToDismissdismissOnBackdroponDismiss={() => setIsMusicPanelOpen(false)}ariaLabelledBy="run-music-title"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"
53 unmodified lines54555657585953 unmodified linesassert.equal((await s.api.reconcileRun()).checkpoint.elapsedSec,45);s = setup(async () => ({active:null}));s.api.storeRun(cp());assert.equal(await s.api.reconcileRun(),null);assert.equal(s.api.readRun().ended,true);53 unmodified lines5455565758596061626353 unmodified linesassert.equal((await s.api.reconcileRun()).checkpoint.elapsedSec,45);s = setup(async () => ({active:null}));s.api.storeRun(cp());assert.equal((await s.api.reconcileRun()).checkpoint.sessionId,'one');assert.equal(s.api.readRun().ended,false,'server absence cannot erase an unuploaded checkpoint');s = setup(async () => ({active:null,ended_session_id:'one'}));s.api.storeRun(cp());assert.equal(await s.api.reconcileRun(),null);assert.equal(s.api.readRun().ended,true);
12 unmodified lines1314151617181940 unmodified lines606162636465666712 unmodified linesconst sessionGuard = read('app/_components/SessionGuard.tsx');assert.doesNotMatch(sessionGuard, /이전 계정으로 로그인하고 있습니다/);assert.match(sessionGuard, /return <>{children}<\/>;/, 'session restore must run behind the visible app shell');const layout = read('app/layout.tsx');assert.doesNotMatch(layout, /러닝 세션 확인 중/);40 unmodified lines'a successful login must request an interrupted-run prompt');const lobby = read('app/lobby/page.tsx');const routeDetail = read('app/route/[id]/page.tsx');assert.match(lobby, /storeRecentRoutePreview/,'completed recent routes must open a detail preview instead of being disabled');assert.doesNotMatch(lobby, /disabled=\{isCompletedRoute\}/,'completed recent route cards must remain tappable');12 unmodified lines1314151617181940 unmodified lines6061626364656667686912 unmodified linesconst sessionGuard = read('app/_components/SessionGuard.tsx');assert.doesNotMatch(sessionGuard, /이전 계정으로 로그인하고 있습니다/);assert.match(sessionGuard, /return \([\s\S]*?\{children\}/, 'session restore must run behind the visible app shell');const layout = read('app/layout.tsx');assert.doesNotMatch(layout, /러닝 세션 확인 중/);40 unmodified lines'a successful login must request an interrupted-run prompt');const lobby = read('app/lobby/page.tsx');const recentRuns = read('app/_components/RecentRuns.tsx');const routeDetail = read('app/route/[id]/page.tsx');assert.match(lobby, /<RecentRuns /);assert.match(recentRuns, /storeRecentRoutePreview/,'completed recent routes must open a detail preview instead of being disabled');assert.doesNotMatch(lobby, /disabled=\{isCompletedRoute\}/,'completed recent route cards must remain tappable');
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151// Exercise actual recovery, history-card actions and private-detail mapping.const assert = require('node:assert/strict');const fs = require('node:fs');const path = require('node:path');const vm = require('node:vm');const ts = require('../main/node_modules/typescript');const root = path.resolve(__dirname, '../main/app');const flush = async () => { for (let i = 0; i < 30; i++) await Promise.resolve(); };const plain = value => JSON.parse(JSON.stringify(value));
function fixture() { const storage = () => { const values = new Map(); return { getItem: key => values.get(key) ?? null, setItem: (key, value) => values.set(key, String(value)), removeItem: key => values.delete(key) }; }; const localStorage = storage(), sessionStorage = storage(); const login = owner => localStorage.setItem('access_token', `e30.${Buffer.from(JSON.stringify({ sub: owner })).toString('base64url')}.fixture`); login('1'); const window = Object.assign(new EventTarget(), { localStorage, sessionStorage }); const states = [], effects = [], dependencies = [], cleanups = [], navigations = [], requests = []; let cursor = 0, fetcher = async () => ({ ok: true, status: 200, json: async () => ({ routes: [] }) }); const react = { useState(initial) { const key = cursor++; if (!(key in states)) states[key] = typeof initial === 'function' ? initial() : initial; return [states[key], next => { states[key] = typeof next === 'function' ? next(states[key]) : next; }]; }, useEffect(effect, deps) { const key = cursor++; if (!dependencies[key] || deps.some((value, i) => !Object.is(value, dependencies[key][i]))) { dependencies[key] = deps; effects.push(() => { cleanups[key]?.(); cleanups[key] = effect(); }); } }, }; const modules = new Map(); function load(relative) { const filename = path.resolve(root, relative); if (modules.has(filename)) return modules.get(filename); const exports = {}; modules.set(filename, exports); const requireFixture = name => { if (name === 'react') return react; if (name === 'react/jsx-runtime') return { jsx: (type, props) => ({ type, props }), jsxs: (type, props) => ({ type, props }) }; if (name === 'next/navigation') return { useRouter: () => ({ push: url => navigations.push(url) }) }; if (name.endsWith('/LeafletMap')) return { __esModule: true, default: 'LeafletMap' }; if (name.endsWith('/sessionRestore')) return { restoreSession: async () => true, getStoredAccessToken: () => localStorage.getItem('access_token'), requestLogin() {}, SESSION_CHANGED_EVENT: 'session-changed', }; const target = path.resolve(path.dirname(filename), name); return load(path.relative(root, target + (fs.existsSync(target + '.ts') ? '.ts' : '.tsx'))); }; const code = ts.transpileModule(fs.readFileSync(filename, 'utf8'), { compilerOptions: { module: ts.ModuleKind.CommonJS, jsx: ts.JsxEmit.ReactJSX, target: ts.ScriptTarget.ES2020, esModuleInterop: true }, }).outputText; vm.runInNewContext(`(function(require,exports){${code}\n})`, { window, localStorage, sessionStorage, Event, URL, URLSearchParams, AbortController, setTimeout, clearTimeout, atob: value => Buffer.from(value, 'base64').toString('utf8'), crypto: { randomUUID: () => 'writer' }, fetch: async (...args) => { requests.push(args); return fetcher(...args); }, process: { env: {} }, }, { filename })(requireFixture, exports); return exports; } const component = load('_components/RecentRuns.tsx').default; return { load, window, login, navigations, requests, sessionStorage, localStorage, fetchWith: next => { fetcher = next; }, render() { cursor = 0; const tree = component({ apiBase: '' }); effects.splice(0).forEach(effect => effect()); return tree; }, dispose() { cleanups.forEach(cleanup => cleanup?.()); }, };}
function nodes(tree, predicate) { if (!tree || typeof tree !== 'object') return []; if (Array.isArray(tree)) return tree.flatMap(child => nodes(child, predicate)); return [...(predicate(tree) ? [tree] : []), ...nodes(tree.props?.children, predicate)];}const button = (tree, label) => nodes(tree, node => node.type === 'button' && node.props['aria-label']?.includes(label))[0];const checkpoint = changes => ({ sessionId: 'running-1', routeId: 'free-run', runUrl: '/run/free-run?runKey=running-1&flowToken=original', mode: 'real', revision: 3, savedAt: Date.now(), elapsedSec: 123, distanceKm: 0.4, isPaused: true, simulationCursor: 0, actualRoute: [[37.5, 127], [37.501, 127]], currentPosition: [37.501, 127], routePayload: {}, guidance: {}, ...changes,});
(async () => { const f = fixture(), recovery = f.load('_utils/activeRun.ts'); const cp = checkpoint(); recovery.storeRun(cp); f.fetchWith(async () => ({ ok: true, status: 200, json: async () => ({ active: null, ended_session_id: null }) })); assert.equal((await recovery.reconcileRun()).checkpoint.sessionId, cp.sessionId, 'server absence preserves a locally saved, unuploaded run'); assert.ok(f.requests[0][0].includes('session_id=running-1')); f.fetchWith(async () => ({ ok: true, status: 200, json: async () => ({ routes: [] }) })); f.render(); await flush(); const resume = button(f.render(), '이어서 달리기'); assert.ok(resume, 'active card is visible alongside completed history'); await resume.props.onClick(); await flush(); assert.equal(f.navigations[0], cp.runUrl, 'resume preserves original runKey, flowToken and checkpoint'); assert.equal(recovery.readRun().checkpoint.elapsedSec, 123); assert.equal(f.requests.filter(([, init]) => init?.method === 'POST').length, 0, 'lobby never creates or resets a session');
f.fetchWith(async () => ({ ok: true, status: 200, json: async () => ({ active: null, ended_session_id: cp.sessionId }) })); assert.equal(await recovery.reconcileRun(), null); assert.equal(recovery.readRun().ended, true); assert.equal(button(f.render(), '이어서 달리기'), undefined, 'terminal session is not resumable'); recovery.storeRun(cp); assert.equal(recovery.readRun().ended, true, 'old data cannot resurrect an ended session'); f.dispose(); console.log('PASS recovery preserves an unuploaded checkpoint, resumes the same session, and respects server termination');
const h = fixture(); const completed = { run_session_id: 8, route_id: null, route_title: '자유 러닝', animal_label: null, actual_distance_km: 0, route_length_km: 5, center_lat: null, center_lng: null, polyline: [], completed_at: '2026-11-09T10:00:00Z', user_rating: null, duration_sec: 123, avg_pace_sec_per_km: null, calories: 12, avg_bpm: 130, achievement_pct: 0, is_completed: true, source: 'nearby', place_text: '서울', }; h.fetchWith(async () => ({ ok: true, status: 200, json: async () => ({ routes: [completed] }) })); h.render(); await flush(); const record = button(h.render(), '러닝 기록 보기'); assert.ok(record, 'a free run without GPS geometry can still open its metrics'); record.props.onClick(); await flush(); const destination = new URL(h.navigations[0], 'https://fixture.invalid'); const previews = h.load('_utils/recentRoutePreview.ts'); const preview = previews.readRecentRoutePreview(destination.searchParams.get('recentRouteKey')); const post = previews.recentRouteToCommunityPost(preview); assert.equal(destination.pathname, '/route/recent-8'); assert.equal(post.stats.distance, '0.00', 'zero actual distance must never fall back to planned distance'); assert.equal(post.stats.time, '02:03'); assert.equal(post.stats.achievement, '0', 'free run has no invented 100% target achievement'); assert.equal(post.stats.calories, '12 kcal'); assert.equal(post.stats.bpm, '130'); assert.equal(post.map.address, '서울'); assert.deepEqual(plain(post.map.polyline), []); const traced = previews.recentRouteToCommunityPost({ ...preview, actualDistanceKm: 2, durationSec: 720, polyline: [[37, 127], [37.1, 127]], isCompleted: false }); assert.equal(traced.stats.pace, "6'00''"); assert.equal(traced.stats.time, '12:00'); assert.ok(traced.content.includes('종료')); h.login('2'); h.window.dispatchEvent(new Event('session-changed')); await flush(); assert.equal(previews.readRecentRoutePreview(destination.searchParams.get('recentRouteKey')), null, 'another account cannot open this private preview'); h.dispose(); console.log('PASS completed/free-run cards open private details with actual metrics, even without geometry');
const race = fixture(); let resolve; race.fetchWith(() => new Promise(done => { resolve = done; })); race.render(); race.login('2'); resolve({ ok: true, status: 200, json: async () => ({ routes: [completed] }) }); await flush(); assert.equal(button(race.render(), '러닝 기록 보기'), undefined, 'in-flight history from another account is discarded'); race.dispose(); console.log('PASS account change during an API response does not expose previous history');})().catch(error => { console.error(error); process.exitCode = 1; });api/auth-service/app/api/v1/endpoints/active_run.py+3-2
api/auth-service/app/api/v1/endpoints/runs.py+39-80
api/auth-service/app/schemas/run.py+9-1
api/auth-service/tests/test_active_run.py+8
api/auth-service/tests/test_recent_runs.pyAdded+75
main/app/_components/ActiveRunGuard.tsx+4-4
main/app/_components/RecentRuns.tsxAdded+234
main/app/_utils/activeRun.ts+7-2
main/app/_utils/recentRoutePreview.ts+71-5
main/app/lobby/page.tsx+12-321
main/app/route/[id]/page.tsx+9-38
main/app/run/[id]/page.tsx+2-1
main/tests/activeRun.cjs+4
main/tests/uiContinuity.cjs+4-2
tools/test-recent-runs.cjsAdded+151