Skip to content

The agent that grows with you

Add dashboard session filtering

Shannon Sandscb0049555114
diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.py
index 763aa496614..b58af30d39c 100644
--- a/hermes_cli/web_server.py
+++ b/hermes_cli/web_server.py
@@ -4891,6 +4891,7 @@ def get_sessions(
archived: str = "exclude",
order: str = "created",
source: str = None,
+ sources: str = None,
exclude_sources: str = None,
cwd_prefix: str = None,
full: bool = False,
@@ -4935,12 +4936,15 @@ def get_sessions(
archived_only = archived == "only"
include_archived = archived == "include"
# Optional source scoping: ``source`` includes a single class,
+ # ``sources`` includes any of several comma-separated classes, and
# ``exclude_sources`` (comma-separated) drops classes. The desktop
# uses these to split recents (exclude=cron) from the cron-jobs
# section (source=cron) into two independent lists.
- exclude_list = [s for s in (exclude_sources or "").split(",") if s.strip()]
+ source_list = [s.strip() for s in (sources or "").split(",") if s.strip()]
+ exclude_list = [s.strip() for s in (exclude_sources or "").split(",") if s.strip()]
sessions = db.list_sessions_rich(
source=source or None,
+ sources=source_list or None,
exclude_sources=exclude_list or None,
cwd_prefix=(cwd_prefix or None),
limit=limit,
@@ -4956,6 +4960,7 @@ def get_sessions(
)
total = db.session_count(
source=source or None,
+ sources=source_list or None,
cwd_prefix=(cwd_prefix or None),
exclude_sources=exclude_list or None,
min_message_count=min_message_count,
@@ -4995,6 +5000,7 @@ def get_profiles_sessions(
order: str = "recent",
profile: str = "all",
source: str = None,
+ sources: str = None,
exclude_sources: str = None,
full: bool = False,
):
@@ -5039,7 +5045,8 @@ def get_profiles_sessions(
# the cron-jobs section passes source=cron — two independent lists so
# newest cron sessions can't starve the recents page.
source_filter = source or None
- exclude_list = [s for s in (exclude_sources or "").split(",") if s.strip()]
+ source_list = [s.strip() for s in (sources or "").split(",") if s.strip()]
+ exclude_list = [s.strip() for s in (exclude_sources or "").split(",") if s.strip()]
# Over-fetch per profile so the merged+sorted window is correct for the
# requested page. Capped so a huge profile can't blow up the response.
per_profile = min(max(limit + offset, limit), 500)
@@ -5064,6 +5071,7 @@ def get_profiles_sessions(
try:
rows = db.list_sessions_rich(
source=source_filter,
+ sources=source_list or None,
exclude_sources=exclude_list or None,
limit=per_profile,
offset=0,
@@ -5076,6 +5084,7 @@ def get_profiles_sessions(
)
profile_total = db.session_count(
source=source_filter,
+ sources=source_list or None,
exclude_sources=exclude_list or None,
min_message_count=min_message_count,
include_archived=include_archived,
@@ -5240,7 +5249,14 @@ def get_profiles_sessions_sidebar(
@app.get("/api/sessions/search")
-async def search_sessions(q: str = "", limit: int = 20, profile: Optional[str] = None):
+async def search_sessions(
+ q: str = "",
+ limit: int = 20,
+ profile: Optional[str] = None,
+ source: str = None,
+ sources: str = None,
+ exclude_sources: str = None,
+):
"""Search sessions by ID plus full-text message content using FTS5.
Direct session-id matches are surfaced first, then FTS message-content
@@ -5257,6 +5273,11 @@ async def search_sessions(q: str = "", limit: int = 20, profile: Optional[str] =
db = _open_session_db_for_profile(profile)
try:
safe_limit = max(1, min(int(limit or 20), 100))
+ source_filter = source or None
+ source_list = [s.strip() for s in (sources or "").split(",") if s.strip()]
+ include_sources = [source_filter] if source_filter else (source_list or None)
+ exclude_list = [s.strip() for s in (exclude_sources or "").split(",") if s.strip()]
+ now = time.time()
# Walk parent_session_id to the compression root, memoized so a
# chain of compression segments only costs one walk. We deliberately
@@ -5341,15 +5362,52 @@ async def search_sessions(q: str = "", limit: int = 20, profile: Optional[str] =
if root in seen or len(seen) >= safe_limit:
return
payload = dict(payload)
- payload["session_id"] = lineage_tip(root)
+ sid = lineage_tip(root)
+ payload["session_id"] = sid
payload["lineage_root"] = root
+ try:
+ row = db._get_session_rich_row(sid)
+ except Exception:
+ row = None
+ if row:
+ payload.update(
+ {
+ "id": row.get("id") or sid,
+ "source": row.get("source"),
+ "model": row.get("model"),
+ "title": row.get("title"),
+ "started_at": row.get("started_at"),
+ "ended_at": row.get("ended_at"),
+ "last_active": row.get("last_active") or row.get("started_at"),
+ "is_active": (
+ row.get("ended_at") is None
+ and (now - (row.get("last_active") or row.get("started_at") or 0)) < 300
+ ),
+ "message_count": row.get("message_count") or 0,
+ "tool_call_count": row.get("tool_call_count") or 0,
+ "input_tokens": row.get("input_tokens") or 0,
+ "output_tokens": row.get("output_tokens") or 0,
+ "preview": row.get("preview"),
+ "parent_session_id": row.get("parent_session_id"),
+ "archived": bool(row.get("archived")),
+ }
+ )
+ else:
+ payload["id"] = sid
seen[root] = payload
# Direct ID matches first: users often paste a session id from CLI,
# logs, or another Hermes surface. FTS can't find those unless the
# id happens to appear in message text. search_sessions_by_id is
# SQL-bounded, so this stays cheap even with thousands of sessions.
- for row in db.search_sessions_by_id(q, limit=safe_limit, include_archived=True):
+ for row in db.search_sessions_by_id(
+ q,
+ limit=safe_limit,
+ include_archived=True,
+ source=source_filter,
+ sources=source_list or None,
+ exclude_sources=exclude_list or None,
+ ):
sid = row.get("id")
preview = (row.get("preview") or "").strip()
snippet = preview or f"Session ID: {sid}"
@@ -5378,7 +5436,12 @@ async def search_sessions(q: str = "", limit: int = 20, profile: Optional[str] =
# Over-fetch so lineage dedup can still surface `limit` distinct
# conversations even when several hits collapse onto one root.
fetch_limit = max(safe_limit * 5, 50)
- matches = db.search_messages(query=prefix_query, limit=fetch_limit)
+ matches = db.search_messages(
+ query=prefix_query,
+ source_filter=include_sources,
+ exclude_sources=exclude_list or None,
+ limit=fetch_limit,
+ )
for m in matches:
if len(seen) >= safe_limit:
diff --git a/hermes_state.py b/hermes_state.py
index 743db7ae394..a1f5cba8022 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -6477,6 +6477,7 @@ class SessionDB:
def list_sessions_rich(
self,
source: str = None,
+ sources: List[str] = None,
exclude_sources: List[str] = None,
cwd_prefix: str = None,
limit: int = 20,
@@ -6554,9 +6555,11 @@ class SessionDB:
where_clauses.append(_LISTABLE_CHILD_SQL)
where_clauses.append(f"{_delegate_from_json('s.model_config')} IS NULL")
- if source:
- where_clauses.append("s.source = ?")
- params.append(source)
+ include_sources = [source] if source else list(sources or [])
+ if include_sources:
+ placeholders = ",".join("?" for _ in include_sources)
+ where_clauses.append(f"s.source IN ({placeholders})")
+ params.extend(include_sources)
if exclude_sources:
placeholders = ",".join("?" for _ in exclude_sources)
where_clauses.append(f"s.source NOT IN ({placeholders})")
@@ -9243,6 +9246,9 @@ class SessionDB:
query: str,
limit: int = 20,
include_archived: bool = True,
+ source: str = None,
+ sources: List[str] = None,
+ exclude_sources: List[str] = None,
) -> List[Dict[str, Any]]:
"""Search surfaced sessions by exact/prefix/substring session id.
@@ -9263,6 +9269,9 @@ class SessionDB:
# in-Python exact/prefix/substring ranking below has enough candidates
# to order, then truncate.
candidates = self.list_sessions_rich(
+ source=source,
+ sources=sources,
+ exclude_sources=exclude_sources,
limit=max(limit * 4, limit),
offset=0,
include_archived=include_archived,
@@ -9338,6 +9347,7 @@ class SessionDB:
def session_count(
self,
source: str = None,
+ sources: List[str] = None,
cwd_prefix: str = None,
min_message_count: int = 0,
include_archived: bool = False,
@@ -9368,9 +9378,11 @@ class SessionDB:
# children (parent ended with end_reason='branched').
where_clauses.append(_LISTABLE_CHILD_SQL)
where_clauses.append(f"{_delegate_from_json('s.model_config')} IS NULL")
- if source:
- where_clauses.append("s.source = ?")
- params.append(source)
+ include_sources = [source] if source else list(sources or [])
+ if include_sources:
+ placeholders = ",".join("?" for _ in include_sources)
+ where_clauses.append(f"s.source IN ({placeholders})")
+ params.extend(include_sources)
if exclude_sources:
placeholders = ",".join("?" for _ in exclude_sources)
where_clauses.append(f"s.source NOT IN ({placeholders})")
diff --git a/tests/hermes_cli/test_web_server.py b/tests/hermes_cli/test_web_server.py
index 868e609e988..0acb0cb6956 100644
--- a/tests/hermes_cli/test_web_server.py
+++ b/tests/hermes_cli/test_web_server.py
@@ -2438,6 +2438,36 @@ class TestWebServerEndpoints:
resp = self.client.get("/api/sessions?order=sideways")
assert resp.status_code == 400
+ def test_get_sessions_source_filters_match_totals(self):
+ from hermes_state import SessionDB
+
+ db = SessionDB()
+ try:
+ db.create_session(session_id="chat-session", source="cli")
+ db.create_session(session_id="cron-session", source="cron")
+ db.create_session(session_id="tool-session", source="tool")
+ db.create_session(session_id="api-session", source="api_server")
+ db.create_session(session_id="acp-session", source="acp")
+ finally:
+ db.close()
+
+ chats = self.client.get(
+ "/api/sessions?exclude_sources=cron,tool,api_server,acp&limit=10"
+ ).json()
+ assert chats["total"] == 1
+ assert [s["id"] for s in chats["sessions"]] == ["chat-session"]
+
+ automation = self.client.get(
+ "/api/sessions?sources=cron,tool,api_server,acp&limit=10"
+ ).json()
+ assert automation["total"] == 4
+ assert {s["id"] for s in automation["sessions"]} == {
+ "cron-session",
+ "tool-session",
+ "api-session",
+ "acp-session",
+ }
+
def test_get_sessions_order_recent_surfaces_compression_tip(self):
"""A long-running conversation that auto-compresses must stay on the
first page by recency, listed under its live continuation id."""
@@ -2549,6 +2579,55 @@ class TestWebServerEndpoints:
for r in results
)
+ def test_search_sessions_respects_source_filters_for_messages_and_ids(self):
+ from hermes_state import SessionDB
+
+ db = SessionDB()
+ try:
+ db.create_session(session_id="filter-chat-id", source="cli")
+ db.append_message(
+ session_id="filter-chat-id",
+ role="user",
+ content="filterneedle human question",
+ )
+ db.create_session(session_id="filter-cron-id", source="cron")
+ db.append_message(
+ session_id="filter-cron-id",
+ role="user",
+ content="filterneedle scheduled run",
+ )
+ db.create_session(session_id="idmatch-chat", source="cli")
+ db.append_message(session_id="idmatch-chat", role="user", content="ordinary")
+ db.create_session(session_id="idmatch-cron", source="cron")
+ db.append_message(session_id="idmatch-cron", role="user", content="ordinary")
+ finally:
+ db.close()
+
+ message_resp = self.client.get(
+ "/api/sessions/search?q=filterneedle&exclude_sources=cron"
+ )
+ assert message_resp.status_code == 200
+ message_results = message_resp.json()["results"]
+ assert {r["session_id"] for r in message_results} == {"filter-chat-id"}
+ assert message_results[0]["id"] == "filter-chat-id"
+ assert "message_count" in message_results[0]
+
+ id_resp = self.client.get(
+ "/api/sessions/search?q=idmatch&exclude_sources=cron"
+ )
+ assert id_resp.status_code == 200
+ assert {r["session_id"] for r in id_resp.json()["results"]} == {
+ "idmatch-chat"
+ }
+
+ automation_resp = self.client.get(
+ "/api/sessions/search?q=idmatch&sources=cron"
+ )
+ assert automation_resp.status_code == 200
+ assert {r["session_id"] for r in automation_resp.json()["results"]} == {
+ "idmatch-cron"
+ }
+
def test_get_session_messages_follows_compression_tip(self):
"""Reading a compressed session by its old id should hydrate from the
live continuation, matching /resume behavior."""
diff --git a/tests/test_hermes_state.py b/tests/test_hermes_state.py
index 2b503e0ede9..89017c6d4ce 100644
--- a/tests/test_hermes_state.py
+++ b/tests/test_hermes_state.py
@@ -5267,6 +5267,18 @@ class TestExcludeSources:
assert "s2" not in ids
assert "s3" not in ids
+ def test_list_sessions_rich_includes_multiple_sources(self, db):
+ db.create_session("s1", "cli")
+ db.create_session("s2", "tool")
+ db.create_session("s3", "cron")
+ db.create_session("s4", "telegram")
+
+ sessions = db.list_sessions_rich(sources=["tool", "cron"])
+ ids = {s["id"] for s in sessions}
+
+ assert ids == {"s2", "s3"}
+ assert db.session_count(sources=["tool", "cron"]) == 2
+
def test_search_messages_excludes_tool_source(self, db):
db.create_session("s1", "cli")
db.append_message("s1", "user", "Python deployment question")
@@ -7038,8 +7050,8 @@ class TestSessionPinAndStaleArchive:
class TestSessionIdSearch:
"""Session id search backs Desktop's Search Sessions UX."""
- def _seed(self, db, sid, *, content="ordinary message", archived=False):
- db.create_session(session_id=sid, source="cli", model="test-model")
+ def _seed(self, db, sid, *, content="ordinary message", archived=False, source="cli"):
+ db.create_session(session_id=sid, source=source, model="test-model")
db.append_message(session_id=sid, role="user", content=content)
if archived:
db.set_session_archived(sid, True)
@@ -7087,6 +7099,29 @@ class TestSessionIdSearch:
assert [s["id"] for s in matches] == [tip]
assert matches[0]["_lineage_root_id"] == root
+ def test_search_sessions_by_id_respects_source_filters(self, db):
+ self._seed(db, "20260603_090200_cli")
+ self._seed(db, "20260603_090200_cron", source="cron")
+ self._seed(db, "20260603_090200_tool", source="tool")
+
+ automation = {
+ s["id"]
+ for s in db.search_sessions_by_id(
+ "20260603_090200",
+ sources=["cron", "tool"],
+ )
+ }
+ chats = {
+ s["id"]
+ for s in db.search_sessions_by_id(
+ "20260603_090200",
+ exclude_sources=["cron", "tool"],
+ )
+ }
+
+ assert automation == {"20260603_090200_cron", "20260603_090200_tool"}
+ assert chats == {"20260603_090200_cli"}
+
class TestListCronJobRuns:
"""``list_cron_job_runs`` powers the desktop cron run-history endpoint.
diff --git a/web/src/i18n/af.ts b/web/src/i18n/af.ts
index 8a7c8a1b96e..d7c16c1bd92 100644
--- a/web/src/i18n/af.ts
+++ b/web/src/i18n/af.ts
@@ -129,8 +129,14 @@ export const af: Translations = {
title: "Sessies",
history: "Geskiedenis",
overview: "Oorsig",
+ filterChats: "Chats",
+ filterAutomation: "Automation",
+ filterAll: "All",
+ sourceFilter: "Session source",
+ anySource: "Any source",
searchPlaceholder: "Soek boodskap-inhoud...",
noSessions: "Nog geen sessies nie",
+ noSessionsInFilter: "No sessions in this filter",
noMatch: "Geen sessies stem ooreen met jou soektog nie",
startConversation: "Begin 'n gesprek om dit hier te sien",
noMessages: "Geen boodskappe",
diff --git a/web/src/i18n/de.ts b/web/src/i18n/de.ts
index 4a5bcb23461..5057497fec1 100644
--- a/web/src/i18n/de.ts
+++ b/web/src/i18n/de.ts
@@ -129,8 +129,14 @@ export const de: Translations = {
title: "Sitzungen",
history: "Verlauf",
overview: "Übersicht",
+ filterChats: "Chats",
+ filterAutomation: "Automation",
+ filterAll: "All",
+ sourceFilter: "Session source",
+ anySource: "Any source",
searchPlaceholder: "Nachrichteninhalt suchen...",
noSessions: "Noch keine Sitzungen",
+ noSessionsInFilter: "No sessions in this filter",
noMatch: "Keine Sitzungen entsprechen deiner Suche",
startConversation: "Starte eine Unterhaltung, um sie hier zu sehen",
noMessages: "Keine Nachrichten",
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts
index 38c61a15ca3..dda0dd0e937 100644
--- a/web/src/i18n/en.ts
+++ b/web/src/i18n/en.ts
@@ -144,8 +144,14 @@ export const en: Translations = {
title: "Sessions",
history: "History",
overview: "Overview",
+ filterChats: "Chats",
+ filterAutomation: "Automation",
+ filterAll: "All",
+ sourceFilter: "Session source",
+ anySource: "Any source",
searchPlaceholder: "Search message content...",
noSessions: "No sessions yet",
+ noSessionsInFilter: "No sessions in this filter",
noMatch: "No sessions match your search",
startConversation: "Start a conversation to see it here",
noMessages: "No messages",
diff --git a/web/src/i18n/es.ts b/web/src/i18n/es.ts
index fd209b5c1d6..6fa3300961e 100644
--- a/web/src/i18n/es.ts
+++ b/web/src/i18n/es.ts
@@ -129,8 +129,14 @@ export const es: Translations = {
title: "Sesiones",
history: "Historial",
overview: "Resumen",
+ filterChats: "Chats",
+ filterAutomation: "Automation",
+ filterAll: "All",
+ sourceFilter: "Session source",
+ anySource: "Any source",
searchPlaceholder: "Buscar contenido de mensajes...",
noSessions: "Aún no hay sesiones",
+ noSessionsInFilter: "No sessions in this filter",
noMatch: "Ninguna sesión coincide con tu búsqueda",
startConversation: "Inicia una conversación para verla aquí",
noMessages: "Sin mensajes",
diff --git a/web/src/i18n/fr.ts b/web/src/i18n/fr.ts
index f822232cc69..7900000e42f 100644
--- a/web/src/i18n/fr.ts
+++ b/web/src/i18n/fr.ts
@@ -129,8 +129,14 @@ export const fr: Translations = {
title: "Sessions",
history: "Historique",
overview: "Aperçu",
+ filterChats: "Chats",
+ filterAutomation: "Automation",
+ filterAll: "All",
+ sourceFilter: "Session source",
+ anySource: "Any source",
searchPlaceholder: "Rechercher dans les messages...",
noSessions: "Aucune session pour l'instant",
+ noSessionsInFilter: "No sessions in this filter",
noMatch: "Aucune session ne correspond à votre recherche",
startConversation: "Démarrez une conversation pour la voir ici",
noMessages: "Aucun message",
diff --git a/web/src/i18n/ga.ts b/web/src/i18n/ga.ts
index 7f7f82ef191..8762c8eaf18 100644
--- a/web/src/i18n/ga.ts
+++ b/web/src/i18n/ga.ts
@@ -129,8 +129,14 @@ export const ga: Translations = {
title: "Seisiúin",
history: "Stair",
overview: "Forbhreathnú",
+ filterChats: "Chats",
+ filterAutomation: "Automation",
+ filterAll: "All",
+ sourceFilter: "Session source",
+ anySource: "Any source",
searchPlaceholder: "Cuardaigh ábhar teachtaireachta...",
noSessions: "Gan seisiúin go fóill",
+ noSessionsInFilter: "No sessions in this filter",
noMatch: "Níl seisiún ar bith ag teacht le do chuardach",
startConversation: "Tosaigh comhrá chun é a fheiceáil anseo",
noMessages: "Gan teachtaireachtaí",
diff --git a/web/src/i18n/hu.ts b/web/src/i18n/hu.ts
index beab21dcc8d..02f7e16dbb9 100644
--- a/web/src/i18n/hu.ts
+++ b/web/src/i18n/hu.ts
@@ -129,8 +129,14 @@ export const hu: Translations = {
title: "Munkamenetek",
history: "Előzmények",
overview: "Áttekintés",
+ filterChats: "Chats",
+ filterAutomation: "Automation",
+ filterAll: "All",
+ sourceFilter: "Session source",
+ anySource: "Any source",
searchPlaceholder: "Keresés üzenettartalomban...",
noSessions: "Még nincsenek munkamenetek",
+ noSessionsInFilter: "No sessions in this filter",
noMatch: "Nincs a keresésnek megfelelő munkamenet",
startConversation: "Indítson egy beszélgetést, hogy itt megjelenjen",
noMessages: "Nincsenek üzenetek",
diff --git a/web/src/i18n/it.ts b/web/src/i18n/it.ts
index beb22f5f0df..42d90b0193b 100644
--- a/web/src/i18n/it.ts
+++ b/web/src/i18n/it.ts
@@ -129,8 +129,14 @@ export const it: Translations = {
title: "Sessioni",
history: "Cronologia",
overview: "Panoramica",
+ filterChats: "Chats",
+ filterAutomation: "Automation",
+ filterAll: "All",
+ sourceFilter: "Session source",
+ anySource: "Any source",
searchPlaceholder: "Cerca nel contenuto dei messaggi...",
noSessions: "Nessuna sessione",
+ noSessionsInFilter: "No sessions in this filter",
noMatch: "Nessuna sessione corrisponde alla ricerca",
startConversation: "Avvia una conversazione per vederla qui",
noMessages: "Nessun messaggio",
diff --git a/web/src/i18n/ja.ts b/web/src/i18n/ja.ts
index b3bb658a329..f0200b4bc09 100644
--- a/web/src/i18n/ja.ts
+++ b/web/src/i18n/ja.ts
@@ -129,8 +129,14 @@ export const ja: Translations = {
title: "セッション",
history: "履歴",
overview: "概要",
+ filterChats: "Chats",
+ filterAutomation: "Automation",
+ filterAll: "All",
+ sourceFilter: "Session source",
+ anySource: "Any source",
searchPlaceholder: "メッセージ内容を検索...",
noSessions: "まだセッションがありません",
+ noSessionsInFilter: "No sessions in this filter",
noMatch: "検索条件に一致するセッションはありません",
startConversation: "会話を開始するとここに表示されます",
noMessages: "メッセージがありません",
diff --git a/web/src/i18n/ko.ts b/web/src/i18n/ko.ts
index adac224948c..7d5d96e4e1b 100644
--- a/web/src/i18n/ko.ts
+++ b/web/src/i18n/ko.ts
@@ -129,8 +129,14 @@ export const ko: Translations = {
title: "세션",
history: "기록",
overview: "개요",
+ filterChats: "Chats",
+ filterAutomation: "Automation",
+ filterAll: "All",
+ sourceFilter: "Session source",
+ anySource: "Any source",
searchPlaceholder: "메시지 내용 검색...",
noSessions: "아직 세션이 없습니다",
+ noSessionsInFilter: "No sessions in this filter",
noMatch: "검색과 일치하는 세션이 없습니다",
startConversation: "대화를 시작하면 여기에 표시됩니다",
noMessages: "메시지가 없습니다",
diff --git a/web/src/i18n/pt.ts b/web/src/i18n/pt.ts
index 7e2513f4a9e..d625c3927d6 100644
--- a/web/src/i18n/pt.ts
+++ b/web/src/i18n/pt.ts
@@ -129,8 +129,14 @@ export const pt: Translations = {
title: "Sessões",
history: "Histórico",
overview: "Visão geral",
+ filterChats: "Chats",
+ filterAutomation: "Automation",
+ filterAll: "All",
+ sourceFilter: "Session source",
+ anySource: "Any source",
searchPlaceholder: "Pesquisar conteúdo das mensagens...",
noSessions: "Ainda não há sessões",
+ noSessionsInFilter: "No sessions in this filter",
noMatch: "Nenhuma sessão corresponde à pesquisa",
startConversation: "Inicie uma conversa para a ver aqui",
noMessages: "Sem mensagens",
diff --git a/web/src/i18n/ru.ts b/web/src/i18n/ru.ts
index c8db540f11d..3a4fb049902 100644
--- a/web/src/i18n/ru.ts
+++ b/web/src/i18n/ru.ts
@@ -129,8 +129,14 @@ export const ru: Translations = {
title: "Сессии",
history: "История",
overview: "Обзор",
+ filterChats: "Chats",
+ filterAutomation: "Automation",
+ filterAll: "All",
+ sourceFilter: "Session source",
+ anySource: "Any source",
searchPlaceholder: "Поиск по содержимому сообщений...",
noSessions: "Сессий пока нет",
+ noSessionsInFilter: "No sessions in this filter",
noMatch: "Нет сессий, соответствующих запросу",
startConversation: "Начните разговор, чтобы увидеть его здесь",
noMessages: "Нет сообщений",
diff --git a/web/src/i18n/tr.ts b/web/src/i18n/tr.ts
index dc9a62894b1..fc470fb9b64 100644
--- a/web/src/i18n/tr.ts
+++ b/web/src/i18n/tr.ts
@@ -129,8 +129,14 @@ export const tr: Translations = {
title: "Oturumlar",
history: "Geçmiş",
overview: "Genel bakış",
+ filterChats: "Chats",
+ filterAutomation: "Automation",
+ filterAll: "All",
+ sourceFilter: "Session source",
+ anySource: "Any source",
searchPlaceholder: "Mesaj içeriğinde ara...",
noSessions: "Henüz oturum yok",
+ noSessionsInFilter: "No sessions in this filter",
noMatch: "Aramanızla eşleşen oturum yok",
startConversation: "Burada görmek için bir konuşma başlatın",
noMessages: "Mesaj yok",
diff --git a/web/src/i18n/types.ts b/web/src/i18n/types.ts
index 1991a20f51d..5c79a937e5f 100644
--- a/web/src/i18n/types.ts
+++ b/web/src/i18n/types.ts
@@ -162,8 +162,14 @@ export interface Translations {
title: string;
history: string;
overview: string;
+ filterChats: string;
+ filterAutomation: string;
+ filterAll: string;
+ sourceFilter: string;
+ anySource: string;
searchPlaceholder: string;
noSessions: string;
+ noSessionsInFilter: string;
noMatch: string;
startConversation: string;
noMessages: string;
diff --git a/web/src/i18n/uk.ts b/web/src/i18n/uk.ts
index 7cf91b02480..1ed996d6c38 100644
--- a/web/src/i18n/uk.ts
+++ b/web/src/i18n/uk.ts
@@ -129,8 +129,14 @@ export const uk: Translations = {
title: "Сесії",
history: "Історія",
overview: "Огляд",
+ filterChats: "Chats",
+ filterAutomation: "Automation",
+ filterAll: "All",
+ sourceFilter: "Session source",
+ anySource: "Any source",
searchPlaceholder: "Пошук у вмісті повідомлень...",
noSessions: "Поки немає сесій",
+ noSessionsInFilter: "No sessions in this filter",
noMatch: "Жодна сесія не відповідає вашому пошуку",
startConversation: "Почніть розмову, щоб побачити її тут",
noMessages: "Немає повідомлень",
diff --git a/web/src/i18n/zh-hant.ts b/web/src/i18n/zh-hant.ts
index eeb72988ca1..675c4997a40 100644
--- a/web/src/i18n/zh-hant.ts
+++ b/web/src/i18n/zh-hant.ts
@@ -129,8 +129,14 @@ export const zhHant: Translations = {
title: "工作階段",
history: "歷史",
overview: "總覽",
+ filterChats: "Chats",
+ filterAutomation: "Automation",
+ filterAll: "All",
+ sourceFilter: "Session source",
+ anySource: "Any source",
searchPlaceholder: "搜尋訊息內容...",
noSessions: "尚無工作階段",
+ noSessionsInFilter: "No sessions in this filter",
noMatch: "沒有符合的工作階段",
startConversation: "開始對話後將顯示於此",
noMessages: "尚無訊息",
diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts
index 4cf821c85aa..f34a96273e7 100644
--- a/web/src/i18n/zh.ts
+++ b/web/src/i18n/zh.ts
@@ -128,8 +128,14 @@ export const zh: Translations = {
title: "会话",
history: "历史",
overview: "概览",
+ filterChats: "Chats",
+ filterAutomation: "Automation",
+ filterAll: "All",
+ sourceFilter: "Session source",
+ anySource: "Any source",
searchPlaceholder: "搜索消息内容...",
noSessions: "暂无会话",
+ noSessionsInFilter: "No sessions in this filter",
noMatch: "没有匹配的会话",
startConversation: "开始对话后将显示在此处",
noMessages: "暂无消息",
diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts
index 06a919826fa..0d83cdefda0 100644
--- a/web/src/lib/api.ts
+++ b/web/src/lib/api.ts
@@ -304,6 +304,45 @@ function appendProfileParam(url: string, profile?: string): string {
return `${url}${url.includes("?") ? "&" : "?"}profile=${encodeURIComponent(profile)}`;
}
+function appendQueryParam(url: string, key: string, value?: string): string {
+ if (!value) return url;
+ return `${url}${url.includes("?") ? "&" : "?"}${key}=${encodeURIComponent(value)}`;
+}
+
+export interface SessionQueryOptions {
+ profile?: string;
+ order?: "created" | "recent";
+ source?: string | null;
+ sources?: string[];
+ excludeSources?: string[];
+}
+
+function normalizeSessionQueryOptions(
+ profileOrOptions?: string | SessionQueryOptions,
+ order: "created" | "recent" = "created",
+): SessionQueryOptions {
+ if (typeof profileOrOptions === "string") {
+ return { profile: profileOrOptions, order };
+ }
+ return {
+ profile: getManagementProfile(),
+ order,
+ ...(profileOrOptions ?? {}),
+ };
+}
+
+function appendSessionFilters(url: string, options: SessionQueryOptions): string {
+ let next = url;
+ next = appendQueryParam(next, "source", options.source ?? undefined);
+ if (options.sources && options.sources.length > 0) {
+ next = appendQueryParam(next, "sources", options.sources.join(","));
+ }
+ if (options.excludeSources && options.excludeSources.length > 0) {
+ next = appendQueryParam(next, "exclude_sources", options.excludeSources.join(","));
+ }
+ return appendProfileParam(next, options.profile);
+}
+
export const api = {
buildWsUrl,
getStatus: () => fetchJSON<StatusResponse>("/api/status"),
@@ -342,15 +381,17 @@ export const api = {
getSessions: (
limit = 20,
offset = 0,
- profile = getManagementProfile(),
+ profileOrOptions: string | SessionQueryOptions = getManagementProfile(),
order: "created" | "recent" = "created",
- ) =>
- fetchJSON<PaginatedSessions>(
- appendProfileParam(
- `/api/sessions?limit=${limit}&offset=${offset}&order=${order}`,
- profile,
+ ) => {
+ const options = normalizeSessionQueryOptions(profileOrOptions, order);
+ return fetchJSON<PaginatedSessions>(
+ appendSessionFilters(
+ `/api/sessions?limit=${limit}&offset=${offset}&order=${options.order ?? order}`,
+ options,
),
- ),
+ );
+ },
getSessionMessages: (id: string, profile = getManagementProfile()) =>
fetchJSON<SessionMessagesResponse>(
appendProfileParam(`/api/sessions/${encodeURIComponent(id)}/messages`, profile),
@@ -773,10 +814,18 @@ export const api = {
),
// Session search (FTS5)
- searchSessions: (q: string, profile = getManagementProfile()) =>
- fetchJSON<SessionSearchResponse>(
- appendProfileParam(`/api/sessions/search?q=${encodeURIComponent(q)}`, profile),
- ),
+ searchSessions: (
+ q: string,
+ profileOrOptions: string | SessionQueryOptions = getManagementProfile(),
+ ) => {
+ const options = normalizeSessionQueryOptions(profileOrOptions);
+ return fetchJSON<SessionSearchResponse>(
+ appendSessionFilters(
+ `/api/sessions/search?q=${encodeURIComponent(q)}`,
+ options,
+ ),
+ );
+ },
// OAuth provider management
getOAuthProviders: () =>
@@ -2265,13 +2314,12 @@ export interface ToolsetEnvResult {
is_set: Record<string, boolean>;
}
-export interface SessionSearchResult {
+export interface SessionSearchResult extends SessionInfo {
session_id: string;
snippet: string;
role: string | null;
- source: string | null;
- model: string | null;
session_started: number | null;
+ lineage_root?: string;
}
export interface SessionSearchResponse {
diff --git a/web/src/pages/SessionsPage.tsx b/web/src/pages/SessionsPage.tsx
index f14ebee63dd..50e48d8c9a8 100644
--- a/web/src/pages/SessionsPage.tsx
+++ b/web/src/pages/SessionsPage.tsx
@@ -1,6 +1,7 @@
import {
useEffect,
useLayoutEffect,
+ useMemo,
useState,
useCallback,
useRef,
@@ -13,6 +14,7 @@ import {
ChevronLeft,
ChevronRight,
Database,
+ ListFilter,
MessageSquare,
Search,
Trash2,
@@ -75,13 +77,94 @@ import { isDashboardEmbeddedChatEnabled } from "@/lib/dashboard-flags";
const SOURCE_CONFIG: Record<string, { icon: typeof Terminal; color: string }> =
{
cli: { icon: Terminal, color: "text-primary" },
+ tui: { icon: Terminal, color: "text-primary" },
telegram: { icon: MessageCircle, color: "text-[oklch(0.65_0.15_250)]" },
discord: { icon: Hash, color: "text-[oklch(0.65_0.15_280)]" },
slack: { icon: MessageSquare, color: "text-[oklch(0.7_0.15_155)]" },
whatsapp: { icon: Globe, color: "text-success" },
+ whatsapp_cloud: { icon: Globe, color: "text-success" },
+ signal: { icon: MessageCircle, color: "text-success" },
+ matrix: { icon: MessageCircle, color: "text-[oklch(0.65_0.15_250)]" },
+ email: { icon: MessageSquare, color: "text-[oklch(0.7_0.15_155)]" },
+ sms: { icon: MessageCircle, color: "text-success" },
cron: { icon: Clock, color: "text-warning" },
+ tool: { icon: Play, color: "text-warning" },
+ api_server: { icon: Globe, color: "text-muted-foreground" },
+ acp: { icon: Database, color: "text-muted-foreground" },
+ hermes_flow: { icon: Play, color: "text-warning" },
+ vulcan_delegate: { icon: Play, color: "text-warning" },
+ webhook: { icon: Globe, color: "text-warning" },
};
+const AUTOMATION_SESSION_SOURCES = [
+ "cron",
+ "tool",
+ "api_server",
+ "acp",
+ "hermes_flow",
+ "vulcan_delegate",
+ "webhook",
+];
+const AUTOMATION_SESSION_SOURCE_SET = new Set(AUTOMATION_SESSION_SOURCES);
+const NO_MATCHING_SESSION_SOURCE = "__hermes_dashboard_no_matching_source__";
+
+type SessionFilterCategory = "chats" | "automation" | "all";
+type SourceSelectionsByCategory = Record<SessionFilterCategory, string[] | null>;
+
+function isAutomationSource(source: string): boolean {
+ return AUTOMATION_SESSION_SOURCE_SET.has(source);
+}
+
+function sourceBelongsToCategory(
+ source: string,
+ category: SessionFilterCategory,
+): boolean {
+ if (category === "all") return true;
+ if (category === "automation") return isAutomationSource(source);
+ return !isAutomationSource(source);
+}
+
+function sourceLabel(source: string): string {
+ switch (source) {
+ case "api_server":
+ return "API server";
+ case "acp":
+ return "ACP";
+ case "cli":
+ return "CLI";
+ case "tui":
+ return "TUI";
+ case "telegram":
+ return "Telegram";
+ case "discord":
+ return "Discord";
+ case "slack":
+ return "Slack";
+ case "whatsapp":
+ return "WhatsApp";
+ case "whatsapp_cloud":
+ return "WhatsApp Cloud";
+ case "sms":
+ return "SMS";
+ case "cron":
+ return "Cron";
+ case "tool":
+ return "Tool";
+ case "hermes_flow":
+ return "Hermes Flow";
+ case "vulcan_delegate":
+ return "Vulcan delegate";
+ case "webhook":
+ return "Webhook";
+ default:
+ return source
+ .split("_")
+ .filter(Boolean)
+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
+ .join(" ");
+ }
+}
+
/** Render an FTS5 snippet with highlighted matches.
* The backend wraps matches in >>> and <<< delimiters. */
function SnippetHighlight({ snippet }: { snippet: string }) {
@@ -415,8 +498,9 @@ function SessionRow({
};
}, [isExpanded, session.id, messages]);
+ const sourceKey = session.source?.split(":")[0];
const sourceInfo = (session.source
- ? SOURCE_CONFIG[session.source]
+ ? SOURCE_CONFIG[session.source] ?? (sourceKey ? SOURCE_CONFIG[sourceKey] : null)
: null) ?? { icon: Globe, color: "text-muted-foreground" };
const SourceIcon = sourceInfo.icon;
const hasTitle = session.title && session.title !== "Untitled";
@@ -439,7 +523,8 @@ function SessionRow({
const actionButtons = (
<>
<Badge tone="outline" className="text-xs">
- {session.source ?? "local"}
+ <SourceIcon className={`mr-1 h-3 w-3 ${sourceInfo.color}`} />
+ {session.source ? sourceLabel(session.source) : "local"}
</Badge>
{resumeInChatEnabled && (
@@ -743,6 +828,17 @@ export default function SessionsPage() {
const [status, setStatus] = useState<StatusResponse | null>(null);
const [overviewSessions, setOverviewSessions] = useState<SessionInfo[]>([]);
const [view, setView] = useState<SessionsView>("overview");
+ const [sessionCategory, setSessionCategory] =
+ useState<SessionFilterCategory>("chats");
+ const [sourceSelectionsByCategory, setSourceSelectionsByCategory] =
+ useState<SourceSelectionsByCategory>({
+ chats: null,
+ automation: null,
+ all: null,
+ });
+ const [sourceMenuOpen, setSourceMenuOpen] = useState(false);
+ const sourceMenuRef = useRef<HTMLDivElement | null>(null);
+ const sessionsRequestRef = useRef(0);
// Count of empty (no-message, ended, non-archived) sessions across the
// entire DB, populated by /api/sessions/empty/count. Used to:
// • hide the "Delete empty" button when there's nothing to clean up
@@ -777,6 +873,111 @@ export default function SessionsPage() {
const { setAfterTitle, setEnd } = usePageHeader();
const { activeAction, actionStatus, dismissLog } = useSystemActions();
const resumeInChatEnabled = isDashboardEmbeddedChatEnabled();
+ const selectedSources = sourceSelectionsByCategory[sessionCategory];
+
+ const pinnedSourceSelections = useMemo(
+ () =>
+ Object.values(sourceSelectionsByCategory).flatMap(
+ (selection) => selection ?? [],
+ ),
+ [sourceSelectionsByCategory],
+ );
+
+ const allSourceOptions = useMemo(() => {
+ const entries = Object.entries(stats?.by_source ?? {}).sort(
+ ([aSource, aCount], [bSource, bCount]) =>
+ bCount - aCount || sourceLabel(aSource).localeCompare(sourceLabel(bSource)),
+ );
+ const seen = new Set(entries.map(([source]) => source));
+ for (const source of pinnedSourceSelections) {
+ if (!seen.has(source)) {
+ entries.unshift([source, 0]);
+ seen.add(source);
+ }
+ }
+ return entries;
+ }, [pinnedSourceSelections, stats]);
+
+ const allSourceNames = useMemo(
+ () => allSourceOptions.map(([source]) => source),
+ [allSourceOptions],
+ );
+
+ const sessionQueryOptions = useMemo(() => {
+ if (selectedSources !== null) {
+ if (selectedSources.length === 0) {
+ return allSourceNames.length > 0
+ ? { excludeSources: allSourceNames }
+ : { source: NO_MATCHING_SESSION_SOURCE };
+ }
+ if (selectedSources.length === 1) {
+ return { source: selectedSources[0] };
+ }
+ const selected = new Set(selectedSources);
+ const excludedSources = allSourceNames.filter(
+ (source) => !selected.has(source),
+ );
+ return excludedSources.length > 0 ? { excludeSources: excludedSources } : {};
+ }
+ if (sessionCategory === "chats") {
+ return { excludeSources: AUTOMATION_SESSION_SOURCES };
+ }
+ if (sessionCategory === "automation") {
+ const excludedSources = allSourceNames.filter(
+ (source) => !isAutomationSource(source),
+ );
+ return excludedSources.length > 0
+ ? { excludeSources: excludedSources }
+ : { sources: AUTOMATION_SESSION_SOURCES };
+ }
+ return {};
+ }, [selectedSources, sessionCategory, allSourceNames]);
+
+ const categoryDefaultSources = useMemo(() => {
+ return allSourceNames.filter((source) =>
+ sourceBelongsToCategory(source, sessionCategory),
+ );
+ }, [sessionCategory, allSourceNames]);
+
+ const sourceOptions = useMemo(() => {
+ const selected = new Set(selectedSources ?? []);
+ return allSourceOptions.filter(
+ ([source]) =>
+ sourceBelongsToCategory(source, sessionCategory) || selected.has(source),
+ );
+ }, [allSourceOptions, selectedSources, sessionCategory]);
+
+ const effectiveSelectedSources = selectedSources ?? categoryDefaultSources;
+
+ const selectedSourceSet = useMemo(
+ () => new Set(effectiveSelectedSources),
+ [effectiveSelectedSources],
+ );
+
+ const defaultSourceFilterLabel = useMemo(() => {
+ if (sessionCategory === "chats") return "Any chat source";
+ if (sessionCategory === "automation") return "Any automation source";
+ return t.sessions.anySource;
+ }, [sessionCategory, t.sessions.anySource]);
+
+ const sourceMenuTitle = useMemo(() => {
+ if (sessionCategory === "chats") return "Chat sources";
+ if (sessionCategory === "automation") return "Automation sources";
+ return t.sessions.sourceFilter;
+ }, [sessionCategory, t.sessions.sourceFilter]);
+
+ const sourceFilterLabel = useMemo(() => {
+ if (selectedSources === null) {
+ return defaultSourceFilterLabel;
+ }
+ if (selectedSources.length === 0) {
+ return "No sources";
+ }
+ if (selectedSources.length === 1) {
+ return sourceLabel(selectedSources[0]);
+ }
+ return `${selectedSources.length} sources`;
+ }, [defaultSourceFilterLabel, selectedSources]);
const refreshEmptyCount = useCallback(() => {
api
@@ -821,23 +1022,44 @@ export default function SessionsPage() {
};
}, [setEnd]);
+ useEffect(() => {
+ if (!sourceMenuOpen) return;
+
+ const handlePointerDown = (event: PointerEvent) => {
+ if (!sourceMenuRef.current?.contains(event.target as Node)) {
+ setSourceMenuOpen(false);
+ }
+ };
+
+ document.addEventListener("pointerdown", handlePointerDown);
+ return () => {
+ document.removeEventListener("pointerdown", handlePointerDown);
+ };
+ }, [sourceMenuOpen]);
+
const loadSessions = useCallback((p: number, silent = false) => {
// ``silent`` skips the loading spinner so background refreshes
// (triggered when the overview poll detects a new session from
// another process) don't flicker the whole page or drop the user's
// scroll position.
+ const requestId = silent
+ ? sessionsRequestRef.current
+ : sessionsRequestRef.current + 1;
+ if (!silent) sessionsRequestRef.current = requestId;
if (!silent) setLoading(true);
api
- .getSessions(PAGE_SIZE, p * PAGE_SIZE)
+ .getSessions(PAGE_SIZE, p * PAGE_SIZE, sessionQueryOptions)
.then((resp) => {
+ if (requestId !== sessionsRequestRef.current) return;
setSessions(resp.sessions);
setTotal(resp.total);
})
.catch(() => {})
.finally(() => {
+ if (requestId !== sessionsRequestRef.current) return;
if (!silent) setLoading(false);
});
- }, []);
+ }, [sessionQueryOptions]);
const loadStats = useCallback(() => {
api
@@ -906,14 +1128,18 @@ export default function SessionsPage() {
}, [loadSessions, page, refreshEmptyCount]);
useEffect(() => {
+ let cancelled = false;
const loadOverview = () => {
api
.getStatus()
- .then(setStatus)
+ .then((nextStatus) => {
+ if (!cancelled) setStatus(nextStatus);
+ })
.catch(() => {});
api
- .getSessions(50)
+ .getSessions(50, 0, sessionQueryOptions)
.then((r) => {
+ if (cancelled) return;
setOverviewSessions(r.sessions);
// The dashboard server and a terminal CLI are separate
// processes sharing one session DB — there is no push channel,
@@ -932,8 +1158,11 @@ export default function SessionsPage() {
};
loadOverview();
const id = setInterval(loadOverview, 5000);
- return () => clearInterval(id);
- }, [loadSessions]);
+ return () => {
+ cancelled = true;
+ clearInterval(id);
+ };
+ }, [loadSessions, sessionQueryOptions]);
useEffect(() => {
const el = logScrollRef.current;
@@ -971,6 +1200,52 @@ export default function SessionsPage() {
[clearSelection],
);
+ const updateSessionCategory = useCallback(
+ (value: string) => {
+ setSessionCategory(value as SessionFilterCategory);
+ setSourceMenuOpen(false);
+ setPage(0);
+ setExpandedId(null);
+ clearSelection();
+ },
+ [clearSelection],
+ );
+
+ const toggleSourceFilter = useCallback(
+ (source: string) => {
+ setSourceSelectionsByCategory((currentByCategory) => {
+ const current = currentByCategory[sessionCategory];
+ const next = new Set(current ?? categoryDefaultSources);
+ if (next.has(source)) {
+ next.delete(source);
+ } else {
+ next.add(source);
+ }
+ const nextSelection = sourceOptions
+ .map(([optionSource]) => optionSource)
+ .filter((optionSource) => next.has(optionSource));
+ return {
+ ...currentByCategory,
+ [sessionCategory]: nextSelection,
+ };
+ });
+ setPage(0);
+ setExpandedId(null);
+ clearSelection();
+ },
+ [categoryDefaultSources, clearSelection, sessionCategory, sourceOptions],
+ );
+
+ const clearSourceFilters = useCallback(() => {
+ setSourceSelectionsByCategory((currentByCategory) => ({
+ ...currentByCategory,
+ [sessionCategory]: null,
+ }));
+ setPage(0);
+ setExpandedId(null);
+ clearSelection();
+ }, [clearSelection, sessionCategory]);
+
// Debounced FTS search
useEffect(() => {
if (debounceRef.current) clearTimeout(debounceRef.current);
@@ -985,8 +1260,9 @@ export default function SessionsPage() {
debounceRef.current = setTimeout(() => {
setSearching(true);
+ setSearchResults(null);
api
- .searchSessions(search.trim())
+ .searchSessions(search.trim(), sessionQueryOptions)
.then((resp) => setSearchResults(resp.results))
.catch(() => setSearchResults(null))
.finally(() => setSearching(false));
@@ -995,7 +1271,7 @@ export default function SessionsPage() {
return () => {
if (debounceRef.current) clearTimeout(debounceRef.current);
};
- }, [search]);
+ }, [search, sessionQueryOptions]);
const sessionDelete = useConfirmDelete({
onDelete: useCallback(
@@ -1247,14 +1523,11 @@ export default function SessionsPage() {
if (searchResults) {
for (const r of searchResults) {
snippetMap.set(r.session_id, r.snippet);
+ snippetMap.set(r.id, r.snippet);
}
}
- // When searching, filter sessions to those with FTS matches;
- // when not searching, show all sessions
- const filtered = searchResults
- ? sessions.filter((s) => snippetMap.has(s.id))
- : sessions;
+ const filtered = searchResults ?? sessions;
const platformEntries = status
? Object.entries(status.gateway_platforms ?? {})
@@ -1267,7 +1540,7 @@ export default function SessionsPage() {
const showOverviewTab =
platformEntries.length > 0 || recentSessions.length > 0;
const showList = view === "list" || isSearching || !showOverviewTab;
- const showPagination = showList && !searchResults && total > PAGE_SIZE;
+ const showPagination = showList && !isSearching && total > PAGE_SIZE;
const alerts: { message: string; detail?: string }[] = [];
if (status) {
@@ -1433,12 +1706,11 @@ export default function SessionsPage() {
<span className="text-xs text-muted-foreground">Messages</span>
</div>
{Object.keys(stats.by_source).length > 0 && (
- <div className="flex min-w-0 flex-1 flex-wrap items-center gap-1.5">
- {Object.entries(stats.by_source).map(([src, count]) => (
- <Badge key={src} tone="outline" className="text-xs">
- {src}: {count}
- </Badge>
- ))}
+ <div className="flex flex-col">
+ <span className="text-lg font-semibold tabular-nums leading-none">
+ {Object.keys(stats.by_source).length}
+ </span>
+ <span className="text-xs text-muted-foreground">Sources</span>
</div>
)}
</div>
@@ -1533,6 +1805,102 @@ export default function SessionsPage() {
{(showOverviewTab && !isSearching) || showList ? (
<div className="flex w-full min-w-0 flex-wrap items-center gap-2 sm:gap-3">
<div className="flex min-w-0 flex-1 flex-wrap items-center gap-2 sm:gap-3">
+ <Segmented
+ className="w-fit shrink-0"
+ size="md"
+ value={sessionCategory}
+ onChange={updateSessionCategory}
+ options={[
+ { value: "chats", label: t.sessions.filterChats },
+ { value: "automation", label: t.sessions.filterAutomation },
+ { value: "all", label: t.sessions.filterAll },
+ ]}
+ />
+
+ <div ref={sourceMenuRef} className="relative shrink-0">
+ <Button
+ outlined
+ size="sm"
+ prefix={<ListFilter />}
+ suffix={
+ <ChevronDown
+ className={`transition-transform ${sourceMenuOpen ? "rotate-180" : ""}`}
+ />
+ }
+ className="h-8 min-w-[10rem] max-w-[14rem] justify-between text-xs"
+ aria-label={t.sessions.sourceFilter}
+ aria-expanded={sourceMenuOpen}
+ onClick={() => setSourceMenuOpen((open) => !open)}
+ >
+ <span className="min-w-0 truncate">{sourceFilterLabel}</span>
+ </Button>
+
+ {sourceMenuOpen && (
+ <div
+ className="absolute left-0 top-full z-30 mt-1 w-[18rem] max-w-[calc(100vw-2rem)] border border-border bg-background-base shadow-lg"
+ >
+ <div className="flex items-center justify-between gap-2 border-b border-border px-2 py-1.5">
+ <span className="min-w-0 truncate text-xs text-muted-foreground">
+ {sourceMenuTitle}
+ </span>
+ {selectedSources !== null && (
+ <Button
+ ghost
+ size="xs"
+ onClick={clearSourceFilters}
+ className="shrink-0"
+ >
+ {t.common.clear}
+ </Button>
+ )}
+ </div>
+ <div className="max-h-64 overflow-y-auto p-1">
+ {sourceOptions.length === 0 ? (
+ <div className="px-2 py-2 text-xs text-muted-foreground">
+ {sourceMenuTitle}
+ </div>
+ ) : (
+ sourceOptions.map(([source, count]) => {
+ const selected = selectedSourceSet.has(source);
+ const SourceIcon = SOURCE_CONFIG[source]?.icon ?? Terminal;
+ const sourceColor =
+ SOURCE_CONFIG[source]?.color ?? "text-muted-foreground";
+
+ return (
+ <div
+ key={source}
+ className="flex min-w-0 items-center gap-2 px-2 py-1.5 hover:bg-secondary/40"
+ >
+ <Checkbox
+ checked={selected}
+ onClick={(event) => {
+ event.stopPropagation();
+ toggleSourceFilter(source);
+ }}
+ aria-label={`${t.sessions.sourceFilter}: ${sourceLabel(source)}`}
+ />
+ <button
+ type="button"
+ className="flex min-w-0 flex-1 items-center gap-2 text-left text-xs"
+ onClick={() => toggleSourceFilter(source)}
+ >
+ <SourceIcon className={`h-3.5 w-3.5 shrink-0 ${sourceColor}`} />
+ <span className="min-w-0 flex-1 truncate">
+ {sourceLabel(source)}
+ </span>
+ <span className="shrink-0 tabular-nums text-muted-foreground">
+ {count}
+ </span>
+ </button>
+ </div>
+ );
+ })
+ )}
+ </div>
+ </div>
+ )}
+ </div>
+
{showOverviewTab && !isSearching && (
<Segmented
className="w-fit shrink-0"
@@ -1690,9 +2058,13 @@ export default function SessionsPage() {
<div className="flex flex-col items-center justify-center py-16 text-muted-foreground">
<Clock className="h-8 w-8 mb-3 opacity-40" />
<p className="text-sm font-medium">
- {search ? t.sessions.noMatch : t.sessions.noSessions}
+ {search
+ ? t.sessions.noMatch
+ : selectedSources !== null || sessionCategory !== "chats"
+ ? t.sessions.noSessionsInFilter
+ : t.sessions.noSessions}
</p>
- {!search && (
+ {!search && sessionCategory === "chats" && selectedSources === null && (
<p className="text-xs mt-1 text-text-tertiary">
{t.sessions.startConversation}
</p>
@@ -1790,7 +2162,7 @@ export default function SessionsPage() {
className="shrink-0 self-start text-xs sm:self-center"
>
<Database className="mr-1 h-3 w-3" />
- {s.source ?? "local"}
+ {s.source ? sourceLabel(s.source) : "local"}
</Badge>
</div>
))}