fix(cli): resolve -c by true MRU session

- order session listing by computed last_active in SessionDB so callers get MRU rows directly
- keep _resolve_last_session as a single-row lookup and add regression coverage for >20 session sampling
This commit is contained in:
Brooklyn Nicholson
2026-04-26 22:37:37 -05:00
committed by Teknium
parent 730347e38f
commit 164e33aa46
3 changed files with 157 additions and 6 deletions

View File

@@ -1481,16 +1481,29 @@ class SessionDB:
limit: int = 20,
offset: int = 0,
) -> List[Dict[str, Any]]:
"""List sessions, optionally filtered by source."""
"""List sessions, optionally filtered by source.
Returns rows enriched with a computed ``last_active`` column (latest
message timestamp for the session, falling back to ``started_at``),
ordered by most-recently-used first.
"""
select_last_active = (
"COALESCE("
"(SELECT MAX(m.timestamp) FROM messages m WHERE m.session_id = s.id),"
" s.started_at"
") AS last_active"
)
with self._lock:
if source:
cursor = self._conn.execute(
"SELECT * FROM sessions WHERE source = ? ORDER BY started_at DESC LIMIT ? OFFSET ?",
f"SELECT s.*, {select_last_active} FROM sessions s "
"WHERE s.source = ? ORDER BY last_active DESC, s.started_at DESC, s.id DESC LIMIT ? OFFSET ?",
(source, limit, offset),
)
else:
cursor = self._conn.execute(
"SELECT * FROM sessions ORDER BY started_at DESC LIMIT ? OFFSET ?",
f"SELECT s.*, {select_last_active} FROM sessions s "
"ORDER BY last_active DESC, s.started_at DESC, s.id DESC LIMIT ? OFFSET ?",
(limit, offset),
)
return [dict(row) for row in cursor.fetchall()]