Skip to content

The agent that grows with you

fix(desktop): align BOTS roster preview with the session its click opens

NealZhouPanda848478683245
diff --git a/apps/desktop/src/plugins/hermes-bots/plugin.js b/apps/desktop/src/plugins/hermes-bots/plugin.js
index 254e31904ea..7d65060de0b 100644
--- a/apps/desktop/src/plugins/hermes-bots/plugin.js
+++ b/apps/desktop/src/plugins/hermes-bots/plugin.js
@@ -2189,6 +2189,21 @@ function PetTab({ image, onImage }) {
* Gates every SOUL.md protocol append below. */
let serverInjectsProtocol = false
+/** Pins to resolve precisely on the next roster poll: {profile: chatId}.
+ * The backend answers "what about THIS conversation" per entry
+ * (preferred_session), so a row's preview can describe the same session its
+ * click opens (hermes-agent#88200). Unknown params are ignored by older
+ * gateways, which simply omit the field. */
+function preferredSessionIds(allMeta) {
+ const pins = {}
+ for (const [name, meta] of Object.entries(allMeta || {})) {
+ if (meta?.chat) {
+ pins[name] = meta.chat
+ }
+ }
+ return pins
+}
+
function useRoster() {
const activeConnectionId = useValue(host.state.connectionId)
@@ -2197,7 +2212,11 @@ function useRoster() {
queryFn: async () => {
// Rich rows (last_session, ui_meta, has_avatar) come from the ACTIVE
// gateway's profiles.list — unchanged single-source behavior.
- const local = await host.request('profiles.list', {})
+ const pins = preferredSessionIds($botMeta.get())
+ const local = await host.request(
+ 'profiles.list',
+ Object.keys(pins).length ? { preferred_session_ids: pins } : {}
+ )
// Newer backends inject the teammate-messaging protocol into every
// session's system prompt (agent.bot_mode_protocol) — SOUL.md must not
// carry a second copy. Older gateways lack the flag: keep appending.
@@ -2653,55 +2672,94 @@ function createCanonicalChat(name) {
return run
}
-async function openBotCanonicalChat(name, pinned) {
- let id = pinned
+/** Open the bot's ONE forever chat and return the opened id (or the pin).
+ *
+ * Identity rules (hermes-agent#88200 — the row must open the session its
+ * preview describes):
+ * - grandfather: no pin + existing history adopts the previewed session
+ * (`history`, the roster's last_session for this bot) instead of minting
+ * a new empty chat;
+ * - a live pin is verified through the backend's precise preferred_session
+ * resolver (hidden rows still resolve; compression lineages resolve to
+ * the live tip) — never inferred from a paginated, hidden-excluding
+ * session.list window, which misjudged real hidden pins as gone;
+ * - transient lookup failures keep the pin: try the stored id as-is, and
+ * only a rejected open enters recovery. */
+async function openBotCanonicalChat(name, pinned, history) {
+ if (!pinned) {
+ // Grandfather: adopt the conversation the row already previews.
+ const adoptId = history?.id
+ if (adoptId && typeof host.openSession === 'function') {
+ try {
+ await host.openSession(adoptId, { profile: name })
+ saveBotMeta(name, { chat: adoptId })
+ return adoptId
+ } catch {
+ // Adoption raced a vanishing session — fall through to creation.
+ }
+ }
+ return createCanonicalChat(name)
+ }
+ // Precise verification. An older gateway ignores the unknown param and
+ // omits the key — that reads as a lookup failure below, NOT as a missing
+ // session, so legacy backends keep the try-as-is escape hatch.
+ let preferred
+ let lookupFailed = false
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 })
+ const res = await host.request('profiles.list', {
+ include_sessions: true,
+ preferred_session_ids: { [name]: pinned }
+ })
+ const row = (res?.profiles ?? []).find(p => p.name === name)
+ preferred = row?.preferred_session
+ if (preferred === undefined) {
+ lookupFailed = true
}
+ } catch {
+ lookupFailed = true
+ }
- if (!rows.length) {
+ if (lookupFailed) {
+ // Transient gateway state (or an older backend): the pin is innocent
+ // until proven guilty — try it as-is, and only a rejected open clears.
+ try {
+ await host.openSession(pinned, { profile: name })
+ return pinned
+ } catch {
saveBotMeta(name, { chat: null })
return createCanonicalChat(name)
}
+ }
- if (!rows.some(session => session.id === id)) {
- const titled = rows.find(session => session.title === 'Bot Chat')
-
- if (titled) {
- id = titled.id
- saveBotMeta(name, { chat: id })
- }
- // Pin is not in this page and there is no Bot Chat title.
- // Try the stored pin as-is. Do not steal the newest session.
- }
- } catch {
- // 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)
+ if (preferred) {
+ try {
+ await host.openSession(preferred.resolved_id || preferred.id, { profile: name })
+ return pinned
+ } catch (error) {
+ // The precise lookup JUST confirmed this session exists, so a failed
+ // open is transient (reconnect, backend restart). Clearing the pin or
+ // minting a replacement here would fork the bot's forever-chat on
+ // every hiccup — report and keep everything as it is.
+ host.notifyError?.(error, `Could not open ${name}'s chat — try again`)
+ return pinned
}
}
- try {
- await host.openSession(id, { profile: name })
- return id
- } catch {
- // A rejected resume means the pin is unusable even if list recovery was
- // inconclusive. Clear it first so a failed replacement can be retried.
- saveBotMeta(name, { chat: null })
- return createCanonicalChat(name)
+ // Definitively gone (db reset, or the lineage was rewritten past
+ // recovery): re-anchor on the previewed session when there is one.
+ const recoveryId = history?.id
+ if (recoveryId && typeof host.openSession === 'function') {
+ try {
+ await host.openSession(recoveryId, { profile: name })
+ saveBotMeta(name, { chat: recoveryId })
+ return recoveryId
+ } catch {
+ // Fall through to a fresh chat.
+ }
}
+ saveBotMeta(name, { chat: null })
+ return createCanonicalChat(name)
}
async function prepareBotSource(bot, pinnedChat) {
@@ -3625,11 +3683,16 @@ function BotRow({ bot, onDelete, onEdit, onGroup }) {
const unread = !bot.remoteSource && Boolean(unreadByName[bot.name])
// WHO sent the last message (bot-to-bot DM vs human) — the full stored
// history lives in the Sessions workspace (context menu), not inline.
- const { fromBot } = previewKind(last?.preview)
+ // Preview identity must match click identity (#88200): when the backend
+ // resolved the pinned canonical chat, preview THAT session — not the
+ // profile's most recent (but unrelated) activity. Liveness checks above
+ // keep last_session semantics: any recent activity means the bot is alive.
+ const previewSession = bot.preferred_session || last
+ const { fromBot } = previewKind(previewSession?.preview)
// DM previews read like DMs: strip the delivery prefix, keep the message.
const displayPreview = fromBot
- ? (last?.preview || '').replace(A2A_PREFIX_RE, '').trim() || '…'
- : last?.preview || bot.description || 'No conversations yet — say hi'
+ ? (previewSession?.preview || '').replace(A2A_PREFIX_RE, '').trim() || '…'
+ : previewSession?.preview || bot.description || 'No conversations yet — say hi'
const warm = () => {
// Multi-source row: pre-dial the agent's OWN source (feature-detected).
@@ -3687,7 +3750,7 @@ function BotRow({ bot, onDelete, onEdit, onGroup }) {
}
try {
- const id = await openBotCanonicalChat(bot.name, pinnedChat)
+ const id = await openBotCanonicalChat(bot.name, pinnedChat, bot.last_session)
if (id) {
return
@@ -7322,7 +7385,7 @@ function BotsPane() {
}
try {
- const id = await openBotCanonicalChat(bot.name, pinnedChat)
+ const id = await openBotCanonicalChat(bot.name, pinnedChat, bot.last_session)
if (id) {
return
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/active-now-strip.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/active-now-strip.test.mjs
index ae8a816ca1f..59d0a36c700 100644
--- a/apps/desktop/src/plugins/hermes-bots/tests/active-now-strip.test.mjs
+++ b/apps/desktop/src/plugins/hermes-bots/tests/active-now-strip.test.mjs
@@ -94,5 +94,5 @@ test('ActiveNowStrip renders above the roster, is a live region, and is click-ac
assert.match(source, /jsx\(BotFace,\s*\{[\s\S]*?mood: 'work'/)
assert.match(source, /let pinnedChat = botRosterMeta\(bot, allMeta\)\?\.chat/)
assert.match(source, /await prepareBotSource\(bot, pinnedChat\)/)
- assert.match(source, /openBotCanonicalChat\(bot\.name, pinnedChat\)/)
+ assert.match(source, /openBotCanonicalChat\(bot\.name, pinnedChat, bot\.last_session\)/)
})
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 be3cda3de75..76a93ffa410 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
@@ -9,8 +9,15 @@ function loadCanonicalRecovery({ openSession, request }) {
const start = source.indexOf('const canonicalCreations = new Map()')
const end = source.indexOf('function displayName(', start)
const saved = []
+ const requests = []
const context = {
- host: { openSession, request },
+ host: {
+ openSession,
+ request: async (method, params) => {
+ requests.push(method)
+ return request(method, params)
+ }
+ },
saveBotMeta: (name, patch) => saved.push({ name, patch }),
$hideBotChats: { get: () => false },
window: { setTimeout: callback => callback() }
@@ -20,21 +27,26 @@ function loadCanonicalRecovery({ openSession, request }) {
assert.notEqual(start, -1, 'canonical chat section is missing')
assert.notEqual(end, -1, 'canonical chat section delimiter is missing')
vm.runInNewContext(section, context, { filename: 'canonical-recovery.js' })
- return { ...context.__canonical, saved }
+ return { ...context.__canonical, saved, requests }
}
-test('regression: an empty session list clears a stale pin and creates a replacement', async () => {
+test('regression: a definitively-gone pin with no history clears and creates a replacement', async () => {
+ // New contract (hermes-agent#88200): the pin is verified through the
+ // backend's precise preferred_session resolver — NOT a paginated,
+ // hidden-excluding session.list window. preferred_session=null is the
+ // definitive "this session is gone"; with no previewed history to
+ // re-anchor on, recovery clears the pin and creates a fresh chat.
const opened = []
const runtime = loadCanonicalRecovery({
openSession: async id => opened.push(id),
request: async method => {
- if (method === 'session.list') return { sessions: [] }
+ if (method === 'profiles.list') return { profiles: [{ name: 'ops', preferred_session: null }] }
if (method === 'session.create') return { stored_session_id: 'replacement', session_id: 'replacement-runtime' }
return {}
}
})
- assert.equal(await runtime.openBotCanonicalChat('ops', 'stale-pin'), 'replacement')
+ assert.equal(await runtime.openBotCanonicalChat('ops', 'stale-pin', null), 'replacement')
assert.deepEqual(opened, ['replacement'])
assert.deepEqual(JSON.parse(JSON.stringify(runtime.saved)), [
{ name: 'ops', patch: { chat: null } },
@@ -42,71 +54,64 @@ test('regression: an empty session list clears a stale pin and creates a replace
])
})
-test('regression: an unpinned bot adopts an existing Bot Chat instead of creating another', async () => {
+test('regression: an unpinned bot adopts its previewed chat instead of creating another', async () => {
+ // A CLI/A2A exchange can create the canonical chat before the desktop
+ // saves ui_meta.chat. Grandfathering adopts the session the row already
+ // previews (the roster's last_session) rather than minting a new one.
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}`)
+ if (method === 'session.create') throw new Error('must not create')
+ return {}
}
})
- assert.equal(await runtime.openBotCanonicalChat('ops', null), 'existing-canonical')
+ const history = { id: 'existing-canonical', title: 'Bot Chat', preview: 'hey', last_active: 5 }
+ assert.equal(await runtime.openBotCanonicalChat('ops', null, history), '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' } }])
+ assert.deepEqual(JSON.parse(JSON.stringify(runtime.saved)), [
+ { name: 'ops', patch: { chat: 'existing-canonical' } }
+ ])
})
-test('regression: a missing pin reuses a Bot Chat instead of the newest session', async () => {
+test('regression: a dead pin re-anchors on the previewed chat instead of the newest session', async () => {
+ // hermes-agent#88146: recovery must never steal an unrelated scratch
+ // session. A pin the backend reports definitively gone re-anchors on the
+ // previewed history row when one exists — session.create never fires.
const opened = []
const runtime = loadCanonicalRecovery({
openSession: async id => opened.push(id),
request: async method => {
- if (method === 'session.list') {
- return {
- sessions: [
- { id: 'scratch-from-cli', title: 'scratch' },
- { id: 'the-real-bot-chat', title: 'Bot Chat' }
- ]
- }
- }
+ if (method === 'profiles.list') return { profiles: [{ name: 'ops', preferred_session: null }] }
if (method === 'session.create') throw new Error('must not create')
return {}
}
})
- assert.equal(await runtime.openBotCanonicalChat('ops', 'old-pin'), 'the-real-bot-chat')
+ const history = { id: 'the-real-bot-chat', title: 'Bot Chat', preview: 'p', last_active: 9 }
+ assert.equal(await runtime.openBotCanonicalChat('ops', 'old-pin', history), 'the-real-bot-chat')
assert.deepEqual(opened, ['the-real-bot-chat'])
assert.deepEqual(JSON.parse(JSON.stringify(runtime.saved)), [
{ name: 'ops', patch: { chat: 'the-real-bot-chat' } }
])
})
-test('regression: a pin not in the last page is opened as-is when no Bot Chat title exists', async () => {
+test('regression: an inconclusive lookup opens the stored pin as-is and never rewrites it', async () => {
+ // hermes-agent#88146: an older backend (profiles.list without the
+ // preferred_session_ids param) or a transient hiccup is NOT proof the pin
+ // is gone. The pin is opened as-is; nothing is saved, nothing is created.
const opened = []
const runtime = loadCanonicalRecovery({
openSession: async id => opened.push(id),
- request: async (method, params) => {
- if (method === 'session.list') {
- assert.equal(params.limit, 100)
- return { sessions: [{ id: 'recent-0', title: 'scratch' }] }
- }
+ request: async method => {
+ if (method === 'profiles.list') return { profiles: [{ name: 'ops' }] }
if (method === 'session.create') throw new Error('must not create')
return {}
}
})
- assert.equal(await runtime.openBotCanonicalChat('ops', 'old-pin-outside-page'), 'old-pin-outside-page')
+ assert.equal(await runtime.openBotCanonicalChat('ops', 'old-pin-outside-page', null), 'old-pin-outside-page')
assert.deepEqual(opened, ['old-pin-outside-page'])
assert.equal(runtime.saved.length, 0)
})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-identity.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-identity.test.mjs
new file mode 100644
index 00000000000..3209864ad4e
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-identity.test.mjs
@@ -0,0 +1,289 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+import vm from 'node:vm'
+
+const source = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
+// ── canonical open-path harness (slice: createCanonicalChat + openBotCanonicalChat)
+function loadOpenPath({ openSession, request }) {
+ const start = source.indexOf('const canonicalCreations = new Map()')
+ const end = source.indexOf('function displayName(', start)
+ const saved = []
+ const requests = []
+ const context = {
+ host: {
+ openSession,
+ request: async (method, params) => {
+ requests.push({ method, params })
+ return request(method, params)
+ }
+ },
+ saveBotMeta: (name, patch) => saved.push({ name, patch: JSON.parse(JSON.stringify(patch)) }),
+ $hideBotChats: { get: () => false },
+ window: { setTimeout: callback => callback() }
+ }
+ const section = source
+ .slice(start, end)
+ .concat('\nglobalThis.__open = { openBotCanonicalChat };\n')
+
+ assert.notEqual(start, -1, 'canonical creation section is missing')
+ assert.notEqual(end, -1, 'canonical creation section delimiter is missing')
+ vm.runInNewContext(section, context, { filename: 'canonical-open.js' })
+ return { ...context.__open, saved, requests, host: context.host }
+}
+
+const HISTORY = { id: 'hist-1', title: 'Weekly review', preview: 'history preview', last_active: 1000 }
+
+// ── grandfather: no pin + existing history adopts the previewed session ────
+
+test('grandfather: no pin + history opens and pins THAT session, no new chat', async () => {
+ const runtime = loadOpenPath({
+ openSession: async () => undefined,
+ request: async () => ({})
+ })
+
+ const result = await runtime.openBotCanonicalChat('ops', null, HISTORY)
+
+ assert.equal(result, 'hist-1')
+ assert.deepEqual(runtime.saved, [{ name: 'ops', patch: { chat: 'hist-1' } }])
+ assert.equal(runtime.requests.some(r => r.method === 'session.create'), false,
+ 'must not mint a new chat when the previewed session can be adopted')
+})
+
+test('grandfather: no pin + no history keeps the creation flow', async () => {
+ const runtime = loadOpenPath({
+ openSession: async () => undefined,
+ request: async method =>
+ method === 'session.create' ? { stored_session_id: 'stored-1', session_id: 'runtime-1' } : {}
+ })
+
+ const result = await runtime.openBotCanonicalChat('ops', null, null)
+
+ assert.equal(result, 'stored-1')
+ assert.equal(runtime.requests.some(r => r.method === 'session.create'), true)
+})
+
+test('grandfather: adoption open failure falls back to creation without pinning', async () => {
+ const runtime = loadOpenPath({
+ openSession: async id => {
+ if (id === 'hist-1') throw new Error('session vanished')
+ },
+ request: async method =>
+ method === 'session.create' ? { stored_session_id: 'stored-2', session_id: 'runtime-2' } : {}
+ })
+
+ const result = await runtime.openBotCanonicalChat('ops', null, HISTORY)
+
+ assert.equal(result, 'stored-2')
+ assert.equal(runtime.saved.some(s => s.patch?.chat === 'hist-1'), false,
+ 'a failed adoption must not persist the dead id as the pin')
+})
+
+// ── precise pin verification (no session.list pagination/hidden semantics) ─
+
+test('pin: preferred_session present opens the resolved session and keeps the pin', async () => {
+ const runtime = loadOpenPath({
+ openSession: async () => undefined,
+ request: async method => {
+ if (method === 'profiles.list') {
+ return {
+ profiles: [{
+ name: 'ops',
+ preferred_session: {
+ id: 'pin-1', resolved_id: 'pin-1', title: 'Bot Chat',
+ preview: 'latest', started_at: 1, last_active: 2, message_count: 3
+ }
+ }]
+ }
+ }
+ return {}
+ }
+ })
+
+ const result = await runtime.openBotCanonicalChat('ops', 'pin-1', HISTORY)
+
+ assert.equal(result, 'pin-1')
+ assert.equal(runtime.saved.length, 0, 'a live pin must not be rewritten')
+ assert.equal(runtime.requests.some(r => r.method === 'session.create'), false)
+ // The pin is verified through the precise resolver, never session.list.
+ assert.equal(runtime.requests.some(r => r.method === 'session.list'), false)
+})
+
+test('pin: compression-rotated pin opens the live tip, keeps the durable pin', async () => {
+ const opened = []
+ const runtime = loadOpenPath({
+ openSession: async id => { opened.push(id) },
+ request: async method => {
+ if (method === 'profiles.list') {
+ return {
+ profiles: [{
+ name: 'ops',
+ preferred_session: {
+ id: 'root-1', resolved_id: 'tip-9', title: 'Bot Chat',
+ preview: 'post-compression', started_at: 1, last_active: 9, message_count: 42
+ }
+ }]
+ }
+ }
+ return {}
+ }
+ })
+
+ const result = await runtime.openBotCanonicalChat('ops', 'root-1', HISTORY)
+
+ assert.deepEqual(opened, ['tip-9'])
+ assert.equal(result, 'root-1', 'the stored pin keeps its durable identity')
+ assert.equal(runtime.saved.length, 0)
+})
+
+test('pin: definitively gone pin re-pins to the previewed session, not rows[0]', async () => {
+ const runtime = loadOpenPath({
+ openSession: async () => undefined,
+ request: async method => {
+ if (method === 'profiles.list') {
+ return { profiles: [{ name: 'ops', preferred_session: null }] }
+ }
+ return {}
+ }
+ })
+
+ const result = await runtime.openBotCanonicalChat('ops', 'dead-pin', HISTORY)
+
+ assert.equal(result, 'hist-1')
+ assert.deepEqual(runtime.saved, [{ name: 'ops', patch: { chat: 'hist-1' } }])
+ assert.equal(runtime.requests.some(r => r.method === 'session.create'), false)
+})
+
+test('pin: gone pin + no history clears the pin and creates', async () => {
+ const runtime = loadOpenPath({
+ openSession: async () => undefined,
+ request: async method => {
+ if (method === 'profiles.list') {
+ return { profiles: [{ name: 'ops', preferred_session: null }] }
+ }
+ if (method === 'session.create') return { stored_session_id: 'stored-3', session_id: 'runtime-3' }
+ return {}
+ }
+ })
+
+ const result = await runtime.openBotCanonicalChat('ops', 'dead-pin', null)
+
+ assert.equal(result, 'stored-3')
+ // Pin cleared first (dead pin is provably unusable), then the freshly
+ // created chat pins itself inside createCanonicalChat.
+ assert.deepEqual(runtime.saved, [
+ { name: 'ops', patch: { chat: null } },
+ { name: 'ops', patch: { chat: 'stored-3' } }
+ ])
+})
+
+test('pin: precise hit but failed open keeps the pin and reports', async () => {
+ const notes = []
+ const runtime = loadOpenPath({
+ openSession: async () => { throw new Error('socket hiccup') },
+ request: async method => {
+ if (method === 'profiles.list') {
+ return {
+ profiles: [{
+ name: 'ops',
+ preferred_session: {
+ id: 'pin-1', resolved_id: 'pin-1', title: 'Bot Chat',
+ preview: 'latest', started_at: 1, last_active: 2, message_count: 3
+ }
+ }]
+ }
+ }
+ return {}
+ }
+ })
+ runtime.host.notifyError = (error, title) => notes.push({ error: String(error), title })
+
+ const result = await runtime.openBotCanonicalChat('ops', 'pin-1', HISTORY)
+
+ assert.equal(result, 'pin-1')
+ assert.equal(runtime.saved.length, 0, 'a confirmed-live pin must survive a transient open failure')
+ assert.equal(runtime.requests.some(r => r.method === 'session.create'), false,
+ 'must not fork the forever-chat on a hiccup')
+ assert.equal(notes.length, 1, 'the user gets told the open failed')
+})
+
+// ── transient failures must never destroy the pin ──────────────────────────
+
+test('transient: profiles.list failure keeps the pin when the direct open works', async () => {
+ const runtime = loadOpenPath({
+ openSession: async () => undefined,
+ request: async method => {
+ if (method === 'profiles.list') throw new Error('gateway reconnecting')
+ return {}
+ }
+ })
+
+ const result = await runtime.openBotCanonicalChat('ops', 'pin-1', HISTORY)
+
+ assert.equal(result, 'pin-1')
+ assert.equal(runtime.saved.length, 0, 'a hiccup must not clear or rewrite the pin')
+ assert.equal(runtime.requests.some(r => r.method === 'session.create'), false,
+ 'a hiccup must not mint a replacement chat')
+})
+
+test('transient: profiles.list failure + failed direct open clears pin and creates', async () => {
+ const runtime = loadOpenPath({
+ // Only the stale PIN's open is rejected; the creation flow's own
+ // openSession calls must succeed.
+ openSession: async id => {
+ if (id === 'pin-1') throw new Error('resume rejected')
+ },
+ request: async method => {
+ if (method === 'profiles.list') throw new Error('gateway reconnecting')
+ if (method === 'session.create') return { stored_session_id: 'stored-4', session_id: 'runtime-4' }
+ return {}
+ }
+ })
+
+ const result = await runtime.openBotCanonicalChat('ops', 'pin-1', HISTORY)
+
+ assert.equal(result, 'stored-4')
+ assert.deepEqual(runtime.saved, [
+ { name: 'ops', patch: { chat: null } },
+ { name: 'ops', patch: { chat: 'stored-4' } }
+ ])
+})
+
+// ── preferred_session_ids request shaping (pure helper) ────────────────────
+
+function loadHelpers() {
+ const atom = value => ({ get: () => value, set: () => undefined })
+ const jsx = (type, props = {}) => ({ type, props })
+ const context = {
+ atom,
+ jsx,
+ jsxs: jsx,
+ useQuery: () => ({}),
+ useValue: value => (value?.get ? value.get() : value),
+ useState: value => [value, () => undefined],
+ document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } },
+ host: { state: { profile: { get: () => 'ops', listen: () => undefined } }, request: () => undefined }
+ }
+ const code = source
+ .replace(/^import\s+\*\s+as\s+sdk\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^import\s+\{[\s\S]*?\}\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^const \{ McpTab, ToolsetConfigPanel \} = sdk\r?\n/m, '')
+ .replace(/^import .* from 'react'\r?\n/m, '')
+ .replace(/^import .* from 'react\/jsx-runtime'\r?\n/m, '')
+ .replace('export default {', 'globalThis.plugin = {')
+ .concat('\nglobalThis.__preferredSessionIds = preferredSessionIds;')
+ vm.runInNewContext(code, context)
+ return context
+}
+
+test('preferredSessionIds: collects only live pins', () => {
+ // vm-realm objects fail assert.deepEqual prototype checks — compare via JSON.
+ const collect = meta => JSON.parse(JSON.stringify(loadHelpers().__preferredSessionIds(meta)))
+ assert.deepEqual(
+ collect({ ops: { chat: 'pin-1' }, scribe: { chat: null }, chef: { title: 'Chef' } }),
+ { ops: 'pin-1' }
+ )
+ assert.deepEqual(collect({}), {})
+ assert.deepEqual(collect(undefined), {})
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-pin.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-pin.test.mjs
index e6f41a2b179..b2796ba933b 100644
--- a/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-pin.test.mjs
+++ b/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-pin.test.mjs
@@ -1,29 +1,86 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
+import vm from 'node:vm'
-// #24's guarantee (preserve a valid canonical pin instead of clobbering it from
-// a bounded session list) is now enforced inside openBotCanonicalChat(), which
-// #28 introduced to unify the create / recover / replace lifecycle. This test
-// pins that guarantee against the current structure: a valid pinned id present
-// in the session list must be opened as-is (never replaced), and only an
-// ACTUALLY-missing pin triggers recovery.
+// #24's guarantee — a VALID canonical pin is opened as-is, never replaced,
+// and only an ACTUALLY-missing pin triggers recovery — used to be pinned
+// against the old implementation's source shape (session.list rows[0]
+// fallback). hermes-agent#88200 replaced that windowed, hidden-excluding
+// lookup with the backend's precise preferred_session resolver, so the
+// guarantee is now pinned as BEHAVIOR: what gets opened, what gets saved,
+// and what never happens to a live pin.
const source = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
-const start = source.indexOf('async function openBotCanonicalChat(')
-assert.notEqual(start, -1, 'openBotCanonicalChat declaration is missing')
-const end = source.indexOf('\nfunction ', start)
-const fnSource = source.slice(start, end === -1 ? undefined : end)
-
-test('regression: a pinned canonical chat found in the list is opened, not replaced', () => {
- // The pin is opened directly with its own id under the bot's profile.
- assert.match(fnSource, /host\.openSession\(id, \{ profile: name \}\)/)
- // A missing pin looks for a session titled Bot Chat, not the newest row.
- assert.match(fnSource, /if \(!rows\.some\(session => session\.id === id\)\)/)
- assert.match(fnSource, /session\.title === 'Bot Chat'/)
- assert.doesNotMatch(fnSource, /id = rows\[0\]\.id/)
- // ...and an empty list clears the stale pin before recreating (the #28 fix),
- // rather than opening a known-bad id.
- assert.match(fnSource, /if \(!rows\.length\)/)
- assert.match(fnSource, /return createCanonicalChat\(name\)/)
+
+function loadOpenPath({ openSession, request }) {
+ const start = source.indexOf('const canonicalCreations = new Map()')
+ const end = source.indexOf('function displayName(', start)
+ const saved = []
+ const requests = []
+ const context = {
+ host: {
+ openSession,
+ request: async (method, params) => {
+ requests.push({ method, params })
+ return request(method, params)
+ }
+ },
+ saveBotMeta: (name, patch) => saved.push({ name, patch: JSON.parse(JSON.stringify(patch)) }),
+ $hideBotChats: { get: () => false },
+ window: { setTimeout: callback => callback() }
+ }
+ const section = source
+ .slice(start, end)
+ .concat('\nglobalThis.__open = { openBotCanonicalChat };\n')
+
+ assert.notEqual(start, -1, 'canonical chat section is missing')
+ assert.notEqual(end, -1, 'canonical chat section delimiter is missing')
+ vm.runInNewContext(section, context, { filename: 'canonical-pin.js' })
+ return { ...context.__open, saved, requests }
+}
+
+test('regression: a live pinned canonical chat is opened as-is, never replaced', async () => {
+ const opened = []
+ const runtime = loadOpenPath({
+ openSession: async id => opened.push(id),
+ request: async method => {
+ if (method === 'profiles.list') {
+ return {
+ profiles: [{
+ name: 'ops',
+ preferred_session: {
+ id: 'pin-1', resolved_id: 'pin-1', title: 'Bot Chat',
+ preview: 'latest', started_at: 1, last_active: 2, message_count: 3
+ }
+ }]
+ }
+ }
+ return {}
+ }
+ })
+
+ assert.equal(await runtime.openBotCanonicalChat('ops', 'pin-1', null), 'pin-1')
+ assert.deepEqual(opened, ['pin-1'], 'the pin itself is opened under the bot profile')
+ assert.deepEqual(runtime.saved, [], 'a live pin is never rewritten')
+ assert.equal(runtime.requests.some(r => r.method === 'session.create'), false,
+ 'a live pin never triggers a replacement chat')
+})
+
+test('regression: only an actually-missing pin triggers recovery', async () => {
+ const runtime = loadOpenPath({
+ openSession: async () => undefined,
+ request: async method => {
+ if (method === 'profiles.list') {
+ return { profiles: [{ name: 'ops', preferred_session: null }] }
+ }
+ return {}
+ }
+ })
+
+ // Definitively gone, but the roster still previews a live session —
+ // recovery re-anchors on THAT session instead of minting a new chat.
+ const history = { id: 'hist-1', title: 'Weekly review', preview: 'p', last_active: 1 }
+ assert.equal(await runtime.openBotCanonicalChat('ops', 'dead-pin', history), 'hist-1')
+ assert.deepEqual(runtime.saved, [{ name: 'ops', patch: { chat: 'hist-1' } }])
})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/roster-preview.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/roster-preview.test.mjs
index 3558677f299..a91d9513e38 100644
--- a/apps/desktop/src/plugins/hermes-bots/tests/roster-preview.test.mjs
+++ b/apps/desktop/src/plugins/hermes-bots/tests/roster-preview.test.mjs
@@ -189,3 +189,23 @@ test('render: BotRow tolerates a fresh bot with no sessions yet', () => {
const text = textOf(tree)
assert.match(text, /Fresh bot/)
})
+
+test('render: BotRow previews the pinned canonical chat, not an unrelated latest session', () => {
+ // hermes-agent#88200: the row opens the pinned chat on click, so the
+ // preview must describe that same session — not the profile's most recent
+ // (but unrelated) activity.
+ const r = renderRuntime()
+ const tree = r.__BotRow({
+ bot: {
+ name: 'ops',
+ title: 'Ops',
+ description: '',
+ last_session: { id: 'scratch9', title: 'Scratch', preview: 'unrelated scratch content', last_active: 1_800_000_000 },
+ preferred_session: { id: 'pinned1', resolved_id: 'pinned1', title: 'Bot Chat', preview: 'pinned chat content', started_at: 1, last_active: 1_700_000_000, message_count: 5 }
+ },
+ onEdit: () => undefined
+ })
+ const text = textOf(tree)
+ assert.match(text, /pinned chat content/)
+ assert.doesNotMatch(text, /unrelated scratch content/)
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/session-workspace.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/session-workspace.test.mjs
index 1cad2156a6f..3c3665ff8e8 100644
--- a/apps/desktop/src/plugins/hermes-bots/tests/session-workspace.test.mjs
+++ b/apps/desktop/src/plugins/hermes-bots/tests/session-workspace.test.mjs
@@ -126,8 +126,8 @@ test('source contract: bot rows and Active now activate the owner before canonic
assert.match(pluginSource, /async function prepareBotSource\(bot, pinnedChat\)/)
assert.match(pluginSource, /await host\.ensureAgent\(bot\.connectionId, bot\.name\)/)
assert.match(pluginSource, /host\.request\('profiles\.list', \{\}\)/)
- assert.match(pluginSource, /const open = async \(\) => \{[\s\S]*await prepareBotSource\(bot, pinnedChat\)[\s\S]*openBotCanonicalChat\(bot\.name, pinnedChat\)/)
- assert.match(pluginSource, /onOpen: bot => \{[\s\S]*await prepareBotSource\(bot, pinnedChat\)[\s\S]*openBotCanonicalChat\(bot\.name, pinnedChat\)/)
+ assert.match(pluginSource, /const open = async \(\) => \{[\s\S]*await prepareBotSource\(bot, pinnedChat\)[\s\S]*openBotCanonicalChat\(bot\.name, pinnedChat, bot\.last_session\)/)
+ assert.match(pluginSource, /onOpen: bot => \{[\s\S]*await prepareBotSource\(bot, pinnedChat\)[\s\S]*openBotCanonicalChat\(bot\.name, pinnedChat, bot\.last_session\)/)
assert.match(pluginSource, /openBotSessionsWorkspace\(bot\)[\s\S]*children: 'Sessions'/)
})
diff --git a/tests/tui_gateway/test_profiles_list_preferred_session.py b/tests/tui_gateway/test_profiles_list_preferred_session.py
new file mode 100644
index 00000000000..15b2a24dc75
--- /dev/null
+++ b/tests/tui_gateway/test_profiles_list_preferred_session.py
@@ -0,0 +1,208 @@
+"""Tests: profiles.list ``preferred_session_ids`` precise session summaries.
+
+Why: the desktop BOTS roster previews ``last_session`` (the profile's most
+recently active session) but clicking a bot row opens the PINNED canonical
+chat — two different session identities, so the preview shows one
+conversation and the click lands in another (NousResearch/hermes-agent#88200).
+The generic fix at the RPC layer: callers that know which session they care
+about pass ``preferred_session_ids={profile: session_id}`` and receive a
+precise ``preferred_session`` summary per profile — hidden sessions included,
+compression lineages resolved to the live tip, no pagination window — while
+``last_session`` keeps its existing "most recent" contract.
+
+Contract under test:
+- A profile named in the map gets ``preferred_session``: a summary dict when
+ the id resolves, ``None`` when it definitively does not (missing row,
+ denied internal source).
+- Summary keys: ``id`` (the requested pin, durable identity), ``resolved_id``
+ (live compression tip; equal to ``id`` when uncompressed), ``title``,
+ ``preview`` (newest user/assistant text at the tip), ``started_at``,
+ ``last_active``, ``message_count``.
+- Profiles not named in the map carry no ``preferred_session`` key at all.
+- ``last_session`` behaviour is unchanged in every case.
+- ``include_sessions: false`` skips preferred resolution entirely.
+- Resolution reads each profile's OWN state.db (strict per-profile scoping).
+"""
+
+from __future__ import annotations
+
+import pytest
+
+import tui_gateway.server as srv
+
+
+def home(tmp_path, monkeypatch):
+ """Temp HERMES_HOME with the default profile plus one named profile."""
+ h = tmp_path / ".hermes"
+ (h / "profiles" / "ops").mkdir(parents=True)
+ monkeypatch.setenv("HERMES_HOME", str(h))
+ return h
+
+
+def _db(profile_dir):
+ from hermes_state import SessionDB
+
+ return SessionDB(db_path=profile_dir / "state.db")
+
+
+def _add_session(db, sid, *, source="cli", title="", ts, text, hidden=False,
+ parent=None, end_reason=None):
+ """Create one session with a single user message at an exact timestamp."""
+ db.create_session(sid, source, parent_session_id=parent)
+ db.append_message(sid, "user", text, timestamp=ts)
+ with db._lock:
+ db._conn.execute("UPDATE sessions SET title = ? WHERE id = ?", (title, sid))
+ if end_reason:
+ # Mark ended AFTER appending: the DB (correctly) refuses writes
+ # to a compression-closed session.
+ db._conn.execute(
+ "UPDATE sessions SET ended_at = ?, end_reason = ? WHERE id = ?",
+ (ts + 1, end_reason, sid),
+ )
+ if hidden:
+ db.set_session_hidden(sid, True)
+
+
+def _profiles(params):
+ envelope = srv._methods["profiles.list"](1, params)
+ return envelope["result"]["profiles"]
+
+
+def _row(profiles, name):
+ return next(p for p in profiles if p["name"] == name)
+
+
+# ---------------------------------------------------------------------------
+# preferred_session resolution
+# ---------------------------------------------------------------------------
+
+
+def test_preferred_session_summarizes_pin_not_latest(home):
+ db = _db(home)
+ _add_session(db, "pinned1", title="Bot Chat", ts=1000, text="pinned chat content")
+ _add_session(db, "other1", title="Scratch", ts=2000, text="scratch pad content")
+ db.close()
+
+ rows = _profiles({"preferred_session_ids": {"default": "pinned1"}})
+ row = _row(rows, "default")
+
+ pref = row["preferred_session"]
+ assert pref["id"] == "pinned1"
+ assert pref["resolved_id"] == "pinned1"
+ assert pref["title"] == "Bot Chat"
+ assert "pinned chat content" in pref["preview"]
+ # last_session keeps its own contract: the most recently active session.
+ assert row["last_session"]["id"] == "other1"
+
+
+def test_preferred_session_resolves_hidden_pin(home):
+ db = _db(home)
+ _add_session(db, "hiddenpin", title="Bot Chat", ts=1000,
+ text="hidden bot chat content", hidden=True)
+ _add_session(db, "visible1", title="Visible", ts=2000, text="visible content")
+ db.close()
+
+ rows = _profiles({"preferred_session_ids": {"default": "hiddenpin"}})
+ row = _row(rows, "default")
+
+ # The pin is precise: hidden from listings must not mean "does not exist".
+ assert row["preferred_session"] is not None
+ assert row["preferred_session"]["id"] == "hiddenpin"
+ assert "hidden bot chat content" in row["preferred_session"]["preview"]
+ # …while the generic latest-session listing still excludes hidden rows.
+ assert row["last_session"]["id"] == "visible1"
+
+
+def test_preferred_session_missing_returns_none_and_keeps_last_session(home):
+ db = _db(home)
+ _add_session(db, "real1", title="Real", ts=1000, text="real content")
+ db.close()
+
+ rows = _profiles({"preferred_session_ids": {"default": "does-not-exist"}})
+ row = _row(rows, "default")
+
+ assert row["preferred_session"] is None
+ assert row["last_session"]["id"] == "real1"
+
+
+def test_preferred_session_denied_internal_source_returns_none(home):
+ db = _db(home)
+ _add_session(db, "toolrun", source="tool", title="", ts=1000, text="tool output")
+ _add_session(db, "human1", title="Human", ts=2000, text="human content")
+ db.close()
+
+ rows = _profiles({"preferred_session_ids": {"default": "toolrun"}})
+ row = _row(rows, "default")
+
+ # Internal sources (tool sub-agent runs, kanban workers) are not
+ # conversations — a pin pointing at one resolves as absent.
+ assert row["preferred_session"] is None
+
+
+def test_preferred_session_resolves_compression_tip(home):
+ db = _db(home)
+ _add_session(db, "root1", title="Bot Chat", ts=1000,
+ text="pre-compression content", end_reason="compression")
+ _add_session(db, "tip1", title="Bot Chat (continued)", ts=3000,
+ text="post-compression content", parent="root1")
+ _add_session(db, "other1", title="Other", ts=4000, text="other content")
+ db.close()
+
+ rows = _profiles({"preferred_session_ids": {"default": "root1"}})
+ row = _row(rows, "default")
+
+ pref = row["preferred_session"]
+ # The pin keeps its durable identity; the summary comes from the live tip.
+ assert pref["id"] == "root1"
+ assert pref["resolved_id"] == "tip1"
+ assert "post-compression content" in pref["preview"]
+
+
+# ---------------------------------------------------------------------------
+# Contract guards
+# ---------------------------------------------------------------------------
+
+
+def test_no_param_omits_preferred_key(home):
+ db = _db(home)
+ _add_session(db, "s1", title="S", ts=1000, text="content")
+ db.close()
+
+ row = _row(_profiles({}), "default")
+ assert "preferred_session" not in row
+ assert row["last_session"]["id"] == "s1"
+
+
+def test_include_sessions_false_skips_preferred(home):
+ db = _db(home)
+ _add_session(db, "s1", title="S", ts=1000, text="content")
+ db.close()
+
+ row = _row(
+ _profiles({"include_sessions": False,
+ "preferred_session_ids": {"default": "s1"}}),
+ "default",
+ )
+ assert "last_session" not in row
+ assert "preferred_session" not in row
+
+
+def test_preferred_ids_scoped_per_profile_db(home):
+ # Same session id in BOTH profiles' state.db files, different content —
+ # each row must summarize its own profile's database.
+ default_db = _db(home)
+ _add_session(default_db, "shared1", title="Default Bot", ts=1000,
+ text="default profile content")
+ default_db.close()
+
+ ops_db = _db(home / "profiles" / "ops")
+ _add_session(ops_db, "shared1", title="Ops Bot", ts=1000,
+ text="ops profile content")
+ ops_db.close()
+
+ rows = _profiles(
+ {"preferred_session_ids": {"default": "shared1", "ops": "shared1"}}
+ )
+ assert "default profile content" in _row(rows, "default")["preferred_session"]["preview"]
+ assert "ops profile content" in _row(rows, "ops")["preferred_session"]["preview"]
diff --git a/tui_gateway/methods_profiles.py b/tui_gateway/methods_profiles.py
index 53333b21963..29032d6dea1 100644
--- a/tui_gateway/methods_profiles.py
+++ b/tui_gateway/methods_profiles.py
@@ -60,6 +60,74 @@ def _(rid, params: dict) -> dict:
return text[:80] + "..."
return text
+ def _preferred_session_row(profile_path, session_id):
+ """Precise summary for ONE caller-pinned session id, or None.
+
+ Complements ``last_session``: that field answers "what is the newest
+ conversation", this answers "what about THIS conversation". Callers
+ that open a specific session on click (e.g. a roster whose rows open
+ a pinned chat) pass their pins via ``preferred_session_ids`` so the
+ preview and the click target describe the same session
+ (hermes-agent#88200).
+
+ Exact-lookup semantics, deliberately different from the listing:
+ hidden rows still resolve (a hidden-from-sidebar session EXISTS),
+ compression lineages resolve to the live tip with the same resolver
+ ``session.resume`` uses, and denied internal sources (tool/kanban)
+ count as absent. The reported ``id`` stays the caller's durable pin
+ while ``resolved_id`` names the live tip. Best-effort: any failure
+ degrades to None rather than failing the whole profiles.list call.
+ """
+ try:
+ from pathlib import Path
+
+ db_path = Path(profile_path) / "state.db"
+ if not db_path.exists():
+ return None
+ from hermes_state import SessionDB
+
+ deny = frozenset({"kanban", "tool"})
+ db = SessionDB(db_path=db_path)
+ try:
+ row = db.get_session(session_id)
+ if not row:
+ return None
+ if (row.get("source") or "").strip().lower() in deny:
+ return None
+ if row.get("archived"):
+ return None
+ try:
+ tip = db.resolve_resume_session_id(session_id) or session_id
+ except Exception:
+ tip = session_id
+ tip_row = db.get_session(tip) or row
+ preview = ""
+ try:
+ preview = _latest_message_preview(db, tip)
+ except Exception:
+ pass
+ return {
+ "id": session_id,
+ "resolved_id": tip,
+ "title": tip_row.get("title") or "",
+ "preview": preview,
+ "started_at": tip_row.get("started_at") or row.get("started_at") or 0,
+ "last_active": (
+ tip_row.get("last_activity_at")
+ or tip_row.get("started_at")
+ or row.get("started_at")
+ or 0
+ ),
+ "message_count": tip_row.get("message_count") or 0,
+ }
+ finally:
+ try:
+ db.close()
+ except Exception:
+ pass
+ except Exception:
+ return None
+
def _latest_profile_session_row(profile_path):
"""Most recent human-facing session in a profile's state.db, or None.
@@ -116,6 +184,13 @@ def _(rid, params: dict) -> dict:
from hermes_cli.profiles import list_profiles
include_sessions = is_truthy_value(params.get("include_sessions", True))
+ # Optional precise lookups: {profile_name: session_id} from callers
+ # that open a specific session per row (pinned-chat rosters). Only
+ # resolved when include_sessions is on; each named profile row gains
+ # a ``preferred_session`` summary (None when the id is gone).
+ preferred_ids = params.get("preferred_session_ids")
+ if not isinstance(preferred_ids, dict):
+ preferred_ids = {}
out = []
for p in list_profiles():
row = {
@@ -129,6 +204,9 @@ def _(rid, params: dict) -> dict:
}
if include_sessions:
row["last_session"] = _latest_profile_session_row(p.path)
+ pin = preferred_ids.get(p.name)
+ if isinstance(pin, str) and pin.strip():
+ row["preferred_session"] = _preferred_session_row(p.path, pin.strip())
# Client-agnostic UI metadata (avatars, accent colors, pinned
# order, …) — stored server-side in profile.yaml so every