fix(desktop): a bot row click returns to its open tabs instead of re-opening a closed Bot Chat

Ports 7c91079 onto the split modules — it landed on main in plugin.js, which
this branch deletes.

Every roster click resolved the bot's canonical Bot Chat by name and opened
it as a tab. Nothing records a tab close (this plugin keeps no closed set;
core's tile bucket only forgets), so a Bot Chat the user had closed came back
beside every newer thread on every bot switch. A click is now "go to this
bot": when the bot's workspace already holds tabs, the one the user last had
active is fronted and no chat is resolved or opened. The forever-chat opens
only when the bot has nothing open, or on the explicit ask — a new "Open Bot
Chat" row-menu item.

The claim such a click records carries only the fronted tab, so the reclaim
listener skips it and cannot resurrect the closed chat. focusExistingBotTab
is feature-detected, so an older shell keeps opening the canonical chat.

Dropped from the port: the Bots home "Open chat" button, a surface this
branch removes. The .mjs test is replaced by a real one — its two
source-reading cases become a render of the menu item in bot-row.test.tsx
and, for the reclaim guard, the claim-shape invariant the guard reads.
Stubbing usePluginI18n there also means the row's localized labels render as
text in tests instead of empty.
This commit is contained in:
Brooklyn Nicholson
2026-08-27 22:51:39 -05:00
parent 6559448306
commit 008bc186ca
7 changed files with 271 additions and 5 deletions
@@ -0,0 +1,191 @@
/**
* A bot row click is "go to this bot", not "open its Bot Chat". Before this,
* every click resolved the canonical chat by name and opened it as a tab — and
* with no record of a close anywhere (this plugin keeps no closed set; core's
* tile bucket only forgets), a Bot Chat the user closed came back beside every
* newer thread on every bot switch. Now a bot whose workspace already holds
* tabs comes back to the one the user left; the forever-chat is opened only
* when nothing is open, or on the explicit ask (the row menu's "Open Bot Chat").
*
* Ported from tests/bot-row-keeps-closed-chat.test.mjs, which drove a `vm`
* copy of plugin.js. Its two source-reading cases are dropped for real
* assertions: the menu's call site is now a render in bot-row.test.tsx, and
* the reclaim guard's text is asserted here as the claim-shape invariant the
* guard actually reads.
*/
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { RosterRow } from './types'
const { openBotCanonicalChat, prepareBotSource } = vi.hoisted(() => ({
openBotCanonicalChat: vi.fn(),
prepareBotSource: vi.fn()
}))
vi.mock('./canonical-chat', () => ({
ensureBotMetadata: vi.fn(async () => ({})),
notifyBotOpenFailure: vi.fn(),
openBotCanonicalChat,
prepareBotSource,
PROFILE_SESSION_LIST_LIMIT: 200
}))
const { host } = await import('@hermes/plugin-sdk')
const { $openBotChat, $selectedBot } = await import('./bot-state')
const { openRosterBot } = await import('./roster-actions')
const bot = { connectionId: 'local', name: 'alpha' } as RosterRow
/** Swap in a focus API for one test, restoring whatever the SDK really has —
* including its absence, which is the older-shell case. */
function withFocusApi(impl: null | (() => null | string)) {
const had = Object.hasOwn(host, 'focusOpenWorkspaceSession')
const original = host.focusOpenWorkspaceSession
if (impl) {
host.focusOpenWorkspaceSession = impl
} else {
// @ts-expect-error — modelling a Desktop old enough to lack the verb.
delete host.focusOpenWorkspaceSession
}
return () => {
if (had) {
host.focusOpenWorkspaceSession = original
} else {
// @ts-expect-error — same.
delete host.focusOpenWorkspaceSession
}
}
}
beforeEach(() => {
vi.clearAllMocks()
prepareBotSource.mockResolvedValue(undefined)
openBotCanonicalChat.mockResolvedValue({ openedId: 'bot-chat', registryId: 'bot-chat' })
$openBotChat.set(null)
$selectedBot.set('')
})
describe('a row click returns to the tabs the bot already has open', () => {
it('fronts the remembered tab and resolves no canonical chat', async () => {
const focus = vi.fn(() => 'thread-2')
const restore = withFocusApi(focus)
try {
await expect(openRosterBot(bot)).resolves.toBe(true)
expect(focus).toHaveBeenCalledWith('bot:alpha')
expect(openBotCanonicalChat).not.toHaveBeenCalled()
// Open tabs need no source activation either — the bot is already live.
expect(prepareBotSource).not.toHaveBeenCalled()
} finally {
restore()
}
})
it('claims only the fronted tab, with no registry id', async () => {
const restore = withFocusApi(() => 'thread-2')
try {
await openRosterBot(bot)
expect($openBotChat.get()).toEqual({
key: 'local::alpha',
openedRegistryId: '',
openedSessionId: 'thread-2'
})
} finally {
restore()
}
})
})
describe('the canonical chat still opens when it is what was asked for', () => {
it('opens it when the bot has nothing open', async () => {
const restore = withFocusApi(() => null)
try {
await expect(openRosterBot(bot)).resolves.toBe(true)
expect(openBotCanonicalChat).toHaveBeenCalled()
expect($openBotChat.get()?.openedRegistryId).toBe('bot-chat')
} finally {
restore()
}
})
it('skips the open-tab shortcut on the explicit ask', async () => {
const focus = vi.fn(() => 'thread-2')
const restore = withFocusApi(focus)
try {
await expect(openRosterBot(bot, { canonical: true })).resolves.toBe(true)
expect(focus).not.toHaveBeenCalled()
expect($openBotChat.get()?.openedRegistryId).toBe('bot-chat')
} finally {
restore()
}
})
})
describe('a shell that cannot report open tabs behaves as it did before', () => {
it('opens the canonical chat when the verb is missing', async () => {
const restore = withFocusApi(null)
try {
await expect(openRosterBot(bot)).resolves.toBe(true)
expect(openBotCanonicalChat).toHaveBeenCalled()
} finally {
restore()
}
})
it('opens the canonical chat when the verb throws', async () => {
const restore = withFocusApi(() => {
throw new Error('no tree yet')
})
try {
await expect(openRosterBot(bot)).resolves.toBe(true)
expect(openBotCanonicalChat).toHaveBeenCalled()
} finally {
restore()
}
})
})
describe('the claim a fronted tab records cannot resurrect the closed chat', () => {
// The reclaim listener re-resolves the canonical chat for a claim it owns,
// and guards on the registry id to avoid doing so for a fronted tab. That
// guard is only correct because a fronted-tab claim leaves the id empty
// while a real canonical open always fills it — the invariant asserted here.
it('leaves the registry id empty for a fronted tab', async () => {
const restore = withFocusApi(() => 'thread-2')
try {
await openRosterBot(bot)
expect($openBotChat.get()?.openedRegistryId).toBe('')
expect($openBotChat.get()?.openedSessionId).toBeTruthy()
} finally {
restore()
}
})
it('fills the registry id for a real canonical open', async () => {
const restore = withFocusApi(() => null)
try {
await openRosterBot(bot)
expect($openBotChat.get()?.openedRegistryId).toBeTruthy()
} finally {
restore()
}
})
})
@@ -20,6 +20,7 @@ import { fireEvent, render, screen } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { BotRow } from './bot-row'
import { translateBots } from './i18n-test-helper'
import type { RosterRow } from './types'
const { ensureAgent, ensureBotMetadata, notifyError, openRosterBot, requestProfile, warmAgent, warmProfile } =
@@ -38,7 +39,10 @@ vi.mock('@hermes/plugin-sdk', async importOriginal => {
return {
...sdk,
host: { ...sdk.host, ensureAgent, notifyError, requestProfile, warmAgent, warmProfile }
host: { ...sdk.host, ensureAgent, notifyError, requestProfile, warmAgent, warmProfile },
// The plugin bundle normally lands via `ctx.i18n.register` at load, so
// without this every localized label in the row renders empty.
usePluginI18n: () => translateBots
}
})
@@ -128,6 +132,17 @@ describe('the row delegates the open and claims no activation authority', () =>
})
})
describe('the menu carries the explicit ask for the forever-chat', () => {
it('opens the canonical chat, which a plain row click deliberately does not', async () => {
const bot = { name: 'alpha' } as RosterRow
fireEvent.contextMenu(renderRow(bot))
fireEvent.click(await screen.findByText('Open Bot Chat'))
expect(openRosterBot.mock.calls).toEqual([[bot, { canonical: true }]])
})
})
describe('context-menu mutations hydrate the alias first', () => {
it('reads the backend row before toggling pin, and writes to the alias target', async () => {
// A non-identity alias (Desktop calls it `worker`, the backend calls it
@@ -284,6 +284,10 @@ export function BotRow({ bot, onDelete, onEdit, onGroup, showHandle }: BotRowPro
<ContextMenu>
<ContextMenuTrigger asChild>{row}</ContextMenuTrigger>
<ContextMenuContent>
<ContextMenuItem onSelect={() => void openRosterBot(bot, { canonical: true })}>
{b.bot.openBotChat}
</ContextMenuItem>
<ContextMenuSeparator />
<ContextMenuItem
onSelect={() => {
void ensureBotMetadata(bot)
@@ -40,8 +40,11 @@ export const $selectedRosterHydrated = atom(false)
export const $rosterHydrated = atom(false)
/** Mirrors host.paneVisibility('hermes-bots:pane') — wired in register(). */
export const $botsPaneVisible = atom(false)
/** An explicit open landed: {key, openedRegistryId}. This transient view
* observation is empty only for the legacy newChat draft fallback. */
/** An explicit open landed: {key, openedRegistryId, openedSessionId}. The
* registry id is empty for the legacy newChat draft fallback and for a click
* that came back to the bot's already-open tabs (only openedSessionId set — no
* canonical chat was resolved). This transient view observation is never an
* identity preference. */
export const $openBotChat = atom<{ key: string; openedRegistryId: string; openedSessionId?: string } | null>(null)
/** A session owns the main workspace. The roster highlight and the Cronjobs
* lifecycle both key off this rather than reading host.state conditionally
@@ -67,6 +67,9 @@ type BotsMessages = {
helpPromptPlaceholder: string
descriptionHint: string
newChatWith: string
/** Re-opens the forever-chat on purpose. A plain row click only returns to
* the tabs already open, so a closed Bot Chat needs an explicit ask. */
openBotChat: string
duplicate: string
duplicateFailed: string
deleteTitle: string
@@ -190,6 +193,7 @@ const en: BotsMessages = {
helpPromptPlaceholder: 'What should this bot help with?',
descriptionHint: 'Leave blank to generate from the bot’s name and description.',
newChatWith: 'New chat with this bot',
openBotChat: 'Open Bot Chat',
duplicate: 'Duplicate',
duplicateFailed: 'Duplicate failed',
deleteTitle: 'Delete bot and profile?',
@@ -543,6 +543,14 @@ export default {
return
}
// A claim without a registry id is a fronted non-canonical tab
// (focusExistingBotTab / the draft fallback): re-resolving the
// canonical chat here would open the Bot Chat the user has
// closed. Its tile recovers on the next send like any tab.
if (!claim.openedRegistryId) {
return
}
const bot = selectedRosterBot($lastRoster.get(), $selectedRosterKey.get())
if (!bot) {
@@ -105,11 +105,38 @@ export function trackInboundActivity(roster: RosterRow[]) {
}
}
/** The tab this bot's workspace already has open, fronted — or null when it has
* none. A roster click consults this BEFORE the canonical registry so a bot
* with open tabs simply comes back to the one the user left. It is what lets a
* closed Bot Chat STAY closed: the click path used to re-open the forever-chat
* beside every newer thread on every bot switch, and nothing records a close
* (this plugin keeps no closed set; core's tile bucket only forgets), so the
* only honest signal is the open set itself. Feature-detected — older shells
* fall through to the canonical open. */
function focusExistingBotTab(bot: RosterRow): null | string {
if (typeof host.focusOpenWorkspaceSession !== 'function') {
return null
}
try {
const focused = host.focusOpenWorkspaceSession(botWorkspaceOwnerKey(bot))
return typeof focused === 'string' && focused ? focused : null
} catch {
return null
}
}
/** Select one exact roster owner, then open its named canonical chat only when
* the current Desktop can route that owner without guessing. The workspace
* remembers only this transient opened-view observation; it never stores or
* resolves a canonical-chat id. */
export async function openRosterBot(bot: RosterRow): Promise<boolean> {
* resolves a canonical-chat id.
*
* `canonical`: the user asked for the forever-chat itself (the row menu's
* "Open Bot Chat"). A plain row click is "go to this bot": when its workspace
* already holds tabs, the one the user last had active is fronted and no chat
* is resolved or opened — see focusExistingBotTab. */
export async function openRosterBot(bot: RosterRow, { canonical = false } = {}): Promise<boolean> {
const generation = bumpBotOpenGeneration()
const key = botRosterKey(bot)
const meta = botRosterMeta(bot, $botMeta.get())
@@ -163,6 +190,20 @@ export async function openRosterBot(bot: RosterRow): Promise<boolean> {
// a bot open deliberately leaves the gateway on the launch profile.
ackStoredSessionId(botCanonicalSessionId(bot), bot.name)
if (!canonical) {
const focused = focusExistingBotTab(bot)
if (focused) {
// Open tabs win: no source activation, no registry consult, no open. The
// claim carries only the fronted tab so the focus edge it fires keeps it
// (releaseStaleOpenBotChat) and no registry id is recorded, because none
// was resolved.
$openBotChat.set({ key, openedRegistryId: '', openedSessionId: focused })
return true
}
}
try {
// Activation selects this row's source only. Canonical identity is resolved
// after that by the owner profile's "Bot Chat" title registry.