Coverage for src / moai_adk / statusline / metrics_tracker.py: 27.50%

40 statements  

« prev     ^ index     » next       coverage.py v7.12.0, created at 2025-11-20 20:52 +0900

1# type: ignore 

2""" 

3Session metrics tracker for statusline 

4 

5""" 

6 

7import logging 

8from datetime import datetime, timedelta 

9from typing import Optional 

10 

11logger = logging.getLogger(__name__) 

12 

13 

14class MetricsTracker: 

15 """Tracks session duration with 10-second caching""" 

16 

17 # Configuration 

18 _CACHE_TTL_SECONDS = 10 

19 

20 def __init__(self): 

21 """Initialize metrics tracker""" 

22 self._session_start: datetime = datetime.now() 

23 self._duration_cache: Optional[str] = None 

24 self._cache_time: Optional[datetime] = None 

25 self._cache_ttl = timedelta(seconds=self._CACHE_TTL_SECONDS) 

26 

27 def get_duration(self) -> str: 

28 """ 

29 Get formatted session duration 

30 

31 Returns: 

32 Formatted duration string (e.g., "5m", "1h 30m") 

33 """ 

34 # Check cache validity 

35 if self._is_cache_valid(): 

36 return self._duration_cache 

37 

38 # Calculate and format duration 

39 duration = self._calculate_and_format_duration() 

40 self._update_cache(duration) 

41 return duration 

42 

43 def _calculate_and_format_duration(self) -> str: 

44 """ 

45 Calculate session duration and format it 

46 

47 Returns: 

48 Formatted duration string 

49 """ 

50 elapsed = datetime.now() - self._session_start 

51 total_seconds = int(elapsed.total_seconds()) 

52 

53 # Format based on duration range 

54 if total_seconds < 60: 

55 return f"{total_seconds}s" 

56 elif total_seconds < 3600: 

57 minutes = total_seconds // 60 

58 seconds = total_seconds % 60 

59 if seconds > 0: 

60 return f"{minutes}m {seconds}s" 

61 return f"{minutes}m" 

62 else: 

63 hours = total_seconds // 3600 

64 minutes = (total_seconds % 3600) // 60 

65 if minutes > 0: 

66 return f"{hours}h {minutes}m" 

67 return f"{hours}h" 

68 

69 def _is_cache_valid(self) -> bool: 

70 """Check if duration cache is still valid""" 

71 if self._duration_cache is None or self._cache_time is None: 

72 return False 

73 return datetime.now() - self._cache_time < self._cache_ttl 

74 

75 def _update_cache(self, duration: str) -> None: 

76 """Update duration cache""" 

77 self._duration_cache = duration 

78 self._cache_time = datetime.now()