Files
kshitijk4poor b8c5abc775 fix(api): serve only Bot Mode's ui_meta block from /api/profiles
The cherry-picked commit (#154536) fixed secondary-connection Bot Mode
sections by adding profile.yaml ui_meta to GET /api/profiles verbatim.
Verbatim also shipped every other plugin's ui_meta: hermes-bots-groups
holds group-chat room logs and room images, which the Desktop roster now
pulled every 5s per secondary connection (2.7 KB -> 36.7 KB per response
on a real install) and which a profile-scoped native grant could read for
every profile. A YAML .nan anywhere in ui_meta also made the whole list
500, and the nested dict was shared with the profile.yaml cache, so a
caller mutating it changed the next reader's result.

- read_profile_meta keeps only ui_meta['hermes-bots'] (sections, groups,
  title), serialized as strict JSON in the cache (YAML dates -> ISO via the
  gateway's existing yaml_scalar_to_json, now owned by profiles_cache) and
  parsed per caller; a block that is not JSON-representable becomes {}.
  Group chats keep reading hermes-bots-groups through profiles.list.
- The list fallback rows (list_profiles raised) carry ui_meta too.
- The contributor's tests move into tests/hermes_cli/test_profile_display_name.py
  (tests mirror source), through list_profiles and the fallback path.
2026-11-13 14:30:56 +05:30

59 lines
2.5 KiB
Python

"""The per-profile derived-value cache behind ``list_profiles`` (``hermes_cli.profiles``)."""
import json
from pathlib import Path
from typing import Optional
# (path, kind) -> (file signature, the small derived value). `list_profiles` re-reads three YAML
# files PER PROFILE, and it is the shared body of `GET /api/profiles` and `profiles.list`, which the
# Bots roster polls every 5s per connection — so an installer-seeded config.yaml (the annotated
# template, ~119KB) was re-parsed for every bot every five seconds to yield the same two strings.
# Only DERIVED values are cached, never a document a caller could write back: the raw readers
# (`read_user_config_raw`, `_load_yaml_dict`) keep their uncached contract. See #117378.
_PROFILE_FILE_CACHE: dict[tuple, tuple] = {}
_PROFILE_FILE_CACHE_MAX = 512
def _profile_file_signature(path: Path) -> Optional[tuple]:
"""``(mtime_ns, size, inode)``, or None when the file is absent. The atomic writers rename a
temp file into place, so a rewrite always lands a new inode even within one mtime tick."""
try:
stat = path.stat()
except OSError:
return None
return (stat.st_mtime_ns, stat.st_size, stat.st_ino)
def _cached_profile_read(path: Path, kind: str, compute, signature_of=_profile_file_signature):
"""``compute()``'s value, reused while ``signature_of(path)`` is unchanged. A missing file is never
cached: reading it costs nothing, and one created later must be picked up."""
signature = signature_of(path)
if signature is None:
return compute()
key = (str(path), kind)
cached = _PROFILE_FILE_CACHE.get(key)
if cached is not None and cached[0] == signature:
return cached[1]
value = compute()
if len(_PROFILE_FILE_CACHE) >= _PROFILE_FILE_CACHE_MAX:
_PROFILE_FILE_CACHE.clear()
_PROFILE_FILE_CACHE[key] = (signature, value)
return value
def yaml_scalar_to_json(value):
"""``json.dumps`` default for YAML-only scalars (datetime/date → ISO 8601, else ``str``)."""
isoformat = getattr(value, "isoformat", None)
return isoformat() if callable(isoformat) else str(value)
def json_safe_dumps(value) -> str:
"""``value`` as strict JSON (a cacheable, per-caller-copyable derived value), or ``"{}"`` when it
cannot be one (NaN/inf, unhashable YAML keys): one hand-edited profile.yaml must not fail a list."""
try:
return json.dumps(value, default=yaml_scalar_to_json, allow_nan=False)
except (TypeError, ValueError):
return "{}"