Skip to content

The agent that grows with you

fix(desktop): deduplicate Bots roster and reuse canonical chats

Jakub Wolniewicz7dd945b92062
diff --git a/apps/desktop/electron/connection-registry.test.ts b/apps/desktop/electron/connection-registry.test.ts
index cc1a54ae1c3..9e6ce7665fb 100644
--- a/apps/desktop/electron/connection-registry.test.ts
+++ b/apps/desktop/electron/connection-registry.test.ts
@@ -195,6 +195,32 @@ test('roster: unreachable sources contribute no rows and cannot fake duplicates'
assert.equal(roster[0].handle, 'research')
})
+test('roster: duplicate profiles from one connection remain one routable agent', () => {
+ const local = { id: 'local', kind: 'local' as const, label: 'This device' }
+ const homelab = { id: 'homelab', kind: 'remote' as const, label: 'Homelab', url: 'http://h:1' }
+
+ const roster = buildAgentRoster([
+ { connection: local, profiles: ['default', 'research', 'default'] },
+ // A duplicate registry enumeration must not make local/research a second
+ // bot identity either.
+ { connection: local, profiles: ['research'] },
+ { connection: homelab, profiles: ['research', 'research'] }
+ ])
+
+ assert.deepEqual(
+ roster.map(agent => `${agent.connectionId}/${agent.profile}`),
+ ['local/default', 'local/research', 'homelab/research']
+ )
+ assert.equal(
+ roster.find(agent => agent.connectionId === 'local' && agent.profile === 'research')?.handle,
+ 'research-this-device'
+ )
+ assert.equal(
+ roster.find(agent => agent.connectionId === 'homelab' && agent.profile === 'research')?.handle,
+ 'research-homelab'
+ )
+})
+
// --- updateEligibility ---
test('update fan-out: cloud is platform-managed, everything else eligible', () => {
diff --git a/apps/desktop/electron/connection-registry.ts b/apps/desktop/electron/connection-registry.ts
index 260e4430f47..a49fba76e26 100644
--- a/apps/desktop/electron/connection-registry.ts
+++ b/apps/desktop/electron/connection-registry.ts
@@ -238,29 +238,39 @@ export interface RosterAgent {
* policy is testable without IPC; main.ts feeds it live enumerations.
*/
export function buildAgentRoster(enumerations: ConnectionAgents[]): RosterAgent[] {
- const counts = new Map<string, number>()
+ // A connection can transiently report the same profile more than once (or
+ // arrive twice while registry state is reconciling). A roster row represents
+ // one routable identity, so collapse strictly by connection + profile before
+ // counting names for @name-device disambiguation.
+ const identities = new Map<string, { connection: RegistryConnection; profile: string }>()
- for (const { profiles } of enumerations) {
+ for (const { connection, profiles } of enumerations) {
for (const profile of profiles || []) {
const name = String(profile || '').trim() || 'default'
- counts.set(name, (counts.get(name) || 0) + 1)
+ const key = `${connection.id}\0${name}`
+
+ if (!identities.has(key)) {
+ identities.set(key, { connection, profile: name })
+ }
}
}
- const roster: RosterAgent[] = []
+ const counts = new Map<string, number>()
- for (const { connection, profiles } of enumerations) {
- for (const profile of profiles || []) {
- const name = String(profile || '').trim() || 'default'
+ for (const { profile } of identities.values()) {
+ counts.set(profile, (counts.get(profile) || 0) + 1)
+ }
- roster.push({
- connectionId: connection.id,
- connectionKind: connection.kind,
- connectionLabel: connection.label,
- profile: name,
- handle: agentHandle(name, connection.label, (counts.get(name) || 0) > 1)
- })
- }
+ const roster: RosterAgent[] = []
+
+ for (const { connection, profile } of identities.values()) {
+ roster.push({
+ connectionId: connection.id,
+ connectionKind: connection.kind,
+ connectionLabel: connection.label,
+ profile,
+ handle: agentHandle(profile, connection.label, (counts.get(profile) || 0) > 1)
+ })
}
return roster
diff --git a/apps/desktop/src/plugins/hermes-bots/plugin.js b/apps/desktop/src/plugins/hermes-bots/plugin.js
index 232b01bb99c..1d190feb6fa 100644
--- a/apps/desktop/src/plugins/hermes-bots/plugin.js
+++ b/apps/desktop/src/plugins/hermes-bots/plugin.js
@@ -2080,7 +2080,23 @@ function useRoster() {
* label so BotRow can badge them and route open/warm through
* ensureAgent/warmAgent. Pure — exercised directly by the tests. */
function mergeMultiSourceRoster(local, union) {
- const profiles = Array.isArray(local?.profiles) ? local.profiles.slice() : []
+ // Keep the first rich local row for every profile. profiles.list is normally
+ // unique, but a duplicated backend response must not turn one agent into an
+ // unbounded list of visually identical Bots rows.
+ const profiles = []
+ const localByName = new Map()
+
+ for (const profile of Array.isArray(local?.profiles) ? local.profiles : []) {
+ const name = String(profile?.name || '').trim()
+
+ if (!name || localByName.has(name)) {
+ continue
+ }
+
+ localByName.set(name, profile)
+ profiles.push(profile)
+ }
+
const agents = Array.isArray(union?.agents) ? union.agents : []
const primaryId = String(union?.primaryConnectionId || '').trim()
@@ -2088,19 +2104,30 @@ function mergeMultiSourceRoster(local, union) {
return { ...local, profiles }
}
- const localByName = new Map(profiles.map(p => [p.name, p]))
+ // host.agents is an Electron/main-process capability. Defend the plugin
+ // boundary too: older shells or reconnect races can still hand us repeated
+ // identities even after the core roster deduplicates them.
+ const seenAgentIdentities = new Set()
for (const agent of agents) {
+ const profile = String(agent?.profile || '').trim()
+ const connectionId = String(agent?.connectionId || '').trim()
+ const identity = `${connectionId}\0${profile}`
+
+ if (!profile || seenAgentIdentities.has(identity)) {
+ continue
+ }
+
+ seenAgentIdentities.add(identity)
+
// The union enumerates EVERY registered connection, including the active
// gateway that already answered profiles.list. Without this the active
// gateway's own agents (connectionKind 'remote' on a remote-primary
// desktop) would be appended as phantom duplicates — every bot listed
// twice. Older Electron builds predate primaryConnectionId; fall back to
// the legacy local-source rule so single-source behavior stays intact.
- const isPrimarySource = primaryId
- ? String(agent.connectionId || '').trim() === primaryId
- : agent.connectionKind === 'local'
- const row = isPrimarySource ? localByName.get(agent.profile) : null
+ const isPrimarySource = primaryId ? connectionId === primaryId : agent.connectionKind === 'local'
+ const row = isPrimarySource ? localByName.get(profile) : null
if (row) {
// Annotate in place: the @name-device handle only differs from the
@@ -2117,9 +2144,9 @@ function mergeMultiSourceRoster(local, union) {
}
profiles.push({
- name: agent.profile,
+ name: profile,
handle: agent.handle,
- connectionId: agent.connectionId,
+ connectionId,
connectionKind: agent.connectionKind,
connectionLabel: agent.connectionLabel,
remoteSource: true
@@ -2235,14 +2262,19 @@ function createCanonicalChat(name) {
async function openBotCanonicalChat(name, pinned) {
let id = pinned
- if (!id) {
- return createCanonicalChat(name)
- }
-
try {
const res = await host.request('session.list', { profile: name, limit: 100 })
const rows = res?.sessions ?? []
+ if (!id && rows.length) {
+ // A CLI/A2A exchange may have created the canonical Bot Chat before the
+ // desktop saved ui_meta.chat. Reuse its explicit title first; for older
+ // bot installs retain the documented grandfathering behavior and adopt
+ // the most recent existing session rather than minting another one.
+ id = rows.find(session => session.title === 'Bot Chat')?.id || rows[0].id
+ saveBotMeta(name, { chat: id })
+ }
+
if (!rows.length) {
saveBotMeta(name, { chat: null })
return createCanonicalChat(name)
@@ -2253,7 +2285,12 @@ async function openBotCanonicalChat(name, pinned) {
saveBotMeta(name, { chat: id })
}
} catch {
- // Gateway hiccup — try the stored pin as-is.
+ // Gateway hiccup — try the stored pin as-is. Without a pin we cannot
+ // safely discover a pre-existing canonical chat, so create one as the
+ // fallback rather than leaving the click inert.
+ if (!id) {
+ return createCanonicalChat(name)
+ }
}
try {
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-empty-recovery.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-empty-recovery.test.mjs
index 9415860328b..1b088ed25aa 100644
--- a/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-empty-recovery.test.mjs
+++ b/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-empty-recovery.test.mjs
@@ -15,9 +15,7 @@ function loadCanonicalRecovery({ openSession, request }) {
$hideBotChats: { get: () => false },
window: { setTimeout: callback => callback() }
}
- const section = source
- .slice(start, end)
- .concat('\nglobalThis.__canonical = { openBotCanonicalChat };\n')
+ const section = source.slice(start, end).concat('\nglobalThis.__canonical = { openBotCanonicalChat };\n')
assert.notEqual(start, -1, 'canonical chat section is missing')
assert.notEqual(end, -1, 'canonical chat section delimiter is missing')
@@ -43,3 +41,28 @@ test('regression: an empty session list clears a stale pin and creates a replace
{ name: 'ops', patch: { chat: 'replacement' } }
])
})
+
+test('regression: an unpinned bot adopts an existing Bot Chat instead of creating another', async () => {
+ const opened = []
+ const requests = []
+ const runtime = loadCanonicalRecovery({
+ openSession: async id => opened.push(id),
+ request: async method => {
+ requests.push(method)
+ if (method === 'session.list') {
+ return {
+ sessions: [
+ { id: 'latest-scratch', title: 'Scratch chat' },
+ { id: 'existing-canonical', title: 'Bot Chat' }
+ ]
+ }
+ }
+ throw new Error(`unexpected ${method}`)
+ }
+ })
+
+ assert.equal(await runtime.openBotCanonicalChat('ops', null), 'existing-canonical')
+ assert.deepEqual(opened, ['existing-canonical'])
+ assert.deepEqual(requests, ['session.list'])
+ assert.deepEqual(JSON.parse(JSON.stringify(runtime.saved)), [{ name: 'ops', patch: { chat: 'existing-canonical' } }])
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/multi-source-roster.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/multi-source-roster.test.mjs
index 5d95a91dcc4..778297c4119 100644
--- a/apps/desktop/src/plugins/hermes-bots/tests/multi-source-roster.test.mjs
+++ b/apps/desktop/src/plugins/hermes-bots/tests/multi-source-roster.test.mjs
@@ -61,7 +61,13 @@ test('merge: local rows are annotated, remote rows appended with source tags', (
profile: 'research',
handle: 'research-homelab'
},
- { connectionId: 'homelab', connectionKind: 'remote', connectionLabel: 'Homelab', profile: 'coder', handle: 'coder' }
+ {
+ connectionId: 'homelab',
+ connectionKind: 'remote',
+ connectionLabel: 'Homelab',
+ profile: 'coder',
+ handle: 'coder'
+ }
]
}
@@ -89,7 +95,13 @@ test('merge: union-only local profiles are NOT invented as thin rows', () => {
const local = { profiles: [{ name: 'default' }] }
const union = {
agents: [
- { connectionId: 'local', connectionKind: 'local', connectionLabel: 'This device', profile: 'ghost', handle: 'ghost' }
+ {
+ connectionId: 'local',
+ connectionKind: 'local',
+ connectionLabel: 'This device',
+ profile: 'ghost',
+ handle: 'ghost'
+ }
]
}
@@ -98,6 +110,43 @@ test('merge: union-only local profiles are NOT invented as thin rows', () => {
assert.equal(out.profiles[0].name, 'default')
})
+test('merge: duplicate source and local identities render once', () => {
+ const { __mergeMultiSourceRoster: merge } = runtime()
+ const local = {
+ profiles: [
+ { name: 'default', last_session: { id: 'newest' } },
+ { name: 'default', last_session: { id: 'stale' } }
+ ]
+ }
+ const union = {
+ agents: [
+ { connectionId: 'local', connectionKind: 'local', profile: 'default', handle: 'default-this-device' },
+ { connectionId: 'local', connectionKind: 'local', profile: 'default', handle: 'default-this-device' },
+ {
+ connectionId: 'homelab',
+ connectionKind: 'remote',
+ connectionLabel: 'Homelab',
+ profile: 'default',
+ handle: 'default-homelab'
+ },
+ {
+ connectionId: 'homelab',
+ connectionKind: 'remote',
+ connectionLabel: 'Homelab',
+ profile: 'default',
+ handle: 'default-homelab'
+ }
+ ]
+ }
+
+ const out = merge(local, union)
+
+ assert.equal(out.profiles.length, 2)
+ assert.equal(out.profiles[0].last_session.id, 'newest')
+ assert.equal(out.profiles[0].handle, 'default-this-device')
+ assert.equal(out.profiles[1].connectionId, 'homelab')
+})
+
test('botHandle: precomputed multi-source handle wins; default stays hermes', () => {
const { __botHandle: botHandle } = runtime()