Skip to content

The agent that grows with you

fix(desktop): name each bot from its own backend; saves never publish cached fields

teknium133261470752f
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index c94a4257625..f3c6bc0b983 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -16550,8 +16550,11 @@ async function enumerateRegistryAgentSources(registry = readDesktopConnectionsRe
metadata.display_name = profile.display_name.trim()
}
- if (typeof profile?.title === 'string' && profile.title.trim()) {
- metadata.title = profile.title.trim()
+ // `/api/profiles` names the Bot Mode title `bot_title`. Carried even
+ // when empty: "this backend has no title" is what lets the renderer
+ // drop a stale local one instead of painting it on this bot.
+ if (typeof profile?.bot_title === 'string') {
+ metadata.title = profile.bot_title.trim()
}
if (profile?.ui_meta && typeof profile.ui_meta === 'object') {
diff --git a/apps/desktop/src/plugins/hermes-bots/bot-row.test.tsx b/apps/desktop/src/plugins/hermes-bots/bot-row.test.tsx
index 443ae6973b5..85531fb5205 100644
--- a/apps/desktop/src/plugins/hermes-bots/bot-row.test.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/bot-row.test.tsx
@@ -69,7 +69,10 @@ beforeEach(() => {
vi.clearAllMocks()
ensureBotMetadata.mockResolvedValue({ pinned: true })
openRosterBot.mockResolvedValue(true)
- requestProfile.mockResolvedValue({})
+ // A save reads the bot's server namespace (profiles.list) before writing it.
+ requestProfile.mockImplementation(async (_route: unknown, method: string) =>
+ method === 'profiles.list' ? { profiles: [{ name: 'backend-worker' }] } : {}
+ )
})
describe('group-turn presence', () => {
diff --git a/apps/desktop/src/plugins/hermes-bots/data.bot-meta.test.ts b/apps/desktop/src/plugins/hermes-bots/data.bot-meta.test.ts
index d4a6eac1123..efba5c34310 100644
--- a/apps/desktop/src/plugins/hermes-bots/data.bot-meta.test.ts
+++ b/apps/desktop/src/plugins/hermes-bots/data.bot-meta.test.ts
@@ -18,8 +18,12 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
-import { $botMeta, botMetaWriteAt, saveBotMeta } from './data'
+import { $botMeta, $lastRoster, botMentionTag, botMetaWriteAt, saveBotMeta } from './data'
+import { groupSpeakerLabel } from './group-chat'
+import { buildGroupChatTurnPrompt } from './group-round-prompt'
+import { displayName } from './labels'
import { mergeServerMeta } from './profile-ops'
+import { botRosterMeta } from './routing'
import type { RosterRow } from './types'
const { hostMock, storageMock } = vi.hoisted(() => ({
@@ -53,6 +57,12 @@ vi.mock('./shared', () => ({ getPluginCtx: () => ({ storage: storageMock }), ID:
vi.mock('./avatar-image', () => ({ isBackfilledFacePng: () => false }))
vi.mock('./canonical-chat', () => ({ ensureBotMetadata: vi.fn() }))
+/** The backend's profile listing: a save reads the bot's server namespace
+ * before it writes, so every profile a case saves has to exist there. */
+const SERVED_PROFILES = {
+ profiles: ['beta', 'ops', 'researcher', 'source', 'source-2'].map(name => ({ name, ui_meta_revisions: {} }))
+}
+
/** Every `host.request` recorded, with the params frozen at call time. */
function recordRequests(reply: (method: string) => unknown = () => ({})) {
const calls: Array<{ method: string; params: Record<string, unknown> }> = []
@@ -60,7 +70,7 @@ function recordRequests(reply: (method: string) => unknown = () => ({})) {
hostMock.request.mockImplementation(async (method: string, params: Record<string, unknown>) => {
calls.push({ method, params: structuredClone(params ?? {}) })
- return reply(method)
+ return method === 'profiles.list' ? SERVED_PROFILES : reply(method)
})
return calls
@@ -132,7 +142,11 @@ describe('a save for a bot on the pooled local backend', () => {
throw new Error('Local backend start for "beta" timed out while waiting for a free slot. (background)')
}
- return method === 'profiles.configure' ? { applied: { ui_meta: true } } : {}
+ return method === 'profiles.configure'
+ ? { applied: { ui_meta: true } }
+ : method === 'profiles.list'
+ ? SERVED_PROFILES
+ : {}
}
)
@@ -349,3 +363,82 @@ describe('server metadata reconciliation', () => {
}
})
})
+
+// Two machines, both with a profile literally named `default`: the VPS bot is
+// "Agent A" on its own backend; this Desktop's local agent is "Agent B", whose
+// title still sits under the bare legacy key from its single-source days.
+describe('a bot is named by its own backend, never by another bot\'s cached record', () => {
+ const vps = {
+ connectionId: 'vps',
+ display_name: 'Agent A',
+ name: 'default',
+ remoteSource: true,
+ sourceScoped: true
+ } as RosterRow
+
+ it('a save writes its own patch onto the server namespace, and re-reads after losing a CAS race', async () => {
+ $botMeta.set({ 'vps::default': { color: '#ff0000', title: 'Agent B' } })
+ let revision = 3
+ const configures: Array<Record<string, unknown>> = []
+
+ hostMock.requestProfile.mockImplementation(async (_route: unknown, method: string, params: Record<string, unknown>) => {
+ if (method === 'profiles.list') {
+ return {
+ profiles: [
+ {
+ name: 'default',
+ ui_meta: { 'hermes-bots': { color: '#0000ff', groups: [] } },
+ ui_meta_revisions: { 'hermes-bots': revision }
+ }
+ ]
+ }
+ }
+
+ if (method === 'profiles.configure') {
+ configures.push(structuredClone(params))
+
+ // Another writer lands between this save's read and its write, once.
+ if (configures.length === 1) {
+ revision = 4
+
+ return { applied: { ui_meta: false, ui_meta_conflicts: { 'hermes-bots': { actual: 4, expected: 3 } } } }
+ }
+
+ return { applied: { ui_meta: true } }
+ }
+
+ return {}
+ })
+
+ await expect(saveBotMeta(vps, { groups: ['room'] })).resolves.toMatchObject({ serverOutcome: 'persisted' })
+
+ expect(configures.map(params => params.ui_meta_expected_revisions)).toEqual([
+ { 'hermes-bots': 3 },
+ { 'hermes-bots': 4 }
+ ])
+ // The local cache's stale title and color never travel: only the patch rides the server's copy.
+ expect(configures.at(-1)?.ui_meta).toEqual({ 'hermes-bots': { color: '#0000ff', groups: ['room'] } })
+ })
+
+ it('names, tags, and prompts the bot with what its backend reports', () => {
+ $botMeta.set({ default: { title: 'Agent B' }, 'vps::default': { title: 'Agent B' } })
+ // `/api/profiles` reports no Bot Mode title for the VPS bot.
+ const thin = { ...vps, title: '' } as RosterRow
+
+ mergeServerMeta([thin])
+
+ expect(displayName(thin, botRosterMeta(thin, $botMeta.get()))).toBe('Agent A')
+ expect(botMentionTag(thin)).toBe('agent-a')
+
+ // Window switched to the VPS: its rows are the active source's (scoped, not remote).
+ const active = { ...vps, remoteSource: false, ui_meta_revisions: {} } as RosterRow
+
+ expect(buildGroupChatTurnPrompt({ deltaLines: [], groupName: 'g', members: [active], viewer: active })).toContain(
+ 'You are @agent-a,'
+ )
+
+ // A keyed speaker with no live roster row (Bots pane not mounted).
+ $lastRoster.set([])
+ expect(groupSpeakerLabel('vps::default')).not.toBe('Agent B')
+ })
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/data.ts b/apps/desktop/src/plugins/hermes-bots/data.ts
index ae7bb22c83d..c9df5a4e1af 100644
--- a/apps/desktop/src/plugins/hermes-bots/data.ts
+++ b/apps/desktop/src/plugins/hermes-bots/data.ts
@@ -317,7 +317,100 @@ interface BotMetaSaveResult {
/** `profiles.configure` reply. Older gateways answer without `applied` at all,
* which is what makes the field optional rather than the contract. */
interface ProfilesConfigureResult {
- applied?: { ui_meta?: boolean }
+ applied?: {
+ ui_meta?: boolean
+ ui_meta_conflicts?: Record<string, unknown>
+ }
+}
+
+/** The bot's `hermes-bots` namespace as its OWN backend holds it right now. */
+interface ServerBotMeta {
+ meta: StoredBotMeta
+ /** Per-key CAS revision; null on gateways that predate `ui_meta_revisions`. */
+ revision: null | number
+}
+
+/** How many times a save re-reads the server after losing a CAS race. */
+const BOT_META_CAS_ATTEMPTS = 3
+
+async function readServerBotMeta(bot: RosterRow, name: string, route: null | ProfileRoute): Promise<null | ServerBotMeta> {
+ const params = { include_sessions: false }
+
+ // The read is the first half of a user's save: it dials foreground like the write.
+ const result = (await (route
+ ? requestForBot(bot, 'profiles.list', params, { spawnPriority: 'foreground' })
+ : host.request('profiles.list', params))) as {
+ profiles?: RosterRow[]
+ }
+
+ const target = route?.targetProfile || name
+ const row = (Array.isArray(result?.profiles) ? result.profiles : []).find(profile => profile?.name === target)
+
+ if (!row) {
+ return null
+ }
+
+ const meta = row.ui_meta?.['hermes-bots']
+ const revisions = row.ui_meta_revisions
+
+ return {
+ meta: meta && typeof meta === 'object' && !Array.isArray(meta) ? (meta as StoredBotMeta) : {},
+ revision: revisions && typeof revisions === 'object' ? Math.max(0, Number(revisions['hermes-bots'] || 0)) : null
+ }
+}
+
+/** Write ONE save's patch onto the server's current namespace. The local cache is never the
+ * write base: it can hold another bot's fields (a restored or name-keyed record, a window that
+ * missed a rename) and a whole-cache write publishes them as this bot's identity — to every
+ * Desktop, every relay roster, and every group prompt. CAS turns a concurrent writer's newer
+ * value into a re-read instead of a silent overwrite. */
+async function persistBotMetaPatch(
+ bot: RosterRow,
+ name: string,
+ route: null | ProfileRoute,
+ patch: StoredBotMeta
+): Promise<null | ProfilesConfigureResult> {
+ const { image: _image, pet: _pet, ...fields } = patch
+
+ for (let attempt = 0; attempt < BOT_META_CAS_ATTEMPTS; attempt++) {
+ const server = await readServerBotMeta(bot, name, route)
+
+ if (!server) {
+ return null
+ }
+
+ const { chat: _chat, ...base } = server.meta
+
+ const params: Record<string, unknown> = {
+ name,
+ ui_meta: {
+ 'hermes-bots': {
+ ...base,
+ ...fields
+ }
+ }
+ }
+
+ if (server.revision !== null) {
+ params.ui_meta_expected_revisions = {
+ 'hermes-bots': server.revision
+ }
+ }
+
+ const result = (await (route
+ ? requestForBot(bot, 'profiles.configure', params)
+ : host.request('profiles.configure', params))) as ProfilesConfigureResult
+
+ if (!result?.applied?.ui_meta_conflicts) {
+ return result
+ }
+ }
+
+ return {
+ applied: {
+ ui_meta: false
+ }
+ }
}
export async function saveBotMeta(owner: RosterRow | string, patch: StoredBotMeta): Promise<BotMetaSaveResult> {
@@ -357,26 +450,10 @@ export async function saveBotMeta(owner: RosterRow | string, patch: StoredBotMet
// rides every profiles.list); the avatar IMAGE goes to the profile asset
// store instead (profiles.set_asset), which is server-side and uncapped by
// the list call — so pfps follow the profile across machines too.
- let serverRequest: null | Promise<ProfilesConfigureResult> = null
+ let serverRequest: null | Promise<null | ProfilesConfigureResult> = null
try {
- const { image, pet, ...rest } = next[key] || {}
-
- const request = route
- ? requestForBot(bot, 'profiles.configure', {
- name,
- ui_meta: {
- 'hermes-bots': rest
- }
- })
- : host.request('profiles.configure', {
- name,
- ui_meta: {
- 'hermes-bots': rest
- }
- })
-
- serverRequest = Promise.resolve(request) as Promise<ProfilesConfigureResult>
+ serverRequest = persistBotMetaPatch(bot, name, route, patch)
} catch {
/* older/unavailable gateway — the local fallback remains saved */
}
@@ -1095,13 +1172,17 @@ export function mentionNameForms(value: null | string | undefined): string[] {
/** Every friendly (renameable) name a roster row carries: the Bot Mode title
* (server-synced via ui_meta, locally stored, or persisted on a durable
* group descriptor) and the core profile display_name — in displayName's
- * precedence order. Remote rows never borrow local meta (two `default`s
- * must not share a title) — EXCEPT the connection-exact alias identity
- * (#89131): a backend row claimed by a configured alias route carries the
- * alias's friendly names, so @moxie keeps resolving after handoff. */
+ * precedence order. Local meta is read under the row's OWN key only: a bare
+ * name key belongs to whichever single-source gateway wrote it, so reading it
+ * for a scoped row hands one machine's `default` title to another's — and the
+ * group prompt then tells that bot it is someone else. The one cross-key read
+ * is the connection-exact alias identity (#89131): a backend row claimed by a
+ * configured alias route carries the alias's friendly names, so @moxie keeps
+ * resolving after handoff. */
export function botFriendlyNames(bot: Partial<RosterRow> | null | undefined): Array<null | string | undefined> {
const metaByName: Record<string, BotMeta | undefined> | null = typeof $botMeta !== 'undefined' ? $botMeta.get() : null
- const localTitle = !bot?.remoteSource ? metaByName?.[bot?.name!]?.title : null
+ const ownKey = bot ? botMetaKey(bot) : undefined
+ const localTitle = ownKey ? metaByName?.[ownKey]?.title : null
const alias = aliasIdentityFor(bot)
const aliasTitle = alias
diff --git a/apps/desktop/src/plugins/hermes-bots/group-chat.ts b/apps/desktop/src/plugins/hermes-bots/group-chat.ts
index df2e7c6cca3..5f231b2ca06 100644
--- a/apps/desktop/src/plugins/hermes-bots/group-chat.ts
+++ b/apps/desktop/src/plugins/hermes-bots/group-chat.ts
@@ -1478,7 +1478,9 @@ export function groupSpeakerLabel(name?: null | string, group?: null | string) {
if (boundary !== -1) {
const connection = trimmed.slice(0, boundary)
const profile = trimmed.slice(boundary + 2)
- const title = String(meta?.[trimmed]?.title || meta?.[profile]?.title || '').trim()
+ // Exact key only: the bare `profile` key is a single-source record and
+ // names whichever machine wrote it, never this connection's bot.
+ const title = String(meta?.[trimmed]?.title || '').trim()
const label = title || (profile.toLowerCase() === 'default' ? 'Hermes' : profile)
// Another connection still exposes this name: keep them tellable apart.
@@ -1495,8 +1497,11 @@ export function groupSpeakerLabel(name?: null | string, group?: null | string) {
}
// Legacy rungs for names the roster cannot place: a bare-keyed Bot Mode
- // title, then the local row's display_name, then default → Hermes.
- const title = String(meta?.[trimmed]?.title || '').trim()
+ // title (single-source rosters only — once rows are connection-scoped the
+ // bare key cannot say which machine it named), then the local row's
+ // display_name, then default → Hermes.
+ const scoped = rows.some(bot => bot.sourceScoped || bot.remoteSource)
+ const title = scoped ? '' : String(meta?.[trimmed]?.title || '').trim()
if (title) {
return title
diff --git a/apps/desktop/src/plugins/hermes-bots/hidden-bots.test.ts b/apps/desktop/src/plugins/hermes-bots/hidden-bots.test.ts
index 5ddfae7fb13..cc65372616c 100644
--- a/apps/desktop/src/plugins/hermes-bots/hidden-bots.test.ts
+++ b/apps/desktop/src/plugins/hermes-bots/hidden-bots.test.ts
@@ -81,7 +81,12 @@ beforeAll(async () => {
beforeEach(() => {
vi.clearAllMocks()
- request.mockResolvedValue({ applied: { ui_meta: true } })
+ // A save reads the bot's server namespace (profiles.list) before writing it.
+ request.mockImplementation(async (method: string) =>
+ method === 'profiles.list'
+ ? { profiles: [{ name: 'default' }, { name: 'ghost' }] }
+ : { applied: { ui_meta: true } }
+ )
})
describe('hiding persists locally and cross-machine', () => {
diff --git a/apps/desktop/src/plugins/hermes-bots/labels.ts b/apps/desktop/src/plugins/hermes-bots/labels.ts
index 587a98390ca..433a60c0ca1 100644
--- a/apps/desktop/src/plugins/hermes-bots/labels.ts
+++ b/apps/desktop/src/plugins/hermes-bots/labels.ts
@@ -21,13 +21,15 @@ export function displayName(bot: Partial<RosterRow>, meta?: BotMeta | null): str
// connection label — the active gateway's own default must keep reading
// "Hermes". Annotated active rows carry sourceScoped too, and keying this
// off sourceScoped renamed the user's main agent to an IP-derived label
- // (community report, Aug 17 2026).
+ // (community report, Aug 17 2026). A display_name its own backend reports
+ // is a real name, never traded for a Desktop-side label.
if (
bot?.remoteSource &&
(bot.name || '').trim().toLowerCase() === 'default' &&
bot.connectionLabel &&
!alias &&
- !meta?.title?.trim()
+ !meta?.title?.trim() &&
+ !bot.display_name?.trim()
) {
return bot.connectionLabel
}
diff --git a/apps/desktop/src/plugins/hermes-bots/plugin.tsx b/apps/desktop/src/plugins/hermes-bots/plugin.tsx
index 18eaefff83b..adc7deb5ed2 100644
--- a/apps/desktop/src/plugins/hermes-bots/plugin.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/plugin.tsx
@@ -175,7 +175,7 @@ export default {
for (const profile of offered) {
const handle = botHandle(profile.name, profile)
- const display = displayName(profile, $botMeta.get()[profile.name])
+ const display = displayName(profile, botRosterMeta(profile, $botMeta.get()))
// Renamed bots complete on their friendly name — the tag is the
// renamed slug when one exists, the profile handle otherwise.
const tag = botMentionTag(profile)
diff --git a/apps/desktop/src/plugins/hermes-bots/profile-ops.test.ts b/apps/desktop/src/plugins/hermes-bots/profile-ops.test.ts
index 691175201da..58806433448 100644
--- a/apps/desktop/src/plugins/hermes-bots/profile-ops.test.ts
+++ b/apps/desktop/src/plugins/hermes-bots/profile-ops.test.ts
@@ -54,7 +54,8 @@ beforeEach(() => {
hostMock.request.mockImplementation(async (method: string, params: Record<string, unknown>) => {
calls.push({ method, params: structuredClone(params ?? {}) })
- return { ok: true }
+ // A save reads the bot's server namespace (profiles.list) before writing it.
+ return method === 'profiles.list' ? { profiles: [{ name: 'researcher' }, { name: 'researcher-2' }] } : { ok: true }
})
})
diff --git a/apps/desktop/src/plugins/hermes-bots/profile-ops.ts b/apps/desktop/src/plugins/hermes-bots/profile-ops.ts
index 74918cbe3d1..8fe8b51de3a 100644
--- a/apps/desktop/src/plugins/hermes-bots/profile-ops.ts
+++ b/apps/desktop/src/plugins/hermes-bots/profile-ops.ts
@@ -35,7 +35,7 @@ import {
} from './data'
import { botConnectionRoute, botRouteKey, requestForBot } from './routing'
import { getPluginCtx } from './shared'
-import type { RosterRow } from './types'
+import type { BotMeta, RosterRow } from './types'
const avatarFetchInflight = new Set<string>()
const avatarPushInflight = new Set<string>()
@@ -216,6 +216,23 @@ export function pullServerAvatars(roster: RosterRow[]) {
}
}
+/** The Bot Mode title a row's OWN backend reports: `''` when it reports none,
+ * undefined when the row cannot say (an older backend, an unenumerated
+ * source). Rich rows answer from ui_meta (CAS-era rows always carry
+ * `ui_meta_revisions`); thin rows from another connection carry `title`
+ * from that backend's `/api/profiles` `bot_title`. */
+function serverReportedTitle(bot: RosterRow, server: BotMeta | null): string | undefined {
+ if (server) {
+ return String(server.title || '').trim()
+ }
+
+ if (Object.prototype.hasOwnProperty.call(bot, 'ui_meta_revisions')) {
+ return ''
+ }
+
+ return typeof bot.title === 'string' ? bot.title.trim() : undefined
+}
+
/** Server ui_meta (per roster row) beats local storage for the compact
* fields it carries; local-only fields (avatar image data URL, extracted
* pet icon) are PRESERVED — the server copy never includes them, so a
@@ -239,9 +256,11 @@ export function mergeServerMeta(roster: RosterRow[], fetchedAt = 0) {
}
for (const bot of roster) {
- const server = bot.ui_meta?.['hermes-bots']
+ const raw = bot.ui_meta?.['hermes-bots']
+ const server = raw && typeof raw === 'object' ? raw : null
+ const title = serverReportedTitle(bot, server)
- if (server && typeof server === 'object') {
+ if (server || title !== undefined) {
const key = botMetaKey(bot)
if (fetchedAt && fetchedAt < (botMetaWriteAt.get(key) || 0)) {
@@ -255,6 +274,15 @@ export function mergeServerMeta(roster: RosterRow[], fetchedAt = 0) {
...server
}
+ // The name is the backend's: a local title it does not carry is stale or
+ // another bot's (a restored record, a legacy name-keyed one), never this
+ // bot's identity.
+ if (title) {
+ merged.title = title
+ } else {
+ delete merged.title
+ }
+
// Local-only fields survive the server overlay.
if (mine.image) {
merged.image = mine.image
@@ -270,7 +298,7 @@ export function mergeServerMeta(roster: RosterRow[], fetchedAt = 0) {
// so retaining the local scalar would resurrect a membership that another
// desktop just removed.
if (
- Array.isArray(server.groups) &&
+ Array.isArray(server?.groups) &&
Object.prototype.hasOwnProperty.call(mine, 'group') &&
!Object.prototype.hasOwnProperty.call(server, 'group')
) {
diff --git a/apps/desktop/src/plugins/hermes-bots/roster-pane-lifecycle.ts b/apps/desktop/src/plugins/hermes-bots/roster-pane-lifecycle.ts
index 100bfe5c957..6fdfe69b49c 100644
--- a/apps/desktop/src/plugins/hermes-bots/roster-pane-lifecycle.ts
+++ b/apps/desktop/src/plugins/hermes-bots/roster-pane-lifecycle.ts
@@ -43,7 +43,13 @@ export function usePublishRosterSnapshot({ data, live, roster, allMeta, activeSo
$lastSources.set(data.sources)
}
- mergeServerMeta(activeSourceRoster, data?.fetchedAt || 0)
+ // Every live row, not just the active source's: a bot on another
+ // connection reports its own title too, and skipping it left that bot
+ // named by whatever this Desktop last cached for it.
+ mergeServerMeta(
+ roster.filter(row => !row?.ghost),
+ data?.fetchedAt || 0
+ )
pullServerAvatars(activeSourceRoster)
trackInboundActivity(roster)
backfillMessagingProtocol(activeSourceRoster)