fix(desktop): /new inside a bot chat compared against a property that does not exist
A bot's canonical chat is the relationship — /new inside one would fork it into a scratch session, so the composer reroutes /new to /compact there. The guard deciding "is this chat the canonical one" read host.activeSessionId, which is not on the host: the real atoms are host.state.activeSessionId (runtime id) and host.state.focusedStoredSessionId (stored id). The optional chain swallowed it, the comparison ran against null every turn, and /new reset forever-chats for as long as the guard shipped. It reads the focused STORED id now, which is the id space canonical_session reports in. The comparison itself moves into isCanonicalChatOnScreen so a test can drive it — matching either the durable registry row or the compression-lineage tip, since a compacted Bot Chat is on screen under its tip id while the registry still names it by the root.
This commit is contained in:
@@ -53,6 +53,29 @@ const CANONICAL_CHAT_TITLE = 'Bot Chat'
|
||||
interface CanonicalChatRow extends CanonicalSession {
|
||||
readonly message_count?: number
|
||||
}
|
||||
|
||||
/** Is the chat on screen the given bot's forever-chat?
|
||||
*
|
||||
* Identity comes off the roster's `canonical_session`, resolved server-side
|
||||
* by title, and matches EITHER the durable registry row or the
|
||||
* compression-lineage tip — a compacted Bot Chat is on screen under its tip
|
||||
* id while the registry still names it by the root.
|
||||
*
|
||||
* Takes the STORED id. The runtime id belongs to a different id space and
|
||||
* matches neither, which is how the `/new` guard that calls this went dead. */
|
||||
export function isCanonicalChatOnScreen(
|
||||
bot: null | RosterRow | undefined,
|
||||
storedSessionId: null | string | undefined
|
||||
): boolean {
|
||||
const canonical = bot?.canonical_session
|
||||
|
||||
if (!storedSessionId || !canonical) {
|
||||
return false
|
||||
}
|
||||
|
||||
return [canonical.id, canonical.resolved_id].filter(Boolean).map(String).includes(String(storedSessionId))
|
||||
}
|
||||
|
||||
async function openStoredBotChat(
|
||||
owner: RosterRow | string,
|
||||
storedId: string,
|
||||
@@ -61,10 +84,12 @@ async function openStoredBotChat(
|
||||
if (!storedId || typeof host.openSession !== 'function') {
|
||||
throw new Error('This Hermes Desktop version cannot open stored sessions')
|
||||
}
|
||||
|
||||
const { bot, name, route } = botOwner(owner)
|
||||
const ownerKey = botWorkspaceOwnerKey(bot)
|
||||
const hasAuthoritativeCount = typeof summary?.message_count === 'number' && Number.isFinite(summary.message_count)
|
||||
const expectHistory = hasAuthoritativeCount ? summary.message_count > 0 : true
|
||||
|
||||
// Current SDKs export the Bot-specific budget. The fallback preserves
|
||||
// compatibility with older hosts and isolated plugin test harnesses.
|
||||
const hydrationTimeoutMs =
|
||||
@@ -110,6 +135,7 @@ async function openStoredBotChat(
|
||||
retryHydrationTimeoutOnce: true,
|
||||
tabTitle: CANONICAL_CHAT_TITLE
|
||||
})
|
||||
|
||||
return storedId
|
||||
}
|
||||
|
||||
@@ -119,12 +145,16 @@ async function openStoredBotChat(
|
||||
function isCanonicalBotChatHistory(history: CanonicalChatRow) {
|
||||
const rootTitle = String(history?.root_title || '').trim()
|
||||
const title = String(history?.title || '').trim()
|
||||
|
||||
return rootTitle === CANONICAL_CHAT_TITLE || (!rootTitle && title === CANONICAL_CHAT_TITLE)
|
||||
}
|
||||
|
||||
function botModeGatewayNeedsUpdate(error: unknown) {
|
||||
const message = String((error as RpcErrorLike)?.message || error || '')
|
||||
|
||||
return /(?:method not found|no handler for|unknown method|unsupported rpc)/i.test(message)
|
||||
}
|
||||
|
||||
export function notifyBotOpenFailure(error: unknown, bot: RosterRow, fallbackMessage: string) {
|
||||
if (botModeGatewayNeedsUpdate(error)) {
|
||||
const gateway = bot.connectionLabel || bot.connectionId || 'this gateway'
|
||||
@@ -133,8 +163,10 @@ export function notifyBotOpenFailure(error: unknown, bot: RosterRow, fallbackMes
|
||||
title: 'Update this gateway to use Bot Mode',
|
||||
message: `Update ${gateway}, then try again.`
|
||||
})
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
host.notifyError?.(error, fallbackMessage)
|
||||
}
|
||||
|
||||
@@ -161,6 +193,7 @@ async function findExistingCanonicalChat(owner: RosterRow | string): Promise<Can
|
||||
// matters doubly for remote bots. Both open paths catch and toast "try
|
||||
// again", which is the correct outcome: retry, never mint.
|
||||
let res: { sessions?: CanonicalChatRow[] }
|
||||
|
||||
try {
|
||||
res = await requestForBot<{ sessions?: CanonicalChatRow[] }>(bot, 'session.list', {
|
||||
profile: backendTargetProfile(route, name),
|
||||
@@ -176,7 +209,9 @@ async function findExistingCanonicalChat(owner: RosterRow | string): Promise<Can
|
||||
const detail = message ? ` (${message})` : ''
|
||||
throw new Error(`Could not check ${name}'s Bot Chat registry${detail} — not starting a new chat`)
|
||||
}
|
||||
|
||||
const rows = res?.sessions ?? []
|
||||
|
||||
return rows.find(row => isCanonicalBotChatHistory(row)) || null
|
||||
}
|
||||
|
||||
@@ -214,10 +249,12 @@ export function createCanonicalChat(
|
||||
): Promise<null | string> {
|
||||
const { bot, name, key, route } = botOwner(owner)
|
||||
const inflight = canonicalCreations.get(key)
|
||||
|
||||
if (inflight) {
|
||||
if (!openingStillCurrent) {
|
||||
return inflight.run!
|
||||
}
|
||||
|
||||
return inflight.run!.then(async sid => {
|
||||
if (sid && openingStillCurrent() && typeof host.openSession === 'function') {
|
||||
await host.openSession(sid, {
|
||||
@@ -234,23 +271,30 @@ export function createCanonicalChat(
|
||||
tabTitle: CANONICAL_CHAT_TITLE
|
||||
})
|
||||
}
|
||||
|
||||
return sid
|
||||
})
|
||||
}
|
||||
|
||||
const flight: CanonicalCreation = {
|
||||
run: null
|
||||
}
|
||||
|
||||
const canNavigate = () => !openingStillCurrent || openingStillCurrent()
|
||||
|
||||
const run = (async () => {
|
||||
const existing = await findExistingCanonicalChat(owner)
|
||||
|
||||
if (existing?.id) {
|
||||
if (typeof host.openSession === 'function' && canNavigate()) {
|
||||
// The exact-lookup gateway reports the compression-lineage tip as
|
||||
// resolved_id; open the tip, the registry row stays the identity.
|
||||
await openStoredBotChat(owner, existing.resolved_id || existing.id, existing)
|
||||
}
|
||||
|
||||
return existing.id
|
||||
}
|
||||
|
||||
const res = await requestForBot<{ session_id?: string; stored_session_id?: string }>(bot, 'session.create', {
|
||||
profile: backendTargetProfile(route, name),
|
||||
title: CANONICAL_CHAT_TITLE,
|
||||
@@ -260,6 +304,7 @@ export function createCanonicalChat(
|
||||
// ignore the unknown param and it stays visible.
|
||||
hidden: true
|
||||
})
|
||||
|
||||
const sid = res?.stored_session_id
|
||||
const runtime = res?.session_id
|
||||
|
||||
@@ -274,6 +319,7 @@ export function createCanonicalChat(
|
||||
// untitled window. Older gateways may not support the eager write; retain
|
||||
// the kickoff-and-retry fallback below.
|
||||
let titled = false
|
||||
|
||||
if (runtime) {
|
||||
try {
|
||||
await requestForBot(bot, 'session.title', {
|
||||
@@ -292,10 +338,12 @@ export function createCanonicalChat(
|
||||
// (the gateway prunes it).
|
||||
if (/already in use/i.test(String((error as RpcErrorLike)?.message || ''))) {
|
||||
const winner = await findExistingCanonicalChat(owner)
|
||||
|
||||
if (winner?.id) {
|
||||
if (typeof host.openSession === 'function') {
|
||||
await openStoredBotChat(owner, winner.resolved_id || winner.id, winner)
|
||||
}
|
||||
|
||||
return winner.id
|
||||
}
|
||||
}
|
||||
@@ -306,6 +354,7 @@ export function createCanonicalChat(
|
||||
// Mount the session view FIRST, then send the kickoff — submitting into
|
||||
// an unmounted session left the intro reply invisible until reopen.
|
||||
let opened = false
|
||||
|
||||
if (sid && typeof host.openSession === 'function' && canNavigate()) {
|
||||
try {
|
||||
await host.openSession(sid, {
|
||||
@@ -331,6 +380,7 @@ export function createCanonicalChat(
|
||||
// after prompt.submit below instead of leaving the chat off-screen.
|
||||
}
|
||||
}
|
||||
|
||||
if (runtime) {
|
||||
// Intro turn: only on genuine New Agent creation (`kickoff`), or as the
|
||||
// COMPAT persistence write when the eager title failed — an old gateway
|
||||
@@ -338,13 +388,16 @@ export function createCanonicalChat(
|
||||
// the chat never survives its own creation. A titled row needs neither:
|
||||
// the user speaks first.
|
||||
const submitIntro = kickoff || !titled
|
||||
|
||||
if (submitIntro) {
|
||||
await new Promise(resolve => window.setTimeout(resolve, 400))
|
||||
|
||||
try {
|
||||
await requestForBot(bot, 'prompt.submit', {
|
||||
session_id: runtime,
|
||||
text: 'Hey, tell me about yourself!'
|
||||
})
|
||||
|
||||
if (!opened && sid && typeof host.openSession === 'function' && canNavigate()) {
|
||||
await host.openSession(sid, {
|
||||
...(route
|
||||
@@ -394,14 +447,17 @@ export function createCanonicalChat(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return sid || null
|
||||
})().finally(() => {
|
||||
if (canonicalCreations.get(key) === flight) {
|
||||
canonicalCreations.delete(key)
|
||||
}
|
||||
})
|
||||
|
||||
flight.run = run
|
||||
canonicalCreations.set(key, flight)
|
||||
|
||||
return run
|
||||
}
|
||||
|
||||
@@ -418,12 +474,15 @@ export async function openBotCanonicalChat(
|
||||
openingStillCurrent: (() => boolean) | null = null
|
||||
): Promise<{ openedId: string; registryId: string } | null> {
|
||||
const existing = await findExistingCanonicalChat(owner)
|
||||
|
||||
if (existing?.id && typeof host.openSession === 'function') {
|
||||
if (openingStillCurrent && !openingStillCurrent()) {
|
||||
return null
|
||||
}
|
||||
|
||||
const openedId = existing.resolved_id || existing.id
|
||||
await openStoredBotChat(owner, openedId, existing)
|
||||
|
||||
// Both identities matter downstream: the durable registry row names the
|
||||
// chat; the resolved lineage tip is what actually takes session focus.
|
||||
// Callers matching focus against only the registry id mistook every
|
||||
@@ -433,9 +492,11 @@ export async function openBotCanonicalChat(
|
||||
openedId: String(openedId)
|
||||
}
|
||||
}
|
||||
|
||||
const created = await createCanonicalChat(owner, {
|
||||
openingStillCurrent
|
||||
})
|
||||
|
||||
return created
|
||||
? {
|
||||
registryId: String(created),
|
||||
@@ -443,6 +504,7 @@ export async function openBotCanonicalChat(
|
||||
}
|
||||
: null
|
||||
}
|
||||
|
||||
export async function prepareBotSource(bot: RosterRow) {
|
||||
if (!bot.sourceScoped) {
|
||||
return
|
||||
@@ -453,12 +515,14 @@ export async function prepareBotSource(bot: RosterRow) {
|
||||
// activation is a UI concern that never authorizes the calls. All this
|
||||
// gate does is refuse when the desktop predates routed profile requests.
|
||||
const route = botConnectionRoute(bot)
|
||||
|
||||
if (route && typeof host.requestProfile !== 'function') {
|
||||
throw new Error(
|
||||
getPluginCtx()?.i18n.t('bot.remoteConnectionsUnsupported') ??
|
||||
'Update Hermes Desktop to chat with bots on other connections.'
|
||||
)
|
||||
}
|
||||
|
||||
if (!route && typeof host.ensureAgent === 'function') {
|
||||
// Source-annotated row on the ACTIVE connection (no captured route):
|
||||
// legacy activation path, unchanged. An absent connectionId is fine —
|
||||
@@ -466,19 +530,24 @@ export async function prepareBotSource(bot: RosterRow) {
|
||||
await host.ensureAgent(bot.connectionId, bot.name)
|
||||
}
|
||||
}
|
||||
|
||||
export async function ensureBotMetadata(bot: RosterRow): Promise<BotMeta> {
|
||||
if (!bot?.sourceScoped) {
|
||||
return botRosterMeta(bot, $botMeta.get()) || {}
|
||||
}
|
||||
|
||||
const route = botConnectionRoute(bot)
|
||||
const backendProfile = backendTargetProfile(route, bot.name)
|
||||
|
||||
const result = await requestForBot<{ profiles?: Array<Pick<RosterRow, 'name' | 'ui_meta'>> }>(
|
||||
bot,
|
||||
'profiles.list',
|
||||
{}
|
||||
)
|
||||
|
||||
const row = (result?.profiles || []).find(profile => profile?.name === backendProfile)
|
||||
const server = row?.ui_meta?.['hermes-bots']
|
||||
|
||||
if (server && typeof server === 'object') {
|
||||
const key = botMetaKey(bot)
|
||||
$botMeta.set({
|
||||
@@ -490,5 +559,6 @@ export async function ensureBotMetadata(bot: RosterRow): Promise<BotMeta> {
|
||||
})
|
||||
persistBotMetaSnapshot($botMeta.get(), true)
|
||||
}
|
||||
|
||||
return botRosterMeta(bot, $botMeta.get()) || {}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
* The /new → /compact guard's identity check.
|
||||
*
|
||||
* `/new` inside a bot's canonical forever-chat would fork the relationship
|
||||
* into a scratch session — the one thing Bots mode promises never happens. The
|
||||
* composer middleware reroutes it to `/compact` (same felt effect: fresh
|
||||
* working context, SAME conversation), but only when the chat on screen really
|
||||
* is the forever-chat.
|
||||
*
|
||||
* Identity is the NAME — the profile's session titled "Bot Chat" — reported by
|
||||
* the gateway as `canonical_session` on every roster row. No stored meta.chat
|
||||
* pointer is consulted: pointers dangle, the registry row cannot.
|
||||
*
|
||||
* Its predecessor could only regex the guard's source text for the strings
|
||||
* `canonical_session` / `canonical?.id`, which is precisely why it never
|
||||
* noticed the guard was dead in production: the id it compared against came
|
||||
* from `host.activeSessionId`, a property that does not exist. The comparison
|
||||
* ran against null on every turn, so `/new` reset forever-chats for as long as
|
||||
* the guard shipped. These tests drive the comparison itself.
|
||||
*/
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import type { RosterRow } from './types'
|
||||
|
||||
vi.mock('@hermes/plugin-sdk', () => ({
|
||||
BOT_CHAT_SESSION_HYDRATION_TIMEOUT_MS: 15_000,
|
||||
host: {}
|
||||
}))
|
||||
vi.mock('./routing', () => ({
|
||||
backendTargetProfile: (_route: unknown, name: string) => name,
|
||||
botConnectionRoute: () => null,
|
||||
botRosterMeta: () => ({}),
|
||||
botWorkspaceOwnerKey: () => '',
|
||||
requestForBot: vi.fn()
|
||||
}))
|
||||
vi.mock('./data', () => ({
|
||||
$botMeta: { get: () => ({}), set: vi.fn() },
|
||||
botMetaKey: () => '',
|
||||
botOwner: (owner: string) => ({ bot: { name: owner }, key: owner, name: owner, route: null }),
|
||||
persistBotMetaSnapshot: vi.fn()
|
||||
}))
|
||||
vi.mock('./shared', () => ({ getPluginCtx: () => null }))
|
||||
|
||||
const { isCanonicalChatOnScreen } = await import('./canonical-chat')
|
||||
|
||||
function bot(canonical: null | { id?: string; resolved_id?: string }): RosterRow {
|
||||
return { canonical_session: canonical, name: 'ops' } as RosterRow
|
||||
}
|
||||
|
||||
describe('isCanonicalChatOnScreen', () => {
|
||||
it('matches the durable registry row', () => {
|
||||
expect(isCanonicalChatOnScreen(bot({ id: 'forever-chat' }), 'forever-chat')).toBe(true)
|
||||
})
|
||||
|
||||
it('matches the compression-lineage tip', () => {
|
||||
// A compacted Bot Chat is on screen under its tip id while the registry
|
||||
// still names it by the root — both are the same forever-chat.
|
||||
const compacted = bot({ id: 'root-1', resolved_id: 'tip-9' })
|
||||
|
||||
expect(isCanonicalChatOnScreen(compacted, 'tip-9')).toBe(true)
|
||||
expect(isCanonicalChatOnScreen(compacted, 'root-1')).toBe(true)
|
||||
})
|
||||
|
||||
it('leaves an ordinary session alone', () => {
|
||||
// Sessions-mode scratchpads on the same profile keep full /new freedom.
|
||||
expect(isCanonicalChatOnScreen(bot({ id: 'forever-chat' }), 'scratch')).toBe(false)
|
||||
})
|
||||
|
||||
it('declines when the bot has no registry row yet', () => {
|
||||
expect(isCanonicalChatOnScreen(bot(null), 'anything')).toBe(false)
|
||||
})
|
||||
|
||||
it('declines on a missing id rather than matching everything', () => {
|
||||
// The regression itself: a null id must never satisfy the guard, and must
|
||||
// never be read as "no canonical chat, so let /new through" by accident of
|
||||
// a loose comparison.
|
||||
expect(isCanonicalChatOnScreen(bot({ id: 'forever-chat' }), null)).toBe(false)
|
||||
expect(isCanonicalChatOnScreen(bot({ id: 'forever-chat' }), '')).toBe(false)
|
||||
expect(isCanonicalChatOnScreen(undefined, 'forever-chat')).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -15,12 +15,10 @@
|
||||
* bot-initiated sends use `hermes -p <bot> chat --in ~ -c "Bot Chat"`.
|
||||
*/
|
||||
|
||||
import { CHAT_EMPTY_AREA, COMPOSER_AREAS, EmptyState, host, PALETTE_AREA, translateNow } from '@hermes/plugin-sdk'
|
||||
import { CHAT_EMPTY_AREA, COMPOSER_AREAS, host, PALETTE_AREA, translateNow } from '@hermes/plugin-sdk'
|
||||
import type { ChatEmptyProps, PluginContext } from '@hermes/plugin-sdk'
|
||||
import type { ChangeEvent, KeyboardEvent } from 'react'
|
||||
|
||||
import { startFaceClock, stopFaceClock } from './avatar'
|
||||
import { BotChatEmpty } from './chat-empty'
|
||||
import {
|
||||
$botChatFocused,
|
||||
$botsPaneVisible,
|
||||
@@ -31,7 +29,8 @@ import {
|
||||
$selectedRosterKey,
|
||||
focusedMentionProfile
|
||||
} from './bot-state'
|
||||
import { openBotCanonicalChat } from './canonical-chat'
|
||||
import { isCanonicalChatOnScreen, openBotCanonicalChat } from './canonical-chat'
|
||||
import { BotChatEmpty } from './chat-empty'
|
||||
import { bindProfileSync, RoutinesPane } from './cron'
|
||||
import {
|
||||
$botMeta,
|
||||
@@ -71,7 +70,7 @@ import {
|
||||
import { botRosterMeta, botWorkspaceOwnerKey, setBotsWorkspaceOwner } from './routing'
|
||||
import { startHideSweepScheduler } from './session-sweep'
|
||||
import { bumpBotOpenGeneration, getBotOpenGeneration, ID, setPluginCtx } from './shared'
|
||||
import type { GroupChat, GroupPromptKind, RosterRow } from './types'
|
||||
import type { GroupChat, RosterRow } from './types'
|
||||
|
||||
// ── plugin ───────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -102,6 +101,7 @@ export default {
|
||||
// The cross-connection relay rides every gateway socket this Desktop
|
||||
// holds: roster sync + envelope drain/deliver/reply loops.
|
||||
startBotRelay()
|
||||
|
||||
// Disabling the plugin (or a hot reload) must actually stop the clock —
|
||||
// before this, the rAF loop + 1Hz document scan ran until app restart.
|
||||
if (typeof ctx.onDispose === 'function') {
|
||||
@@ -123,25 +123,31 @@ export default {
|
||||
provide: (query: string): MentionCompletionItem[] => {
|
||||
const roster = cachedUnionRoster()
|
||||
const profiles = Array.isArray(roster?.profiles) ? roster.profiles : []
|
||||
|
||||
if (!profiles.length) {
|
||||
return []
|
||||
}
|
||||
|
||||
const active = focusedMentionProfile()
|
||||
const q = (query || '').toLowerCase()
|
||||
const items: MentionCompletionItem[] = []
|
||||
|
||||
const live = {
|
||||
name: active,
|
||||
connectionId: String(host.state.connectionId?.get?.() || host.activeConnectionId?.() || 'local')
|
||||
}
|
||||
|
||||
for (const profile of profiles) {
|
||||
if (!profile?.name || isActiveRosterBot(profile, live)) {
|
||||
continue
|
||||
}
|
||||
|
||||
const handle = botHandle(profile.name, profile)
|
||||
const display = displayName(profile, $botMeta.get()[profile.name])
|
||||
// Renamed bots complete on their friendly name — the tag is the
|
||||
// renamed slug when one exists, the profile handle otherwise.
|
||||
const tag = botMentionTag(profile)
|
||||
|
||||
if (
|
||||
q &&
|
||||
!tag.toLowerCase().startsWith(q) &&
|
||||
@@ -150,6 +156,7 @@ export default {
|
||||
) {
|
||||
continue
|
||||
}
|
||||
|
||||
const source = profile.connectionLabel ? ` · ${profile.connectionLabel}` : ''
|
||||
items.push({
|
||||
insert: `@${tag}`,
|
||||
@@ -157,6 +164,7 @@ export default {
|
||||
meta: `Bot · ${display}${source}`
|
||||
})
|
||||
}
|
||||
|
||||
return items.slice(0, 8)
|
||||
}
|
||||
}
|
||||
@@ -215,6 +223,7 @@ export default {
|
||||
.then(async value => {
|
||||
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
||||
const rooms: Record<string, GroupChat> = {}
|
||||
|
||||
for (const [name, room] of Object.entries(value)) {
|
||||
if (room && Array.isArray(room.log)) {
|
||||
rooms[name] = {
|
||||
@@ -238,6 +247,7 @@ export default {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$groupChats.set({
|
||||
...rooms,
|
||||
...$groupChats.get()
|
||||
@@ -253,10 +263,13 @@ export default {
|
||||
typeof window !== 'undefined'
|
||||
? await Promise.resolve(window.hermesDesktop?.connections?.list?.()).catch(() => null)
|
||||
: null
|
||||
|
||||
const liveIds = Array.isArray(registry?.connections)
|
||||
? new Set(registry.connections.map(connection => String(connection?.id || '').trim()).filter(Boolean))
|
||||
: null
|
||||
|
||||
const annotated = annotateOrphanedGroupChatMembers($groupChats.get(), liveIds)
|
||||
|
||||
if (annotated.changed) {
|
||||
// Per-room updateGroupChat keeps the durable record's full
|
||||
// shape (sessionOwners, holds) in storage; sync:false —
|
||||
@@ -305,6 +318,7 @@ export default {
|
||||
// older Electron mains don't emit it, and bare vm test harnesses have
|
||||
// no window global.
|
||||
let unbindConnectionsChanged: null | (() => void) = null
|
||||
|
||||
try {
|
||||
if (typeof window !== 'undefined') {
|
||||
unbindConnectionsChanged =
|
||||
@@ -317,15 +331,19 @@ export default {
|
||||
} catch {
|
||||
/* registry lifecycle push unavailable — hydrate-time annotate still covers it */
|
||||
}
|
||||
|
||||
if (typeof ctx.onDispose === 'function') {
|
||||
ctx.onDispose(() => {
|
||||
stopGroupChatServerSync()
|
||||
|
||||
if (typeof unbindProfileListener === 'function') {
|
||||
unbindProfileListener()
|
||||
}
|
||||
|
||||
if (typeof unbindGatewayListener === 'function') {
|
||||
unbindGatewayListener()
|
||||
}
|
||||
|
||||
if (typeof unbindConnectionsChanged === 'function') {
|
||||
unbindConnectionsChanged()
|
||||
}
|
||||
@@ -414,10 +432,12 @@ export default {
|
||||
},
|
||||
render: () => <RoutinesPane />
|
||||
})
|
||||
|
||||
if (typeof host.paneVisibility === 'function') {
|
||||
// The contribution-scoped pane id (`register` prefixes `${ID}:`).
|
||||
const $sidebarVisible = host.paneVisibility(`${ID}:pane`)
|
||||
let unregisterRoutines: null | (() => void) = null
|
||||
|
||||
const syncRoutinesPane = () => {
|
||||
if (botChatOwnsWorkspace()) {
|
||||
unregisterRoutines ??= registerRoutinesPane()
|
||||
@@ -428,16 +448,20 @@ export default {
|
||||
// a pane must never unregister itself out from under its own click.
|
||||
// Leaving Bot Mode ($botsPaneVisible false) still unregisters.
|
||||
const $self = host.paneVisibility(`${ID}:routines`)
|
||||
if ($botsPaneVisible.get() && $self && typeof $self.get === 'function' && $self.get()) return
|
||||
|
||||
if ($botsPaneVisible.get() && $self && typeof $self.get === 'function' && $self.get()) {return}
|
||||
unregisterRoutines()
|
||||
unregisterRoutines = null
|
||||
}
|
||||
}
|
||||
|
||||
const stopSidebarSync = $sidebarVisible.listen(visible => {
|
||||
$botsPaneVisible.set(Boolean(visible))
|
||||
|
||||
if (visible) {
|
||||
const group = $groupChatWorkspace.get()
|
||||
const selected = selectedRosterBot($lastRoster.get(), $selectedRosterKey.get())
|
||||
|
||||
// Owner routing only. With neither a group nor a selected bot there
|
||||
// is no bot-owned surface to scope, so leave the workspace on
|
||||
// whatever the user was already looking at — the roster-hydration
|
||||
@@ -459,9 +483,12 @@ export default {
|
||||
bumpBotOpenGeneration()
|
||||
host.setWorkspaceScope?.('sessions')
|
||||
}
|
||||
|
||||
syncRoutinesPane()
|
||||
})
|
||||
|
||||
const stopGroupSync = $groupChatWorkspace.listen(syncRoutinesPane)
|
||||
|
||||
// React on the NEXT tick — a layout notification arrives mid-mutation,
|
||||
// and registering/unregistering panes from inside it would re-enter the
|
||||
// tree store.
|
||||
@@ -472,10 +499,12 @@ export default {
|
||||
syncRoutinesPane()
|
||||
}
|
||||
}
|
||||
|
||||
// Tab focus moves without swapping the gateway socket, so the focused
|
||||
// STORED session is the truth about session focus; older shells fall
|
||||
// back to the active session id.
|
||||
const focusStore = host.state.focusedStoredSessionId || host.state.activeSessionId
|
||||
|
||||
const stopFocusSync =
|
||||
typeof focusStore?.listen === 'function'
|
||||
? focusStore.listen(id => {
|
||||
@@ -500,17 +529,23 @@ export default {
|
||||
const payload = (event?.payload || {}) as { stored_session_id?: string }
|
||||
const stored = String(payload.stored_session_id || '')
|
||||
const claim = $openBotChat.get()
|
||||
|
||||
if (!stored || !claim) {
|
||||
return
|
||||
}
|
||||
|
||||
const owned = [claim.openedSessionId, claim.openedRegistryId].filter(Boolean)
|
||||
|
||||
if (!owned.includes(stored)) {
|
||||
return
|
||||
}
|
||||
|
||||
const bot = selectedRosterBot($lastRoster.get(), $selectedRosterKey.get())
|
||||
|
||||
if (!bot) {
|
||||
return
|
||||
}
|
||||
|
||||
const generation = getBotOpenGeneration()
|
||||
void openBotCanonicalChat(bot)
|
||||
.then(opened => {
|
||||
@@ -518,6 +553,7 @@ export default {
|
||||
if (!opened || generation !== getBotOpenGeneration()) {
|
||||
return
|
||||
}
|
||||
|
||||
$openBotChat.set({
|
||||
key: claim.key,
|
||||
openedRegistryId: opened.registryId,
|
||||
@@ -529,12 +565,14 @@ export default {
|
||||
})
|
||||
})
|
||||
: null
|
||||
|
||||
$botsPaneVisible.set(Boolean($sidebarVisible.get()))
|
||||
$botChatFocused.set(sessionOwnsWorkspace())
|
||||
// A persisted layout can boot directly into Bot Mode. Reconcile now,
|
||||
// then once more after the layout mutation finishes.
|
||||
syncRoutinesPane()
|
||||
scheduleRoutinesSync()
|
||||
|
||||
if (typeof ctx.onDispose === 'function') {
|
||||
// The registration disposer is already tracked by ctx.register; only
|
||||
// the listeners need explicit teardown or they survive plugin disable.
|
||||
@@ -548,6 +586,7 @@ export default {
|
||||
} else {
|
||||
registerRoutinesPane()
|
||||
}
|
||||
|
||||
// A bot's chat before it has spoken: core's splash is Hermes' wordmark and
|
||||
// stands down for any session that exists, so the bot titles its own.
|
||||
ctx.register({
|
||||
@@ -595,6 +634,7 @@ export default {
|
||||
// guards the canonical chat: Sessions-mode scratchpads on the
|
||||
// same profile keep full /new freedom.
|
||||
const slashNew = /^\/(new|reset)\s*$/.exec(text.trim())
|
||||
|
||||
if (slashNew) {
|
||||
const activeBot = $selectedBot.get()
|
||||
// Canonical identity is the profile's "Bot Chat" registry row —
|
||||
@@ -603,12 +643,13 @@ export default {
|
||||
// the compression-lineage tip currently on screen.
|
||||
const roster = $lastRoster.get()
|
||||
const row = Array.isArray(roster) ? roster.find(bot => bot?.name === activeBot) : null
|
||||
const canonical = row?.canonical_session || null
|
||||
// TODO(bot-mode-types): host.activeSessionId does not exist — see host.state.activeSessionId
|
||||
// @ts-expect-error typed as written so the live bug stays visible instead of being fixed here.
|
||||
const currentId = host.activeSessionId?.get?.() ?? null
|
||||
const canonicalIds = [canonical?.id, canonical?.resolved_id].filter(Boolean).map(String)
|
||||
if (activeBot && currentId && canonicalIds.includes(String(currentId))) {
|
||||
|
||||
// The STORED id, which is the id space canonical_session is keyed
|
||||
// in. `host.state.activeSessionId` is the runtime id and could
|
||||
// never match, so the guard read `host.activeSessionId` — no such
|
||||
// property — and silently resolved to null on every turn: /new
|
||||
// reset the forever-chat instead of compacting it.
|
||||
if (activeBot && isCanonicalChatOnScreen(row, host.state.focusedStoredSessionId.get())) {
|
||||
host.notify({
|
||||
kind: 'info',
|
||||
title: 'This chat never resets',
|
||||
@@ -616,27 +657,33 @@ export default {
|
||||
'Bot chats are one continuous conversation — compacting instead. ' +
|
||||
'For a throwaway session with this bot, use Sessions mode.'
|
||||
})
|
||||
|
||||
return {
|
||||
...draft,
|
||||
text: '/compact'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!/(^|\s)@[a-z0-9][a-z0-9_-]*/i.test(text)) {
|
||||
return draft
|
||||
}
|
||||
|
||||
const live = {
|
||||
name: focusedMentionProfile(),
|
||||
connectionId: String(host.state.connectionId?.get?.() || host.activeConnectionId?.() || 'local')
|
||||
}
|
||||
|
||||
const cached = cachedUnionRoster()
|
||||
const roster = Array.isArray(cached?.profiles) ? cached.profiles : null
|
||||
let mentionedBots = roster ? resolveRosterMentions(text, roster, live) : []
|
||||
|
||||
if (!roster) {
|
||||
try {
|
||||
const res = await host.request<{ profiles?: RosterRow[] }>('profiles.list', {
|
||||
include_sessions: false
|
||||
})
|
||||
|
||||
// Same resolver as the cached path — renamed bots (display_name
|
||||
// / ui_meta title) stay taggable when the roster cache is cold.
|
||||
mentionedBots = resolveRosterMentions(text, res?.profiles ?? [], live).map(bot => ({
|
||||
@@ -647,6 +694,7 @@ export default {
|
||||
return draft
|
||||
}
|
||||
}
|
||||
|
||||
if (!mentionedBots.length) {
|
||||
return draft
|
||||
}
|
||||
@@ -658,19 +706,25 @@ export default {
|
||||
// resolves against the Desktop-synced relay roster.
|
||||
const lines = mentionedBots.map(bot => {
|
||||
const handle = botHandle(bot.name, bot)
|
||||
|
||||
const title = String(
|
||||
botRosterMeta(bot, $botMeta.get())?.title || bot.ui_meta?.['hermes-bots']?.title || bot.title || ''
|
||||
).trim()
|
||||
|
||||
const target = bot.remoteSource && bot.connectionId ? `${handle}@${bot.connectionId}` : handle
|
||||
|
||||
const where = bot.remoteSource
|
||||
? ` — on ${bot.connectionLabel || bot.connectionId} (message_agent target: "${target}")`
|
||||
: ''
|
||||
|
||||
return `@${handle} = agent profile "${bot.name}"${title ? ` ("${title}")` : ''}${where}`
|
||||
})
|
||||
|
||||
const note =
|
||||
'\n\n[@mentions resolved from the Bot Mode roster — the user is referring to: ' +
|
||||
lines.join('; ') +
|
||||
'. If they want one of these agents contacted, compose your own message and send it with your message_agent tool (agents on other connected machines are reachable too — the Desktop relays it); never forward the user\u2019s text verbatim. If this session has no message_agent tool, agent messaging is unavailable here — say so.]'
|
||||
|
||||
return {
|
||||
...draft,
|
||||
text: text + note
|
||||
|
||||
Reference in New Issue
Block a user