The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(bots): size live_message_count with SessionDB's own display projection
Brooklyn Nicholsonfe5b728bd9d6
diff --git a/apps/desktop/src/plugins/hermes-bots/canonical-chat.ts b/apps/desktop/src/plugins/hermes-bots/canonical-chat.tsindex ffb11653e95..050b235f7c8 100644--- a/apps/desktop/src/plugins/hermes-bots/canonical-chat.ts+++ b/apps/desktop/src/plugins/hermes-bots/canonical-chat.ts@@ -10,6 +10,7 @@import * as sdk from '@hermes/plugin-sdk'import { host } from '@hermes/plugin-sdk'+import type { SessionListRow } from '@hermes/plugin-sdk'import { $botMeta, botMetaKey, botOwner, persistBotMetaSnapshot } from './data'import { botsText } from './i18n'@@ -54,10 +55,9 @@ export const CANONICAL_CHAT_TITLE = 'Bot Chat'* read through an aliased guard, which TS only narrows for immutable* properties. */interface CanonicalChatRow extends CanonicalSession {- readonly message_count?: number- /** Rows a stored-transcript read can paint (active + compaction-archived);- * absent on older gateways, which only report the denormalized total. */- readonly live_message_count?: number+ readonly message_count?: SessionListRow['message_count']+ /** Absent on older gateways, which only report the denormalized total. */+ readonly live_message_count?: SessionListRow['live_message_count']}/** Should the open wait for a painted transcript? The paintable row count@@ -66,7 +66,7 @@ interface CanonicalChatRow extends CanonicalSession {* guesswork anyway — wait, so an empty paint still surfaces as an error* instead of a silent blank chat. */export function resolveExpectHistory(- summary: null | undefined | { message_count?: number; live_message_count?: number }+ summary: null | undefined | Pick<SessionListRow, 'live_message_count' | 'message_count'>): boolean {if (typeof summary?.live_message_count === 'number' && Number.isFinite(summary.live_message_count)) {return summary.live_message_count > 0diff --git a/apps/desktop/src/plugins/hermes-bots/types.ts b/apps/desktop/src/plugins/hermes-bots/types.tsindex 92c6571108c..14c9f6884b1 100644--- a/apps/desktop/src/plugins/hermes-bots/types.ts+++ b/apps/desktop/src/plugins/hermes-bots/types.ts@@ -9,6 +9,8 @@* required is a claim that every one of those paths supplies it.*/+import type { ProfileSessionPreview } from '@hermes/plugin-sdk'+/*** The compact age suffixes the sidebar's session rows render ("now", "m", "h",* "d"). Structural rather than an import of core's `Translations`, which the@@ -53,8 +55,7 @@ export interface SessionPreview {/** Unix seconds, not milliseconds. */last_active?: numbermessage_count?: number- /** Rows a stored-transcript read can paint; absent on older gateways. */- live_message_count?: number+ live_message_count?: ProfileSessionPreview['live_message_count']preview?: stringtitle?: string}diff --git a/apps/desktop/src/sdk/index.ts b/apps/desktop/src/sdk/index.tsindex fd148c8cc34..f47dfa846af 100644--- a/apps/desktop/src/sdk/index.ts+++ b/apps/desktop/src/sdk/index.ts@@ -2054,6 +2054,8 @@ export type { StatusResponse } from '@/types/hermes'export type { GatewayEvent as RpcEvent } from '@hermes/shared'/** Bot Screen wire shapes, generated from `tui_gateway/contracts/display.py`. */export type { DisplayLease, DisplayObserveResult, DisplayStatus, DisplayThumbnailResult } from '@hermes/shared'+/** `session.list` / `profiles.list` session rows, generated from `tui_gateway/contracts`. */+export type { ProfileSessionPreview, SessionListRow } from '@hermes/shared'/** THE compact-number formatter — every user-facing count/token figure goes* through here (1230 → "1.2k", 1_500_000 → "1.5M"). Don't hand-roll `/1000`. */export { compactNumber } from '@hermes/shared'diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex 42f540bcd41..4ca52374a76 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -1923,6 +1923,7 @@ export interface ProfileSessionPreview {started_at?: numberlast_active?: numbermessage_count?: number+ live_message_count?: number | null}/** Newest kanban/tool worker row, so rosters can show a profile as working. */export interface ProfileWorkerSession {@@ -1941,6 +1942,7 @@ export interface ProfileCanonicalSession {started_at?: numberlast_active?: numbermessage_count?: number+ live_message_count?: number | null}/** ``clone_from`` omitted = fresh profile + bundled skills; ``mirror_credentials`` defaults on so a headless bot has a provider. */export interface ProfilesCreateParams {@@ -3127,6 +3129,7 @@ export interface SessionListRow {preview?: stringstarted_at?: numbermessage_count?: number+ live_message_count?: number | nullsource?: string}export interface SessionMostRecentParams {diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex 4cfbe7a93c9..53080ab114b 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -23291,6 +23291,18 @@"default": 0,"title": "Message Count","type": "integer"+ },+ "live_message_count": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Live Message Count"}},"required": [@@ -23592,6 +23604,18 @@"default": 0,"title": "Message Count","type": "integer"+ },+ "live_message_count": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Live Message Count"}},"required": [@@ -30595,6 +30619,18 @@"title": "Message Count","type": "integer"},+ "live_message_count": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Live Message Count"+ },"source": {"default": "","title": "Source",diff --git a/hermes_state_messages.py b/hermes_state_messages.pyindex ea9f333d8b1..c0df36136ae 100644--- a/hermes_state_messages.py+++ b/hermes_state_messages.py@@ -1452,6 +1452,15 @@ class SessionMessagesMixin:(session_id, -1 if limit is None else limit, offset, session_id),).fetchall()+ def display_message_count(self, session_id: str) -> int:+ """Rows a display read of this segment paints: one per ``display_order`` group of+ ``_display_rows_from_conn``'s set. Unindexed legacy rows count as one group (the read+ backfills them), so the count is zero exactly when the read paints nothing."""+ row = self._read_one(+ "SELECT COUNT(*) FROM (SELECT DISTINCT display_order FROM messages"+ f" WHERE session_id = ?{_DISPLAY_ACTIVE_CLAUSE}{DISPLAY_VISIBLE_SQL})", (session_id,))+ return int(row[0])+def _display_messages_from_conn(self, conn, session_id: str) -> Optional[List[Dict[str, Any]]]:"""Exact display snapshot on an already-held transaction; None means fail closed."""if conn.execute("SELECT 1 FROM sessions WHERE id = ? LIMIT 1", (session_id,)).fetchone() is None:diff --git a/tests/tui_gateway/test_profiles_list_canonical_session.py b/tests/tui_gateway/test_profiles_list_canonical_session.pyindex df8490079bf..0c928f3c6b1 100644--- a/tests/tui_gateway/test_profiles_list_canonical_session.py+++ b/tests/tui_gateway/test_profiles_list_canonical_session.py@@ -26,8 +26,12 @@ Contract under test:from __future__ import annotations+import json+import pytest+from agent.context_compressor import MODEL_ONLY_DISPLAY_METADATA_KEY+import tui_gateway.server as srv@@ -221,6 +225,21 @@ def test_canonical_session_live_count_zero_when_all_rows_folded(home):assert canonical["live_message_count"] == 0+def test_canonical_session_live_count_skips_model_only_rows_like_the_reader(home):+ """Micro-compaction's model-only rows never paint, so they must not make the open wait."""+ db = _db(home)+ _add_session(db, "modelonly", title="Bot Chat", ts=1000, text="for the model", hidden=True)+ with db._lock:+ db._conn.execute("UPDATE messages SET display_metadata = ? WHERE session_id = ?",+ (json.dumps({MODEL_ONLY_DISPLAY_METADATA_KEY: True}), "modelonly"))+ painted = db.get_messages_as_conversation("modelonly", include_compacted=True)+ db.close()++ canonical = _row(_profiles({}), "default")["canonical_session"]++ assert canonical["live_message_count"] == len(painted) == 0++def test_canonical_session_live_count_counts_paintable_rows(home):db = _db(home)_add_session(db, "livechat", title="Bot Chat", ts=1000,diff --git a/tui_gateway/contracts/profiles_vault_complete_foreign_subagents.py b/tui_gateway/contracts/profiles_vault_complete_foreign_subagents.pyindex 27b483acb42..21d508b4d1f 100644--- a/tui_gateway/contracts/profiles_vault_complete_foreign_subagents.py+++ b/tui_gateway/contracts/profiles_vault_complete_foreign_subagents.py@@ -122,6 +122,7 @@ class ProfileSessionPreview(Result):started_at: float | int = 0last_active: float | int = 0message_count: int = 0+ live_message_count: int | None = Noneclass ProfileWorkerSession(Result):@@ -144,6 +145,7 @@ class ProfileCanonicalSession(Result):started_at: float | int = 0last_active: float | int = 0message_count: int = 0+ live_message_count: int | None = Noneclass ProfileRow(Result):diff --git a/tui_gateway/contracts/sessions.py b/tui_gateway/contracts/sessions.pyindex 685161f1e74..b1a8a57b978 100644--- a/tui_gateway/contracts/sessions.py+++ b/tui_gateway/contracts/sessions.py@@ -226,6 +226,7 @@ class SessionListRow(Result):preview: str = ""started_at: float = 0message_count: int = 0+ live_message_count: int | None = Nonesource: str = ""diff --git a/tui_gateway/methods_profiles.py b/tui_gateway/methods_profiles.pyindex afd8092b01e..4436174f4d1 100644--- a/tui_gateway/methods_profiles.py+++ b/tui_gateway/methods_profiles.py@@ -5,6 +5,7 @@ onto server.py, so they must not collide with its globals."""import contextlib+import sqlite3from .method_ctx import HandlerRegistry, bind_module@@ -146,9 +147,14 @@ def _resurrect_recoverable_canonical(db, profile_path, session_id):def _live_count_field(db, session_id) -> dict:- """``{"live_message_count": n}`` for the row a stored-transcript read can paint, else ``{}``."""- live = _display_row_count(db, session_id)- return {} if live is None else {"live_message_count": live}+ """``{"live_message_count": n}`` sized like a stored-transcript read, else ``{}`` (older stores).++ The denormalized ``message_count`` also counts folded rows (orphaned compaction marks, full+ rewinds, model-only rows), which once made the roster wait for history no reader serves."""+ try:+ return {"live_message_count": db.display_message_count(str(session_id))}+ except sqlite3.Error:+ return {}def _canonical_session_row(db, profile_path):@@ -178,17 +184,12 @@ def _canonical_session_row(db, profile_path):tip = _try(lambda: db.get_compression_tip(session_id), None) or session_idtip_row = db.get_session(tip) or rowstarted = row.get("started_at") or 0- # live_message_count sizes what a stored-transcript read can actually paint; the- # denormalized message_count counts folded rows too (orphaned compaction marks,- # full rewinds) and once made the roster demand history no reader serves.- live = _display_row_count(db, tip)return {"id": session_id, "resolved_id": tip, "root_title": row.get("title") or "","title": tip_row.get("title") or "", "preview": _latest_message_preview(db, tip),"started_at": tip_row.get("started_at") or started,"last_active": tip_row.get("last_activity_at") or tip_row.get("started_at") or started,- "message_count": tip_row.get("message_count") or 0,- **({} if live is None else {"live_message_count": live})}+ "message_count": tip_row.get("message_count") or 0, **_live_count_field(db, tip)}except Exception:return Nonediff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.pyindex 3e011e43465..537ca8761dc 100644--- a/tui_gateway/methods_session.py+++ b/tui_gateway/methods_session.py@@ -117,38 +117,13 @@ def _cwd_info(session: dict, cwd: str, branch=None) -> dict:def _session_row_summary(row: dict, *, tip_row: dict | None = None, resolved_id=None, db=None) -> dict:"""Compact session.list row; ``tip_row``/``resolved_id`` come from the compression tip.-- ``live_message_count`` (present when ``db`` is given) counts exactly the rows a- stored-transcript read can paint — the tip's display set (``active = 1 OR- compacted = 1``). ``message_count`` is the denormalized total and counts folded- rows too, so a session whose rows are all inactive (orphaned compaction marks,- fully rewound chats) advertises history no reader serves."""+ ``db`` adds ``live_message_count`` (see ``_live_count_field``)."""tip_row = tip_row or row- summary = {"id": row["id"], **({} if resolved_id is None else {"resolved_id": resolved_id}),- "title": row.get("title") or "", "preview": tip_row.get("preview") or "",- "started_at": row.get("started_at") or 0, "message_count": tip_row.get("message_count") or 0,- "source": row.get("source") or ""}- if db is not None:- live = _display_row_count(db, resolved_id if resolved_id is not None else row["id"])- if live is not None:- summary["live_message_count"] = live- return summary---def _display_row_count(db, session_id) -> int | None:- """Painted-transcript size of one session segment, or None when unreadable (older stores).-- Mirrors ``_display_rows_from_conn``: the read paints one representative per- ``display_order`` group among ``active = 1 OR compacted = 1`` rows (legacy rows- without a display order collapse into one group, matching the legacy page)."""- try:- with db._lock:- return int(db._conn.execute(- "SELECT COUNT(*) FROM (SELECT DISTINCT display_order FROM messages"- " WHERE session_id = ? AND (active = 1 OR compacted = 1))",- (str(session_id),)).fetchone()[0])- except Exception:- return None+ return {"id": row["id"], **({} if resolved_id is None else {"resolved_id": resolved_id}),+ "title": row.get("title") or "", "preview": tip_row.get("preview") or "",+ "started_at": row.get("started_at") or 0, "message_count": tip_row.get("message_count") or 0,+ "source": row.get("source") or "",+ **({} if db is None else _live_count_field(db, row["id"] if resolved_id is None else resolved_id))}from hermes_state_sessions import INTERNAL_LISTING_SOURCES