Skip to content

The agent that grows with you

fix(bot-mode): kill the canonical-chat infinite-fork loop; drop the per-bot Sessions browser (#90732)

Teknium5ab74737e0a4
diff --git a/apps/desktop/src/plugins/hermes-bots/plugin.js b/apps/desktop/src/plugins/hermes-bots/plugin.js
index 10d06429a5c..d17fcf23658 100644
--- a/apps/desktop/src/plugins/hermes-bots/plugin.js
+++ b/apps/desktop/src/plugins/hermes-bots/plugin.js
@@ -195,17 +195,13 @@ const $selectedBot = atom('default')
* the socket happened to be homed on. */
const $focusedBotProfile = host.state.focusedSessionProfile || host.state.profile
-/** Optional secondary navigation inside the Bots pane. Primary row clicks still
- * open the bot's canonical chat; this state opens its stored-session browser. */
-const $botSessionsWorkspace = atom(null)
-const $botSelectedSessions = atom({})
-const $sessionsGatewayGeneration = atom(0)
+/** Optional secondary navigation inside the Bots pane (group-chat rooms). */
/** Group-chat rooms: { [group]: { log: [{from:{kind,name},text,at}], watermarks:{[member]:idx}, epoch, running } }.
* Log + watermarks persist via plugin storage; epoch/running are runtime-only. */
const $groupChats = atom({})
-/** Group whose room view is open in the Bots pane (secondary navigation,
- * same pattern as $botSessionsWorkspace). */
+/** Group whose room view is open in the Bots pane (secondary navigation
+ * inside the pane; a normal row click returns to the roster). */
const $groupChatWorkspace = atom(null)
/** Groups whose latest room activity mentions @user — the needs-you badge. */
const $groupNeedsYou = atom({})
@@ -297,8 +293,6 @@ function groupActivityTone(kind) {
}
function handleSessionsGatewayTransition() {
- $sessionsGatewayGeneration.set($sessionsGatewayGeneration.get() + 1)
- $botSelectedSessions.set({})
// A gateway swap invalidates any in-flight room drive: bump every room's
// epoch so running loops bail at their next member boundary.
const rooms = { ...$groupChats.get() }
@@ -3354,6 +3348,10 @@ function showsHandle(name, meta, bot) {
// In-flight creations, keyed by bot name — double-clicking a row must not
// mint two canonical chats.
const canonicalCreations = new Map()
+
+/** Upper bound for per-profile session.list scans (hide sweep, canonical-chat
+ * adoption, stored-session lookups). */
+const PROFILE_SESSION_LIST_LIMIT = 200
let botOpenGeneration = 0
async function openStoredBotChat(name, storedId, summary) {
@@ -3383,10 +3381,35 @@ async function openStoredBotChat(name, storedId, summary) {
return storedId
}
+/** Adopt-before-mint: the profile may already own a canonical Bot Chat that
+ * the pin lost track of (pin cleared during an outage, ui_meta rolled back,
+ * a fork squatting the title). The core UNIQUE title index guarantees at
+ * most ONE session titled "Bot Chat" per profile db, so a title scan is an
+ * exact registry lookup, not a heuristic. Minting while a "Bot Chat" row
+ * exists is always wrong twice over: it forks the forever-chat AND the new
+ * row can never take the (already held) canonical title, so the next
+ * identity check misreads it and forks again — the infinite-fork loop.
+ * include_hidden is required (canonical chats are always hidden); an older
+ * gateway without it simply finds nothing and we fall through to mint. */
+async function findExistingCanonicalChat(name) {
+ try {
+ const res = await host.request('session.list', {
+ profile: name,
+ limit: PROFILE_SESSION_LIST_LIMIT,
+ include_hidden: true
+ })
+ const rows = res?.sessions ?? []
+ return rows.find(row => isCanonicalBotChatHistory(row)) || null
+ } catch {
+ return null
+ }
+}
+
/** Create the bot's ONE forever chat: a real session opened with a kickoff
* message (the gateway prunes zero-message sessions, so the chat is born
* with the bot introducing itself). Pins the stored id in bot meta and
- * returns it. */
+ * returns it. Adopts an existing "Bot Chat" row instead of creating when
+ * the profile already has one (see findExistingCanonicalChat). */
function createCanonicalChat(name) {
const inflight = canonicalCreations.get(name)
@@ -3395,6 +3418,18 @@ function createCanonicalChat(name) {
}
const run = (async () => {
+ const existing = await findExistingCanonicalChat(name)
+
+ if (existing?.id) {
+ saveBotMeta(name, { chat: existing.id })
+
+ if (typeof host.openSession === 'function') {
+ await openStoredBotChat(name, existing.id, existing)
+ }
+
+ return existing.id
+ }
+
const res = await host.request('session.create', {
profile: name,
title: 'Bot Chat',
@@ -3524,8 +3559,29 @@ async function openBotCanonicalChat(name, pinned, history) {
if (preferred) {
// The stored pointer resolved to a real session, but not to Bot Mode's
- // plumbing session. Treat it as corrupted metadata rather than opening or
- // hiding the user's ordinary conversation.
+ // titled plumbing session. Two legitimate ways to get here, and neither
+ // means "mint a new chat":
+ // - the pin IS the forever-chat but its title drifted (grandfathered
+ // pre-convention chats; the LLM auto-titler renaming an untitled row
+ // after a silent unique-title conflict dropped "Bot Chat"). A pinned
+ // session carrying real history is the user's conversation — forking
+ // away from it silently loses their thread, the exact bug this whole
+ // resolver exists to prevent. The pin is the durable intent: keep it
+ // and open it, even when some other (likely forked) row holds the
+ // "Bot Chat" title. The hide sweep only matches plumbing titles, so
+ // an adopted odd-titled chat is never swept out of the user's
+ // ordinary session list.
+ // - the pin resolves to an EMPTY non-plumbing session (a stray draft):
+ // genuinely corrupted metadata. Clear it — createCanonicalChat then
+ // adopts the profile's existing "Bot Chat" row if one exists before
+ // ever creating a new one.
+ const messageCount = Number(preferred.message_count) || 0
+
+ if (messageCount > 0) {
+ await openStoredBotChat(name, preferred.resolved_id || preferred.id, preferred)
+ return pinned
+ }
+
await saveBotMeta(name, { chat: null })
return createCanonicalChat(name)
}
@@ -4997,8 +5053,8 @@ function BotRow({ bot, onDelete, onEdit, onGroup }) {
// thin to rich; conditionally calling useValue here breaks React hook order.
const unreadByName = useValue($botUnread)
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.
+ // WHO sent the last message (bot-to-bot DM vs human) — shown in the row
+ // preview; the conversation itself lives in the bot's one canonical chat.
const { fromBot } = previewKind(previewSession?.preview)
// DM previews read like DMs: strip the delivery prefix, keep the message.
const displayPreview = stripPreviewMarkdown(
@@ -5246,10 +5302,6 @@ function BotRow({ bot, onDelete, onEdit, onGroup }) {
children: meta?.hidden ? 'Unhide Bot' : 'Hide Bot'
}),
jsx(ContextMenuSeparator, {}),
- jsx(ContextMenuItem, {
- onSelect: () => openBotSessionsWorkspace(bot),
- children: 'Sessions'
- }),
jsx(ContextMenuItem, { onSelect: () => onEdit(bot), children: 'Edit Profile' }),
!bot.remoteSource
? jsx(ContextMenuItem, {
@@ -7952,162 +8004,6 @@ function RoutinesPane() {
})
}
-// ── profile session workspace ────────────────────────────────────────────────
-
-const PROFILE_SESSION_LIST_LIMIT = 200
-
-function openBotSessionsWorkspace(bot) {
- if (bot?.name && NAME_RE.test(bot.name)) {
- $botSessionsWorkspace.set(bot.name)
- }
-}
-
-function filterProfileSessions(sessions, query) {
- const needle = String(query || '').trim().toLowerCase()
- const rows = Array.isArray(sessions) ? sessions : []
- if (!needle) return rows
- return rows.filter(session =>
- `${session?.title || ''} ${session?.preview || ''} ${session?.source || ''}`.toLowerCase().includes(needle)
- )
-}
-
-function useProfileSessions(botName, gatewayGeneration) {
- return useQuery({
- queryKey: [ID, 'profile-sessions', botName, gatewayGeneration],
- enabled: Boolean(botName),
- // include_hidden: this browser exists precisely to see the profile's own
- // (always-hidden) Bot Mode sessions alongside its regular ones.
- queryFn: () => host.request('session.list', { profile: botName, limit: PROFILE_SESSION_LIST_LIMIT, include_hidden: true }),
- refetchInterval: 8000,
- staleTime: 4000,
- retry: false
- })
-}
-
-async function openProfileSession(botName, session, gatewayGeneration) {
- const profile = String(botName || '')
- const id = String(session?.id || '')
- if (!NAME_RE.test(profile) || !id || gatewayGeneration !== $sessionsGatewayGeneration.get()) return
- if (typeof host.openSession !== 'function') {
- throw new Error('This Hermes Desktop version cannot open stored sessions')
- }
-
- // Same hydration contract as canonical Bot Chats (#89206): a bare open can
- // focus a main surface whose runtime/transcript silently vanished, leaving a
- // blank pane while the row preview still shows the conversation. Waiting on
- // hydration lets the SDK issue the explicit resume when the surface is stale.
- const hasAuthoritativeCount =
- typeof session?.message_count === 'number' && Number.isFinite(session.message_count)
- const expectHistory = hasAuthoritativeCount ? session.message_count > 0 : Boolean(session?.preview)
-
- await host.openSession(id, { profile, awaitHydration: true, expectHistory, keepAllProfilesScope: true })
- if (gatewayGeneration !== $sessionsGatewayGeneration.get()) return
- $botSelectedSessions.set({ ...$botSelectedSessions.get(), [profile]: id })
-}
-
-function ProfileSessionRow({ session, botName, active, gatewayGeneration }) {
- return jsxs('button', {
- type: 'button',
- 'aria-current': active ? 'page' : undefined,
- onClick: () => void openProfileSession(botName, session, gatewayGeneration).catch(err => host.notifyError(err, 'Could not open session')),
- className: cn(
- 'flex w-full flex-col gap-0.5 overflow-hidden rounded-md px-2 py-1.5 text-left transition-colors',
- 'hover:bg-(--chrome-action-hover)',
- active && 'bg-(--ui-row-active-background)'
- ),
- children: [
- jsx('span', {
- className: 'truncate text-[0.8125rem] font-medium',
- children: session.title || 'Untitled session'
- }),
- jsx('div', {
- className: 'truncate text-[0.7rem] text-(--ui-text-tertiary)',
- children: session.preview || session.source || 'No messages yet'
- })
- ]
- })
-}
-
-function ProfileSessionsWorkspace({ bot }) {
- const gatewayGeneration = useValue($sessionsGatewayGeneration)
- const { data, isLoading, error } = useProfileSessions(bot.name, gatewayGeneration)
- const selectedByProfile = useValue($botSelectedSessions)
- const [query, setQuery] = useState('')
- const sourceSessions = data?.sessions || []
- const sessions = filterProfileSessions(sourceSessions, query)
- const inventoryBounded = sourceSessions.length >= PROFILE_SESSION_LIST_LIMIT
- const selectedId = selectedByProfile[bot.name] || ''
-
- const header = jsxs('div', {
- className: 'flex items-center gap-2 px-2.5 pt-2.5 pb-2',
- children: [
- jsx(Button, {
- variant: 'ghost',
- size: 'sm',
- onClick: () => $botSessionsWorkspace.set(null),
- children: 'Back'
- }),
- jsx('div', {
- className: 'min-w-0 flex-1 truncate text-sm font-semibold',
- children: `${displayName(bot, $botMeta.get()[bot.name])} sessions`
- })
- ]
- })
-
- return jsxs('div', {
- className: 'flex h-full flex-col',
- children: [
- header,
- jsx('div', {
- className: 'px-2 pb-2',
- children: jsx(Input, {
- 'aria-label': 'Filter sessions',
- placeholder: 'Filter sessions…',
- value: query,
- onChange: event => setQuery(event.target.value)
- })
- }),
- inventoryBounded
- ? jsx('div', {
- className: 'px-2.5 pb-2 text-[0.65rem] text-(--ui-text-quaternary)',
- children: `Showing the ${PROFILE_SESSION_LIST_LIMIT} most recent sessions.`
- })
- : null,
- isLoading
- ? jsx('div', {
- className: 'flex flex-1 items-center justify-center',
- children: jsx(GlyphSpinner, { spinner: 'breathe' })
- })
- : error
- ? jsx('div', {
- className: 'px-3 py-3 text-xs text-(--ui-text-tertiary)',
- children: 'Could not load sessions for this profile.'
- })
- : jsx(ScrollArea, {
- className: 'min-h-0 flex-1',
- children: jsx('div', {
- className: 'grid gap-0.5 px-1.5 pb-2',
- children: sessions.length
- ? sessions.map(session => jsx(ProfileSessionRow, {
- session,
- botName: bot.name,
- active: selectedId === session.id,
- gatewayGeneration
- }, session.id))
- : jsx('div', {
- className: 'px-2 py-3 text-center text-xs text-(--ui-text-tertiary)',
- children: query.trim()
- ? inventoryBounded
- ? `No matching sessions in the ${PROFILE_SESSION_LIST_LIMIT} most recent.`
- : 'No sessions match that filter.'
- : 'No stored sessions yet.'
- })
- })
- })
- ]
- })
-}
-
// ── roster pane ──────────────────────────────────────────────────────────────
/** "Active now" presence strip above the roster: chips for every bot that is
@@ -9763,7 +9659,6 @@ function BotsPane() {
const [grouping, setGrouping] = useState(null)
const [query, setQuery] = useState('')
const activityToasts = useValue($activityToasts)
- const sessionsWorkspaceName = useValue($botSessionsWorkspace)
const groupChatName = useValue($groupChatWorkspace)
// Main-tab ownership is a module Map; this rev subscription makes the
// shouldRenderGroupChatInPane gate below reactive to tab open/close
@@ -9860,11 +9755,6 @@ function BotsPane() {
const staleNotice = error && !live && roster.length
? 'Roster refresh failed — showing the last good list.' + (gatewayUp ? '' : ' Waiting for the gateway to reconnect…')
: null
- const sessionsWorkspaceBot = roster.find(bot => bot.name === sessionsWorkspaceName)
-
- if (sessionsWorkspaceBot) {
- return jsx(ProfileSessionsWorkspace, { bot: sessionsWorkspaceBot })
- }
const groupChatMembers = groupChatName ? groupChatMemberBots(groupChatName, roster, allMeta) : []
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-adopt-before-mint.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-adopt-before-mint.test.mjs
new file mode 100644
index 00000000000..06d98252401
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-adopt-before-mint.test.mjs
@@ -0,0 +1,155 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+import vm from 'node:vm'
+
+// Regression suite for the infinite-fork loop (hermes-agent#88200 follow-up):
+// the core UNIQUE title index means at most one session per profile db holds
+// the "Bot Chat" title. When a fork squats it, every later mint's title is
+// silently dropped, the LLM titler renames the untitled row, and the next
+// title-based identity check misreads the fresh chat as "not plumbing" —
+// clearing the pin and minting again, forever. Two invariants kill the loop:
+// 1. createCanonicalChat ADOPTS an existing "Bot Chat" row before creating.
+// 2. A pin that resolves to a NON-plumbing session with real history is the
+// user's conversation — keep it; only an empty stray draft is replaced.
+
+const source = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
+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: JSON.parse(JSON.stringify(params ?? null)) })
+ 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 = { createCanonicalChat, 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-adopt.js' })
+ return { ...context.__open, saved, requests }
+}
+
+// ── invariant 1: adopt-before-mint ──────────────────────────────────────────
+
+test('createCanonicalChat adopts an existing hidden "Bot Chat" row instead of creating', async () => {
+ const runtime = loadOpenPath({
+ openSession: async () => undefined,
+ request: async method => {
+ if (method === 'session.list') {
+ return {
+ sessions: [
+ { id: 'newer-ordinary', title: 'help me with x', message_count: 12 },
+ { id: 'real-forever-chat', title: 'Bot Chat', message_count: 930 }
+ ]
+ }
+ }
+ if (method === 'session.create') {
+ throw new Error('must not create: the profile already owns a Bot Chat')
+ }
+ return {}
+ }
+ })
+
+ assert.equal(await runtime.createCanonicalChat('ops'), 'real-forever-chat')
+ assert.deepEqual(runtime.saved, [{ name: 'ops', patch: { chat: 'real-forever-chat' } }])
+ const list = runtime.requests.find(r => r.method === 'session.list')
+ assert.equal(list?.params?.include_hidden, true,
+ 'adoption scan must see hidden rows — canonical chats are always hidden')
+})
+
+test('createCanonicalChat still creates when no Bot Chat row exists', async () => {
+ const runtime = loadOpenPath({
+ openSession: async () => undefined,
+ request: async method => {
+ if (method === 'session.list') {
+ return { sessions: [{ id: 'ordinary', title: 'help me with x', message_count: 3 }] }
+ }
+ if (method === 'session.create') return { stored_session_id: 'fresh-1', session_id: 'rt-1' }
+ return {}
+ }
+ })
+
+ assert.equal(await runtime.createCanonicalChat('newbie'), 'fresh-1')
+})
+
+test('createCanonicalChat mints when the adoption scan fails (older gateway)', async () => {
+ const runtime = loadOpenPath({
+ openSession: async () => undefined,
+ request: async method => {
+ if (method === 'session.list') throw new Error('unknown method')
+ if (method === 'session.create') return { stored_session_id: 'fresh-2', session_id: 'rt-2' }
+ return {}
+ }
+ })
+
+ assert.equal(await runtime.createCanonicalChat('legacy'), 'fresh-2')
+})
+
+// ── invariant 2: a resolving pin with history is never abandoned ────────────
+
+test('pin resolving to a renamed session WITH history keeps the pin (no fork)', 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: 'grandfathered', resolved_id: 'grandfathered',
+ root_title: 'Use computer use to inspect…', title: 'Use computer use to inspect…',
+ message_count: 930
+ }
+ }]
+ }
+ }
+ if (method === 'session.create') throw new Error('must not fork a chat with 930 messages')
+ return {}
+ }
+ })
+
+ assert.equal(await runtime.openBotCanonicalChat('ops', 'grandfathered', null), 'grandfathered')
+ assert.equal(opened.includes('grandfathered'), true)
+ assert.deepEqual(runtime.saved, [], 'pin must not be cleared or rewritten')
+})
+
+test('pin resolving to an EMPTY stray draft is replaced via adoption, not a blind mint', async () => {
+ const runtime = loadOpenPath({
+ openSession: async () => undefined,
+ request: async method => {
+ if (method === 'profiles.list') {
+ return {
+ profiles: [{
+ name: 'ops',
+ preferred_session: { id: 'stray', resolved_id: 'stray', root_title: 'Untitled', title: 'Untitled', message_count: 0 }
+ }]
+ }
+ }
+ if (method === 'session.list') {
+ return { sessions: [{ id: 'real-forever-chat', title: 'Bot Chat', message_count: 42 }] }
+ }
+ if (method === 'session.create') throw new Error('must adopt the existing Bot Chat')
+ return {}
+ }
+ })
+
+ assert.equal(await runtime.openBotCanonicalChat('ops', 'stray', null), 'real-forever-chat')
+ assert.deepEqual(runtime.saved, [
+ { name: 'ops', patch: { chat: null } },
+ { name: 'ops', patch: { chat: 'real-forever-chat' } }
+ ])
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/hide-bot-chats.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/hide-bot-chats.test.mjs
index 0e3cf2845db..0fc0f261ccb 100644
--- a/apps/desktop/src/plugins/hermes-bots/tests/hide-bot-chats.test.mjs
+++ b/apps/desktop/src/plugins/hermes-bots/tests/hide-bot-chats.test.mjs
@@ -175,9 +175,11 @@ test('hideOwnedBotSessions chains the ownership sweep and survives its absence o
assert.match(source, /return Promise\.all\(\[known, sweepBotProfileSessions\(\)\.catch\(\(\) => undefined\)\]\)/)
})
-test('the Bots session browser lists with include_hidden', () => {
- // The one session.list consumer that must see the always-hidden rows.
- // (Canonical-chat recovery now goes through profiles.list
+test('the canonical-chat adoption scan lists with include_hidden', () => {
+ // The one session.list consumer that must see the always-hidden rows:
+ // findExistingCanonicalChat (adopt-before-mint) — canonical Bot Chats are
+ // born hidden, so a visible-only scan would miss the very row whose
+ // existence forbids minting. (Pin recovery goes through profiles.list
// preferred_session_ids, whose resolver already sees hidden rows.)
- assert.match(source, /session\.list', \{ profile: botName, limit: PROFILE_SESSION_LIST_LIMIT, include_hidden: true \}/)
+ assert.match(source, /include_hidden: true\s*\}\)\s*const rows = res\?\.sessions \?\? \[\]\s*return rows\.find\(row => isCanonicalBotChatHistory\(row\)\)/)
})
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
deleted file mode 100644
index 238d863ed1e..00000000000
--- a/apps/desktop/src/plugins/hermes-bots/tests/session-workspace.test.mjs
+++ /dev/null
@@ -1,157 +0,0 @@
-import assert from 'node:assert/strict'
-import { readFileSync } from 'node:fs'
-import test from 'node:test'
-import vm from 'node:vm'
-
-const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
-const plain = value => JSON.parse(JSON.stringify(value))
-
-function load({ profile = 'ops', request, openSession } = {}) {
- const values = new Map()
- const atom = initial => {
- const slot = {
- get: () => values.get(slot),
- set: value => values.set(slot, typeof value === 'function' ? value(values.get(slot)) : value)
- }
- values.set(slot, initial)
- return slot
- }
- const calls = []
- const host = {
- state: {
- profile: { get: () => profile, listen: () => undefined },
- gateway: { get: () => 'open', listen: () => undefined }
- },
- request: async (method, params) => {
- calls.push([method, params])
- return request?.(method, params)
- },
- openSession: async (...args) => {
- calls.push(['openSession', ...args])
- return openSession?.(...args)
- },
- newChat: (...args) => calls.push(['newChat', ...args]),
- notify: () => undefined,
- notifyError: () => undefined
- }
- const context = {
- atom,
- host,
- PALETTE_AREA: 'palette',
- COMPOSER_AREAS: { middleware: 'middleware' },
- document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } }
- }
- const source = pluginSource
- .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.__sessions = {
- openBotSessionsWorkspace,
- openProfileSession,
- filterProfileSessions,
- $botSessionsWorkspace,
- $botSelectedSessions,
- $sessionsGatewayGeneration,
- handleSessionsGatewayTransition
- };\n`)
- vm.runInNewContext(source, context, { filename: 'plugin.js' })
- return { ...context, calls }
-}
-
-test('sessions workspace: selecting the secondary workspace does not navigate', () => {
- const runtime = load()
- runtime.__sessions.openBotSessionsWorkspace({ name: 'ops' })
- assert.equal(runtime.__sessions.$botSessionsWorkspace.get(), 'ops')
- assert.equal(runtime.calls.some(([method]) => method === 'openSession'), false)
-})
-
-test('sessions workspace: invalid profile names are ignored', () => {
- const runtime = load()
- runtime.__sessions.openBotSessionsWorkspace({ name: '../ops' })
- assert.equal(runtime.__sessions.$botSessionsWorkspace.get(), null)
-})
-
-test('sessions workspace: filtering searches title, preview, and source without privileged rows', () => {
- const { filterProfileSessions } = load().__sessions
- const rows = [
- { id: 'named', title: 'Oversight', preview: 'ordinary user session', source: 'user' },
- { id: 'deploy', title: 'Deploy API', preview: 'shipping', source: 'cli' },
- { id: 'docs', title: 'Write docs', preview: 'guide', source: 'desktop' }
- ]
- assert.deepEqual(plain(filterProfileSessions(rows, '').map(row => row.id)), ['named', 'deploy', 'docs'])
- assert.deepEqual(plain(filterProfileSessions(rows, 'ship').map(row => row.id)), ['deploy'])
- assert.deepEqual(plain(filterProfileSessions(rows, 'DESKTOP').map(row => row.id)), ['docs'])
-})
-
-test('sessions workspace: opening a stored row uses profile-aware navigation and records selection', async () => {
- const runtime = load({ profile: 'default' })
- await runtime.__sessions.openProfileSession('ops', { id: 'stored-123', message_count: 4 }, 0)
- assert.deepEqual(plain(runtime.calls), [
- ['openSession', 'stored-123', { profile: 'ops', awaitHydration: true, expectHistory: true, keepAllProfilesScope: true }]
- ])
- assert.equal(runtime.__sessions.$botSelectedSessions.get().ops, 'stored-123')
-})
-
-test('sessions workspace: malformed profile or session input is a no-op', async () => {
- const runtime = load()
- await runtime.__sessions.openProfileSession('../ops', { id: 'stored-123' }, 0)
- await runtime.__sessions.openProfileSession('ops', { id: '' }, 0)
- assert.deepEqual(runtime.calls, [])
-})
-
-test('sessions workspace: a gateway lifecycle change clears selection and rejects stale row clicks', async () => {
- const runtime = load()
- runtime.__sessions.$botSelectedSessions.set({ ops: 'stored-123' })
- runtime.__sessions.handleSessionsGatewayTransition()
- assert.equal(runtime.__sessions.$sessionsGatewayGeneration.get(), 1)
- assert.deepEqual(plain(runtime.__sessions.$botSelectedSessions.get()), {})
-
- await runtime.__sessions.openProfileSession('ops', { id: 'stored-123' }, 0)
- assert.deepEqual(runtime.calls, [])
-})
-
-test('sessions workspace: an empty session with no preview does not demand history', async () => {
- const runtime = load()
- await runtime.__sessions.openProfileSession('ops', { id: 'stored-empty', message_count: 0 }, 0)
- assert.deepEqual(plain(runtime.calls), [
- ['openSession', 'stored-empty', { profile: 'ops', awaitHydration: true, expectHistory: false, keepAllProfilesScope: true }]
- ])
-})
-
-test('sessions workspace: an in-flight open cannot restore selection after gateway replacement', async () => {
- let runtime
- runtime = load({
- openSession: async () => runtime.__sessions.handleSessionsGatewayTransition()
- })
-
- await runtime.__sessions.openProfileSession('ops', { id: 'stored-123', preview: 'last line' }, 0)
- assert.equal(runtime.calls.length, 1)
- assert.deepEqual(plain(runtime.__sessions.$botSelectedSessions.get()), {})
-})
-
-test('source contract: bot rows and Active now activate the owner before canonical chat', () => {
- 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, previewSession\)/)
- assert.match(pluginSource, /onOpen: bot => \{[\s\S]*await prepareBotSource\(bot, pinnedChat\)[\s\S]*bot\.preferred_session \|\| bot\.last_session/)
- assert.match(pluginSource, /openBotSessionsWorkspace\(bot\)[\s\S]*children: 'Sessions'/)
-})
-
-test('source contract: workspaces disclose the bounded recent-session inventory', () => {
- assert.match(pluginSource, /queryKey: \[ID, 'profile-sessions', botName, gatewayGeneration\]/)
- assert.match(pluginSource, /enabled: Boolean\(botName\)/)
- assert.match(pluginSource, /host\.request\('session\.list', \{ profile: botName, limit: PROFILE_SESSION_LIST_LIMIT, include_hidden: true \}\)/)
- assert.match(pluginSource, /Showing the \$\{PROFILE_SESSION_LIST_LIMIT\} most recent sessions\./)
- assert.match(pluginSource, /No matching sessions in the \$\{PROFILE_SESSION_LIST_LIMIT\} most recent\./)
- assert.doesNotMatch(pluginSource, /children: 'Activate profile'/)
- assert.match(pluginSource, /host\.state\.gateway\.listen\(handleSessionsGatewayTransition\)/)
-})
-
-test('source contract: session controls expose filter and selection state to assistive technology', () => {
- assert.match(pluginSource, /'aria-label': 'Filter sessions'/)
- assert.match(pluginSource, /'aria-current': active \? 'page' : undefined/)
-})