Skip to content

The agent that grows with you

Merge upstream main into fix/remote-bot-routing

Sara Burke723dbda0414c
diff --cc apps/desktop/electron/main.ts
index b0b25c49b99,8e35bbefd9d..73177fffd93
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@@ -252,6 -254,6 +254,7 @@@ import { rehomePrimaryConnection } fro
import {
assertLocalProfileCanStart,
decideProfileDeleteAction,
++ dispatchConnectionScopedProfileDelete,
localProfilePoolKeys,
ProfileDeletionGate,
profileNameFromDeleteRequest,
@@@ -13541,6 -13503,6 +13504,40 @@@ async function pooledRegistrySessionSou
return sources
}
++async function dispatchRegistryApiRequest(request, registryConnectionId, routeProfile = request?.profile) {
++ const connection: any = await ensureRegistryBackend(registryConnectionId, routeProfile)
++
++ const requestPath = connection.sharedRemote
++ ? pathWithProfileScope(request.path, request?.profile)
++ : translateSelfProfileQuery(request.path, request?.profile, connection.remoteProfile)
++
++ return fetchJsonForBackend(connection, requestPath, {
++ method: request?.method,
++ body: request?.body,
++ upload: request?.upload,
++ timeoutMs: resolveTimeoutMs(request?.timeoutMs, DEFAULT_FETCH_TIMEOUT_MS)
++ })
++}
++
++function registryConnectionKind(connectionId) {
++ const registry = readDesktopConnectionsRegistry()
++ const source = registry.connections.find(connection => connection.id === connectionId)
++
++ if (!source) {
++ throw new Error(`No connection with id "${connectionId}".`)
++ }
++
++ return source.kind
++}
++
++async function teardownConnectionScopedProfileBackend(connectionId, profile, request) {
++ const key = backendScopeKey(connectionId, request?.profile || profile)
++ await Promise.all([
++ poolStopper.stop(key),
++ sshBootstrapCoordinator.cancelAndWait(key).then(() => teardownSshConnection(key))
++ ])
++}
++
async function handleHermesApiRequest(request) {
// Registry-pinned request (request.connectionId): the renderer is working
// against a REGISTERED gateway connection, so the data — cron jobs and their
@@@ -13552,22 -13515,22 +13550,7 @@@
const registryConnectionId = apiRequestRegistryConnectionId(request)
if (registryConnectionId) {
-- const connection: any = await ensureRegistryBackend(registryConnectionId, request?.profile)
--
-- // A shared remote host serves every profile via ?profile=; an SSH-scoped
-- // backend instead runs AS one remote profile, so an explicit self-profile
-- // filter must be translated from the desktop routing label into that
-- // backend namespace (same contract as the v1 profileRouteOptions path).
-- const requestPath = connection.sharedRemote
-- ? pathWithProfileScope(request.path, request?.profile)
-- : translateSelfProfileQuery(request.path, request?.profile, connection.remoteProfile)
--
-- return fetchJsonForBackend(connection, requestPath, {
-- method: request?.method,
-- body: request?.body,
-- upload: request?.upload,
-- timeoutMs: resolveTimeoutMs(request?.timeoutMs, DEFAULT_FETCH_TIMEOUT_MS)
-- })
++ return dispatchRegistryApiRequest(request, registryConnectionId)
}
// Remote-profile session requests would otherwise hit the local primary off
@@@ -13678,6 -13641,6 +13661,20 @@@ ipcMain.handle('hermes:api', async (_ev
// respawn the old-name backend and recreate its HERMES_HOME (#45474).
const deletingProfile = profileNameFromDeleteRequest(request)
const mutatingProfile = deletingProfile || profileRenameFromRequest(request)?.oldName || null
++ const registryConnectionId = apiRequestRegistryConnectionId(request)
++
++ if (deletingProfile && registryConnectionId) {
++ return dispatchConnectionScopedProfileDelete(request, {
++ acquire: profile => profileDeletionGate.acquire(profile),
++ connectionKind: connectionId => registryConnectionKind(connectionId),
++ dispatch: routeProfile => dispatchRegistryApiRequest(request, registryConnectionId, routeProfile),
++ isDefaultProfile: profile => profile === 'default',
++ isValidProfileName: profile => PROFILE_NAME_RE.test(profile),
++ prepareLocal: localRequest => prepareProfileDeleteRequest(localRequest).then(() => undefined),
++ teardownConnection: (connectionId, profile) =>
++ teardownConnectionScopedProfileBackend(connectionId, profile, request)
++ })
++ }
if (!mutatingProfile) {
return handleHermesApiRequest(request)
diff --cc apps/desktop/electron/profile-delete-routing.test.ts
index df8ff09a079,df8ff09a079..7538f63c172
--- a/apps/desktop/electron/profile-delete-routing.test.ts
+++ b/apps/desktop/electron/profile-delete-routing.test.ts
@@@ -5,6 -5,6 +5,7 @@@ import { test } from 'vitest
import {
assertLocalProfileCanStart,
decideProfileDeleteAction,
++ dispatchConnectionScopedProfileDelete,
localProfilePoolKeys,
ProfileDeletionGate,
profileNameFromDeleteRequest,
@@@ -151,3 -151,3 +152,136 @@@ test('localProfilePoolKeys returns ever
test('resolveRouteProfile preserves a primary-backend route from another routing policy', () => {
assert.equal(resolveRouteProfile(null, null), null)
})
++
++test('explicit registered local DELETE holds one gate through teardown and dispatch', async () => {
++ const events: string[] = []
++ const gate = new ProfileDeletionGate()
++ const result = await dispatchConnectionScopedProfileDelete(
++ { connectionId: 'local', method: 'DELETE', path: '/api/profiles/worker', profile: 'worker' },
++ {
++ ...deps,
++ acquire: profile => {
++ events.push(`gate:${profile}`)
++ const release = gate.acquire(profile)
++ return () => {
++ events.push(`release:${profile}`)
++ release()
++ }
++ },
++ connectionKind: () => 'local',
++ dispatch: async routeProfile => {
++ assert.equal(gate.blocks('worker'), true)
++ events.push(`dispatch:${routeProfile ?? 'primary'}`)
++ return 'deleted'
++ },
++ prepareLocal: async request => {
++ assert.equal(gate.blocks('worker'), true)
++ events.push(`prepare:${request.connectionId}:worker`)
++ },
++ teardownConnection: async () => assert.fail('local deletion must use prepareProfileDeleteRequest')
++ }
++ )
++
++ assert.equal(result, 'deleted')
++ assert.deepEqual(events, [
++ 'gate:worker',
++ 'prepare:local:worker',
++ 'dispatch:primary',
++ 'release:worker'
++ ])
++})
++
++test('explicit registered SSH DELETE tears down its source backend before dispatch', async () => {
++ const events: string[] = []
++ const result = await dispatchConnectionScopedProfileDelete(
++ { connectionId: 'build-host', method: 'DELETE', path: '/api/profiles/worker', profile: 'worker' },
++ {
++ ...deps,
++ acquire: profile => {
++ events.push(`gate:${profile}`)
++ return () => events.push(`release:${profile}`)
++ },
++ connectionKind: () => 'ssh',
++ dispatch: async routeProfile => {
++ events.push(`dispatch:${routeProfile ?? 'primary'}`)
++ return 'deleted'
++ },
++ prepareLocal: async () => assert.fail('SSH deletion must not use local profile teardown'),
++ teardownConnection: async (connectionId, profile) => {
++ events.push(`teardown:${connectionId}:${profile}`)
++ }
++ }
++ )
++
++ assert.equal(result, 'deleted')
++ assert.deepEqual(events, [
++ 'gate:worker',
++ 'teardown:build-host:worker',
++ 'dispatch:primary',
++ 'release:worker'
++ ])
++})
++
++test('connection-scoped default DELETE rejects before gate, preparation, teardown, or dispatch', async () => {
++ const events: string[] = []
++
++ await assert.rejects(
++ dispatchConnectionScopedProfileDelete(
++ { connectionId: 'build-host', method: 'DELETE', path: '/api/profiles/default', profile: 'default' },
++ {
++ acquire: profile => {
++ events.push(`gate:${profile}`)
++ return () => events.push(`release:${profile}`)
++ },
++ connectionKind: () => 'ssh',
++ dispatch: async () => {
++ events.push('dispatch')
++ return 'deleted'
++ },
++ isDefaultProfile: profile => profile === 'default',
++ isValidProfileName: profile => /^[a-z0-9][a-z0-9_-]{0,63}$/.test(profile),
++ prepareLocal: async () => {
++ events.push('prepare')
++ },
++ teardownConnection: async () => {
++ events.push('teardown')
++ }
++ }
++ ),
++ /default profile cannot be deleted/i
++ )
++
++ assert.deepEqual(events, [])
++})
++
++test('connection-scoped invalid-name DELETE rejects before gate, preparation, teardown, or dispatch', async () => {
++ const events: string[] = []
++
++ await assert.rejects(
++ dispatchConnectionScopedProfileDelete(
++ { connectionId: 'local', method: 'DELETE', path: '/api/profiles/bad%20name', profile: 'bad name' },
++ {
++ acquire: profile => {
++ events.push(`gate:${profile}`)
++ return () => events.push(`release:${profile}`)
++ },
++ connectionKind: () => 'local',
++ dispatch: async () => {
++ events.push('dispatch')
++ return 'deleted'
++ },
++ isDefaultProfile: profile => profile === 'default',
++ isValidProfileName: profile => /^[a-z0-9][a-z0-9_-]{0,63}$/.test(profile),
++ prepareLocal: async () => {
++ events.push('prepare')
++ },
++ teardownConnection: async () => {
++ events.push('teardown')
++ }
++ }
++ ),
++ /invalid profile name/i
++ )
++
++ assert.deepEqual(events, [])
++})
diff --cc apps/desktop/electron/profile-delete-routing.ts
index 3338fe2420c,3338fe2420c..bf6d25e2d7a
--- a/apps/desktop/electron/profile-delete-routing.ts
+++ b/apps/desktop/electron/profile-delete-routing.ts
@@@ -60,6 -60,6 +60,64 @@@ export interface ProfileDeleteDecisionD
primaryProfileKey: () => string
}
++export interface ConnectionScopedProfileDeleteRequest {
++ connectionId?: unknown
++ method?: unknown
++ path?: unknown
++ profile?: unknown
++}
++
++export interface ConnectionScopedProfileDeleteDeps<T> {
++ acquire: (profile: string) => () => void
++ connectionKind: (connectionId: string) => string
++ dispatch: (routeProfile: null) => Promise<T>
++ isDefaultProfile: (profile: string) => boolean
++ isValidProfileName: (profile: string) => boolean
++ prepareLocal: (request: ConnectionScopedProfileDeleteRequest) => Promise<void>
++ teardownConnection: (connectionId: string, profile: string) => Promise<void>
++}
++
++/**
++ * Run an explicit registry profile DELETE under the same process-wide gate as
++ * legacy deletion. Teardown and dispatch are injected so the Electron caller
++ * can stop either local profile pools or one connection-qualified backend.
++ * Dispatch deliberately receives a null route profile: resolving the deleted
++ * profile again would recurse into the gate (and could recreate its home).
++ */
++export async function dispatchConnectionScopedProfileDelete<T>(
++ request: ConnectionScopedProfileDeleteRequest,
++ deps: ConnectionScopedProfileDeleteDeps<T>
++): Promise<T> {
++ const profile = profileNameFromDeleteRequest(request)
++ const connectionId = String(request.connectionId ?? '').trim()
++
++ if (!profile || !connectionId) {
++ throw new Error('Connection-scoped profile deletion requires a connection and profile.')
++ }
++
++ if (deps.isDefaultProfile(profile)) {
++ throw new Error('The default profile cannot be deleted.')
++ }
++
++ if (!deps.isValidProfileName(profile)) {
++ throw new Error(`Invalid profile name: ${profile}`)
++ }
++
++ const release = deps.acquire(profile)
++
++ try {
++ if (deps.connectionKind(connectionId) === 'local') {
++ await deps.prepareLocal(request)
++ } else {
++ await deps.teardownConnection(connectionId, profile)
++ }
++
++ return await deps.dispatch(null)
++ } finally {
++ release()
++ }
++}
++
/**
* Process-local barrier for profile deletion. Electron IPC handlers run
* concurrently, so tearing down a pooled backend is not enough by itself: a
diff --cc apps/desktop/src/hermes.ts
index e8cf3e78221,aab8cb1ab2d..6c0a4748fba
--- a/apps/desktop/src/hermes.ts
+++ b/apps/desktop/src/hermes.ts
@@@ -787,12 -780,11 +794,15 @@@ export function searchSessions(query: s
// the given `profile`). The backend resolves exact ids and unique prefixes and
// 404s when the id isn't on that profile — so a cheap by-id lookup replaces the
// cross-profile list scan when locating an unknown id's owner.
-export function getSession(id: string, profile?: string | null): Promise<SessionInfo> {
- const suffix = profile ? `?profile=${encodeURIComponent(profile)}` : ''
+export function getSession(id: string, profile?: ProfileScope): Promise<SessionInfo> {
+ const scoped = sessionScoped(profile)
+ const suffix = sessionScopeQuery(profile)
- return window.hermesDesktop.api<SessionInfo>({
+ return hermesApi<SessionInfo>({
- ...(profile ? { profile } : {}),
+ ...scoped,
++ ...(profile && typeof profile === 'object' && profile.connectionId?.trim() === 'local'
++ ? { connectionId: 'local' }
++ : {}),
path: `/api/sessions/${encodeURIComponent(id)}${suffix}`
})
}
@@@ -832,8 -822,8 +842,11 @@@ export function getSessionMessages
const suffix = query.size ? `?${query.toString()}` : ''
- return window.hermesDesktop.api<SessionMessagesResponse>({
+ return hermesApi<SessionMessagesResponse>({
- ...(profile ? { profile } : {}),
+ ...scoped,
++ ...(profile && typeof profile === 'object' && profile.connectionId?.trim() === 'local'
++ ? { connectionId: 'local' }
++ : {}),
path: `/api/sessions/${encodeURIComponent(id)}/messages${suffix}`
})
}
@@@ -934,9 -924,9 +947,12 @@@ export async function getAllSessionMess
return { session_id: resolvedSessionId, messages }
}
-export function deleteSession(id: string, profile?: string | null): Promise<{ ok: boolean }> {
+export function deleteSession(id: string, profile?: ProfileScope): Promise<{ ok: boolean }> {
- return window.hermesDesktop.api<{ ok: boolean }>({
+ return hermesApi<{ ok: boolean }>({
- ...(profile ? { profile } : {}),
+ ...sessionScoped(profile),
++ ...(profile && typeof profile === 'object' && profile.connectionId?.trim() === 'local'
++ ? { connectionId: 'local' }
++ : {}),
path: `/api/sessions/${encodeURIComponent(id)}`,
method: 'DELETE'
})
@@@ -1788,21 -1778,9 +1804,24 @@@ export function renameProfile(name: str
})
}
-export function deleteProfile(name: string): Promise<{ ok: boolean; path: string }> {
+export function deleteProfile(name: string, scope?: ProfileScope): Promise<{ ok: boolean; path: string }> {
+ const normalized = name.trim()
+ const scopedProfile = scope && typeof scope === 'object' ? scope.profile?.trim() : undefined
+
+ if (!normalized) {
+ return Promise.reject(new Error('Profile name required'))
+ }
+
+ if (normalized.toLowerCase() === 'default' || scopedProfile?.toLowerCase() === 'default') {
+ return Promise.reject(new Error('The default profile cannot be deleted.'))
+ }
+
- return window.hermesDesktop.api<{ ok: boolean; path: string }>({
+ return hermesApi<{ ok: boolean; path: string }>({
- path: `/api/profiles/${encodeURIComponent(name)}`,
+ ...capabilityScoped(scope),
++ ...(scope && typeof scope === 'object' && scope.connectionId?.trim() === 'local'
++ ? { connectionId: 'local' }
++ : {}),
+ path: `/api/profiles/${encodeURIComponent(normalized)}`,
method: 'DELETE'
})
}
diff --cc apps/desktop/src/plugins/hermes-bots/plugin.js
index cab453ae274,cf7b36a5cd4..ebe1b30f4d3
--- a/apps/desktop/src/plugins/hermes-bots/plugin.js
+++ b/apps/desktop/src/plugins/hermes-bots/plugin.js
@@@ -188,6 -181,16 +188,65 @@@ const $lastJobs = atom([]
* (the bot you're actually chatting with) and roster clicks. */
const $selectedBot = atom('default')
-/** Owner profile of the chat the user is LOOKING AT. Newer desktops expose
- * `host.state.focusedSessionProfile` (the focused session row's stamped
- * owner, gateway profile for drafts); older builds fall back to the gateway
- * profile atom — the socket's home — which is the previous behavior. The
- * distinction matters because tab/tile focus moves WITHOUT swapping the
- * gateway socket: with only the socket atom, opening another bot's chat in
- * a tab left the roster highlight (and the Cronjobs tile) on whichever bot
- * the socket happened to be homed on. */
++/** Owner of the chat the user is LOOKING AT. Newer desktops expose a
++ * connection-qualified owner. Older builds synthesize the previous
++ * profile/gateway fallback and listen to both atoms when available. */
+ const $focusedBotProfile = host.state.focusedSessionProfile || host.state.profile
+
++function fallbackFocusedBotOwner(profile = $focusedBotProfile.get?.()) {
++ const focusedProfile = String(profile || 'default').trim() || 'default'
++ const activeProfile = String(host.state.profile?.get?.() || 'default').trim() || 'default'
++
++ // focusedSessionProfile without focusedSessionOwner is a legacy half-shape:
++ // it carries no source identity. Only reuse the active connection when the
++ // focused profile is also the active profile; otherwise fail closed rather
++ // than manufacturing a cross-source owner from unrelated atoms.
++ if (host.state.focusedSessionProfile && focusedProfile !== activeProfile) {
++ return null
++ }
++
++ const connectionId = String(
++ host.state.connectionId?.get?.() ||
++ (typeof host.activeConnectionId === 'function' ? host.activeConnectionId() : '') ||
++ ''
++ ).trim()
++
++ return {
++ authoritative: false,
++ connectionId,
++ profile: focusedProfile
++ }
++}
++
++const hasFocusedSessionOwnerSupport = Boolean(host.state.focusedSessionOwner)
++const $focusedBotOwner = host.state.focusedSessionOwner || {
++ get: () => fallbackFocusedBotOwner(),
++ listen: listener => {
++ const emit = profile => listener(fallbackFocusedBotOwner(profile))
++ const unbindProfile = $focusedBotProfile.listen(emit)
++ const unbindConnection = host.state.connectionId?.listen?.(() => emit($focusedBotProfile.get?.()))
++
++ return () => {
++ unbindProfile?.()
++ unbindConnection?.()
++ }
++ }
++}
++
++function focusedRosterOwner(owner) {
++ const name = String(owner?.profile || owner?.name || '').trim()
++
++ if (!owner || !name) {
++ return null
++ }
++
++ return {
++ authoritative: owner.authoritative !== false,
++ connectionId: String(owner.connectionId || '').trim(),
++ name
++ }
++}
++
/** 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)
@@@ -221,52 -310,9 +366,75 @@@ function handleSessionsGatewayTransitio
* { [botName]: { shape, color, title } } */
const $botMeta = atom({})
-async function saveBotMeta(name, patch) {
- const prevMeta = $botMeta.get()[name] || {}
- const next = { ...$botMeta.get(), [name]: { ...prevMeta, ...patch } }
+function commitBotMetaV2(storage, snapshot) {
+ const commit = botMetaV2Commit.then(async () => {
+ if (typeof storage?.remove !== 'function' || typeof storage?.set !== 'function') {
+ throw new Error('bot metadata v2 storage is unavailable')
+ }
+
++ const [previousSnapshot, previousMarker] = typeof storage.get === 'function'
++ ? await Promise.all([
++ storage.get(BOT_META_V2_KEY),
++ storage.get(BOT_META_MIGRATION_KEY)
++ ])
++ : [null, null]
++ const hasCommittedPrevious = previousMarker === true &&
++ previousSnapshot &&
++ typeof previousSnapshot === 'object' &&
++ !Array.isArray(previousSnapshot)
++
+ try {
+ await storage.remove(BOT_META_MIGRATION_KEY)
+ await storage.set(BOT_META_V2_KEY, snapshot)
+ await storage.set(BOT_META_MIGRATION_KEY, true)
+ } catch (error) {
- await Promise.allSettled(
- [BOT_META_MIGRATION_KEY, BOT_META_V2_KEY].map(key => storage.remove(key))
- )
++ if (hasCommittedPrevious) {
++ try {
++ await storage.set(BOT_META_V2_KEY, previousSnapshot)
++ await storage.set(BOT_META_MIGRATION_KEY, true)
++ } catch {
++ await Promise.allSettled([
++ storage.remove(BOT_META_MIGRATION_KEY),
++ storage.remove(BOT_META_V2_KEY)
++ ])
++ }
++ } else {
++ await Promise.allSettled(
++ [BOT_META_MIGRATION_KEY, BOT_META_V2_KEY].map(key => storage.remove(key))
++ )
++ }
+ throw error
+ }
+ })
+
+ botMetaV2Commit = commit.catch(() => undefined)
+
+ return commit
+}
+
+function botOwner(owner) {
+ if (typeof owner === 'string') {
+ const name = owner.trim()
+ const route = migratedLocalRoutes.get(name)
+
+ return {
+ bot: route ? { name, sourceScoped: true, route } : { name },
+ name,
+ key: route ? botRouteKey(route) : name,
+ route: route || null
+ }
+ }
+
+ const name = String(owner?.name || '').trim()
+ const route = botConnectionRoute(owner)
+
+ return { bot: owner, name, key: route ? botRouteKey(route) : name, route }
+}
+
+async function saveBotMeta(owner, patch) {
+ const { bot, key, name, route } = botOwner(owner)
+ const prevMeta = $botMeta.get()[key] || {}
+ const next = { ...$botMeta.get(), [key]: { ...prevMeta, ...patch } }
$botMeta.set(next)
// Local plugin storage: instant, and the fallback for older gateways.
@@@ -904,25 -777,13 +1072,27 @@@ async function duplicateBot(bot, roster
* renderer's socket reconnect respawns it mid-delete, resurrecting the
* directory (hermes-agent#52279). That is the "can't delete a bot" error. */
async function deleteBot(bot) {
+ const route = botConnectionRoute(bot)
+
+ if (isDefaultBot(bot) || String(route?.targetProfile || '').toLowerCase() === 'default') {
+ throw new Error('The default profile cannot be deleted.')
+ }
+
if (typeof host.deleteProfile === 'function') {
- await host.deleteProfile(bot.name)
+ if (route) {
+ await host.deleteProfile(route)
+ } else {
+ await host.deleteProfile(bot.name)
+ }
} else {
- // Older desktop without the SDK verb — best effort via the CLI.
+ // Older desktop without the SDK verb — source-scoped rows fail closed.
- const result = await (route ? requestForBot(bot, 'cli.exec', {
- argv: ['profile', 'delete', bot.name, '--yes']
- }) : host.request('cli.exec', {
++ if (route) {
++ throw new Error('Source-scoped profile deletion requires host.deleteProfile.')
++ }
++
+ const result = await host.request('cli.exec', {
argv: ['profile', 'delete', bot.name, '--yes']
- }))
+ })
if (result?.blocked || result?.code !== 0) {
throw new Error(result?.hint || result?.output || `Could not delete profile ${bot.name}.`)
@@@ -956,7 -813,7 +1126,12 @@@
queryClient.invalidateQueries({ queryKey: ROSTER_KEY })
-- if (host.state.profile.get?.() === bot.name && typeof host.newChat === 'function') {
++ const activeOwner = focusedRosterOwner($focusedBotOwner.get?.())
++ const deletedOwnerIsActive = route
++ ? activeOwner?.connectionId === route.connectionId && activeOwner?.name === route.profile
++ : activeOwner?.name === bot.name
++
++ if (deletedOwnerIsActive && typeof host.newChat === 'function') {
host.newChat('default')
}
}
@@@ -2844,17 -2705,11 +3023,19 @@@ let serverInjectsProtocol = fals
* (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) {
+function preferredSessionIds(allMeta, activeRoute = null) {
const pins = {}
- for (const [name, meta] of Object.entries(allMeta || {})) {
+ for (const [key, meta] of Object.entries(allMeta || {})) {
if (meta?.chat) {
- pins[name] = meta.chat
+ const name = key.includes('::')
- ? (activeRoute && key === botRouteKey(activeRoute) ? activeRoute.profile : null)
++ ? (activeRoute && key === botRouteKey(activeRoute)
++ ? backendTargetProfile(activeRoute, activeRoute.profile)
++ : null)
+ : key
+
+ if (name) {
+ pins[name] = meta.chat
+ }
}
}
return pins
@@@ -3119,7 -2933,7 +3300,11 @@@ function botHandle(name, bot)
}
function isActiveRosterBot(bot, active) {
-- const activeName = String(active?.name || 'default').trim() || 'default'
++ if (!active) {
++ return false
++ }
++
++ const activeName = String(active.name || 'default').trim() || 'default'
const activeId = String(active?.connectionId || '').trim()
const botId = String(bot?.connectionId || '').trim()
const botName = String(bot?.name || '').trim() || 'default'
@@@ -3336,7 -3125,7 +3521,7 @@@ async function deliverRemoteRosterMenti
const connectionId = String(bot?.connectionId || '').trim()
const profile = String(bot?.name || '').trim() || 'default'
-- if (!connectionId || connectionId === 'local') {
++ if (!connectionId) {
continue
}
@@@ -3440,62 -3206,13 +3625,91 @@@ function botConnectionRoute(bot)
return null
}
- const profile = String(bot?.name || '').trim() || 'default'
+ const candidate = bot.route || {
+ connectionId: bot.connectionId,
+ mode: bot.connectionKind === 'local' ? 'local' : 'remote',
+ profile: bot.name,
+ targetProfile: bot.targetProfile || bot.name
+ }
+ const connectionId = String(candidate?.connectionId || '').trim()
+ const profile = String(candidate?.profile || bot?.name || '').trim() || 'default'
+ const targetProfile = String(candidate?.targetProfile || profile).trim() || profile
+
+ if (!connectionId) {
+ throw new Error(`Bot ${profile} has no connection owner`)
+ }
+
+ return Object.freeze({
+ connectionId,
+ mode: candidate.mode === 'local' || connectionId === 'local' ? 'local' : 'remote',
+ profile,
+ targetProfile
+ })
+}
+
++function backendTargetProfile(route, fallbackProfile = 'default') {
++ if (!route) {
++ return fallbackProfile
++ }
++
++ return route.targetProfile || route.profile
++}
++
++function rewriteCliProfileOperands(argv, logical, target) {
++ const next = [...argv]
++
++ for (let index = 0; index < next.length; index += 1) {
++ if (next[index] === '--profile' && next[index + 1] === logical) {
++ next[index + 1] = target
++ index += 1
++ } else if (next[index] === `--profile=${logical}`) {
++ next[index] = `--profile=${target}`
++ }
++ }
++
++ const profileCommand = next.indexOf('profile')
++ const operand = profileCommand >= 0 ? profileCommand + 2 : -1
++ if (operand < next.length && next[operand] === logical) {
++ next[operand] = target
++ }
++
++ return next
++}
++
+function scopedBotParams(route, method, params) {
+ const logical = route.profile
- const target = route.targetProfile || logical
++ const target = backendTargetProfile(route, logical)
+ let next = params
+
+ if (Object.prototype.hasOwnProperty.call(params, 'profile')) {
+ next = { ...next, profile: target }
+ }
+
+ if (method.startsWith('profiles.') && method !== 'profiles.create' && params.name === logical) {
+ next = { ...next, name: target }
+ }
+
+ if (params.clone_from === logical) {
+ next = { ...next, clone_from: target }
+ }
+
+ if (method === 'cli.exec' && Array.isArray(params.argv)) {
- next = { ...next, argv: params.argv.map(arg => arg === logical ? target : arg) }
++ next = { ...next, argv: rewriteCliProfileOperands(params.argv, logical, target) }
+ }
+
+ return next
+}
+
+function botBackendProfileScope(route, fallbackProfile = 'default') {
+ if (!route) {
+ return fallbackProfile
+ }
- return { connectionId: route.connectionId, profile: route.targetProfile || route.profile }
- return { connectionId: id, mode: 'remote', profile, targetProfile: profile }
++ return { connectionId: route.connectionId, profile: backendTargetProfile(route, fallbackProfile) }
}
-/** Gateway RPC on the bot's OWN source: requestProfile for remote rows,
- * the active gateway for local ones. Never activates/foregrounds. */
+/** Gateway RPC on the bot's OWN source. Source-scoped rows always use the
+ * explicit descriptor, including a registered local source. */
async function requestForBot(bot, method, params = {}) {
const route = botConnectionRoute(bot)
@@@ -3613,7 -3317,7 +3828,12 @@@ function createCanonicalChat(owner)
if (sid && typeof host.openSession === 'function') {
try {
- await host.openSession(sid, { ...(route ? { route } : {}), profile: name, intent: 'main' })
- await host.openSession(sid, { profile: name, intent: 'main', keepAllProfilesScope: false })
++ await host.openSession(sid, {
++ ...(route ? { route } : {}),
++ profile: name,
++ intent: 'main',
++ keepAllProfilesScope: false
++ })
opened = true
} catch {
// The stored row may not exist until the kickoff persists it. Retry
@@@ -3625,10 -3329,10 +3845,15 @@@
await new Promise(resolve => window.setTimeout(resolve, 400))
try {
- await host.request('prompt.submit', { session_id: runtime, text: 'Hey, tell me about yourself!' })
+ await requestForBot(bot, 'prompt.submit', { session_id: runtime, text: 'Hey, tell me about yourself!' })
if (!opened && sid && typeof host.openSession === 'function') {
- await host.openSession(sid, { ...(route ? { route } : {}), profile: name, intent: 'main' })
- await host.openSession(sid, { profile: name, intent: 'main', keepAllProfilesScope: false })
++ await host.openSession(sid, {
++ ...(route ? { route } : {}),
++ profile: name,
++ intent: 'main',
++ keepAllProfilesScope: false
++ })
}
} catch {
// The chat already exists. Keep the pin so the next click
@@@ -3657,9 -3361,7 +3882,10 @@@
* 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) {
+async function openBotCanonicalChat(owner, pinned, history) {
- const { bot, name } = botOwner(owner)
++ const { bot, name, route } = botOwner(owner)
++ const backendProfile = backendTargetProfile(route, name)
+
if (!pinned) {
// Grandfather: adopt the conversation the row already previews.
const adoptId = history?.id
@@@ -3677,11 -3379,11 +3903,11 @@@
let preferred
let lookupFailed = false
try {
- const res = await host.request('profiles.list', {
+ const res = await requestForBot(bot, 'profiles.list', {
include_sessions: true,
-- preferred_session_ids: { [name]: pinned }
++ preferred_session_ids: { [backendProfile]: pinned }
})
-- const row = (res?.profiles ?? []).find(p => p.name === name)
++ const row = (res?.profiles ?? []).find(p => p.name === backendProfile)
preferred = row?.preferred_session
if (preferred === undefined) {
lookupFailed = true
@@@ -3728,11 -3430,29 +3954,13 @@@ async function prepareBotSource(bot, pi
return pinnedChat
}
- if (typeof host.ensureAgent !== 'function') {
- throw new Error('Update Hermes Desktop to chat with agents on other connections.')
- }
-
- await host.ensureAgent(bot.connectionId, bot.name)
-
- if (!bot.remoteSource) {
- return pinnedChat
- }
-
- const liveId = String(typeof host.activeConnectionId === 'function' ? host.activeConnectionId() || '' : '').trim()
- const targetId = String(bot.connectionId || '').trim()
-
- if (targetId && targetId !== 'local' && liveId !== targetId) {
- throw new Error(`Still on ${liveId || 'this device'}, not ${bot.connectionLabel || targetId}`)
- }
-
- // Thin rows deliberately omit metadata from the active source. Once their
- // owner is active, recover that source's canonical-chat pointer so
- // same-named agents never reuse or overwrite each other's pin.
+ // Thin rows deliberately omit metadata. Read it on the captured owner
+ // route; activation is a UI concern and cannot authorize this RPC.
try {
- const refreshed = await host.request('profiles.list', {})
- const owner = refreshed?.profiles?.find(profile => profile.name === bot.name)
++ const route = botConnectionRoute(bot)
++ const backendProfile = backendTargetProfile(route, bot.name)
+ const refreshed = await requestForBot(bot, 'profiles.list', {})
- const owner = refreshed?.profiles?.find(profile => profile.name === bot.name)
++ const owner = refreshed?.profiles?.find(profile => profile.name === backendProfile)
return owner?.ui_meta?.['hermes-bots']?.chat || null
} catch {
@@@ -3741,24 -3461,6 +3969,26 @@@
}
}
+async function ensureBotMetadata(bot) {
+ if (!bot?.sourceScoped) {
+ return botRosterMeta(bot, $botMeta.get()) || {}
+ }
+
++ const route = botConnectionRoute(bot)
++ const backendProfile = backendTargetProfile(route, bot.name)
+ const result = await requestForBot(bot, 'profiles.list', {})
- const row = (result?.profiles || []).find(profile => profile?.name === bot.name)
++ 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({ ...$botMeta.get(), [key]: { ...($botMeta.get()[key] || {}), ...server } })
+ persistBotMetaSnapshot($botMeta.get(), true)
+ }
+
+ return botRosterMeta(bot, $botMeta.get()) || {}
+}
+
function displayName(bot, meta) {
// Only THIN rows from another source trade the friendly name for their
// connection label — the active gateway's own default must keep reading
@@@ -5044,11 -4780,19 +5313,21 @@@ function activeBots(roster, activeProfi
function BotRow({ bot, onDelete, onEdit, onGroup }) {
const activeProfile = useValue(host.state.profile)
- const focusedProfile = useValue($focusedBotProfile)
++ const focusedOwner = focusedRosterOwner(useValue($focusedBotOwner))
+ const activeGroup = useValue($groupChatWorkspace)
const meta = botRosterMeta(bot, useValue($botMeta))
const groups = botGroups(meta)
const last = bot.last_session
+ // Highlight follows the chat on screen (focused session's owner), not the
+ // gateway socket's home — a focused tab doesn't swap the socket, and on the
+ // old keying the wrong bot stayed highlighted while you read another's chat.
+ // A selected group chat suppresses every bot-row highlight: the group row
+ // owns the selection then (#88979).
- const isActive = !activeGroup && !bot.remoteSource && bot.name === focusedProfile
+ const activeConnectionId = String(host.state.connectionId?.get?.() || 'local').trim()
- const isActive = isActiveRosterBot(bot, { name: activeProfile, connectionId: activeConnectionId })
++ const isActive = !activeGroup && isActiveRosterBot(bot, focusedOwner)
+ // Turn-busy is a SOCKET fact: only the gateway-home profile can be mid-turn.
- const isGatewayHome = !bot.remoteSource && bot.name === activeProfile
++ const isGatewayHome = !bot.remoteSource && bot.name === activeProfile &&
++ isActiveRosterBot(bot, { name: activeProfile, connectionId: activeConnectionId })
const { shape, color, image } = botAppearance(bot.name, meta)
// Keep user photos/pets. Drop the 160px SVG backfill so the math face can move.
const photo = Boolean(image && !isBackfilledFacePng(image))
@@@ -5103,7 -4847,18 +5382,8 @@@
const open = async () => {
const generation = ++botOpenGeneration
haptic('tap')
+ $groupChatWorkspace.set(null)
- $selectedBot.set(bot.name)
-
- if (bot.remoteSource) {
- const handle = botHandle(bot.name, bot)
- host.notify?.({
- kind: 'info',
- title: displayName(bot),
- message: `Stay in this chat and @${handle} to message them. Gateway stays on this device.`
- })
- return
- }
+ $selectedBot.set(botSelectionKey(bot))
let pinnedChat = meta?.chat
@@@ -7309,14 -7031,10 +7592,15 @@@ async function loadRoutines(owner)
}
}
-function useRoutines(profile) {
+function useRoutines(owner) {
+ const bot = typeof owner === 'string' ? { name: owner } : owner
+ const route = botConnectionRoute(bot)
+ const key = route ? botRosterKey(bot) : bot?.name || ''
+
return useQuery({
- queryKey: [...ROUTINES_KEY, profile || ''],
- queryFn: () => loadRoutines(profile),
+ queryKey: [...ROUTINES_KEY, key],
+ queryFn: () => loadRoutines(bot),
++ enabled: Boolean(bot?.name),
refetchInterval: 20000,
staleTime: 8000
})
@@@ -7887,34 -7599,45 +8171,81 @@@ function CreateRoutineDialog({ bot, ope
})
}
+ /** Keeps $selectedBot in sync with the focused chat's owner profile.
+ * nanostores' `.listen()` never replays the current value the way
+ * `.subscribe()` does, so a disable → profile switch → re-enable sequence
+ * would otherwise leave $selectedBot pointed at whichever bot was active
+ * before the plugin was disabled — reseeding here on every register() call
- * closes that gap. Returns the unbind function for ctx.onDispose. */
-function bindProfileSync(profileStore) {
- const current = profileStore.get?.()
- if (current && typeof current === 'string') {
- $selectedBot.set(current)
- }
- return profileStore.listen(profile => {
- if (profile && typeof profile === 'string') {
- $selectedBot.set(profile)
++ * closes that gap. Connection qualification keeps same-named owners isolated.
++ * Returns the unbind function for ctx.onDispose. */
++function bindProfileSync(ownerStore) {
++ const sync = owner => {
++ const profile = typeof owner === 'string' ? owner : owner?.profile
++
++ if (!profile || typeof profile !== 'string') {
++ return
+ }
- })
++
++ const connectionId = String(
++ typeof owner === 'object' ? owner?.connectionId || '' : ''
++ ).trim()
++ $selectedBot.set(connectionId ? `${connectionId}::${profile}` : profile)
++ }
++
++ sync(ownerStore.get?.())
++
++ return ownerStore.listen(sync)
++}
++
++function resolveRoutineOwner(roster, focusedOwner, selected) {
++ if (hasFocusedSessionOwnerSupport && !focusedOwner) {
++ return null
++ }
++
++ const focusedBot = focusedOwner
++ ? roster.find(bot => isActiveRosterBot(bot, focusedOwner))
++ : null
++
++ if (focusedOwner?.authoritative) {
++ return focusedBot || null
++ }
++
++ const selectedBot = roster.find(bot => botSelectionKey(bot) === selected)
++ return focusedBot || selectedBot || (focusedOwner ? { name: focusedOwner.name } : null)
+ }
+
function RoutinesPane() {
const selected = useValue($selectedBot)
- const gatewayProfile = useValue(host.state.profile)
- // The tile maps to the bot you're chatting with: the live gateway profile
- // is the truth once a chat opens; $selectedBot covers the gap between a
- // roster click and the profile swap landing.
- const roster = $lastRoster.get()
- const selectedBot = roster.find(bot => botSelectionKey(bot) === selected)
- const activeBot = roster.find(bot =>
- isActiveRosterBot(bot, {
- name: gatewayProfile,
- connectionId: String(host.state.connectionId?.get?.() || host.activeConnectionId?.() || 'local')
- })
- )
- const owner = selectedBot || activeBot || { name: (gatewayProfile || selected || 'default').trim() || 'default' }
- const bot = owner.name
- const meta = botRosterMeta(owner, useValue($botMeta))
- const focusedProfile = useValue($focusedBotProfile)
- // The tile maps to the bot you're chatting with: the focused chat's owner
- // profile is the truth once a chat opens (on older desktops without the
- // focused-owner atom this is the live gateway profile, the previous
- // behavior); $selectedBot covers the gap between a roster click and the
- // focus/profile swap landing.
- const bot = (focusedProfile || selected || 'default').trim() || 'default'
- const meta = useValue($botMeta)[bot]
++ const focusedOwner = focusedRosterOwner(useValue($focusedBotOwner))
++ // A complete focused owner is authoritative. If its exact roster row is
++ // absent, fail closed instead of routing cron reads/mutations through a
++ // stale selection or an unscoped profile name.
++ const owner = resolveRoutineOwner($lastRoster.get(), focusedOwner, selected)
++ const bot = String(owner?.name || focusedOwner?.name || 'default').trim() || 'default'
++ const allMeta = useValue($botMeta)
++ const meta = owner ? botRosterMeta(owner, allMeta) : null
const { shape, color, image } = botAppearance(bot, meta)
- const { data, error, isLoading, refetch } = useRoutines(bot)
+ const { data, error, isLoading, refetch } = useRoutines(owner)
const [createOpen, setCreateOpen] = useState(false)
const [createOwner, setCreateOwner] = useState(null)
-- const createTarget = routineCreateTarget(createOwner, bot)
++ const createTarget = owner ? routineCreateTarget(createOwner, bot) : null
const openCreate = () => {
- setCreateOwner(bot)
++ if (!owner) {
++ return
++ }
++
+ setCreateOwner(owner)
setCreateOpen(true)
}
++ if (!owner) {
++ return jsx('div', {
++ className: 'flex h-full items-center justify-center px-4 text-center text-xs text-(--ui-text-tertiary)',
++ children: 'Cronjobs are unavailable until this agent appears in the roster.'
++ })
++ }
++
const view = selectRoutineJobs(data, error, $lastJobs.get(), bot)
if (view.live) {
$lastJobs.set(view.live)
@@@ -8100,17 -7811,12 +8431,18 @@@ async function openProfileSession(bot,
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: false })
+ await host.openSession(id, {
+ ...(route ? { route } : {}),
+ profile,
+ awaitHydration: true,
- expectHistory
++ expectHistory,
++ keepAllProfilesScope: false
+ })
if (gatewayGeneration !== $sessionsGatewayGeneration.get()) return
- $botSelectedSessions.set({ ...$botSelectedSessions.get(), [profile]: id })
+ $botSelectedSessions.set({ ...$botSelectedSessions.get(), [selectionKey]: id })
}
-function ProfileSessionRow({ session, botName, active, gatewayGeneration }) {
+function ProfileSessionRow({ session, bot, active, gatewayGeneration }) {
return jsxs('button', {
type: 'button',
'aria-current': active ? 'page' : undefined,
@@@ -10264,16 -10091,7 +10690,7 @@@ export default
// Capture the unbinds: without them a disable → re-enable cycle stacks a
// duplicate listener per cycle (same survives-disable class as the face
// clock before its onDispose hook — these kept firing until app restart).
- const unbindProfileListener = host.state.profile.listen(profile => {
- if (profile && typeof profile === 'string') {
- const connectionId = String(
- host.state.connectionId?.get?.() ||
- (typeof host.activeConnectionId === 'function' ? host.activeConnectionId() : '') ||
- ''
- ).trim()
- $selectedBot.set(connectionId ? `${connectionId}::${profile}` : profile)
- }
- })
- const unbindProfileListener = bindProfileSync($focusedBotProfile)
++ const unbindProfileListener = bindProfileSync($focusedBotOwner)
const unbindGatewayListener = host.state.gateway.listen(handleSessionsGatewayTransition)
if (typeof ctx.onDispose === 'function') {
diff --cc apps/desktop/src/plugins/hermes-bots/tests/bot-delete.test.mjs
index c79ae659531,872ad062788..63c58f0d14a
--- a/apps/desktop/src/plugins/hermes-bots/tests/bot-delete.test.mjs
+++ b/apps/desktop/src/plugins/hermes-bots/tests/bot-delete.test.mjs
@@@ -5,12 -5,11 +5,13 @@@ import vm from 'node:vm
const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
--function load({ sdkDeleteProfile = false } = {}) {
++function load({ activeConnectionId = 'local', activeProfile = 'default', sdkDeleteProfile = false } = {}) {
const requests = []
const sdkDeletes = []
const invalidations = []
++ const newChats = []
const stored = []
+ const storageOps = []
const values = new Map()
const atom = initial => {
const slot = { get: () => values.get(slot), set: value => values.set(slot, value) }
@@@ -24,13 -23,13 +25,15 @@@
document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } },
host: {
state: {
-- profile: { listen: () => undefined },
++ profile: { get: () => activeProfile, listen: () => undefined },
++ connectionId: { get: () => activeConnectionId, listen: () => undefined },
gateway: { listen: () => undefined }
},
++ newChat: profile => newChats.push(profile),
...(sdkDeleteProfile
? {
- deleteProfile: async name => {
- sdkDeletes.push(name)
+ deleteProfile: async profile => {
+ sdkDeletes.push(profile)
}
}
: {}),
@@@ -61,7 -56,7 +64,7 @@@
},
register: () => undefined
})
- return { context, requests, sdkDeletes, invalidations, stored, storageOps }
- return { context, requests, sdkDeletes, invalidations, stored }
++ return { context, requests, sdkDeletes, invalidations, newChats, stored, storageOps }
}
test('unit: deleting a bot prefers the SDK deleteProfile (teardown-routed REST path)', async () => {
@@@ -73,75 -68,6 +76,116 @@@
assert.equal(requests.filter(r => r.method === 'cli.exec').length, 0)
})
+test('unit: source-scoped deletion preserves the route targetProfile', async () => {
+ const { context, sdkDeletes } = load({ sdkDeleteProfile: true })
+ const route = {
+ connectionId: 'source-a',
+ mode: 'remote',
+ profile: 'worker',
+ targetProfile: 'backend-worker'
+ }
+
+ await context.__delete.deleteBot({ name: 'worker', sourceScoped: true, route })
+
+ assert.deepEqual(JSON.parse(JSON.stringify(sdkDeletes)), [route])
+})
+
++test('unit: deleting same-name bot on another connection keeps the active chat', async () => {
++ const { context, newChats } = load({
++ activeConnectionId: 'source-b',
++ activeProfile: 'worker',
++ sdkDeleteProfile: true
++ })
++
++ await context.__delete.deleteBot({
++ name: 'worker',
++ sourceScoped: true,
++ route: {
++ connectionId: 'source-a',
++ mode: 'remote',
++ profile: 'worker',
++ targetProfile: 'worker'
++ }
++ })
++
++ assert.deepEqual(newChats, [])
++})
++
+test('unit: source-scoped deletion commits bot-meta-v2 atomically', async () => {
+ const { context, storageOps } = load({ sdkDeleteProfile: true })
+ const route = {
+ connectionId: 'source-a',
+ mode: 'remote',
+ profile: 'worker',
+ targetProfile: 'backend-worker'
+ }
+ const key = 'source-a::worker'
+ context.__delete.$botMeta.set({
+ [key]: { title: 'Worker' },
+ 'source-a::writer': { title: 'Writer' }
+ })
+
+ await context.__delete.deleteBot({
+ name: 'worker',
+ sourceScoped: true,
+ route
+ })
+
+ assert.deepEqual(
+ JSON.parse(JSON.stringify(storageOps.slice(-3))),
+ [
+ { op: 'remove', key: 'bot-meta-v2-migrated' },
+ {
+ op: 'set',
+ key: 'bot-meta-v2',
+ value: { 'source-a::writer': { title: 'Writer' } }
+ },
+ { op: 'set', key: 'bot-meta-v2-migrated', value: true }
+ ]
+ )
+})
+
+test('unit: an alias targeting backend default is rejected before deletion', async () => {
+ const { context, sdkDeletes, requests } = load({ sdkDeleteProfile: true })
+
+ await assert.rejects(
+ context.__delete.deleteBot({
+ name: 'worker',
+ sourceScoped: true,
+ route: {
+ connectionId: 'source-a',
+ mode: 'remote',
+ profile: 'worker',
+ targetProfile: 'default'
+ }
+ }),
+ /default profile cannot be deleted/i
+ )
+
+ assert.deepEqual(sdkDeletes, [])
+ assert.equal(requests.some(request => request.method === 'cli.exec'), false)
++})
++
++test('unit: source-scoped deletion without host.deleteProfile fails closed without CLI execution', async () => {
++ const { context, requests } = load()
++
++ await assert.rejects(
++ context.__delete.deleteBot({
++ name: 'worker',
++ sourceScoped: true,
++ route: {
++ connectionId: 'source-a',
++ mode: 'remote',
++ profile: 'worker',
++ targetProfile: 'worker'
++ }
++ }),
++ /source-scoped profile deletion requires host\.deleteProfile/i
++ )
++
++ assert.equal(requests.some(request => request.method === 'cli.exec'), false)
+})
+
test('unit: older desktop without host.deleteProfile falls back to the non-interactive profile CLI command', async () => {
const { context, requests } = load()
diff --cc apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-empty-recovery.test.mjs
index b3a8439a3b5,76a93ffa410..1378aaf39ce
--- 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
@@@ -19,8 -19,6 +19,9 @@@ function loadCanonicalRecovery({ openSe
}
},
saveBotMeta: (name, patch) => saved.push({ name, patch }),
++ backendTargetProfile: (route, fallback) => route?.targetProfile || route?.profile || fallback,
+ botOwner: name => ({ bot: { name }, key: name, name, route: null }),
+ requestForBot: (_bot, method, params) => context.host.request(method, params),
$hideBotChats: { get: () => false },
window: { setTimeout: callback => callback() }
}
diff --cc apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-identity.test.mjs
index de8c7b4ed41,7fd8e34bb64..0b1b63d9ee8
--- 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
@@@ -20,8 -20,6 +20,9 @@@ function loadOpenPath({ openSession, re
}
},
saveBotMeta: (name, patch) => saved.push({ name, patch: JSON.parse(JSON.stringify(patch)) }),
++ backendTargetProfile: (route, fallback) => route?.targetProfile || route?.profile || fallback,
+ botOwner: name => ({ bot: { name }, key: name, name, route: null }),
+ requestForBot: (_bot, method, params) => context.host.request(method, params),
$hideBotChats: { get: () => false },
window: { setTimeout: callback => callback() }
}
@@@ -279,6 -278,6 +281,23 @@@ function loadHelpers()
return context
}
++test('preferredSessionIds: source-scoped aliases key pins by backend targetProfile', () => {
++ const collect = (meta, route) => JSON.parse(
++ JSON.stringify(loadHelpers().__preferredSessionIds(meta, route))
++ )
++ const route = {
++ connectionId: 'remote-a',
++ mode: 'remote',
++ profile: 'worker',
++ targetProfile: 'backend-worker'
++ }
++
++ assert.deepEqual(
++ collect({ 'remote-a::worker': { chat: 'pin-worker' } }, route),
++ { 'backend-worker': 'pin-worker' }
++ )
++})
++
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)))
diff --cc apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-pin.test.mjs
index 388862eeca1,b2796ba933b..d3e573fed2a
--- 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
@@@ -27,8 -27,6 +27,9 @@@ function loadOpenPath({ openSession, re
}
},
saveBotMeta: (name, patch) => saved.push({ name, patch: JSON.parse(JSON.stringify(patch)) }),
++ backendTargetProfile: (route, fallback) => route?.targetProfile || route?.profile || fallback,
+ botOwner: name => ({ bot: { name }, key: name, name, route: null }),
+ requestForBot: (_bot, method, params) => context.host.request(method, params),
$hideBotChats: { get: () => false },
window: { setTimeout: callback => callback() }
}
diff --cc apps/desktop/src/plugins/hermes-bots/tests/cross-connection-bots.test.mjs
index af97687327c,876e0a19661..8cfff134b16
--- a/apps/desktop/src/plugins/hermes-bots/tests/cross-connection-bots.test.mjs
+++ b/apps/desktop/src/plugins/hermes-bots/tests/cross-connection-bots.test.mjs
@@@ -96,59 -95,8 +96,61 @@@ test('requestForBot: source-scoped memb
assert.equal(calls[0][0], 'active')
assert.equal(calls[0][1], 'session.create')
assert.equal(calls[1][0], 'routed')
- assert.equal(calls[1][1], 'mac-mini')
- assert.equal(calls[1][2], 'prompt.submit')
+ assert.equal(calls[1][1], 'local')
+ assert.equal(calls[2][0], 'routed')
+ assert.equal(calls[2][1], 'mac-mini')
+ assert.equal(calls[2][2], 'prompt.submit')
+})
+
+test('requestForBot: non-identity aliases translate every backend profile RPC shape', async () => {
+ const ctx = runtime()
+ const calls = []
+ ctx.host.requestProfile = async (route, method, params) => {
+ calls.push({ route, method, params })
+ return {}
+ }
+ const bot = {
+ name: 'worker',
+ sourceScoped: true,
+ route: {
+ connectionId: 'remote-a',
+ mode: 'remote',
+ profile: 'worker',
+ targetProfile: 'backend-worker'
+ }
+ }
+
+ await ctx.__x.requestForBot(bot, 'profiles.describe', { name: 'worker' })
+ await ctx.__x.requestForBot(bot, 'profiles.configure', { name: 'worker', soul: 'x' })
+ await ctx.__x.requestForBot(bot, 'profiles.create', { name: 'worker-2', clone_from: 'worker' })
+ await ctx.__x.requestForBot(bot, 'session.create', { profile: 'worker', title: 'Bot Chat' })
+ await ctx.__x.requestForBot(bot, 'cli.exec', { argv: ['--profile', 'worker', 'config', 'unset', 'model'] })
- await ctx.__x.requestForBot(bot, 'cli.exec', { argv: ['profile', 'describe', 'worker', '--text', 'x'] })
++ await ctx.__x.requestForBot(bot, 'cli.exec', {
++ argv: ['profile', 'describe', 'worker', '--text', 'worker']
++ })
+
+ assert.deepEqual(JSON.parse(JSON.stringify(calls.map(call => call.params))), [
+ { name: 'backend-worker' },
+ { name: 'backend-worker', soul: 'x' },
+ { name: 'worker-2', clone_from: 'backend-worker' },
+ { profile: 'backend-worker', title: 'Bot Chat' },
+ { argv: ['--profile', 'backend-worker', 'config', 'unset', 'model'] },
- { argv: ['profile', 'describe', 'backend-worker', '--text', 'x'] }
++ { argv: ['profile', 'describe', 'backend-worker', '--text', 'worker'] }
+ ])
+ assert.equal(calls.every(call => call.route.profile === 'worker'), true)
+})
+
+test('advanced capability scope keeps Desktop identity separate from backend targetProfile', () => {
+ const scope = runtime().__x.botBackendProfileScope({
+ connectionId: 'remote-a',
+ profile: 'worker',
+ targetProfile: 'backend-worker'
+ })
+
+ assert.deepEqual(JSON.parse(JSON.stringify(scope)), {
+ connectionId: 'remote-a',
+ profile: 'backend-worker'
+ })
})
test('groupMemberKey: local members keep bare names (persisted-room compat), remote members are source-qualified', () => {
diff --cc apps/desktop/src/plugins/hermes-bots/tests/focused-bot-highlight.test.mjs
index 00000000000,bf0b6783529..7b31017a8c0
mode 000000,100644..100644
--- a/apps/desktop/src/plugins/hermes-bots/tests/focused-bot-highlight.test.mjs
+++ b/apps/desktop/src/plugins/hermes-bots/tests/focused-bot-highlight.test.mjs
@@@ -1,0 -1,53 +1,86 @@@
+ 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')
+
+ // The roster highlight and the Routines (Cronjobs) tile must follow the chat
+ // the user is LOOKING AT — the focused session's owner profile — not the
+ // gateway socket's home. Tab/tile focus moves without swapping the socket, so
+ // keying these off `host.state.profile` alone highlighted (and scoped the
+ // Cronjobs panel to) the wrong bot whenever a focused tab showed another
+ // profile's chat (community report: Newsanalyst chat open, Hermes highlighted).
+
-test('$focusedBotProfile prefers the focused-session owner atom and falls back to the gateway profile', () => {
++test('$focusedBotOwner prefers the connection-qualified focused owner atom', () => {
+ assert.match(
+ source,
- /const \$focusedBotProfile = host\.state\.focusedSessionProfile \|\| host\.state\.profile/,
- 'feature-detected: newer desktops expose focusedSessionProfile; older builds keep the previous gateway-profile behavior'
++ /const \$focusedBotOwner = host\.state\.focusedSessionOwner \|\|/,
++ 'newer desktops expose a complete focused owner; older builds retain a feature-detected fallback'
+ )
+ })
+
++test('legacy focused-profile-only SDK never pairs foreign focus with ambient connection', () => {
++ const ownerStart = source.indexOf('const $focusedBotProfile =')
++ const ownerEnd = source.indexOf('/** Optional secondary navigation', ownerStart)
++ const activeStart = source.indexOf('function isActiveRosterBot(')
++ const activeEnd = source.indexOf('function botSelectionKey(', activeStart)
++ const store = value => ({ get: () => value, listen: () => undefined })
++ const context = {
++ host: {
++ activeConnectionId: () => 'source-a',
++ state: {
++ connectionId: store('source-a'),
++ focusedSessionProfile: store('worker'),
++ profile: store('default')
++ }
++ }
++ }
++
++ vm.runInNewContext(
++ `${source.slice(ownerStart, ownerEnd)}\n${source.slice(activeStart, activeEnd)}\n` +
++ 'globalThis.result = { owner: focusedRosterOwner($focusedBotOwner.get()), isActiveRosterBot };',
++ context
++ )
++
++ assert.equal(context.result.owner, null)
++ assert.equal(context.result.isActiveRosterBot({
++ connectionId: 'source-a',
++ name: 'worker',
++ remoteSource: true
++ }, context.result.owner), false)
++ assert.equal(context.result.isActiveRosterBot({ name: 'default' }, context.result.owner), false)
++})
++
+ test('BotRow keys the highlight off the focused profile, not the socket home', () => {
+ const rowStart = source.indexOf('function BotRow(')
+ assert.ok(rowStart >= 0)
+ const row = source.slice(rowStart, rowStart + 2000)
+
- assert.match(row, /const focusedProfile = useValue\(\$focusedBotProfile\)/)
- assert.match(row, /const isActive = !activeGroup && !bot\.remoteSource && bot\.name === focusedProfile/)
++ assert.match(row, /const focusedOwner = focusedRosterOwner\(useValue\(\$focusedBotOwner\)\)/)
++ assert.match(row, /const isActive = !activeGroup && isActiveRosterBot\(bot, focusedOwner\)/)
+ })
+
+ test('BotRow keeps turn-busy (work mood) a socket fact', () => {
+ const rowStart = source.indexOf('function BotRow(')
+ const row = source.slice(rowStart, rowStart + 3000)
+
+ // Only the gateway-home profile can actually be mid-turn: the mood must NOT
+ // switch to the focus-keyed identity.
+ assert.match(row, /const isGatewayHome = !bot\.remoteSource && bot\.name === activeProfile/)
+ assert.match(row, /const botMood = \(isGatewayHome && gatewayState === 'busy'\) \|\| activeNow \? 'work' : 'idle'/)
+ })
+
+ test('RoutinesPane scopes the Cronjobs tile to the focused chat owner', () => {
+ const paneStart = source.indexOf('function RoutinesPane(')
+ assert.ok(paneStart >= 0)
+ const pane = source.slice(paneStart, paneStart + 1200)
+
- assert.match(pane, /const focusedProfile = useValue\(\$focusedBotProfile\)/)
- assert.match(pane, /const bot = \(focusedProfile \|\| selected \|\| 'default'\)\.trim\(\) \|\| 'default'/)
++ assert.match(pane, /const focusedOwner = focusedRosterOwner\(useValue\(\$focusedBotOwner\)\)/)
++ assert.match(pane, /const owner = resolveRoutineOwner\(\$lastRoster\.get\(\), focusedOwner, selected\)/)
+ assert.ok(!/useValue\(host\.state\.profile\)/.test(pane), 'the tile must not read the socket-home atom directly')
+ })
+
+ test('the $selectedBot tracker binds the focused profile ladder (reseed + unbind captured)', () => {
- assert.match(source, /const unbindProfileListener = bindProfileSync\(\$focusedBotProfile\)/)
++ assert.match(source, /const unbindProfileListener = bindProfileSync\(\$focusedBotOwner\)/)
+ })
diff --cc apps/desktop/src/plugins/hermes-bots/tests/group-chat.test.mjs
index d61e04560a2,1bacfca9ba5..f1d8cc844b1
--- a/apps/desktop/src/plugins/hermes-bots/tests/group-chat.test.mjs
+++ b/apps/desktop/src/plugins/hermes-bots/tests/group-chat.test.mjs
@@@ -344,6 -355,39 +355,39 @@@ test('source contract: workspace + main
assert.match(pluginSource, /\[Group chat: "\$\{groupName\}"\]/)
})
+ test('group selection follows main-window open and close', () => {
+ const gc = load(() => '(pass)')
+ let onClose
+
+ gc.host.openWorkspace = (_id, options) => {
+ onClose = options.onClose
+ return () => onClose()
+ }
+
+ gc.openGroupChat('Core')
+ assert.equal(gc.$groupChatWorkspace.get(), 'Core')
+
+ onClose()
+ assert.equal(gc.$groupChatWorkspace.get(), null)
+ })
+
+ test('closing an older selected group does not clear the newer selection', () => {
+ const gc = load(() => '(pass)')
+
+ gc.host.openWorkspace = () => () => undefined
+ gc.openGroupChat('Core')
+ gc.openGroupChat('Ops')
+ gc.closeGroupChatMainTab('Core')
+
+ assert.equal(gc.$groupChatWorkspace.get(), 'Ops')
+ })
+
+ test('source contract: active group styling suppresses bot styling', () => {
- assert.match(pluginSource, /const isActive = !activeGroup && !bot\.remoteSource && bot\.name === focusedProfile/)
++ assert.match(pluginSource, /const isActive = !activeGroup && isActiveRosterBot\(bot, focusedOwner\)/)
+ assert.match(pluginSource, /active && 'bg-\(--ui-row-active-background\)'/)
+ assert.match(pluginSource, /active: groupChatName === row\.name/)
+ })
+
test('disband: removes only this membership, room log, workspace, and needs-you state', async () => {
const gc = load(() => '(pass)')
diff --cc apps/desktop/src/plugins/hermes-bots/tests/profile-prewarm.test.mjs
index e2d6c201978,57ade31cd80..518a0315523
--- a/apps/desktop/src/plugins/hermes-bots/tests/profile-prewarm.test.mjs
+++ b/apps/desktop/src/plugins/hermes-bots/tests/profile-prewarm.test.mjs
@@@ -22,6 -22,6 +22,7 @@@ function renderBotRow(input = 'alpha')
const botRowSource = sourceBetween('function BotRow(', '// ── model picker')
const ensured = []
const opened = []
++ const saved = []
const warmed = []
let liveConnectionId = 'local'
const atom = value => ({
@@@ -41,13 -41,15 +42,26 @@@
ROSTER_KEY: ['hermes-bots', 'roster'],
$botMeta: atom({}),
$botUnread: atom({}),
++ $focusedBotOwner: atom({ connectionId: 'local', profile: 'default' }),
+ $focusedBotProfile: atom('default'),
+ $groupChatWorkspace: atom(null),
$lastRoster: atom([]),
$selectedBot: atom('default'),
botAppearance: () => ({ shape: 'round', color: '#000', image: null }),
++ botConnectionRoute: value => value.route || null,
++ backendTargetProfile: (route, fallback) => route?.targetProfile || route?.profile || fallback,
++ botMetaKey: value => value.sourceScoped
++ ? `${value.route?.connectionId || value.connectionId}::${value.name}`
++ : value.name,
botGroups: () => [],
botHandle: value => value,
botOpenGeneration: 0,
-- botRosterMeta: (_bot, metaByName) => metaByName?.[_bot.name] ?? null,
++ botRosterMeta: (_bot, metaByName) => {
++ const key = _bot.sourceScoped
++ ? `${_bot.route?.connectionId || _bot.connectionId}::${_bot.name}`
++ : _bot.name
++ return metaByName?.[key] ?? null
++ },
cn: (...values) => values.filter(Boolean).join(' '),
createCanonicalChat: async () => null,
displayName: bot => bot.name,
@@@ -56,11 -58,6 +70,12 @@@
// #49 session-aware-row helpers referenced inside BotRow.
previewKind: () => ({ fromBot: false, sender: null }),
generatedSessionTitle: () => null,
++ focusedRosterOwner: owner => ({ connectionId: owner.connectionId, name: owner.profile }),
+ isActiveRosterBot: () => false,
+ isBackfilledFacePng: () => false,
+ botSelectionKey: value => value.sourceScoped ? `${value.connectionId}::${value.name}` : value.name,
+ isDefaultBot: value => value.name === 'default',
+ newBotChat: () => undefined,
openBotCanonicalChat: async (...args) => {
opened.push(args)
return 'stored-chat'
@@@ -88,9 -85,9 +103,18 @@@
jsx: node,
jsxs: node,
onEdit: () => undefined,
++ persistBotMetaSnapshot: () => Promise.resolve(),
queryClient: { invalidateQueries: () => undefined },
relativeTime: () => 'now',
-- saveBotMeta: () => undefined,
++ requestForBot: async (_bot, method) => method === 'profiles.list'
++ ? {
++ profiles: [{
++ name: _bot.route?.targetProfile || _bot.name,
++ ui_meta: { 'hermes-bots': { pinned: true } }
++ }]
++ }
++ : {},
++ saveBotMeta: (_bot, patch) => saved.push([_bot, patch]),
showsHandle: () => false,
stripPreviewMarkdown: text => String(text || ''),
useValue: store => store.get()
@@@ -101,7 -98,7 +125,7 @@@
const tree = context.BotRow({ bot, onEdit: context.onEdit })
const row = tree.type === 'button' ? tree : tree.props.children[0].props.children
-- return { ensured, opened, row, warmed }
++ return { ensured, opened, row, saved, tree, warmed }
}
test('regression: rendering BotsPane does not prewarm the entire roster', () => {
@@@ -126,7 -123,7 +150,31 @@@ test('behavior: pointer entry prewarms
assert.deepEqual(warmed, ['alpha'])
})
-test('behavior: a remote Connections row stays in this chat instead of hopping SSH', async () => {
++test('behavior: context-menu pin mutation hydrates a non-identity alias before toggling', async () => {
++ const bot = {
++ connectionId: 'remote-a',
++ name: 'worker',
++ remoteSource: true,
++ sourceScoped: true,
++ route: {
++ connectionId: 'remote-a',
++ mode: 'remote',
++ profile: 'worker',
++ targetProfile: 'backend-worker'
++ }
++ }
++ const { saved, tree } = renderBotRow(bot)
++ const menuItems = tree.props.children[1].props.children
++
++ menuItems[0].props.onSelect()
++ await new Promise(resolve => setTimeout(resolve, 0))
++
++ assert.equal(saved.length, 1)
++ assert.equal(saved[0][0], bot)
++ assert.deepEqual(JSON.parse(JSON.stringify(saved[0][1])), { pinned: false })
++})
++
+test('behavior: a remote Connections row opens through its captured route without activation authority', async () => {
const { ensured, opened, row, warmed } = renderBotRow({
connectionId: 'work',
connectionLabel: 'Work',
@@@ -174,6 -170,8 +222,9 @@@ test('behavior: remote default never op
ROSTER_KEY: ['hermes-bots', 'roster'],
$botMeta: atom({ default: { chat: 'this-device-chat' } }),
$botUnread: atom({}),
++ $focusedBotOwner: atom({ connectionId: 'mac-mini', profile: 'default' }),
+ $focusedBotProfile: atom('default'),
+ $groupChatWorkspace: atom(null),
$lastRoster: atom([]),
$selectedBot: atom('default'),
botAppearance: () => ({ shape: 'round', color: '#000', image: null }),
@@@ -188,11 -186,6 +239,12 @@@
haptic: () => undefined,
previewKind: () => ({ fromBot: false, sender: null }),
generatedSessionTitle: () => null,
++ focusedRosterOwner: owner => ({ connectionId: owner.connectionId, name: owner.profile }),
+ isActiveRosterBot: () => false,
+ isBackfilledFacePng: () => false,
+ botSelectionKey: value => value.sourceScoped ? `${value.connectionId}::${value.name}` : value.name,
+ isDefaultBot: value => value.name === 'default',
+ newBotChat: () => undefined,
openBotCanonicalChat: async (...args) => {
opened.push(args)
return 'this-device-chat'
diff --cc apps/desktop/src/plugins/hermes-bots/tests/remote-dm-delivery.test.mjs
index d27c25967ea,d864d637ce5..669e0fbc80f
--- a/apps/desktop/src/plugins/hermes-bots/tests/remote-dm-delivery.test.mjs
+++ b/apps/desktop/src/plugins/hermes-bots/tests/remote-dm-delivery.test.mjs
@@@ -127,61 -127,6 +127,120 @@@ test('remote DM carries sender attribut
)
})
+test('remote DM preserves a non-identity targetProfile through list, resume, create, and submit', async () => {
+ const calls = []
+ let submitted = false
+ const ctx = runtime({
+ requestProfile: async (route, method, params) => {
+ calls.push({ route, method, params })
+
+ if (method === 'profiles.list') {
+ return { profiles: [{ name: 'backend-worker', ui_meta: {} }] }
+ }
+
+ if (method === 'session.resume' && params.omit_messages) {
+ throw new Error('not found')
+ }
+
+ if (method === 'session.create') {
+ return { session_id: 'runtime-1', stored_session_id: 'stored-1' }
+ }
+
+ if (method === 'prompt.submit') {
+ submitted = true
+ return {}
+ }
+
+ if (method === 'session.resume') {
+ return submitted
+ ? { messages: [{ role: 'assistant', content: 'done' }], inflight: false, running: false }
+ : { messages: [] }
+ }
+
+ return {}
+ }
+ })
+ const route = {
+ connectionId: 'remote-a',
+ mode: 'remote',
+ profile: 'worker',
+ targetProfile: 'backend-worker'
+ }
+
+ await ctx.__dm.deliverRemoteRosterMentions(
+ [{ name: 'worker', connectionId: 'remote-a', remoteSource: true, route }],
+ 'ping',
+ { name: 'Hermes', handle: 'hermes' }
+ )
+
+ assert.equal(calls.length > 0, true)
+ assert.equal(calls.every(call => call.route.profile === 'worker'), true)
+ assert.equal(calls.every(call => call.route.targetProfile === 'backend-worker'), true)
+ for (const call of calls.filter(call => ['session.resume', 'session.create'].includes(call.method))) {
+ assert.equal(call.params.profile, 'backend-worker')
+ }
+ assert.equal(calls.find(call => call.method === 'prompt.submit')?.params.session_id, 'runtime-1')
+})
+
++test('remote-active DM keeps an immutable local recipient route through lookup, submit, and poll', async () => {
++ const calls = []
++ let submitted = false
++ const ctx = runtime({
++ state: {
++ profile: { get: () => 'sender', listen: () => undefined },
++ connectionId: { get: () => 'remote-a', listen: () => undefined },
++ gateway: { listen: () => undefined }
++ },
++ requestProfile: async (route, method, params) => {
++ calls.push({ route, method, params })
++
++ if (method === 'profiles.list') {
++ return { profiles: [{ name: 'backend-worker', ui_meta: {} }] }
++ }
++
++ if (method === 'session.resume' && params.omit_messages) {
++ throw new Error('not found')
++ }
++
++ if (method === 'session.create') {
++ return { session_id: 'runtime-local', stored_session_id: 'stored-local' }
++ }
++
++ if (method === 'prompt.submit') {
++ submitted = true
++ return {}
++ }
++
++ return submitted
++ ? { messages: [{ role: 'assistant', content: 'local reply' }], inflight: false, running: false }
++ : { messages: [] }
++ }
++ })
++ const route = Object.freeze({
++ connectionId: 'local',
++ mode: 'local',
++ profile: 'worker',
++ targetProfile: 'backend-worker'
++ })
++
++ await ctx.__dm.deliverRemoteRosterMentions(
++ [{ name: 'worker', connectionId: 'local', sourceScoped: true, remoteSource: true, route }],
++ 'ping local',
++ { name: 'Remote Sender', handle: 'sender' }
++ )
++
++ assert.equal(calls.length > 0, true)
++ assert.equal(calls.every(call => call.route.connectionId === 'local'), true)
++ assert.equal(calls.every(call => call.route.profile === 'worker'), true)
++ assert.equal(calls.every(call => call.route.targetProfile === 'backend-worker'), true)
++ assert.equal(calls.some(call => call.method === 'profiles.list'), true)
++ assert.equal(calls.some(call => call.method === 'prompt.submit'), true)
++ assert.equal(calls.filter(call => call.method === 'session.resume').length >= 2, true)
++ for (const call of calls.filter(call => ['session.resume', 'session.create'].includes(call.method))) {
++ assert.equal(call.params.profile, 'backend-worker')
++ }
++})
++
test('source contract: DM poll shares the group-turn shape (bounded, new-assistant-message)', () => {
assert.match(pluginSource, /const REMOTE_DM_TIMEOUT_MS = /)
assert.match(pluginSource, /pollRemoteDmReply/)
diff --cc apps/desktop/src/plugins/hermes-bots/tests/remote-routing-races.test.mjs
index 2ac69d87fa1,00000000000..e1739966f73
mode 100644,000000..100644
--- a/apps/desktop/src/plugins/hermes-bots/tests/remote-routing-races.test.mjs
+++ b/apps/desktop/src/plugins/hermes-bots/tests/remote-routing-races.test.mjs
@@@ -1,521 -1,0 +1,647 @@@
+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')
+
+function deferred() {
+ let resolve
+ let reject
+ const promise = new Promise((res, rej) => {
+ resolve = res
+ reject = rej
+ })
+
+ return { promise, resolve, reject }
+}
+
+function load({ requestProfile, agents, profileRoutes, storage } = {}) {
+ 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),
+ listen: () => undefined
+ }
+ values.set(slot, initial)
+ return slot
+ }
+ const calls = []
+ let activeConnectionId = 'remote-a'
+ const host = {
+ activeConnectionId: () => activeConnectionId,
+ agents: agents || (async () => ({ agents: [], sources: [] })),
+ deleteProfile: async route => calls.push(['deleteProfile', route]),
+ ensureAgent: async (connectionId, profile) => {
+ activeConnectionId = connectionId
+ calls.push(['ensureAgent', connectionId, profile])
+ },
+ newChat: route => calls.push(['newChat', route]),
+ notify: () => undefined,
+ notifyError: () => undefined,
+ profileRoutes: profileRoutes || (async () => []),
+ openSession: async (...args) => calls.push(['openSession', ...args]),
+ request: async (method, params) => {
+ calls.push(['ambient', method, params])
+ return {}
+ },
+ requestProfile: requestProfile || (async (route, method, params) => {
+ calls.push(['profile', route, method, params])
+ return {}
+ }),
+ state: {
+ connectionId: { get: () => activeConnectionId, listen: () => undefined },
+ gateway: { get: () => 'open', listen: () => undefined },
+ profile: { get: () => 'default', listen: () => undefined }
+ }
+ }
+ const context = {
+ atom,
+ clearTimeout,
+ console,
+ Date,
+ document: { createElement: () => ({}), getElementById: () => null, head: { appendChild: () => undefined } },
+ PALETTE_AREA: 'palette',
+ COMPOSER_AREAS: { middleware: 'middleware' },
+ queryClient: { invalidateQueries: () => undefined },
+ setTimeout,
+ host,
+ window: { setTimeout, clearTimeout }
+ }
+ 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(`
+ globalThis.__race = {
+ $botMeta,
+ botConnectionRoute,
+ botRosterKey,
+ botSelectionKey,
+ deleteBot,
+ duplicateBot,
++ ensureBotMetadata,
+ groupMemberKey,
+ migrateBotMeta,
+ migratedLocalRoutes,
+ newBotChat,
+ openBotCanonicalChat,
+ openProfileSession,
+ persistBotMetaSnapshot,
++ prepareBotSource,
+ requestForBot,
+ saveBotMeta,
+ setPluginStorage: storage => { pluginCtx = { storage } },
+ useProfileSessions
+ }
+ `)
+ vm.runInNewContext(code, context, { filename: 'plugin.js' })
+ return {
+ context,
+ calls,
+ host,
+ setActiveConnection: value => {
+ activeConnectionId = value
+ }
+ }
+}
+
+const remoteBot = {
+ connectionId: 'remote-a',
+ connectionLabel: 'Remote A',
+ name: 'default',
+ remoteSource: true,
+ route: { connectionId: 'remote-a', mode: 'remote', profile: 'default', targetProfile: 'remote-default' },
+ sourceScoped: true,
+ targetProfile: 'remote-default'
+}
+
- function recordingStorage(initial, failSetKey = null, failRemoveKeys = []) {
++function recordingStorage(
++ initial,
++ failSetKey = null,
++ failRemoveKeys = [],
++ failSetTimes = Number.POSITIVE_INFINITY
++) {
+ const values = new Map(Object.entries(initial))
+ const operations = []
+ const failedRemovals = new Set(failRemoveKeys)
++ let failedSets = 0
+
+ return {
+ operations,
+ get: async key => values.get(key) ?? null,
+ set: async (key, value) => {
+ operations.push(['set', key, value])
- if (key === failSetKey) {
++ if (key === failSetKey && failedSets < failSetTimes) {
++ failedSets += 1
+ throw new Error('disk full')
+ }
+ values.set(key, value)
+ },
+ remove: async key => {
+ operations.push(['remove', key])
+ if (failedRemovals.has(key)) {
+ throw new Error('remove failed')
+ }
+ values.delete(key)
+ }
+ }
+}
+
+test('same-name bots remain pinned to their own connection under concurrent requests', async () => {
+ const pendingA = deferred()
+ const pendingB = deferred()
+ const seen = []
+ const runtime = load({
+ requestProfile: (route, method) => {
+ seen.push([route, method])
+ return route.connectionId === 'remote-a' ? pendingA.promise : pendingB.promise
+ }
+ })
+ const botB = { ...remoteBot, connectionId: 'remote-b', route: { ...remoteBot.route, connectionId: 'remote-b', targetProfile: 'remote-default-b' } }
+
+ const first = runtime.context.__race.requestForBot(remoteBot, 'profiles.describe')
+ const second = runtime.context.__race.requestForBot(botB, 'profiles.describe')
+ await runtime.host.ensureAgent('remote-b', 'default')
+ pendingB.resolve({ ok: true })
+ pendingA.resolve({ ok: true })
+ await Promise.all([first, second])
+
+ assert.deepEqual(seen.map(([route]) => route.connectionId), ['remote-a', 'remote-b'])
+ assert.deepEqual(seen.map(([route]) => route.targetProfile), ['remote-default', 'remote-default-b'])
+})
+
+test('source-scoped routing fails closed instead of falling back to ambient host.request', async () => {
+ const runtime = load()
+ const ambient = []
+ runtime.host.request = async (...args) => ambient.push(args)
+ runtime.host.requestProfile = undefined
+
+ await assert.rejects(
+ runtime.context.__race.requestForBot(remoteBot, 'profiles.configure'),
+ /Cannot route profiles\.configure/
+ )
+ assert.deepEqual(ambient, [])
+})
+
+test('source-scoped routing rejects a missing connection id before dispatch', async () => {
+ const runtime = load()
+ const incomplete = {
+ ...remoteBot,
+ connectionId: '',
+ route: { ...remoteBot.route, connectionId: '' }
+ }
+
+ await assert.rejects(
+ runtime.context.__race.requestForBot(incomplete, 'profiles.configure'),
+ /no connection owner/i
+ )
+ assert.equal(runtime.calls.some(call => call[0] === 'ambient' || call[0] === 'profile'), false)
+})
+
++test('non-identity alias hydrates metadata from the backend row before Edit saves it', async () => {
++ const calls = []
++ const workerBot = {
++ ...remoteBot,
++ name: 'worker',
++ route: { ...remoteBot.route, profile: 'worker', targetProfile: 'backend-worker' },
++ targetProfile: 'backend-worker'
++ }
++ const runtime = load({
++ requestProfile: async (_route, method, params) => {
++ calls.push([method, params])
++ if (method === 'profiles.list') {
++ return {
++ profiles: [{
++ name: 'backend-worker',
++ ui_meta: {
++ 'hermes-bots': { title: 'Hydrated', pinned: true, chat: 'worker-chat' }
++ }
++ }]
++ }
++ }
++ return { applied: { ui_meta: true } }
++ }
++ })
++
++ const prepared = await runtime.context.__race.prepareBotSource(workerBot, null)
++ assert.equal(prepared, 'worker-chat')
++
++ const hydrated = await runtime.context.__race.ensureBotMetadata(workerBot)
++ assert.deepEqual(JSON.parse(JSON.stringify(hydrated)), {
++ title: 'Hydrated',
++ pinned: true,
++ chat: 'worker-chat'
++ })
++
++ await runtime.context.__race.saveBotMeta(workerBot, { title: 'Edited' })
++ const edit = calls.find(([method]) => method === 'profiles.configure')
++ assert.deepEqual(JSON.parse(JSON.stringify(edit[1])), {
++ name: 'backend-worker',
++ ui_meta: {
++ 'hermes-bots': { title: 'Edited', pinned: true, chat: 'worker-chat' }
++ }
++ })
++})
++
++test('non-identity alias reuses a canonical pin through the backend profile name', async () => {
++ const requests = []
++ const workerBot = {
++ ...remoteBot,
++ name: 'worker',
++ route: { ...remoteBot.route, profile: 'worker', targetProfile: 'backend-worker' },
++ targetProfile: 'backend-worker'
++ }
++ const runtime = load({
++ requestProfile: async (_route, method, params) => {
++ requests.push([method, params])
++ return {
++ profiles: [{
++ name: 'backend-worker',
++ preferred_session: {
++ id: 'pin-worker',
++ resolved_id: 'pin-worker-tip',
++ message_count: 3
++ }
++ }]
++ }
++ }
++ })
++
++ const result = await runtime.context.__race.openBotCanonicalChat(
++ workerBot,
++ 'pin-worker',
++ { message_count: 3 }
++ )
++
++ assert.equal(result, 'pin-worker')
++ assert.deepEqual(JSON.parse(JSON.stringify(requests[0])), [
++ 'profiles.list',
++ {
++ include_sessions: true,
++ preferred_session_ids: { 'backend-worker': 'pin-worker' }
++ }
++ ])
++ const opened = runtime.calls.find(call => call[0] === 'openSession')
++ assert.equal(opened[1], 'pin-worker-tip')
++})
++
+test('delayed edit, group mutation, and canonical session RPCs retain the route', async () => {
+ const pending = deferred()
+ const seen = []
+ const runtime = load({
+ requestProfile: (route, method, params) => {
+ seen.push([route, method, params])
+ return pending.promise
+ }
+ })
+
+ const edit = runtime.context.__race.saveBotMeta(remoteBot, { title: 'Remote title' })
+ const group = runtime.context.__race.requestForBot(remoteBot, 'profiles.configure', { name: 'default' })
+ const open = runtime.context.__race.openBotCanonicalChat(remoteBot, 'stored-remote', { message_count: 2 })
+ await runtime.host.ensureAgent('remote-b', 'default')
+ pending.resolve({ applied: { ui_meta: true }, profiles: [{ name: 'default', preferred_session: { id: 'stored-remote' } }] })
+ await Promise.all([edit, group, open])
+
+ assert.ok(seen.length >= 3)
+ assert.ok(seen.every(([route]) => route.connectionId === 'remote-a'))
+ assert.ok(seen.every(([route]) => Object.isFrozen(route)))
+})
+
+test('delayed duplicate, delete, and new chat keep source ownership', async () => {
+ const pending = deferred()
+ const runtime = load({
+ requestProfile: (route, method) => {
+ runtime.calls.push(['profile', route, method])
+ return pending.promise
+ }
+ })
+ const workerBot = {
+ ...remoteBot,
+ name: 'worker',
+ route: { ...remoteBot.route, profile: 'worker', targetProfile: 'backend-worker' },
+ targetProfile: 'backend-worker'
+ }
+ runtime.context.__race.$botMeta.set({ 'remote-a::worker': { title: 'Original' } })
+
+ const duplicate = runtime.context.__race.duplicateBot(workerBot, [workerBot])
+ const edit = runtime.context.__race.saveBotMeta(workerBot, { pinned: true })
+ await runtime.host.ensureAgent('remote-b', 'default')
+ pending.resolve({ profiles: [{ name: 'default' }], applied: { ui_meta: true } })
+ await Promise.all([duplicate, edit])
+
+ runtime.context.__race.newBotChat(workerBot)
+ const deletePromise = runtime.context.__race.deleteBot(workerBot)
+ await deletePromise
+
+ const routes = runtime.calls
+ .filter(call => call[0] === 'profile' || call[0] === 'deleteProfile' || call[0] === 'newChat')
+ .map(call => call[1])
+ .filter(value => value && typeof value === 'object')
+ assert.ok(routes.length >= 3)
+ assert.ok(routes.every(route => route.connectionId === 'remote-a'))
+})
+
+test('remote session browsing and opening use the captured route after activation changes', async () => {
+ const runtime = load()
+ let query
+ runtime.context.useQuery = config => {
+ query = config
+ return config
+ }
+ const result = runtime.context.__race.useProfileSessions(remoteBot, 0)
+ await runtime.host.ensureAgent('remote-b', 'default')
+ await result.queryFn()
+ assert.equal(query.queryKey[2], 'remote-a::default')
+ const routedList = runtime.calls.find(call => call[0] === 'profile' && call[2] === 'session.list')
+ assert.equal(routedList[1].connectionId, 'remote-a')
+
+ await runtime.context.__race.openProfileSession(remoteBot, { id: 'stored-remote', message_count: 1 }, 0)
+ const open = runtime.calls.find(call => call[0] === 'openSession')
+ assert.equal(open[2].route.connectionId, 'remote-a')
+ assert.equal(open[2].route.targetProfile, 'remote-default')
+ assert.equal(runtime.calls.some(call => call[0] === 'ambient'), false)
+})
+
+test('default deletion is rejected in the executable mutation layer', async () => {
+ const runtime = load()
+ await assert.rejects(runtime.context.__race.deleteBot(remoteBot), /default profile cannot be deleted/i)
+ assert.equal(runtime.calls.some(call => call[0] === 'deleteProfile'), false)
+})
+
+test('source-scoped bot metadata save commits v2 marker after its data', async () => {
+ const storage = recordingStorage({ 'bot-meta-v2-migrated': true })
+ const runtime = load({
+ requestProfile: async () => ({ applied: { ui_meta: true } })
+ })
+ runtime.context.__race.setPluginStorage(storage)
+
+ await runtime.context.__race.saveBotMeta(remoteBot, { title: 'Remote' })
+
+ assert.deepEqual(storage.operations.map(operation => operation.slice(0, 2)), [
+ ['remove', 'bot-meta-v2-migrated'],
+ ['set', 'bot-meta-v2'],
+ ['set', 'bot-meta-v2-migrated']
+ ])
+})
+
+test('scoped metadata reconciliation commits v2 marker after its data', async () => {
+ const storage = recordingStorage({ 'bot-meta-v2-migrated': true })
+ const runtime = load()
+ runtime.context.__race.setPluginStorage(storage)
+
+ await runtime.context.__race.persistBotMetaSnapshot({
+ 'remote-a::default': { hidden: true }
+ }, true)
+
+ assert.deepEqual(storage.operations.map(operation => operation.slice(0, 2)), [
+ ['remove', 'bot-meta-v2-migrated'],
+ ['set', 'bot-meta-v2'],
+ ['set', 'bot-meta-v2-migrated']
+ ])
+})
+
+test('v1 metadata migrates only for a provable sole-local topology and keeps rollback data', async () => {
+ const writes = []
+ const runtime = load({
+ agents: async () => ({
+ agents: [{ connectionId: 'local', connectionKind: 'local', profile: 'default' }],
+ sources: [{ connectionId: 'local', kind: 'local' }]
+ }),
+ profileRoutes: async () => [{ connectionId: 'local', mode: 'local', profile: 'default', targetProfile: 'default' }],
+ storage: {
+ get: async key => key === 'bot-meta' ? { default: { title: 'Local' } } : null,
+ set: async (key, value) => writes.push([key, value])
+ }
+ })
+
+ const migrated = await runtime.context.__race.migrateBotMeta({
+ get: async key => key === 'bot-meta' ? { default: { title: 'Local' } } : null,
+ remove: async () => undefined,
+ set: async (key, value) => writes.push([key, value])
+ })
+ assert.equal(migrated, true)
+ assert.deepEqual(Object.keys(runtime.context.__race.$botMeta.get()), ['local::default'])
+ assert.deepEqual(writes.map(([key]) => key), ['bot-meta-v2', 'bot-meta-v2-migrated'])
+})
+
+test('migration rolls back routes when a later v1 profile has no local route', async () => {
+ const runtime = load({
+ agents: async () => ({
+ agents: [{ connectionId: 'local', connectionKind: 'local', profile: 'first' }],
+ sources: [{ connectionId: 'local', kind: 'local' }]
+ }),
+ profileRoutes: async () => [
+ { connectionId: 'local', mode: 'local', profile: 'first', targetProfile: 'backend-first' }
+ ]
+ })
+
+
+ const migrated = await runtime.context.__race.migrateBotMeta({
+ get: async key => key === 'bot-meta'
+ ? { first: { title: 'First' }, missing: { title: 'Missing' } }
+ : null,
+ set: async () => assert.fail('storage must not be written before every route is proven')
+ })
+
+ assert.equal(migrated, false)
+ assert.equal(runtime.context.__race.migratedLocalRoutes.size, 0)
+ assert.deepEqual(JSON.parse(JSON.stringify(runtime.context.__race.$botMeta.get())), {
+ first: { title: 'First' },
+ missing: { title: 'Missing' }
+ })
+})
+
++test('failed normal v2 successor commit preserves the last committed generation on reload', async () => {
++ const committed = {
++ 'remote-a::default': { title: 'B' }
++ }
++ const storage = recordingStorage(
++ {
++ 'bot-meta-v2': committed,
++ 'bot-meta-v2-migrated': true
++ },
++ 'bot-meta-v2-migrated',
++ [],
++ 1
++ )
++ const runtime = load({
++ requestProfile: async () => ({ applied: { ui_meta: true } }),
++ storage
++ })
++ runtime.context.__race.setPluginStorage(storage)
++ assert.equal(await runtime.context.__race.migrateBotMeta(storage), true)
++
++ await runtime.context.__race.saveBotMeta(remoteBot, { title: 'D' })
++
++ const reloaded = load({ storage })
++ assert.equal(await reloaded.context.__race.migrateBotMeta(storage), true)
++ assert.deepEqual(
++ JSON.parse(JSON.stringify(reloaded.context.__race.$botMeta.get())),
++ committed
++ )
++})
++
+test('failed marker commit rolls persisted v2 back and reload keeps v1 authoritative', async () => {
+ const storage = recordingStorage(
+ { 'bot-meta': { first: { title: 'First' } } },
+ 'bot-meta-v2-migrated'
+ )
+ const options = {
+ agents: async () => ({
+ agents: [{ connectionId: 'local', connectionKind: 'local', profile: 'first' }],
+ sources: [{ connectionId: 'local', kind: 'local' }]
+ }),
+ profileRoutes: async () => [
+ { connectionId: 'local', mode: 'local', profile: 'first', targetProfile: 'backend-first' }
+ ],
+ storage
+ }
+ const runtime = load(options)
+
+ const migrated = await runtime.context.__race.migrateBotMeta(storage)
+
+ assert.equal(migrated, false)
+ assert.equal(runtime.context.__race.migratedLocalRoutes.size, 0)
+ assert.deepEqual(JSON.parse(JSON.stringify(runtime.context.__race.$botMeta.get())), {
+ first: { title: 'First' }
+ })
+ assert.deepEqual(storage.operations.map(operation => operation.slice(0, 2)), [
+ ['remove', 'bot-meta-v2-migrated'],
+ ['set', 'bot-meta-v2'],
+ ['set', 'bot-meta-v2-migrated'],
+ ['remove', 'bot-meta-v2-migrated'],
+ ['remove', 'bot-meta-v2']
+ ])
+
+ const reloaded = load(options)
+ const acceptedAfterReload = await reloaded.context.__race.migrateBotMeta(storage)
+
+ assert.equal(acceptedAfterReload, false)
+ assert.deepEqual(JSON.parse(JSON.stringify(reloaded.context.__race.$botMeta.get())), {
+ first: { title: 'First' }
+ })
+})
+
+test('failed marker and failed v2 cleanup still reload v1 instead of markerless v2', async () => {
+ const storage = recordingStorage(
+ { 'bot-meta': { first: { title: 'Rollback' } } },
+ 'bot-meta-v2-migrated',
+ ['bot-meta-v2']
+ )
+ const options = {
+ agents: async () => ({
+ agents: [{ connectionId: 'local', connectionKind: 'local', profile: 'first' }],
+ sources: [{ connectionId: 'local', kind: 'local' }]
+ }),
+ profileRoutes: async () => [
+ { connectionId: 'local', mode: 'local', profile: 'first', targetProfile: 'backend-first' }
+ ],
+ storage
+ }
+ const runtime = load(options)
+
+ assert.equal(await runtime.context.__race.migrateBotMeta(storage), false)
+
+ const reloaded = load(options)
+ assert.equal(await reloaded.context.__race.migrateBotMeta(storage), false)
+ assert.deepEqual(JSON.parse(JSON.stringify(reloaded.context.__race.$botMeta.get())), {
+ first: { title: 'Rollback' }
+ })
+})
+
+test('crash-window v2 write without a marker reloads v1 rollback data', async () => {
+ const storage = recordingStorage({
+ 'bot-meta': { first: { title: 'Rollback' } },
+ 'bot-meta-v2': { 'local::first': { title: 'Crash window' } }
+ })
+ const runtime = load({ storage })
+
+ assert.equal(await runtime.context.__race.migrateBotMeta(storage), false)
+ assert.deepEqual(JSON.parse(JSON.stringify(runtime.context.__race.$botMeta.get())), {
+ first: { title: 'Rollback' }
+ })
+})
+
+test('v1 metadata is not projected onto same-name bots in a multi-source topology', async () => {
+ const writes = []
+ const runtime = load({
+ agents: async () => ({
+ agents: [
+ { connectionId: 'local', connectionKind: 'local', profile: 'default' },
+ { connectionId: 'remote-a', connectionKind: 'remote', profile: 'default' }
+ ],
+ sources: [
+ { connectionId: 'local', kind: 'local' },
+ { connectionId: 'remote-a', kind: 'remote' }
+ ]
+ }),
+ profileRoutes: async () => [
+ { connectionId: 'local', mode: 'local', profile: 'default', targetProfile: 'default' },
+ remoteBot.route
+ ]
+ })
+
+ const migrated = await runtime.context.__race.migrateBotMeta({
+ get: async key => key === 'bot-meta' ? { default: { title: 'Legacy local' } } : null,
+ set: async (key, value) => writes.push([key, value])
+ })
+
+ assert.equal(migrated, false)
+ assert.deepEqual(JSON.parse(JSON.stringify(runtime.context.__race.$botMeta.get())), {
+ default: { title: 'Legacy local' }
+ })
+ assert.deepEqual(writes, [])
+})
+
+test('bot-meta-v2 is authoritative only with its persisted commit marker', async () => {
+ const runtime = load()
+ const v2 = {
+ 'remote-a::default': { title: 'A' },
+ 'remote-b::default': { title: 'B' }
+ }
+
+ const migrated = await runtime.context.__race.migrateBotMeta({
+ get: async key => key === 'bot-meta-v2'
+ ? v2
+ : key === 'bot-meta-v2-migrated'
+ ? true
+ : null,
+ set: async () => assert.fail('existing v2 must not be rewritten during hydration')
+ })
+
+ assert.equal(migrated, true)
+ assert.deepEqual(JSON.parse(JSON.stringify(runtime.context.__race.$botMeta.get())), v2)
+})
+
+test('markerless bot-meta-v2 is ignored on reload', async () => {
+ const runtime = load()
+ const markerlessV2 = { 'remote-a::default': { title: 'Uncommitted' } }
+
+ const migrated = await runtime.context.__race.migrateBotMeta({
+ get: async key => key === 'bot-meta-v2' ? markerlessV2 : null,
+ set: async () => assert.fail('markerless v2 must not be committed implicitly')
+ })
+
+ assert.equal(migrated, false)
+ assert.deepEqual(JSON.parse(JSON.stringify(runtime.context.__race.$botMeta.get())), {})
+})
+
+test('selection and metadata keys do not collide for same-name connections', () => {
+ const runtime = load()
+ const { botRosterKey, botSelectionKey, botConnectionRoute } = runtime.context.__race
+ const botB = {
+ ...remoteBot,
+ connectionId: 'remote-b',
+ route: { ...remoteBot.route, connectionId: 'remote-b' }
+ }
+ const a = botConnectionRoute(remoteBot)
+ const b = botConnectionRoute(botB)
+
+ assert.notEqual(botRosterKey({ ...remoteBot, route: a }), botRosterKey({ ...botB, route: b }))
+ assert.notEqual(botSelectionKey({ ...remoteBot, route: a }), botSelectionKey({ ...botB, route: b }))
+})
diff --cc apps/desktop/src/plugins/hermes-bots/tests/routine-owner.test.mjs
index 3ebf4308276,f0e09041b06..0e830b48080
--- a/apps/desktop/src/plugins/hermes-bots/tests/routine-owner.test.mjs
+++ b/apps/desktop/src/plugins/hermes-bots/tests/routine-owner.test.mjs
@@@ -74,11 -74,11 +74,11 @@@ test('source contract: row mutations in
test('source contract: create mutations and dialog state retain one owner', () => {
assert.match(
pluginSource,
- /function CreateRoutineDialog\(\{ bot, open, onClose \}\)[\s\S]*await host\.request\('cron\.manage', \{[\s\S]*\.\.\.\(bot \? \{ profile: bot \} : \{\}\)[\s\S]*await invalidateRoutineOwner\(bot\)/
+ /function CreateRoutineDialog\(\{ bot, open, onClose \}\)[\s\S]*await requestForBot\(bot, 'cron\.manage',[\s\S]*\.\.\.\(profile \? \{ profile \} : \{\}\)[\s\S]*await invalidateRoutineOwner\(bot\)/
)
assert.match(pluginSource, /const \[createOwner, setCreateOwner\] = useState\(null\)/)
- assert.match(pluginSource, /const openCreate = \(\) => \{[\s\S]*setCreateOwner\(bot\)[\s\S]*setCreateOpen\(true\)/)
- assert.match(pluginSource, /const createTarget = routineCreateTarget\(createOwner, bot\)/)
+ assert.match(pluginSource, /const openCreate = \(\) => \{[\s\S]*setCreateOwner\(owner\)[\s\S]*setCreateOpen\(true\)/)
- assert.match(pluginSource, /const createTarget = routineCreateTarget\(createOwner, bot\)/)
++ assert.match(pluginSource, /const createTarget = owner \? routineCreateTarget\(createOwner, bot\) : null/)
// key must be the jsx() THIRD argument (a `key:` prop is silently ignored
// by the react/jsx-runtime and the dialog would keep stale per-bot state).
assert.match(pluginSource, /jsx\(CreateRoutineDialog, \{[\s\S]*?\}, createTarget\)/)
diff --cc apps/desktop/src/plugins/hermes-bots/tests/routines-selected-bot.test.mjs
index 00000000000,4eb1abf43d4..ff438f06838
mode 000000,100644..100644
--- a/apps/desktop/src/plugins/hermes-bots/tests/routines-selected-bot.test.mjs
+++ b/apps/desktop/src/plugins/hermes-bots/tests/routines-selected-bot.test.mjs
@@@ -1,0 -1,97 +1,159 @@@
+ import assert from 'node:assert/strict'
+ import { readFileSync } from 'node:fs'
+ import test from 'node:test'
+ import vm from 'node:vm'
+
+ // #89625 follow-up (PR #89637 residual): nanostores' `.listen()` never replays
+ // the current value the way `.subscribe()` does, so the $focusedBotProfile
+ // listener in register() only kept $selectedBot current from the moment it was
+ // attached. A disable -> profile switch -> re-enable cycle (Settings > Plugins)
+ // left $selectedBot pointed at whichever bot was active before the plugin was
+ // disabled. bindProfileSync() reseeds $selectedBot from the store's CURRENT
+ // value before attaching the listener, so every register() starts in sync.
+
+ const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
-function load() {
++function load({ focusedSessionOwnerSupported = false, focusedSessionOwner = null } = {}) {
+ const values = new Map()
+ const atom = initial => {
+ const slot = { get: () => values.get(slot), set: value => values.set(slot, value) }
+ values.set(slot, initial)
+ return slot
+ }
++ const state = { profile: { listen: () => undefined } }
++ if (focusedSessionOwnerSupported) {
++ state.focusedSessionOwner = atom(focusedSessionOwner)
++ }
+ const context = {
+ atom,
+ PALETTE_AREA: 'palette',
+ COMPOSER_AREAS: { middleware: 'middleware' },
+ document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } },
- host: { state: { profile: { listen: () => undefined } } }
++ host: { state }
+ }
+ 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.__api = { bindProfileSync, $selectedBot };\n')
++ .concat(`
++ globalThis.__api = {
++ bindProfileSync,
++ resolveRoutineOwner: typeof resolveRoutineOwner === 'function' ? resolveRoutineOwner : undefined,
++ $selectedBot
++ };
++ `)
+ vm.runInNewContext(source, context, { filename: 'plugin.js' })
+ return context
+ }
+
+ // Mimic real nanostores atom semantics (get + non-replaying listen) — not a
+ // mock that assumes the fix — so this fails honestly if bindProfileSync
+ // regresses to a plain, non-reseeding listen().
+ function fakeProfileStore(initial) {
+ let value = initial
+ const listeners = new Set()
+ return {
+ get: () => value,
+ set: next => {
+ value = next
+ for (const listener of listeners) listener(value)
+ },
+ listen: listener => {
+ listeners.add(listener)
+ return () => listeners.delete(listener)
+ }
+ }
+ }
+
+ test('regression: re-enabling after a profile switch while disabled resyncs, not stays stale', () => {
+ const { bindProfileSync, $selectedBot } = load().__api
+ const profile = fakeProfileStore('blog-writer')
+
+ const unbind1 = bindProfileSync(profile)
+ assert.equal($selectedBot.get(), 'blog-writer', 'reseeded to the live profile on first bind')
+
+ unbind1() // plugin disabled: listener torn down
+ profile.set('researcher') // profile changes while nothing is listening
+
+ bindProfileSync(profile) // plugin re-enabled: register() runs again
+ assert.equal($selectedBot.get(), 'researcher', 'reseeded to the live profile on re-bind, not left stale')
+ })
+
+ test('unit: bindProfileSync keeps forwarding live profile changes after (re)binding', () => {
+ const { bindProfileSync, $selectedBot } = load().__api
+ const profile = fakeProfileStore('default')
+
+ bindProfileSync(profile)
+ profile.set('researcher')
+ assert.equal($selectedBot.get(), 'researcher', 'live changes still flow through the listener')
+ })
+
++test('unit: bindProfileSync follows connection changes for the same profile name', () => {
++ const { bindProfileSync, $selectedBot } = load().__api
++ const owner = fakeProfileStore({ connectionId: 'source-a', profile: 'default' })
++
++ bindProfileSync(owner)
++ assert.equal($selectedBot.get(), 'source-a::default')
++
++ owner.set({ connectionId: 'source-b', profile: 'default' })
++ assert.equal($selectedBot.get(), 'source-b::default')
++})
++
+ test('unit: an empty/non-string current value is not seeded into $selectedBot', () => {
+ const { bindProfileSync, $selectedBot } = load().__api
+ const before = $selectedBot.get()
+ bindProfileSync(fakeProfileStore(''))
+ assert.equal($selectedBot.get(), before, 'falsy current value leaves $selectedBot untouched')
+ })
+
-test('unit: register() wires the focused-profile ladder through bindProfileSync', () => {
++test('unit: an authoritative focused owner missing from the roster fails closed', () => {
++ const { resolveRoutineOwner } = load().__api
++ const roster = [{
++ connectionId: 'source-a',
++ name: 'default',
++ remoteSource: true,
++ sourceScoped: true
++ }]
++ const focusedOwner = {
++ authoritative: true,
++ connectionId: 'source-b',
++ name: 'worker'
++ }
++
++ assert.equal(resolveRoutineOwner(roster, focusedOwner, 'source-a::default'), null)
++})
++
++test('unit: an authoritative null focused owner disables routines instead of using selection', () => {
++ const { resolveRoutineOwner } = load({ focusedSessionOwnerSupported: true }).__api
++ const roster = [{
++ connectionId: 'source-a',
++ name: 'default',
++ remoteSource: true,
++ sourceScoped: true
++ }]
++
++ assert.equal(resolveRoutineOwner(roster, null, 'source-a::default'), null)
++})
++
++test('unit: a legacy SDK without focused owner support may use selection', () => {
++ const { resolveRoutineOwner } = load().__api
++ const roster = [{
++ connectionId: 'source-a',
++ name: 'default',
++ remoteSource: true,
++ sourceScoped: true
++ }]
++
++ assert.equal(resolveRoutineOwner(roster, null, 'source-a::default'), roster[0])
++})
++
++test('unit: register() wires the focused-owner ladder through bindProfileSync', () => {
+ assert.match(
+ pluginSource,
- /const unbindProfileListener = bindProfileSync\(\$focusedBotProfile\)/,
- 'the reseeding helper must own the $focusedBotProfile subscription'
++ /const unbindProfileListener = bindProfileSync\(\$focusedBotOwner\)/,
++ 'the reseeding helper must own the connection-qualified focused owner subscription'
+ )
+ })
diff --cc apps/desktop/src/sdk/host-state.test.ts
index 68dc8918dd0,b372fd73258..487b8edc1d2
--- a/apps/desktop/src/sdk/host-state.test.ts
+++ b/apps/desktop/src/sdk/host-state.test.ts
@@@ -129,6 -129,56 +129,132 @@@ describe('host.state focused-session at
})
})
+ describe('host.state.focusedSessionProfile', () => {
+ beforeEach(() => {
+ window.localStorage.clear()
+ vi.resetModules()
+ })
+
+ afterEach(() => {
+ vi.resetModules()
+ })
+
+ async function setup() {
+ const { host } = await import('@/sdk/index')
+ const profile = await import('@/store/profile')
+ const session = await import('@/store/session')
+ const states = await import('@/store/session-states')
+
+ return { host, profile, session, states }
+ }
+
+ it('is a readonly atom that falls back to the gateway profile with no focused session', async () => {
+ const { host, profile } = await setup()
+
+ expect(typeof host.state.focusedSessionProfile.get).toBe('function')
+ expect(typeof host.state.focusedSessionProfile.listen).toBe('function')
+
+ profile.$activeGatewayProfile.set('newsanalyst')
+ expect(host.state.focusedSessionProfile.get()).toBe('newsanalyst')
+ profile.$activeGatewayProfile.set('default')
+ })
+
+ it('resolves the focused session to the owner stamped on its session row, not the socket home', async () => {
+ const { host, profile, session } = await setup()
+
+ // The gateway socket is homed on default (e.g. cold start), but the chat
+ // on screen belongs to newsanalyst — the readout must say newsanalyst.
+ profile.$activeGatewayProfile.set('default')
+ session.$sessions.set([{ id: 'news-1', profile: 'newsanalyst' } as never])
+ session.$selectedStoredSessionId.set('news-1')
+
+ expect(host.state.focusedSessionProfile.get()).toBe('newsanalyst')
+
+ // An uncached/unstamped id inherits the gateway profile (the old ladder).
+ session.$selectedStoredSessionId.set('unknown-id')
+ expect(host.state.focusedSessionProfile.get()).toBe('default')
+
+ session.$sessions.set([])
+ session.$selectedStoredSessionId.set(null)
+ })
++
++ it('fails closed when duplicate stored or lineage ids resolve to different connections', async () => {
++ const { host, session } = await setup()
++
++ session.$sessions.set([
++ {
++ connection_id: 'source-a',
++ id: 'shared-tip-a',
++ _lineage_root_id: 'shared-root',
++ profile: 'worker'
++ } as never,
++ {
++ connection_id: 'source-b',
++ id: 'shared-root',
++ profile: 'worker'
++ } as never
++ ])
++ session.$selectedStoredSessionId.set('shared-root')
++
++ expect(host.state.focusedSessionOwner.get()).toBeNull()
++
++ session.$sessions.set([])
++ session.$selectedStoredSessionId.set(null)
++ })
++
++ it('fails closed when the same focused id has ambiguous owner hints', async () => {
++ const { host, session } = await setup()
++
++ session.setSessionOwnerHint('ambiguous-hint', {
++ connectionId: 'source-a',
++ mode: 'remote',
++ profile: 'worker',
++ targetProfile: 'backend-worker-a'
++ })
++ session.setSessionOwnerHint('ambiguous-hint', {
++ connectionId: 'source-b',
++ mode: 'remote',
++ profile: 'worker',
++ targetProfile: 'backend-worker-b'
++ })
++ session.$sessions.set([{
++ connection_id: 'source-a',
++ id: 'ambiguous-hint',
++ profile: 'worker'
++ } as never])
++ session.$selectedStoredSessionId.set('ambiguous-hint')
++
++ expect(host.state.focusedSessionOwner.get()).toBeNull()
++
++ session.$sessions.set([])
++ session.$selectedStoredSessionId.set(null)
++ })
++
++ it('keeps the focused session connection when same-named profiles share a handle', async () => {
++ const { host, profile, session } = await setup()
++
++ profile.$activeGatewayProfile.set('default')
++ session.setConnection({ connectionId: 'source-a', mode: 'remote' } as never)
++ session.$sessions.set([
++ {
++ connection_id: 'source-b',
++ id: 'shared-default',
++ profile: 'default'
++ } as never
++ ])
++ session.$selectedStoredSessionId.set('shared-default')
++
++ expect(host.state.focusedSessionOwner.get()).toEqual({
++ connectionId: 'source-b',
++ profile: 'default'
++ })
++
++ session.$sessions.set([])
++ session.$selectedStoredSessionId.set(null)
++ session.setConnection(null)
++ })
+ })
+
describe('host.state busy vs gateway', () => {
afterEach(() => {
$sessionStates.set({})
diff --cc apps/desktop/src/sdk/index.ts
index 3332a731649,ffafa03f0a8..1582f8a9506
--- a/apps/desktop/src/sdk/index.ts
+++ b/apps/desktop/src/sdk/index.ts
@@@ -66,8 -65,9 +66,12 @@@ import
$gatewayState,
$messages,
$selectedStoredSessionId,
- setSessionOwnerHint,
+ $sessions,
++ getSessionOwnerHints,
+ rememberedSessionProfile,
requestSessionResume,
++ sessionMatchesStoredId,
++ setSessionOwnerHint,
setResumeExhaustedSessionId
} from '@/store/session'
import {
@@@ -107,6 -107,22 +111,70 @@@ const $focusedAwaitingResponse = focuse
PRIMARY_SESSION_VIEW.$awaitingResponse
)
++export interface PluginFocusedSessionOwner {
++ connectionId: string
++ profile: string
++}
++
+ /**
- * Owner profile of the FOCUSED chat. The gateway-routing atom
++ * Connection-qualified owner of the FOCUSED chat. The gateway-routing atom
+ * (`$activeGatewayProfile`) answers "which backend is the live socket homed
+ * on" — but tab/tile focus moves without swapping the socket, and a cold
+ * start can restore a route into a session the booting gateway doesn't own.
- * Any per-bot readout (roster highlight, a bot-scoped panel) must follow the
- * chat the user is LOOKING AT, so this resolves the focused stored session to
- * the owner stamped on its session row (the cross-profile aggregator tags
- * every row) and only falls back to the gateway profile for a draft or an
- * uncached id — the same ladder the remembered-navigation key and the HUD use.
++ * Any per-bot readout must follow the chat the user is LOOKING AT, so this
++ * resolves the focused stored session to a unique immutable owner hint or a
++ * unique connection-qualified aggregated row. Ambiguous or unresolved focused
++ * ids fail closed with null; only a draft/no focused id uses the active gateway
++ * owner. `focusedSessionProfile` remains the profile-only compatibility ladder.
+ */
++const $focusedSessionOwner = computed(
++ [$focusedStoredSessionId, $sessions, $activeGatewayProfile, $connection],
++ (focused, sessions, activeProfile, connection): PluginFocusedSessionOwner | null => {
++ const activeConnectionId = String(
++ connection?.connectionId || (connection?.mode === 'local' ? 'local' : '')
++ ).trim()
++ const fallback = {
++ connectionId: activeConnectionId,
++ profile: normalizeProfileKey(activeProfile)
++ }
++
++ if (!focused) {
++ return fallback
++ }
++
++ const hints = getSessionOwnerHints(focused)
++
++ if (hints.length === 1) {
++ return {
++ connectionId: hints[0].connectionId,
++ profile: normalizeProfileKey(hints[0].profile)
++ }
++ }
++
++ if (hints.length > 1) {
++ return null
++ }
++
++ const owners = new Map<string, PluginFocusedSessionOwner>()
++ for (const row of sessions.filter(session => sessionMatchesStoredId(session, focused))) {
++ const connectionId = String(row.connection_id || '').trim()
++ const profile = normalizeProfileKey(row.profile)
++
++ if (connectionId) {
++ owners.set(`${connectionId}::${profile}`, { connectionId, profile })
++ }
++ }
++
++ return owners.size === 1 ? [...owners.values()][0] : null
++ }
++)
++
+ const $focusedSessionProfile = computed(
- [$focusedStoredSessionId, $sessions, $activeGatewayProfile],
- (focused, sessions, activeProfile) => normalizeProfileKey(rememberedSessionProfile(sessions, focused, activeProfile))
++ [$focusedSessionOwner, $focusedStoredSessionId, $sessions, $activeGatewayProfile],
++ (owner, focused, sessions, activeProfile) => owner?.profile ||
++ rememberedSessionProfile(sessions, focused, activeProfile)
+ )
+
export interface PluginProfileRoute {
connectionId: string
mode: 'local' | 'remote'
@@@ -328,6 -335,11 +396,13 @@@ export const host =
* primary. Prefer this over `activeSessionId` for any readout that
* should follow the user between tiles (context, tokens, cost). */
focusedSessionId: readonlyAtom<null | string>($focusedRuntimeId),
++ /** Connection-qualified owner of the focused chat. Prefer this for any
++ * readout or mutation where separate sources can share a profile name. */
++ focusedSessionOwner: readonlyAtom<PluginFocusedSessionOwner | null>($focusedSessionOwner),
+ /** Owner profile of the focused chat (session-row stamp, falling back to
- * the gateway profile for drafts/uncached ids). Prefer this over
- * `profile` for any readout keyed to the bot/profile the user is looking
- * at — tab focus moves without swapping the gateway socket. */
++ * the gateway profile for drafts/uncached ids). Compatibility projection
++ * of `focusedSessionOwner`; use the complete owner for source routing. */
+ focusedSessionProfile: readonlyAtom<string>($focusedSessionProfile),
/** Stored (durable) id of the focused session — for navigation and
* session-list matching, where runtime ids don't survive reloads. */
focusedStoredSessionId: readonlyAtom<null | string>($focusedStoredSessionId),
diff --cc apps/desktop/src/sdk/profile-routing.test.ts
index 68a83d45237,da517a37306..1f8f44da948
--- a/apps/desktop/src/sdk/profile-routing.test.ts
+++ b/apps/desktop/src/sdk/profile-routing.test.ts
@@@ -28,8 -28,10 +28,11 @@@ vi.mock('@/store/session', async () =>
$gatewayState: atom('open'),
$messages: atom([]),
$selectedStoredSessionId: atom(null),
+ $sessions: atom([]),
+ rememberedSessionProfile: (_sessions: unknown, _sessionId: null | string, activeProfile: null | string) =>
+ (activeProfile ?? '').trim() || 'default',
requestSessionResume: vi.fn(),
+ setSessionOwnerHint: vi.fn(),
setResumeExhaustedSessionId: vi.fn()
}
})
diff --cc apps/desktop/src/store/session.ts
index 9532c42f429,eff88f92fbd..421e63e23b0
--- a/apps/desktop/src/store/session.ts
+++ b/apps/desktop/src/store/session.ts
@@@ -606,57 -604,6 +606,65 @@@ export interface SessionResumeRequest
}
let sessionResumeRequestSequence = 0
export const $sessionResumeRequest = atom<SessionResumeRequest | null>(null)
+const SESSION_OWNER_HINT_LIMIT = 256
+const sessionOwnerHints = new Map<string, { id: string; route: SessionProfileRoute }>()
+
+function sessionOwnerHintKey(sessionId: string, route: Pick<SessionProfileRoute, 'connectionId' | 'profile'>): string {
+ return JSON.stringify([route.connectionId.trim(), route.profile.trim() || 'default', sessionId])
+}
+
+export function setSessionOwnerHint(sessionId: string, route: SessionProfileRoute): void {
+ const id = sessionId.trim()
+ const normalized = {
+ ...route,
+ connectionId: route.connectionId.trim(),
+ profile: route.profile.trim() || 'default',
+ ...(route.targetProfile ? { targetProfile: route.targetProfile.trim() || 'default' } : {})
+ }
+
+ if (!id || !normalized.connectionId) {
+ return
+ }
+
+ const key = sessionOwnerHintKey(id, normalized)
+ sessionOwnerHints.delete(key)
+ sessionOwnerHints.set(key, { id, route: normalized })
+
+ while (sessionOwnerHints.size > SESSION_OWNER_HINT_LIMIT) {
+ const oldest = sessionOwnerHints.keys().next().value
+
+ if (oldest === undefined) {
+ break
+ }
+
+ sessionOwnerHints.delete(oldest)
+ }
+}
+
++export function getSessionOwnerHints(sessionId: string): SessionProfileRoute[] {
++ const id = sessionId.trim()
++
++ return [...sessionOwnerHints.values()]
++ .filter(entry => entry.id === id)
++ .map(entry => ({ ...entry.route }))
++}
++
+export function getSessionOwnerHint(
+ sessionId: string,
+ scope?: Pick<SessionProfileRoute, 'connectionId' | 'profile'>
+): SessionProfileRoute | undefined {
+ const id = sessionId.trim()
+
+ if (scope) {
+ const entry = sessionOwnerHints.get(sessionOwnerHintKey(id, scope))
+
+ return entry ? { ...entry.route } : undefined
+ }
+
+ const matches = [...sessionOwnerHints.values()].filter(entry => entry.id === id)
+
+ return matches.length === 1 ? { ...matches[0].route } : undefined
+}
// Stored-session id whose resume has EXHAUSTED its bounded auto-retries (the
// terminal-failure latch above kept failing through all MAX_RESUME_RETRIES
// attempts). Distinct from $resumeFailedSessionId, which is armed *during* the