Skip to content

The agent that grows with you

fix(bot-mode): sync renamed profile names and handles in existing group chats

Kevin Rajan68f81c4fae0b
diff --git a/apps/desktop/src/plugins/hermes-bots/data.ts b/apps/desktop/src/plugins/hermes-bots/data.ts
index 5646b75f31d..e73d45cee91 100644
--- a/apps/desktop/src/plugins/hermes-bots/data.ts
+++ b/apps/desktop/src/plugins/hermes-bots/data.ts
@@ -1187,6 +1187,25 @@ export function resolveRosterMentions(
}
}
+ // Previous profile names fill gaps only: a bot renamed after a handle was
+ // typed (or remembered) still resolves, but a live name always wins over
+ // another bot's rename history (#110200).
+ for (const bot of members) {
+ if (!bot?.name || isActiveRosterBot(bot, active)) {
+ continue
+ }
+
+ const previous = Array.isArray(bot.previous_names) ? bot.previous_names : []
+
+ for (const name of previous) {
+ for (const form of mentionNameForms(name)) {
+ if (form && !byForm.has(form)) {
+ byForm.set(form, bot)
+ }
+ }
+ }
+ }
+
const mentioned: RosterRow[] = []
const seen = new Set<string>()
diff --git a/apps/desktop/src/plugins/hermes-bots/group-membership.test.ts b/apps/desktop/src/plugins/hermes-bots/group-membership.test.ts
index 8c3476e551c..a35dc2b18ee 100644
--- a/apps/desktop/src/plugins/hermes-bots/group-membership.test.ts
+++ b/apps/desktop/src/plugins/hermes-bots/group-membership.test.ts
@@ -370,3 +370,58 @@ describe('legacy display-name descriptors', () => {
expect(modules.membership.groupChatMemberBots('room', [TAIYI], {})[0]).toBe(TAIYI)
})
})
+
+describe('renamed profile descriptors (#110200)', () => {
+ const RENAMED: RosterRow = {
+ connectionId: 'local',
+ handle: 'niezalezny',
+ name: 'niezalezny',
+ previous_names: ['niezale-ny'],
+ remoteSource: false
+ }
+
+ it('re-seat a renamed member under its live identity, not as a stale ghost', () => {
+ modules.chat.$groupChats.set(
+ rooms({
+ room: {
+ log: [],
+ members: [{ connectionId: 'local', handle: 'niezale-ny', name: 'niezale-ny' }]
+ }
+ })
+ )
+
+ const seated = modules.membership.groupChatMemberBots('room', [RENAMED], {})
+
+ // One member under the NEW identity: the stale handle is gone from the
+ // roster and @-completion.
+ expect(seated.map(row => row.name)).toEqual(['niezalezny'])
+ })
+
+ it('never match a previous name across connections', () => {
+ const remoteTwin: RosterRow = {
+ connectionId: 'other-box',
+ name: 'niezalezny',
+ previous_names: ['niezale-ny'],
+ remoteSource: true
+ }
+
+ modules.chat.$groupChats.set(
+ rooms({ room: { log: [], members: [{ connectionId: 'local', name: 'niezale-ny' }] } })
+ )
+
+ const seated = modules.membership.groupChatMemberBots('room', [remoteTwin], {})
+
+ // The local descriptor must not be captured by another connection's history.
+ expect(seated.map(row => row.name)).toEqual(['niezale-ny'])
+ expect(seated[0].connectionId).toBe('local')
+ })
+
+ it('persist the healed descriptor with its rename history', () => {
+ // durableGroupChatMembers carries previous_names down so an @old-handle
+ // keeps resolving after the heal, even when the live row is unreachable.
+ const healed = modules.membership.durableGroupChatMembers([RENAMED])
+
+ expect(healed[0].name).toBe('niezalezny')
+ expect(healed[0].previous_names).toEqual(['niezale-ny'])
+ })
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/group-membership.ts b/apps/desktop/src/plugins/hermes-bots/group-membership.ts
index 53d290395f5..b4c622c95f8 100644
--- a/apps/desktop/src/plugins/hermes-bots/group-membership.ts
+++ b/apps/desktop/src/plugins/hermes-bots/group-membership.ts
@@ -335,10 +335,11 @@ export function groupChatMemberBots(
/** A stored member descriptor, resolved against the live roster when its
* `name` is not a real slug (#92794). Exact key matches pass through
- * untouched; only a descriptor whose key matches NO roster row is re-tried
- * by friendly name against rows on the same connection. Unresolvable
- * descriptors return as-is — they stay visible-but-degraded ghosts and must
- * never be used as a `profile:` target. */
+ * untouched; only a descriptor whose key matches NO roster row is re-tried —
+ * by friendly name, then by recorded previous profile names (#110200) —
+ * against rows on the same connection. Unresolvable descriptors return as-is
+ * — they stay visible-but-degraded ghosts and must never be used as a
+ * `profile:` target. */
function resolveLegacyMemberDescriptor(descriptor: RosterRow, roster: RosterRow[]): RosterRow {
const rows = roster || []
@@ -381,7 +382,20 @@ function resolveLegacyMemberDescriptor(descriptor: RosterRow, roster: RosterRow[
String(name || '')
.trim()
.toLowerCase() === wanted
- )
+ ) ||
+ // … or a profile renamed after the descriptor was persisted
+ // ('niezale-ny' for 'niezalezny'): the CLI records previous_names in
+ // profile.yaml and the gateway surfaces them on profiles.list.
+ // Returning the live row re-seats the member under its new identity;
+ // the next persistence pass rewrites the stored descriptor, so the
+ // repair is self-healing.
+ (Array.isArray(bot?.previous_names) &&
+ bot.previous_names.some(
+ previous =>
+ String(previous || '')
+ .trim()
+ .toLowerCase() === wanted
+ ))
)
return match || descriptor
@@ -418,6 +432,14 @@ export function durableGroupChatMembers(bots: RosterRow[]): GroupMember[] {
display_name: bot.display_name
}
: {}),
+ // Previous profile names ride along so @-mentions using a pre-rename
+ // handle still resolve after the descriptor heals to the new slug,
+ // even when the live roster row is unreachable (#110200).
+ ...(Array.isArray(bot.previous_names) && bot.previous_names.length > 0
+ ? {
+ previous_names: [...bot.previous_names]
+ }
+ : {}),
connectionId: bot.connectionId,
connectionKind: bot.connectionKind,
connectionLabel: bot.connectionLabel,
diff --git a/apps/desktop/src/plugins/hermes-bots/group-rounds.test.ts b/apps/desktop/src/plugins/hermes-bots/group-rounds.test.ts
index 65527f5f96d..a6f9084ec53 100644
--- a/apps/desktop/src/plugins/hermes-bots/group-rounds.test.ts
+++ b/apps/desktop/src/plugins/hermes-bots/group-rounds.test.ts
@@ -134,6 +134,30 @@ describe('routing', () => {
expect(rounds.groupReplyMentionTag({ name: 'ops', title: 'The Ops' }, MEMBERS)).toBe('the-ops')
})
+ it('resolves a pre-rename handle to the renamed member (#110200)', async () => {
+ const { rounds } = await loadRoom()
+
+ const members: GroupMember[] = [{ name: 'niezalezny', previous_names: ['niezale-ny'] }, { name: 'builder' }]
+
+ const parsed = rounds.parseGroupChatMentions('@niezale-ny please check', members)
+
+ expect(parsed.mentioned.has('niezalezny')).toBe(true)
+ expect(parsed.mentioned.size).toBe(1)
+ })
+
+ it('prefers a live name over another member\u2019s rename history', async () => {
+ const { rounds } = await loadRoom()
+
+ // Someone later claimed the old name as their own profile: the live name
+ // wins, the alias must not steal the mention.
+ const members: GroupMember[] = [{ name: 'niezalezny', previous_names: ['niezale-ny'] }, { name: 'niezale-ny' }]
+
+ const parsed = rounds.parseGroupChatMentions('@niezale-ny take this', members)
+
+ expect(parsed.mentioned.has('niezale-ny')).toBe(true)
+ expect(parsed.mentioned.size).toBe(1)
+ })
+
it('rotates the lead speaker each round', async () => {
const { rounds } = await loadRoom()
diff --git a/apps/desktop/src/plugins/hermes-bots/group-rounds.ts b/apps/desktop/src/plugins/hermes-bots/group-rounds.ts
index ab6fded8c31..f644f0e4f99 100644
--- a/apps/desktop/src/plugins/hermes-bots/group-rounds.ts
+++ b/apps/desktop/src/plugins/hermes-bots/group-rounds.ts
@@ -95,6 +95,23 @@ export function parseGroupChatMentions(text: unknown, members: GroupMember[]) {
}
}
+ // Renamed members keep answering to their previous handles: a profile
+ // renamed after the room was created (or @-typed from muscle memory)
+ // still routes to the right member. Previous-name forms only fill gaps —
+ // a live name always wins over another member's history (#110200).
+ for (const member of members) {
+ const key = groupMemberKey(member)
+ const previous = Array.isArray(member.previous_names) ? member.previous_names : []
+
+ for (const name of previous) {
+ for (const form of mentionNameForms(name)) {
+ if (form && !handles.has(form)) {
+ handles.set(form, key)
+ }
+ }
+ }
+ }
+
for (const match of source.matchAll(/@([a-z0-9][a-z0-9._-]*)/gi)) {
const handle = match[1].toLowerCase()
diff --git a/apps/desktop/src/plugins/hermes-bots/types.ts b/apps/desktop/src/plugins/hermes-bots/types.ts
index b00cc12be87..7db8cfc2530 100644
--- a/apps/desktop/src/plugins/hermes-bots/types.ts
+++ b/apps/desktop/src/plugins/hermes-bots/types.ts
@@ -113,6 +113,11 @@ export interface RosterRow {
/** Nullable: the gateway sends `null` for a profile with no configured role,
* and the create form threads its own optional title through the same shape. */
title?: null | string
+ /** Canonical ids this profile was previously known by (`hermes profile
+ * rename` records them in profile.yaml; the gateway surfaces them on
+ * profiles.list). Lets group chats re-link persisted member descriptors
+ * after a rename (#110200). */
+ previous_names?: string[]
ui_meta?: Record<string, unknown> & { 'hermes-bots'?: BotMeta }
/** Compare-and-swap revisions, per ui_meta key. */
ui_meta_revisions?: Record<string, number>
@@ -130,6 +135,7 @@ export type GroupMember = Pick<
| 'handle'
| 'installId'
| 'name'
+ | 'previous_names'
| 'remoteSource'
| 'route'
| 'sourceMissing'
diff --git a/hermes_cli/profiles.py b/hermes_cli/profiles.py
index 9169885f3b9..32ed22a11c4 100644
--- a/hermes_cli/profiles.py
+++ b/hermes_cli/profiles.py
@@ -12,7 +12,7 @@ import subprocess
import sys
import threading
import time
-from dataclasses import dataclass
+from dataclasses import dataclass, field
from pathlib import Path
from typing import Dict, List, Optional, Tuple
@@ -548,6 +548,10 @@ class ProfileInfo:
# Bot Mode title (``profile.yaml`` ``ui_meta['hermes-bots'].title``) — the name
# the Bots roster shows. Presentation-only, like ``display_name``.
bot_title: str = ""
+ # Canonical ids this profile was previously known by (``hermes profile rename``
+ # appends here). Lets Bot Mode group chats re-link persisted member
+ # descriptors to the renamed live profile (#110200).
+ previous_names: List[str] = field(default_factory=list)
def _load_yaml_dict(path: Path) -> Optional[dict]:
@@ -733,9 +737,9 @@ def _cached_skill_count(profile_dir: Path) -> int:
def read_profile_meta(profile_dir: Path) -> dict:
- """Read ``profile.yaml`` -> ``{description, description_auto, display_name}`` (empty
- defaults when missing/unreadable). Never raises — a corrupt file on one profile must not
- break ``hermes profile list``."""
+ """Read ``profile.yaml`` -> ``{description, description_auto, display_name,
+ previous_names}`` (empty defaults when missing/unreadable). Never raises — a
+ corrupt file on one profile must not break ``hermes profile list``."""
data = _load_yaml_dict(profile_dir / "profile.yaml") or {}
ui_meta = data.get("ui_meta")
bot_title = ""
@@ -748,12 +752,28 @@ def read_profile_meta(profile_dir: Path) -> dict:
"description_auto": bool(data.get("description_auto", False)),
"display_name": str(data.get("display_name") or "").strip(),
"bot_title": bot_title,
+ "previous_names": _clean_previous_names(data.get("previous_names")),
}
+def _clean_previous_names(raw) -> List[str]:
+ """Normalize the ``previous_names`` list from ``profile.yaml``: strings only,
+ stripped, de-duplicated preserving order. Never raises."""
+ if not isinstance(raw, list):
+ return []
+ cleaned: List[str] = []
+ seen = set()
+ for item in raw:
+ name = str(item or "").strip()
+ if name and name not in seen:
+ seen.add(name)
+ cleaned.append(name)
+ return cleaned
+
+
def write_profile_meta(
profile_dir: Path, *, description: Optional[str] = None, description_auto: Optional[bool] = None,
- display_name: Optional[str] = None,
+ display_name: Optional[str] = None, previous_names: Optional[List[str]] = None,
) -> None:
"""Update ``profile.yaml`` in place: only passed fields are overwritten; the file is
created if missing. The profile directory itself must exist."""
@@ -771,6 +791,14 @@ def write_profile_meta(
existing["display_name"] = display_name.strip()
else:
existing.pop("display_name", None)
+ if previous_names is not None:
+ # Rename history for group-chat member sync (#110200): consumers match
+ # stale persisted handles against the live roster via these names.
+ cleaned = _clean_previous_names(previous_names)
+ if cleaned:
+ existing["previous_names"] = cleaned
+ else:
+ existing.pop("previous_names", None)
# Atomic write: bare open("w") truncates before the dump, and the read path swallows
# parse errors as {}, so a crashed write would silently drop unspecified fields.
# See #51356.
@@ -1957,6 +1985,18 @@ def _migrate_honcho_profile_host(old_name: str, new_name: str, new_dir: Path) ->
print(f"✓ Honcho host updated: {source_host} → {new_host}")
+def _record_profile_rename(new_dir: Path, old_canon: str) -> None:
+ """Append ``old_canon`` to the renamed profile's ``previous_names`` history.
+ Best-effort: never raises, so a metadata write failure cannot fail the rename."""
+ try:
+ history = read_profile_meta(new_dir).get("previous_names") or []
+ if old_canon not in history:
+ history = [*history, old_canon]
+ write_profile_meta(new_dir, previous_names=history)
+ except Exception:
+ pass
+
+
def rename_profile(old_name: str, new_name: str) -> Path:
"""Rename a profile: directory, wrapper script, service, active_profile. The default
profile's home IS the installation root, so "renaming" it sets a presentation-only
@@ -2016,6 +2056,11 @@ def rename_profile(old_name: str, new_name: str) -> Path:
if live_mux:
clear_named_profile_deleted(old_dir)
+ # 2b. Record the rename so Bot Mode group chats can re-link persisted
+ # member descriptors to the new slug (#110200). Best-effort: a metadata
+ # write failure must never fail the rename itself.
+ _record_profile_rename(new_dir, old_canon)
+
# 3. Update profile-scoped Honcho host blocks, preserving aiPeer identity
_migrate_honcho_profile_host(old_canon, new_canon, new_dir)
diff --git a/tests/hermes_cli/test_profiles.py b/tests/hermes_cli/test_profiles.py
index 0d1bfff4a8d..59342694454 100644
--- a/tests/hermes_cli/test_profiles.py
+++ b/tests/hermes_cli/test_profiles.py
@@ -1260,6 +1260,41 @@ class TestRenameProfile:
assert "agent:newname:feishu:dm:chatA" in routing
root_db2.close()
+ def test_rename_records_previous_name(self, profile_env):
+ create_profile("oldname", no_alias=True)
+
+ # Mock alias collision to avoid subprocess calls
+ with patch("hermes_cli.profiles.check_alias_collision", return_value="skip"):
+ new_dir = rename_profile("oldname", "newname")
+
+ # The rename history is recorded in the new profile's metadata ...
+ assert profiles.read_profile_meta(new_dir)["previous_names"] == ["oldname"]
+ # ... and surfaces through list_profiles (the gateway's profiles.list
+ # source), so Bot Mode group chats can re-link stale member handles.
+ info = next(p for p in list_profiles() if p.name == "newname")
+ assert info.previous_names == ["oldname"]
+
+ def test_rename_accumulates_previous_names(self, profile_env):
+ create_profile("firstname", no_alias=True)
+
+ with patch("hermes_cli.profiles.check_alias_collision", return_value="skip"):
+ rename_profile("firstname", "secondname")
+ rename_profile("secondname", "thirdname")
+
+ info = next(p for p in list_profiles() if p.name == "thirdname")
+ assert info.previous_names == ["firstname", "secondname"]
+
+ def test_rename_succeeds_when_previous_name_write_fails(self, profile_env):
+ create_profile("oldname", no_alias=True)
+
+ # The history write is best-effort: it must never fail the rename.
+ with patch("hermes_cli.profiles.check_alias_collision", return_value="skip"), \
+ patch("hermes_cli.profiles.write_profile_meta", side_effect=OSError("disk full")):
+ new_dir = rename_profile("oldname", "newname")
+
+ assert new_dir.is_dir()
+
+
class TestExportImport:
"""Tests for export_profile() / import_profile()."""
diff --git a/tui_gateway/methods_profiles.py b/tui_gateway/methods_profiles.py
index 83938e5d718..54b1c1525df 100644
--- a/tui_gateway/methods_profiles.py
+++ b/tui_gateway/methods_profiles.py
@@ -256,7 +256,8 @@ def _(rid, params: dict) -> dict:
for p in list_profiles(lazy_skill_count=True):
row = {"name": p.name, "path": str(p.path), "is_default": bool(p.is_default), "model": p.model,
"provider": p.provider, "description": p.description or "",
- "display_name": p.display_name or "", "skill_count": p.skill_count or 0}
+ "display_name": p.display_name or "", "skill_count": p.skill_count or 0,
+ "previous_names": list(p.previous_names or [])}
if include_sessions:
_profile_session_fields(row, p.path)
_profile_ui_meta_fields(row, Path(str(p.path)))