Skip to content

The agent that grows with you

Merge current upstream into hybrid remote Bot routing

Sara Burke052513f65b6d
diff --cc apps/desktop/electron/main.ts
index 0cada4507e3,8acc4e7eeb9..c03190e050f
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@@ -13283,40 -13418,6 +13419,45 @@@ async function pooledRegistrySessionSou
return sources
}
- async function dispatchRegistryApiRequest(request, registryConnectionId, routeProfile = request?.profile) {
++async function dispatchRegistryApiRequest(
++ request,
++ registryConnectionId,
++ routeProfile = request?.profile,
++ requestProfile = 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)
++ ? pathWithProfileScope(request.path, requestProfile)
++ : translateSelfProfileQuery(request.path, requestProfile, 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)
++async function teardownConnectionScopedProfileBackend(connectionId, profile) {
++ const key = backendScopeKey(connectionId, 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
@@@ -13440,20 -13556,6 +13581,21 @@@ 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),
++ dispatch: routeProfile =>
++ dispatchRegistryApiRequest(request, registryConnectionId, routeProfile, deletingProfile),
+ isDefaultProfile: profile => profile === 'default',
+ isValidProfileName: profile => PROFILE_NAME_RE.test(profile),
+ prepareLocal: localRequest => prepareProfileDeleteRequest(localRequest).then(() => undefined),
+ teardownConnection: (connectionId, profile) =>
- teardownConnectionScopedProfileBackend(connectionId, profile, request)
++ teardownConnectionScopedProfileBackend(connectionId, profile)
+ })
+ }
if (!mutatingProfile) {
return handleHermesApiRequest(request)
diff --cc apps/desktop/electron/profile-delete-routing.test.ts
index 7538f63c172,df8ff09a079..b7f3b97e43a
--- a/apps/desktop/electron/profile-delete-routing.test.ts
+++ b/apps/desktop/electron/profile-delete-routing.test.ts
@@@ -152,136 -151,3 +152,171 @@@ 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('non-identity connection DELETE tears down the logical pool and deletes the backend target', async () => {
++ const events: string[] = []
++ const request = {
++ connectionId: 'source-a',
++ method: 'DELETE',
++ path: '/api/profiles/backend-worker',
++ profile: 'worker'
++ }
++
++ await dispatchConnectionScopedProfileDelete(request, {
++ ...deps,
++ acquire: profile => {
++ events.push(`gate:${profile}`)
++ return () => events.push(`release:${profile}`)
++ },
++ connectionKind: () => 'ssh',
++ dispatch: async routeProfile => {
++ events.push(`delete:${request.path}:${routeProfile ?? 'primary'}`)
++ return 'deleted'
++ },
++ prepareLocal: async () => assert.fail('remote deletion must not use local profile teardown'),
++ teardownConnection: async (connectionId, profile) => {
++ events.push(`teardown:${connectionId}:${profile}`)
++ assert.notEqual(profile, 'backend-worker', 'must not stop the backend-target pool')
++ }
++ })
++
++ assert.deepEqual(events, [
++ 'gate:backend-worker',
++ 'teardown:source-a:worker',
++ 'delete:/api/profiles/backend-worker:primary',
++ 'release:backend-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 bf6d25e2d7a,3338fe2420c..39bada976a7
--- a/apps/desktop/electron/profile-delete-routing.ts
+++ b/apps/desktop/electron/profile-delete-routing.ts
@@@ -60,64 -60,6 +60,65 @@@ 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 targetProfile = profileNameFromDeleteRequest(request)
++ const logicalProfile = String(request.profile ?? '').trim() || targetProfile || ''
+ const connectionId = String(request.connectionId ?? '').trim()
+
- if (!profile || !connectionId) {
++ if (!targetProfile || !connectionId) {
+ throw new Error('Connection-scoped profile deletion requires a connection and profile.')
+ }
+
- if (deps.isDefaultProfile(profile)) {
++ if (deps.isDefaultProfile(targetProfile)) {
+ throw new Error('The default profile cannot be deleted.')
+ }
+
- if (!deps.isValidProfileName(profile)) {
- throw new Error(`Invalid profile name: ${profile}`)
++ if (!deps.isValidProfileName(targetProfile)) {
++ throw new Error(`Invalid profile name: ${targetProfile}`)
+ }
+
- const release = deps.acquire(profile)
++ const release = deps.acquire(targetProfile)
+
+ try {
+ if (deps.connectionKind(connectionId) === 'local') {
+ await deps.prepareLocal(request)
+ } else {
- await deps.teardownConnection(connectionId, profile)
++ await deps.teardownConnection(connectionId, logicalProfile)
+ }
+
+ 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/app/chat/index.tsx
index bf5e4d9cc9c,3f45065a562..1a7043c3cdc
--- a/apps/desktop/src/app/chat/index.tsx
+++ b/apps/desktop/src/app/chat/index.tsx
@@@ -46,8 -45,8 +47,8 @@@ import
sessionPinId,
shouldMigrateComposerScope
} from '@/store/session'
- import { sessionTileDelegate } from '@/store/session-states'
+ import { $focusedStoredSessionId, sessionTileDelegate } from '@/store/session-states'
-import { $transcriptTailBySessionId } from '@/store/transcript-tail'
+import { $transcriptTailBySessionId, transcriptTailState } from '@/store/transcript-tail'
import { isAuxiliaryWindow, isWatchWindow } from '@/store/windows'
import type { ModelOptionsResponse } from '@/types/hermes'
diff --cc apps/desktop/src/app/session/hooks/use-session-actions.test.tsx
index 64f8c47c5b4,1ab86bcb92e..7614a5c1f59
--- a/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx
@@@ -159,55 -141,6 +159,55 @@@ function Harness(
return null
}
+describe('connection-qualified session deletion', () => {
+ afterEach(() => {
+ cleanup()
+ setSessions([])
- vi.restoreAllMocks()
++ vi.clearAllMocks()
+ })
+
+ it('deletes a registry session through its captured connection owner', async () => {
+ const requestGateway = vi.fn().mockResolvedValue({})
+ let actions: HarnessHandle | null = null
+
+ setSessions([
+ storedSession({
+ connection_id: 'source-a',
+ id: 'shared-session',
+ profile: 'worker'
+ })
+ ])
+ vi.mocked(deleteSession).mockResolvedValue({ ok: true })
+ vi.mocked(requestGatewayForAgent).mockResolvedValue({} as never)
+
+ render(
+ <Harness
+ activeSessionId="runtime-shared"
+ onReady={value => { actions = value }}
+ requestGateway={requestGateway}
+ selectedStoredSessionId="shared-session"
+ />
+ )
+ await waitFor(() => expect(actions).not.toBeNull())
+
+ await act(async () => {
+ await actions?.removeSession('shared-session')
+ })
+
+ expect(deleteSession).toHaveBeenCalledWith('shared-session', {
+ connectionId: 'source-a',
+ profile: 'worker'
+ })
+ expect(requestGatewayForAgent).toHaveBeenCalledWith(
+ 'source-a',
+ 'worker',
+ 'session.close',
+ { session_id: 'runtime-shared' }
+ )
+ expect(requestGateway).not.toHaveBeenCalledWith('session.close', expect.anything())
+ })
+})
+
function StoredIdRotationHarness({
activeSessionIdRef,
getRoutedStoredSessionId,
diff --cc apps/desktop/src/app/session/hooks/use-session-actions/index.ts
index cf9907e69e3,7cf4646e6b6..001e82b6560
--- a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
@@@ -13,15 -13,15 +13,16 @@@ import { setSessionYolo } from '@/lib/y
import { normalizeChoices, setClarifyRequest } from '@/store/clarify'
import { migrateSessionDraft } from '@/store/composer'
import { clearQueuedPrompts, migrateQueuedPrompts } from '@/store/composer-queue'
-import { openGatewayForAgent, openGatewayForProfile } from '@/store/gateway'
++import { openGatewayForAgent, openGatewayForProfile, requestGatewayForAgent } from '@/store/gateway'
import { $gatewaySwitching } from '@/store/gateway-switch'
- import { requestGatewayForAgent } from '@/store/gateway'
import { $pinnedSessionIds } from '@/store/layout'
import { clearNotifications, notify, notifyError } from '@/store/notifications'
import {
$activeGatewayProfile,
$gatewaySwapTarget,
$newChatProfile,
+ $newChatRoute,
+ $showAllProfiles,
ensureGatewayAgent,
ensureGatewayProfile,
normalizeProfileKey
@@@ -768,16 -743,16 +770,30 @@@ export function useSessionActions(
// A row spliced from a CONNECTED registry gateway (#88880) carries its
// owning connection — activate THAT gateway, not a same-named local
// profile. Rows without the tag keep the legacy profile path.
+ const sessionOwner: SessionOwnerScope = ownerRoute ||
+ (storedForProfile?.connection_id
+ ? {
+ connectionId: storedForProfile.connection_id,
+ profile: sessionProfile || 'default'
+ }
+ : sessionProfile)
+
- if (ownerRoute?.connectionId || storedForProfile?.connection_id) {
- await ensureGatewayAgent(ownerRoute?.connectionId || storedForProfile?.connection_id || null, sessionProfile || 'default')
+ // All-profiles / plugin navigation must not steal chrome API-home:
+ // dial the owning backend without moving $activeGatewayProfile.
+ if ($showAllProfiles.get()) {
- if (storedForProfile?.connection_id) {
- await openGatewayForAgent(storedForProfile.connection_id, sessionProfile || 'default')
++ if (ownerRoute?.connectionId || storedForProfile?.connection_id) {
++ await openGatewayForAgent(
++ ownerRoute?.connectionId || storedForProfile?.connection_id || null,
++ ownerRoute?.profile || sessionProfile || 'default'
++ )
+ } else if (sessionProfile) {
+ await openGatewayForProfile(normalizeProfileKey(sessionProfile))
+ }
- } else if (storedForProfile?.connection_id) {
- await ensureGatewayAgent(storedForProfile.connection_id, sessionProfile || 'default')
++ } else if (ownerRoute?.connectionId || storedForProfile?.connection_id) {
++ await ensureGatewayAgent(
++ ownerRoute?.connectionId || storedForProfile?.connection_id || null,
++ ownerRoute?.profile || sessionProfile || 'default'
++ )
} else {
await ensureGatewayProfile(sessionProfile)
}
@@@ -1761,12 -1737,7 +1785,13 @@@
const closingRuntimeId = wasSelected ? activeSessionId : null
const previousMessages = $messages.get()
const previousPinned = $pinnedSessionIds.get()
+ const removedOwner: SessionOwnerScope = removed?.connection_id
+ ? {
+ connectionId: removed.connection_id,
+ profile: removed.profile || 'default'
+ }
+ : removed?.profile
+ const previousArchived = $archivedSessions.get()
// Pins are keyed on the durable lineage-root id; the stored id may be the
// live tip after compression. Drop both so the pin can't linger.
const removedPinId = removed ? sessionPinId(removed) : storedSessionId
diff --cc apps/desktop/src/plugins/hermes-bots/plugin.js
index ebe1b30f4d3,51ff7ef4cd4..5cb8eb0f97e
--- a/apps/desktop/src/plugins/hermes-bots/plugin.js
+++ b/apps/desktop/src/plugins/hermes-bots/plugin.js
@@@ -132,10 -129,10 +135,11 @@@ function trackInboundActivity(roster)
watermarksSeeded = true
for (const bot of roster) {
+ const key = botSelectionKey(bot)
- const ts = bot.last_session?.last_active || 0
+ const activity = botActivitySession(bot)
+ const ts = activity?.last_active || 0
- const prev = rosterWatermarks.get(bot.name) || 0
- rosterWatermarks.set(bot.name, Math.max(prev, ts))
+ const prev = rosterWatermarks.get(key) || 0
+ rosterWatermarks.set(key, Math.max(prev, ts))
if (seeding || ts <= prev) {
continue
@@@ -158,9 -155,9 +162,9 @@@
// Toasts are opt-in: the unread badge is always set above, but the
// per-message notification fires only when the user enabled it.
if ($activityToasts.get()) {
- const meta = $botMeta.get()[bot.name]
+ const meta = botRosterMeta(bot, $botMeta.get())
const label = displayName(bot, meta)
- const preview = (bot.last_session?.preview || '').trim()
+ const preview = (activity?.preview || '').trim()
const inbound = /^Message from/i.test(preview)
host.notify({
@@@ -180,78 -177,25 +184,73 @@@ const $lastJobs = atom([]
// sessions are room plumbing — neither is a scratch conversation, and a
// 6-member room would otherwise dump six identical "Group: ..." rows into
// recents. Backed by the core generic `hidden` session flag (session.create
--// hidden:true / session.set_hidden); the Bots pane browses them via
--// session.list include_hidden. Older gateways ignore the flag and the
++// hidden:true / session.set_hidden). Older gateways ignore the flag and the
// sessions simply stay visible there.
/** Bot the Routines tile is scoped to. Follows the live gateway profile
* (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)
- const $botSelectedSessions = atom({})
- const $sessionsGatewayGeneration = atom(0)
+ /** Optional secondary navigation inside the Bots pane (group-chat rooms). */
/** Group-chat rooms: { [group]: { log: [{from:{kind,name},text,at}], watermarks:{[member]:idx}, epoch, running } }.
* Log + watermarks persist via plugin storage; epoch/running are runtime-only. */
@@@ -366,75 -316,24 +371,84 @@@ function handleSessionsGatewayTransitio
* { [botName]: { shape, color, title } } */
const $botMeta = atom({})
-/** Freshness fence for the server-meta overlay: the last moment each bot's
- * local meta was written (stamped again once the server write settles).
- * mergeServerMeta refuses to overlay a roster snapshot FETCHED BEFORE this
- * moment — such a snapshot still carries the pre-write ui_meta, and
- * spreading it over local meta resurrects state the user just changed
- * (disbanded groups reappearing as empty roster rows, renames reverting,
- * unpins undoing). Runtime-only by design: on a fresh window there are no
- * in-flight local writes for a stale snapshot to clobber. */
+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) {
+ 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 }
+}
+
++/** Freshness fence for the server-meta overlay: a roster snapshot fetched
++ * before the latest local/server metadata write must not overwrite it. */
+ const botMetaWriteAt = new Map()
+
-function noteBotMetaWrite(name) {
- botMetaWriteAt.set(name, Date.now())
++function noteBotMetaWrite(key) {
++ botMetaWriteAt.set(key, Date.now())
+ }
+
-async function saveBotMeta(name, patch) {
- const prevMeta = $botMeta.get()[name] || {}
- const next = { ...$botMeta.get(), [name]: { ...prevMeta, ...patch } }
- noteBotMetaWrite(name)
+async function saveBotMeta(owner, patch) {
+ const { bot, key, name, route } = botOwner(owner)
+ const prevMeta = $botMeta.get()[key] || {}
+ const next = { ...$botMeta.get(), [key]: { ...prevMeta, ...patch } }
++ noteBotMetaWrite(key)
$botMeta.set(next)
// Local plugin storage: instant, and the fallback for older gateways.
@@@ -508,10 -397,12 +522,14 @@@
} catch {
/* older/unavailable gateway — the local fallback remains saved */
}
+ // Re-stamp now that the server write settled: a roster snapshot fetched
+ // while profiles.configure was still in flight predates the new ui_meta
+ // just as surely as one fetched before the local write.
- noteBotMetaWrite(name)
++ noteBotMetaWrite(key)
}
+ await localPersistence
+
return { serverPersisted: serverOutcome === 'persisted', serverOutcome }
}
@@@ -710,26 -460,52 +728,81 @@@ function fallbackSelectionAfterHide(nam
* setter is a no-op on already-hidden rows) and feature-detected: older
* gateways lack session.set_hidden and simply keep the rows visible. */
function hideOwnedBotSessions() {
+ const roster = $lastRoster.get()
const canonical = Object.entries($botMeta.get())
- .map(([name, meta]) => ({ name, id: meta && meta.chat }))
- .filter(entry => Boolean(entry.id))
- const rooms = Object.values($groupChats.get())
- .flatMap(room => Object.values(room?.sessions || {}))
- .filter(sid => Boolean(sid) && sid !== true)
-
- // A stale local/server pointer must not be trusted merely because it looks
- // like a session id. Resolve every canonical pointer through the backend and
- // require the canonical Bot Chat title before the hide write. This is
- // deliberately fail-closed: an unavailable/old gateway may leave an old
- // Bot Chat visible, but it must never hide an unrelated user conversation.
- const verifiedCanonical = Promise.resolve()
- .then(() =>
- host.request('profiles.list', {
- include_sessions: true,
- preferred_session_ids: Object.fromEntries(canonical.map(entry => [entry.name, entry.id]))
+ .map(([key, meta]) => {
+ const bot = roster.find(candidate => botMetaKey(candidate) === key)
-
+ return meta?.chat && bot ? { bot, id: meta.chat } : null
+ })
+ .filter(Boolean)
+ const canonicalIds = new Set(canonical.map(({ id }) => id))
- const rooms = Object.values($groupChats.get())
- .flatMap(room => Object.values(room?.sessions || {}))
- .filter(sid => Boolean(sid) && sid !== true && !canonicalIds.has(sid))
- const known = Promise.all([
- ...canonical.map(({ bot, id }) =>
- Promise.resolve(requestForBot(bot, 'session.set_hidden', { session_id: id, hidden: true })).catch(() => undefined)
- ),
- ...rooms.map(sid =>
- Promise.resolve(host.request('session.set_hidden', { session_id: sid, hidden: true })).catch(() => undefined)
- )
- ])
++ const rooms = Object.values($groupChats.get()).flatMap(room =>
++ Object.entries(room?.sessions || {})
++ .map(([key, id]) => {
++ if (!id || id === true || canonicalIds.has(id)) {
++ return null
++ }
++
++ const persisted = room?.sessionOwners?.[key]
++ const derived = (room?.members || []).find(member => groupMemberKey(member) === key)
++ // Bare keys are legacy local rooms. A source-qualified key without its
++ // immutable owner is unsafe: never let it fall through ambient routing.
++ const owner = persisted || derived || (!key.includes('::') ? { name: key } : null)
++
++ if (key.includes('::')) {
++ const route = owner?.route
++ const sourceMarked = owner?.sourceScoped || owner?.remoteSource
++ const routeKey = route?.connectionId && route?.profile
++ ? `${route.connectionId}::${route.profile}`
++ : ''
++
++ if (!sourceMarked || !route?.targetProfile || routeKey !== key) {
++ return null
++ }
++ }
++
++ return owner ? { owner, id } : null
+ })
- )
- .then(res => {
- const profiles = Array.isArray(res?.profiles) ? res.profiles : []
- const valid = []
++ .filter(Boolean)
++ )
+
- for (const entry of canonical) {
- const profile = profiles.find(item => item?.name === entry.name)
- const preferred = profile?.preferred_session
++ // Verify every canonical pointer on its immutable source before hiding it.
++ // A stale pointer must never hide an unrelated ordinary conversation.
++ const verifiedCanonical = Promise.all(
++ canonical.map(async entry => {
++ try {
++ const route = botConnectionRoute(entry.bot)
++ const profile = backendTargetProfile(route, entry.bot.name)
++ const res = await requestForBot(entry.bot, 'profiles.list', {
++ include_sessions: true,
++ preferred_session_ids: { [profile]: entry.id }
++ })
++ const preferred = (res?.profiles || []).find(item => item?.name === profile)?.preferred_session
+ const ids = [preferred?.id, preferred?.resolved_id, preferred?.session_id, preferred?.session_key]
+ .filter(Boolean)
+ .map(String)
+
- if (String(preferred?.title || '').trim() === 'Bot Chat' && ids.includes(String(entry.id))) {
- valid.push(entry.id)
- }
++ return String(preferred?.title || '').trim() === 'Bot Chat' && ids.includes(String(entry.id))
++ ? entry
++ : null
++ } catch {
++ return null
+ }
-
- return valid
+ })
- .catch(() => [])
++ )
+
+ const known = verifiedCanonical.then(validCanonical =>
- Promise.all(
- [...new Set([...validCanonical, ...rooms])].map(sid =>
- Promise.resolve(host.request('session.set_hidden', { session_id: sid, hidden: true })).catch(() => undefined)
++ Promise.all([
++ ...validCanonical.filter(Boolean).map(({ bot, id }) =>
++ Promise.resolve(requestForBot(bot, 'session.set_hidden', { session_id: id, hidden: true })).catch(() => undefined)
++ ),
++ ...rooms.map(({ owner, id }) =>
++ Promise.resolve(requestForBot(owner, 'session.set_hidden', { session_id: id, hidden: true })).catch(
++ () => undefined
++ )
+ )
- )
++ ])
+ )
return Promise.all([known, sweepBotProfileSessions().catch(() => undefined)])
}
@@@ -964,8 -739,10 +1045,11 @@@ function mergeServerMeta(roster, fetche
for (const bot of roster) {
const server = bot.ui_meta?.['hermes-bots']
if (server && typeof server === 'object') {
- if (fetchedAt && fetchedAt < (botMetaWriteAt.get(bot.name) || 0)) {
+ const key = botMetaKey(bot)
++ if (fetchedAt && fetchedAt < (botMetaWriteAt.get(key) || 0)) {
+ continue
+ }
- const mine = next[bot.name] || {}
+ const mine = next[key] || {}
const merged = { ...mine, ...server }
// Local-only fields survive the server overlay.
@@@ -3068,15 -2790,15 +3152,20 @@@ function useRoster()
return useQuery({
queryKey: [...ROSTER_KEY, activeConnectionId],
queryFn: async () => {
+ // Stamp the ISSUE time on the snapshot: mergeServerMeta compares it
+ // against each bot's last local meta write, and a fetch issued before
+ // a write can only carry pre-write ui_meta. (Issue time is the
+ // conservative bound — the server answered no earlier than this.)
+ const issuedAt = Date.now()
// Rich rows (last_session, ui_meta, has_avatar) come from the ACTIVE
// gateway's profiles.list — unchanged single-source behavior.
- const pins = preferredSessionIds($botMeta.get())
- const local = await host.request(
+ const route = await activeBotRoute()
+ const activeBot = route
+ ? { name: route.profile, sourceScoped: true, route }
+ : { name: String(host.state.profile?.get?.() || 'default').trim() || 'default' }
+ const pins = preferredSessionIds($botMeta.get(), route)
+ const local = await requestForBot(
+ activeBot,
'profiles.list',
Object.keys(pins).length ? { preferred_session_ids: pins } : {}
)
@@@ -3299,12 -3006,55 +3388,59 @@@ function botHandle(name, bot)
return (name || '').trim().toLowerCase() === 'default' ? 'hermes' : name
}
+ /** Taggable @-forms derived from a bot's friendly names — the core profile
+ * display name (`hermes profile rename`) and the Bot Mode title. Free text
+ * reduces to the mention charset two ways: slugified ("Research Buddy" →
+ * research-buddy, the form autocomplete inserts) and collapsed
+ * (researchbuddy). Reserved tokens are dropped so a bot renamed "Hermes"
+ * can never hijack the primary profile's @hermes alias. */
+ function mentionNameForms(value) {
+ const name = String(value || '').trim().toLowerCase()
+
+ if (!name) {
+ return []
+ }
+
+ const slug = name.replace(/[^a-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '')
+ const collapsed = name.replace(/[^a-z0-9_-]+/g, '')
+
+ return [...new Set([slug, collapsed])].filter(
+ form => /^[a-z0-9][a-z0-9_-]*$/.test(form) && !['all', 'everyone', 'user', 'default', 'hermes'].includes(form)
+ )
+ }
+
+ /** Every friendly (renameable) name a roster row carries: the Bot Mode title
+ * (server-synced via ui_meta, locally stored, or persisted on a durable
+ * group descriptor) and the core profile display_name — in displayName's
+ * precedence order. Remote rows never borrow local meta (two `default`s
+ * must not share a title). */
+ function botFriendlyNames(bot) {
+ const localTitle = !bot?.remoteSource && typeof $botMeta !== 'undefined' ? $botMeta.get()?.[bot?.name]?.title : null
+
+ return [bot?.ui_meta?.['hermes-bots']?.title, localTitle, bot?.title, bot?.display_name]
+ }
+
+ /** The tag autocomplete inserts for a bot: the renamed (friendly) slug when
+ * the user gave the bot a real name, otherwise the profile @handle. The
+ * resolvers accept both, so older muscle memory keeps working. */
+ function botMentionTag(bot) {
+ for (const friendly of botFriendlyNames(bot)) {
+ const forms = mentionNameForms(friendly)
+
+ if (forms.length) {
+ return forms[0]
+ }
+ }
+
+ return botHandle(bot?.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'
@@@ -3411,50 -3150,49 +3556,99 @@@ function resolveRosterMentions(text, ro
const REMOTE_DM_TIMEOUT_MS = 180000
const REMOTE_DM_POLL_MS = 2000
--/** The remote bot's canonical Bot Chat: pinned stored-id from its profile's
-- * ui_meta first, then resume-by-title, then create. Mirrors
-- * ensureGroupChatSession so DMs land in the ONE forever-chat instead of
-- * minting a fresh "Bot Chat" per mention. */
++/** Resolve the remote bot's canonical Bot Chat with the same no-fork rules
++ * as the interactive opener: precise pin verification, title-drift
++ * preservation, exact hidden-title adoption, and minting only after an
++ * authoritative empty adoption scan. Every successful resolution writes the
++ * durable id through the connection-qualified owner metadata. */
async function ensureRemoteCanonicalChat(route, profile) {
-- let pinned = null
+ const backendProfile = route.targetProfile || profile
++ const owner = { name: profile, sourceScoped: true, remoteSource: route.mode !== 'local', route }
++ const listed = await requestForBot(owner, 'profiles.list', {})
++ const profileRow = (listed?.profiles || []).find(row => row?.name === backendProfile)
-- try {
-- const listed = await host.requestProfile(route, 'profiles.list', {})
- const owner = listed?.profiles?.find(p => p.name === backendProfile)
- const owner = listed?.profiles?.find(p => p.name === profile)
-- pinned = owner?.ui_meta?.['hermes-bots']?.chat || null
-- } catch {
-- /* older remote gateway — title lookup below still works */
++ if (!profileRow) {
++ throw new Error(`Remote profile ${backendProfile} could not be resolved`)
}
-- for (const target of [pinned, 'Bot Chat']) {
-- if (!target) {
-- continue
-- }
++ const pinned = profileRow?.ui_meta?.['hermes-bots']?.chat || null
-- try {
-- const res = await host.requestProfile(route, 'session.resume', {
-- session_id: target,
- profile,
++ if (pinned) {
++ const verified = await requestForBot(owner, 'profiles.list', {
++ include_sessions: true,
++ preferred_session_ids: { [backendProfile]: pinned }
++ })
++ const verifiedRow = (verified?.profiles || []).find(row => row?.name === backendProfile)
++ const preferred = verifiedRow?.preferred_session
++
++ // `undefined` is an older/ambiguous resolver, not proof of absence. Try
++ // the immutable pin and surface any failure rather than minting.
++ if (preferred === undefined) {
++ const resumed = await requestForBot(owner, 'session.resume', {
++ session_id: pinned,
+ profile: backendProfile,
omit_messages: true
})
++ if (!resumed?.session_id) {
++ throw new Error(`Remote canonical session ${pinned} did not resume`)
++ }
++ await saveBotMeta(owner, { chat: pinned })
++ return { runtime: resumed.session_id, stored: pinned }
++ }
-- if (res?.session_id) {
-- return { runtime: res.session_id, stored: res.session_key || pinned }
++ // A canonical title or any real history preserves the pin. Real history
++ // covers grandfathered/title-drifted forever chats exactly as the upstream
++ // interactive resolver does.
++ if (preferred && (isCanonicalBotChatHistory(preferred) || Number(preferred.message_count) > 0)) {
++ const resumed = await requestForBot(owner, 'session.resume', {
++ session_id: preferred.resolved_id || preferred.id || pinned,
++ profile: backendProfile,
++ omit_messages: true
++ })
++ if (!resumed?.session_id) {
++ throw new Error(`Remote canonical session ${pinned} did not resume`)
}
-- } catch {
-- /* fall through */
++ await saveBotMeta(owner, { chat: pinned })
++ return { runtime: resumed.session_id, stored: pinned }
+ }
++ // `null` (or an empty non-plumbing draft) is confirmed recovery territory.
+ }
+
- const created = await host.requestProfile(route, 'session.create', {
- profile,
++ // Adopt-before-mint. This exact lookup must succeed: a transient list error
++ // is ambiguous and therefore propagates instead of forking the forever chat.
++ const existingResult = await requestForBot(owner, 'session.list', {
++ profile: backendProfile,
++ title: 'Bot Chat',
++ limit: PROFILE_SESSION_LIST_LIMIT,
++ include_hidden: true
++ })
++ const existing = (existingResult?.sessions || []).find(row => isCanonicalBotChatHistory(row))
++
++ if (existing?.id) {
++ const resumed = await requestForBot(owner, 'session.resume', {
++ session_id: existing.resolved_id || existing.id,
++ profile: backendProfile,
++ omit_messages: true
++ })
++ if (!resumed?.session_id) {
++ throw new Error(`Remote canonical session ${existing.id} did not resume`)
+ }
++ await saveBotMeta(owner, { chat: existing.id })
++ return { runtime: resumed.session_id, stored: existing.id }
+ }
+
- const created = await host.requestProfile(route, 'session.create', {
++ const created = await requestForBot(owner, 'session.create', {
+ profile: backendProfile,
title: 'Bot Chat',
-- // Bot Mode sessions are always hidden from the global sidebar.
hidden: true
})
++ const stored = created?.stored_session_id || null
+
- return { runtime: created?.session_id || null, stored: created?.stored_session_id || null }
++ if (stored) {
++ await saveBotMeta(owner, { chat: stored })
++ }
+
- return { runtime: created?.session_id || null, stored: created?.stored_session_id || null }
++ return { runtime: created?.session_id || null, stored }
}
/** Bounded reply poll on the recipient's session — same shape as a group
@@@ -3729,9 -3358,9 +3923,27 @@@ async function requestForBot(bot, metho
* remote members get the source-qualified key so `dixie` on the Mini and a
* local `dixie` never share watermarks or sessions. */
function groupMemberKey(member) {
- return member?.remoteSource ? botRosterKey(member) : member?.name
+ return member?.sourceScoped || member?.remoteSource ? botRosterKey(member) : member?.name
+}
+
++/** Serializable immutable owner captured beside every group plumbing session. */
++function groupSessionOwner(member) {
++ const route = botConnectionRoute(member)
++ const name = String(route?.profile || member?.name || '').trim() || 'default'
++
++ if (!route) {
++ return { name }
++ }
++
++ return {
++ connectionId: route.connectionId,
++ name,
++ sourceScoped: true,
++ remoteSource: route.mode !== 'local',
++ route: { ...route }
++ }
+ }
+
// Bot metadata is scoped to the active gateway until the server exposes a
// union of rich profile rows. Never paint that metadata onto a thin row from
// another source: two `default` agents must not borrow each other's title,
@@@ -3768,9 -3391,13 +3980,13 @@@ function showsHandle(name, meta, bot)
// In-flight creations, keyed by bot name — double-clicking a row must not
// mint two canonical chats.
const canonicalCreations = new Map()
+
+ /** Upper bound for per-profile session.list scans (hide sweep, canonical-chat
+ * adoption, stored-session lookups). */
+ const PROFILE_SESSION_LIST_LIMIT = 200
let botOpenGeneration = 0
-async function openStoredBotChat(name, storedId, summary) {
+async function openStoredBotChat(owner, storedId, summary) {
if (!storedId || typeof host.openSession !== 'function') {
throw new Error('This Hermes Desktop version cannot open stored sessions')
}
@@@ -3781,8 -3406,13 +3997,14 @@@
typeof summary?.message_count === 'number' && Number.isFinite(summary.message_count)
const expectHistory = hasAuthoritativeCount ? summary.message_count > 0 : true
+ // A profile backend that just woke up can lose the hydration-timeout race
+ // even though the session is fine (hermes-agent#89617) — clicking Retry
+ // succeeds because the backend is warm by then. retryHydrationTimeoutOnce
+ // asks the SDK layer to retry that same wait internally, BEFORE it arms the
+ // core stranded-session overlay: a plugin-side retry can't do this because
+ // only host.openSession sees the resume-exhausted latch that overlay reads.
await host.openSession(storedId, {
+ ...(route ? { route } : {}),
profile: name,
intent: 'main',
awaitHydration: true,
@@@ -3793,21 -3424,67 +4016,69 @@@
return storedId
}
+ /** Adopt-before-mint: the profile may already own a canonical Bot Chat that
+ * the pin lost track of (pin cleared during an outage, ui_meta rolled back,
+ * a fork squatting the title). The core UNIQUE title index guarantees at
+ * most ONE session titled "Bot Chat" per profile db — Profile → Named
+ * Session is an exact registry, so consult it exactly: `title` asks the
+ * gateway for an indexed WHERE title = ? lookup (window-free; a busy
+ * profile can push the forever-chat past any recency window, which would
+ * re-open the fork loop with a higher trigger threshold). Minting while a
+ * "Bot Chat" row exists is always wrong twice over: it forks the
+ * forever-chat AND the new row can never take the (already held) canonical
+ * title, so the next identity check misreads it and forks again — the
+ * infinite-fork loop. An older gateway ignores the unknown `title` param
+ * and returns the plain windowed listing instead — the pre-exact-lookup
+ * behavior — so the local scan below stays as the compatibility rung.
+ * include_hidden is required (canonical chats are always hidden); a gateway
+ * without it simply finds nothing and we fall through to mint. */
-async function findExistingCanonicalChat(name) {
++async function findExistingCanonicalChat(owner) {
++ const { bot, name, route } = botOwner(owner)
+ try {
- const res = await host.request('session.list', {
- profile: name,
++ const res = await requestForBot(bot, 'session.list', {
++ profile: backendTargetProfile(route, name),
+ title: 'Bot Chat',
+ limit: PROFILE_SESSION_LIST_LIMIT,
+ include_hidden: true
+ })
+ const rows = res?.sessions ?? []
+ return rows.find(row => isCanonicalBotChatHistory(row)) || null
+ } catch {
+ return null
+ }
+ }
+
/** Create the bot's ONE forever chat: a real session opened with a kickoff
* message (the gateway prunes zero-message sessions, so the chat is born
* with the bot introducing itself). Pins the stored id in bot meta and
- * returns it. */
+ * returns it. Adopts an existing "Bot Chat" row instead of creating when
+ * the profile already has one (see findExistingCanonicalChat). */
-function createCanonicalChat(name) {
- const inflight = canonicalCreations.get(name)
+function createCanonicalChat(owner) {
+ const { bot, key, name, route } = botOwner(owner)
+ const inflight = canonicalCreations.get(key)
if (inflight) {
return inflight
}
const run = (async () => {
- const existing = await findExistingCanonicalChat(name)
++ const existing = await findExistingCanonicalChat(owner)
+
+ if (existing?.id) {
- saveBotMeta(name, { chat: existing.id })
++ saveBotMeta(owner, { chat: existing.id })
+
+ if (typeof host.openSession === 'function') {
+ // The exact-lookup gateway reports the compression-lineage tip as
+ // resolved_id; the pin stays the durable row id (same split the
+ // preferred_session path uses).
- await openStoredBotChat(name, existing.resolved_id || existing.id, existing)
++ await openStoredBotChat(owner, existing.resolved_id || existing.id, existing)
+ }
+
+ return existing.id
+ }
+
- const res = await host.request('session.create', {
- profile: name,
+ const res = await requestForBot(bot, 'session.create', {
- profile: name,
++ profile: backendTargetProfile(route, name),
title: 'Bot Chat',
// Always born hidden from the global sidebar — Bot Mode sessions are
// plugin-owned. Core applies this via the generic `hidden` flag
@@@ -3828,12 -3505,7 +4099,12 @@@
if (sid && typeof host.openSession === 'function') {
try {
- await host.openSession(sid, { profile: name, intent: 'main', keepAllProfilesScope: true })
+ await host.openSession(sid, {
+ ...(route ? { route } : {}),
+ profile: name,
+ intent: 'main',
- keepAllProfilesScope: false
++ keepAllProfilesScope: true
+ })
opened = true
} catch {
// The stored row may not exist until the kickoff persists it. Retry
@@@ -3845,15 -3517,10 +4116,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, { profile: name, intent: 'main', keepAllProfilesScope: true })
+ await host.openSession(sid, {
+ ...(route ? { route } : {}),
+ profile: name,
+ intent: 'main',
- keepAllProfilesScope: false
++ keepAllProfilesScope: true
+ })
}
} catch {
// The chat already exists. Keep the pin so the next click
@@@ -3882,19 -3550,24 +4154,26 @@@
* 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. */
+ function isCanonicalBotChatHistory(history) {
+ const rootTitle = String(history?.root_title || '').trim()
+ const title = String(history?.title || '').trim()
+ return rootTitle === 'Bot Chat' || (!rootTitle && title === 'Bot Chat')
+ }
+
-async function openBotCanonicalChat(name, pinned, history) {
+async function openBotCanonicalChat(owner, pinned, history) {
+ 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
+ // Grandfather only an actual Bot Chat. `last_session` is merely the most
+ // recent row for the profile; adopting it blindly can claim an unrelated
+ // user conversation and the hide sweep would then hide that conversation.
+ const adoptId = isCanonicalBotChatHistory(history) ? history.id : null
if (adoptId && typeof host.openSession === 'function') {
- await openStoredBotChat(name, adoptId, history)
- saveBotMeta(name, { chat: adoptId })
+ await openStoredBotChat(owner, adoptId, history)
+ saveBotMeta(owner, { chat: adoptId })
return adoptId
}
- return createCanonicalChat(name)
+ return createCanonicalChat(owner)
}
// Precise verification. An older gateway ignores the unknown param and
@@@ -3921,12 -3594,12 +4200,12 @@@
// until proven guilty — try it as-is. A rejected open is still ambiguous:
// it can be the same reconnect/hydration outage that broke this lookup, so
// preserve the forever-chat pin and surface Retry instead of forking it.
- return openStoredBotChat(name, pinned, history)
+ return openStoredBotChat(owner, pinned, history)
}
- if (preferred) {
+ if (preferred && isCanonicalBotChatHistory(preferred)) {
try {
- await openStoredBotChat(name, preferred.resolved_id || preferred.id, preferred)
+ await openStoredBotChat(owner, preferred.resolved_id || preferred.id, preferred)
return pinned
} catch (error) {
// The precise lookup JUST confirmed this session exists, so a failed
@@@ -3937,16 -3610,47 +4216,47 @@@
}
}
+ if (preferred) {
+ // The stored pointer resolved to a real session, but not to Bot Mode's
+ // titled plumbing session. Two legitimate ways to get here, and neither
+ // means "mint a new chat":
+ // - the pin IS the forever-chat but its title drifted (grandfathered
+ // pre-convention chats; the LLM auto-titler renaming an untitled row
+ // after a silent unique-title conflict dropped "Bot Chat"). A pinned
+ // session carrying real history is the user's conversation — forking
+ // away from it silently loses their thread, the exact bug this whole
+ // resolver exists to prevent. The pin is the durable intent: keep it
+ // and open it, even when some other (likely forked) row holds the
+ // "Bot Chat" title. The hide sweep only matches plumbing titles, so
+ // an adopted odd-titled chat is never swept out of the user's
+ // ordinary session list.
+ // - the pin resolves to an EMPTY non-plumbing session (a stray draft):
+ // genuinely corrupted metadata. Clear it — createCanonicalChat then
+ // adopts the profile's existing "Bot Chat" row if one exists before
+ // ever creating a new one.
+ const messageCount = Number(preferred.message_count) || 0
+
+ if (messageCount > 0) {
- await openStoredBotChat(name, preferred.resolved_id || preferred.id, preferred)
++ await openStoredBotChat(owner, preferred.resolved_id || preferred.id, preferred)
+ return pinned
+ }
+
- await saveBotMeta(name, { chat: null })
- return createCanonicalChat(name)
++ await saveBotMeta(owner, { chat: null })
++ return createCanonicalChat(owner)
+ }
+
// Definitively gone (db reset, or the lineage was rewritten past
// recovery): re-anchor on the previewed session when there is one.
- const recoveryId = history?.id
+ // A previewed row is safe to re-anchor only when it is Bot Mode plumbing.
+ // Otherwise a stale pin must not steal the profile's ordinary latest chat.
+ const recoveryId = isCanonicalBotChatHistory(history) ? history.id : null
if (recoveryId && typeof host.openSession === 'function') {
- await openStoredBotChat(name, recoveryId, history)
- saveBotMeta(name, { chat: recoveryId })
+ await openStoredBotChat(owner, recoveryId, history)
+ saveBotMeta(owner, { chat: recoveryId })
return recoveryId
}
- saveBotMeta(name, { chat: null })
- return createCanonicalChat(name)
+ saveBotMeta(owner, { chat: null })
+ return createCanonicalChat(owner)
}
async function prepareBotSource(bot, pinnedChat) {
@@@ -4163,7 -3863,10 +4473,11 @@@ function groupChatMemberBots(group, ros
* here is what keeps the same room intact across machines. */
function durableGroupChatMembers(bots) {
return (bots || []).map(bot => {
+ const route = botConnectionRoute(bot)
+ // Keep the friendly identity on the stored descriptor: after a
+ // connection switch the live roster row may be gone, and renamed-tag
+ // mentions must still resolve against the persisted member.
+ const title = String(botRosterMeta(bot, $botMeta.get())?.title || bot.ui_meta?.['hermes-bots']?.title || bot.title || '').trim()
return {
name: bot.name,
@@@ -4417,6 -4130,6 +4742,7 @@@ function updateGroupChat(group, mutate
log: room.log,
watermarks: room.watermarks,
sessions: room.sessions || {},
++ sessionOwners: room.sessionOwners || {},
// Timed-out turns awaiting a late reply — keyed by member, valued
// with the pre-turn message baseline. Survives reloads so finished
// work is still harvested after a window restart.
@@@ -4481,6 -4195,6 +4808,7 @@@ async function disbandGroupChat(group,
log: room.log,
watermarks: room.watermarks,
sessions: room.sessions || {},
++ sessionOwners: room.sessionOwners || {},
members: Array.isArray(room.members) ? room.members : [],
image: room.image || null
}
@@@ -4500,9 -4214,16 +4828,16 @@@
continue
}
- const meta = $botMeta.get()[member.name] || {}
- await saveBotMeta(member.name, groupMembershipPatch(meta, group, false))
+ const meta = botRosterMeta(member, $botMeta.get()) || {}
+ await saveBotMeta(member, groupMembershipPatch(meta, group, false))
}
+
+ // Converge on server truth: the cached roster still carries the pre-disband
+ // ui_meta (the write-fence in mergeServerMeta keeps it from resurrecting
+ // the membership, but a fresh snapshot is what makes every surface agree).
+ if (typeof queryClient !== 'undefined' && queryClient?.invalidateQueries) {
+ queryClient.invalidateQueries({ queryKey: ROSTER_KEY })
+ }
}
/** Set or clear a group chat's room picture (small data URL, normalized by
@@@ -4643,7 -4374,7 +4988,17 @@@ async function ensureGroupChatSession(g
})
if (res?.session_id) {
-- return { runtime: res.session_id, stored: res.session_key || known }
++ const stored = res.session_key || known
++
++ if (stored) {
++ updateGroupChat(group, current => {
++ current.sessions = { ...(current.sessions || {}), [key]: stored }
++ current.sessionOwners = { ...(current.sessionOwners || {}), [key]: groupSessionOwner(member) }
++ return current
++ })
++ }
++
++ return { runtime: res.session_id, stored }
}
} catch {
/* fall through to create */
@@@ -4661,6 -4392,6 +5016,7 @@@
if (stored) {
updateGroupChat(group, r => {
r.sessions = { ...(r.sessions || {}), [key]: stored }
++ r.sessionOwners = { ...(r.sessionOwners || {}), [key]: groupSessionOwner(member) }
return r
})
}
@@@ -5340,14 -5276,9 +5903,13 @@@ function BotRow({ bot, onDelete, onEdit
// Subscribe on every render. A source switch turns the same keyed row from
// thin to rich; conditionally calling useValue here breaks React hook order.
const unreadByName = useValue($botUnread)
- const unread = !bot.remoteSource && Boolean(unreadByName[bot.name])
- // WHO sent the last message (bot-to-bot DM vs human) — shown in the row
- // preview; the conversation itself lives in the bot's one canonical chat.
+ const unread = Boolean(unreadByName[botSelectionKey(bot)])
+ // WHO sent the last message (bot-to-bot DM vs human) — the full stored
- // history lives in the Sessions workspace (context menu), not inline.
++ // history lives in the canonical chat, not inline.
+ // Preview identity must match click identity (#88200): when the backend
+ // resolved the pinned canonical chat, preview THAT session — not the
+ // profile's most recent (but unrelated) activity. Liveness checks above
+ // keep last_session semantics: any recent activity means the bot is alive.
- const previewSession = bot.preferred_session || last
const { fromBot } = previewKind(previewSession?.preview)
// DM previews read like DMs: strip the delivery prefix, keep the message.
const displayPreview = stripPreviewMarkdown(
@@@ -5579,18 -5526,13 +6141,14 @@@
children: meta?.hidden ? 'Unhide Bot' : 'Hide Bot'
}),
jsx(ContextMenuSeparator, {}),
- jsx(ContextMenuItem, {
- onSelect: () => openBotSessionsWorkspace(bot),
- children: 'Sessions'
- }),
- jsx(ContextMenuItem, { onSelect: () => onEdit(bot), children: 'Edit Profile' }),
- !bot.remoteSource
- ? jsx(ContextMenuItem, {
- onSelect: () => onGroup(bot),
- children: groups.length ? `Groups: ${groups.join(', ')}…` : 'Manage groups…'
- })
- : null,
+ jsx(ContextMenuItem, {
+ onSelect: () => void ensureBotMetadata(bot).then(() => onEdit(bot)).catch(error => host.notifyError?.(error, 'Could not load bot')),
+ children: 'Edit Profile'
+ }),
+ jsx(ContextMenuItem, {
+ onSelect: () => void ensureBotMetadata(bot).then(() => onGroup(bot)).catch(error => host.notifyError?.(error, 'Could not load bot groups')),
+ children: groups.length ? `Groups: ${groups.join(', ')}…` : 'Manage groups…'
+ }),
jsx(ContextMenuItem, {
onSelect: () => {
host.notify({ kind: 'info', message: `Duplicating ${displayName(bot, meta)}…` })
@@@ -10238,15 -10157,10 +10859,9 @@@ function BotsPane()
const staleNotice = error && !live && roster.length
? 'Roster refresh failed — showing the last good list.' + (gatewayUp ? '' : ' Waiting for the gateway to reconnect…')
: null
- const sessionsWorkspaceBot = roster.find(bot => botSelectionKey(bot) === sessionsWorkspaceName)
-
- if (sessionsWorkspaceBot) {
- return jsx(ProfileSessionsWorkspace, { bot: sessionsWorkspaceBot })
- }
--
const groupChatMembers = groupChatName ? groupChatMemberBots(groupChatName, roster, allMeta) : []
- if (groupChatName && groupChatMembers.length) {
+ if (shouldRenderGroupChatInPane(groupChatName) && groupChatMembers.length) {
return jsx(GroupChatWorkspace, { group: groupChatName, members: groupChatMembers })
}
@@@ -10665,6 -10612,6 +11288,7 @@@ export default
log: assignLegacyThreads(room.log),
watermarks: room.watermarks && typeof room.watermarks === 'object' ? room.watermarks : {},
sessions: room.sessions && typeof room.sessions === 'object' ? room.sessions : {},
++ sessionOwners: room.sessionOwners && typeof room.sessionOwners === 'object' ? room.sessionOwners : {},
stranded: room.stranded && typeof room.stranded === 'object' ? room.stranded : {},
members: Array.isArray(room.members) ? room.members : [],
image: typeof room.image === 'string' && room.image ? room.image : null,
diff --cc apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-adopt-before-mint.test.mjs
index 00000000000,06d98252401..610dd28deea
mode 000000,100644..100644
--- a/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-adopt-before-mint.test.mjs
+++ b/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-adopt-before-mint.test.mjs
@@@ -1,0 -1,155 +1,160 @@@
+ import assert from 'node:assert/strict'
+ import { readFileSync } from 'node:fs'
+ import test from 'node:test'
+ import vm from 'node:vm'
+
+ // Regression suite for the infinite-fork loop (hermes-agent#88200 follow-up):
+ // the core UNIQUE title index means at most one session per profile db holds
+ // the "Bot Chat" title. When a fork squats it, every later mint's title is
+ // silently dropped, the LLM titler renames the untitled row, and the next
+ // title-based identity check misreads the fresh chat as "not plumbing" —
+ // clearing the pin and minting again, forever. Two invariants kill the loop:
+ // 1. createCanonicalChat ADOPTS an existing "Bot Chat" row before creating.
+ // 2. A pin that resolves to a NON-plumbing session with real history is the
+ // user's conversation — keep it; only an empty stray draft is replaced.
+
+ const source = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
+ function loadOpenPath({ openSession, request }) {
+ const start = source.indexOf('const canonicalCreations = new Map()')
+ const end = source.indexOf('function displayName(', start)
+ const saved = []
+ const requests = []
+ const context = {
+ host: {
+ openSession,
+ request: async (method, params) => {
+ requests.push({ method, params: JSON.parse(JSON.stringify(params ?? null)) })
+ return request(method, params)
+ }
+ },
++ backendTargetProfile: (route, name) => route?.targetProfile || name,
++ botOwner: owner => typeof owner === 'string'
++ ? { bot: { name: owner }, key: owner, name: owner, route: null }
++ : { bot: owner, key: owner.name, name: owner.name, route: owner.route || null },
++ requestForBot: (_bot, method, params) => context.host.request(method, params),
+ saveBotMeta: (name, patch) => saved.push({ name, patch: JSON.parse(JSON.stringify(patch)) }),
+ $hideBotChats: { get: () => false },
+ window: { setTimeout: callback => callback() }
+ }
+ const section = source
+ .slice(start, end)
+ .concat('\nglobalThis.__open = { createCanonicalChat, openBotCanonicalChat };\n')
+
+ assert.notEqual(start, -1, 'canonical creation section is missing')
+ assert.notEqual(end, -1, 'canonical creation section delimiter is missing')
+ vm.runInNewContext(section, context, { filename: 'canonical-adopt.js' })
+ return { ...context.__open, saved, requests }
+ }
+
+ // ── invariant 1: adopt-before-mint ──────────────────────────────────────────
+
+ test('createCanonicalChat adopts an existing hidden "Bot Chat" row instead of creating', async () => {
+ const runtime = loadOpenPath({
+ openSession: async () => undefined,
+ request: async method => {
+ if (method === 'session.list') {
+ return {
+ sessions: [
+ { id: 'newer-ordinary', title: 'help me with x', message_count: 12 },
+ { id: 'real-forever-chat', title: 'Bot Chat', message_count: 930 }
+ ]
+ }
+ }
+ if (method === 'session.create') {
+ throw new Error('must not create: the profile already owns a Bot Chat')
+ }
+ return {}
+ }
+ })
+
+ assert.equal(await runtime.createCanonicalChat('ops'), 'real-forever-chat')
+ assert.deepEqual(runtime.saved, [{ name: 'ops', patch: { chat: 'real-forever-chat' } }])
+ const list = runtime.requests.find(r => r.method === 'session.list')
+ assert.equal(list?.params?.include_hidden, true,
+ 'adoption scan must see hidden rows — canonical chats are always hidden')
+ })
+
+ test('createCanonicalChat still creates when no Bot Chat row exists', async () => {
+ const runtime = loadOpenPath({
+ openSession: async () => undefined,
+ request: async method => {
+ if (method === 'session.list') {
+ return { sessions: [{ id: 'ordinary', title: 'help me with x', message_count: 3 }] }
+ }
+ if (method === 'session.create') return { stored_session_id: 'fresh-1', session_id: 'rt-1' }
+ return {}
+ }
+ })
+
+ assert.equal(await runtime.createCanonicalChat('newbie'), 'fresh-1')
+ })
+
+ test('createCanonicalChat mints when the adoption scan fails (older gateway)', async () => {
+ const runtime = loadOpenPath({
+ openSession: async () => undefined,
+ request: async method => {
+ if (method === 'session.list') throw new Error('unknown method')
+ if (method === 'session.create') return { stored_session_id: 'fresh-2', session_id: 'rt-2' }
+ return {}
+ }
+ })
+
+ assert.equal(await runtime.createCanonicalChat('legacy'), 'fresh-2')
+ })
+
+ // ── invariant 2: a resolving pin with history is never abandoned ────────────
+
+ test('pin resolving to a renamed session WITH history keeps the pin (no fork)', async () => {
+ const opened = []
+ const runtime = loadOpenPath({
+ openSession: async id => opened.push(id),
+ request: async method => {
+ if (method === 'profiles.list') {
+ return {
+ profiles: [{
+ name: 'ops',
+ preferred_session: {
+ id: 'grandfathered', resolved_id: 'grandfathered',
+ root_title: 'Use computer use to inspect…', title: 'Use computer use to inspect…',
+ message_count: 930
+ }
+ }]
+ }
+ }
+ if (method === 'session.create') throw new Error('must not fork a chat with 930 messages')
+ return {}
+ }
+ })
+
+ assert.equal(await runtime.openBotCanonicalChat('ops', 'grandfathered', null), 'grandfathered')
+ assert.equal(opened.includes('grandfathered'), true)
+ assert.deepEqual(runtime.saved, [], 'pin must not be cleared or rewritten')
+ })
+
+ test('pin resolving to an EMPTY stray draft is replaced via adoption, not a blind mint', async () => {
+ const runtime = loadOpenPath({
+ openSession: async () => undefined,
+ request: async method => {
+ if (method === 'profiles.list') {
+ return {
+ profiles: [{
+ name: 'ops',
+ preferred_session: { id: 'stray', resolved_id: 'stray', root_title: 'Untitled', title: 'Untitled', message_count: 0 }
+ }]
+ }
+ }
+ if (method === 'session.list') {
+ return { sessions: [{ id: 'real-forever-chat', title: 'Bot Chat', message_count: 42 }] }
+ }
+ if (method === 'session.create') throw new Error('must adopt the existing Bot Chat')
+ return {}
+ }
+ })
+
+ assert.equal(await runtime.openBotCanonicalChat('ops', 'stray', null), 'real-forever-chat')
+ assert.deepEqual(runtime.saved, [
+ { name: 'ops', patch: { chat: null } },
+ { name: 'ops', patch: { chat: 'real-forever-chat' } }
+ ])
+ })
diff --cc apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-creation.test.mjs
index 8df1b70b05a,dc468d1f65b..2395bf92625
--- a/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-creation.test.mjs
+++ b/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-creation.test.mjs
@@@ -12,8 -12,6 +12,9 @@@ function loadCanonicalCreation({ openSe
const context = {
host: { openSession, request },
saveBotMeta: (name, patch) => saved.push({ name, patch }),
++ backendTargetProfile: (route, name) => route?.targetProfile || name,
+ 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/hide-bot-chats.test.mjs
index 412f0344f7c,0fc0f261ccb..3b2a67d9796
--- a/apps/desktop/src/plugins/hermes-bots/tests/hide-bot-chats.test.mjs
+++ b/apps/desktop/src/plugins/hermes-bots/tests/hide-bot-chats.test.mjs
@@@ -28,8 -28,6 +28,9 @@@ function loadCreate()
}
},
saveBotMeta: () => {},
++ backendTargetProfile: (route, name) => route?.targetProfile || name,
+ botOwner: name => ({ bot: { name }, key: name, name, route: null }),
+ requestForBot: (_bot, method, params) => context.host.request(method, params),
window: { setTimeout: cb => cb() }
}
const section = source.slice(start, end).concat('\nglobalThis.__c = { createCanonicalChat };\n')
@@@ -65,9 -71,6 +74,11 @@@ test('hideOwnedBotSessions sweeps canon
}
},
$botMeta: { get: () => ({ alpha: { chat: 'chat-a' }, beta: { chat: 'chat-b' }, gamma: {} }) },
+ $lastRoster: { get: () => [{ name: 'alpha' }, { name: 'beta' }] },
++ backendTargetProfile: (route, name) => route?.targetProfile || name,
++ botConnectionRoute: () => null,
+ botMetaKey: bot => bot.name,
+ requestForBot: (_bot, method, params) => context.host.request(method, params),
$groupChats: {
get: () => ({
Core: { sessions: { alpha: 'room-core-a', beta: 'room-core-b' } },
@@@ -80,9 -83,36 +91,151 @@@
vm.runInNewContext(section, context, { filename: 'h.js' })
await context.__h.hideOwnedBotSessions()
- const ids = calls.map(c => c.params.session_id).sort()
+ const ids = calls.filter(c => c.method === 'session.set_hidden').map(c => c.params.session_id).sort()
assert.deepEqual(ids, ['chat-a', 'chat-b', 'room-core-a', 'room-core-b'])
- assert.ok(calls.every(c => c.method === 'session.set_hidden' && c.params.hidden === true))
+ const hiddenCalls = calls.filter(c => c.method === 'session.set_hidden')
+ assert.ok(hiddenCalls.every(c => c.params.hidden === true))
+ })
+
++test('remote group member sessions derive their immutable owner from persisted room members', async () => {
++ const start = source.indexOf('function hideOwnedBotSessions()')
++ const end = source.indexOf('/** Fetch server-side avatars', start)
++ const ambient = []
++ const routed = []
++ const owner = {
++ name: 'worker',
++ sourceScoped: true,
++ route: {
++ connectionId: 'source-a',
++ mode: 'remote',
++ profile: 'worker',
++ targetProfile: 'backend-worker'
++ }
++ }
++ const context = {
++ host: { request: async (method, params) => ambient.push({ method, params }) },
++ $botMeta: { get: () => ({}) },
++ $lastRoster: { get: () => [] },
++ $groupChats: {
++ get: () => ({
++ Core: {
++ sessions: { 'source-a::worker': 'remote-room-1' },
++ members: [owner]
++ }
++ })
++ },
++ groupMemberKey: member => `${member.route.connectionId}::${member.name}`,
++ requestForBot: async (bot, method, params) => routed.push({ bot, method, params }),
++ sweepBotProfileSessions: async () => undefined
++ }
++ const section = source.slice(start, end).concat('\nglobalThis.__h = { hideOwnedBotSessions };\n')
++ vm.runInNewContext(section, context, { filename: 'h-remote.js' })
++
++ await context.__h.hideOwnedBotSessions()
++
++ assert.equal(ambient.some(call => call.method === 'session.set_hidden'), false)
++ assert.equal(routed.length, 1)
++ assert.equal(routed[0].bot.route.connectionId, 'source-a')
++ assert.equal(routed[0].bot.route.targetProfile, 'backend-worker')
++ assert.equal(routed[0].params.session_id, 'remote-room-1')
++})
++
++test('same session id on two remote group owners never hides an ambient collision', async () => {
++ const start = source.indexOf('function hideOwnedBotSessions()')
++ const end = source.indexOf('/** Fetch server-side avatars', start)
++ const ambient = []
++ const routed = []
++ const owner = connectionId => ({
++ name: 'worker',
++ sourceScoped: true,
++ route: { connectionId, mode: 'remote', profile: 'worker', targetProfile: 'backend-worker' }
++ })
++ const ownerA = owner('source-a')
++ const ownerB = owner('source-b')
++ const context = {
++ host: { request: async (method, params) => ambient.push({ method, params }) },
++ $botMeta: { get: () => ({}) },
++ $lastRoster: { get: () => [] },
++ $groupChats: {
++ get: () => ({
++ A: { sessions: { 'source-a::worker': 'same-id' }, sessionOwners: { 'source-a::worker': ownerA } },
++ B: { sessions: { 'source-b::worker': 'same-id' }, sessionOwners: { 'source-b::worker': ownerB } }
++ })
++ },
++ groupMemberKey: member => `${member.route.connectionId}::${member.name}`,
++ requestForBot: async (bot, method, params) => routed.push({ bot, method, params }),
++ sweepBotProfileSessions: async () => undefined
++ }
++ const section = source.slice(start, end).concat('\nglobalThis.__h = { hideOwnedBotSessions };\n')
++ vm.runInNewContext(section, context, { filename: 'h-collision.js' })
++
++ await context.__h.hideOwnedBotSessions()
++
++ assert.equal(ambient.some(call => call.method === 'session.set_hidden'), false)
++ assert.deepEqual(routed.map(call => call.bot.route.connectionId).sort(), ['source-a', 'source-b'])
++ assert.ok(routed.every(call => call.params.session_id === 'same-id'))
++})
++
++test('malformed persisted owner for a source-qualified group session fails closed', async () => {
++ const start = source.indexOf('function hideOwnedBotSessions()')
++ const end = source.indexOf('/** Fetch server-side avatars', start)
++ const ambient = []
++ const routed = []
++ const context = {
++ host: { request: async (method, params) => ambient.push({ method, params }) },
++ $botMeta: { get: () => ({}) },
++ $lastRoster: { get: () => [] },
++ $groupChats: {
++ get: () => ({
++ LegacyRemote: {
++ sessions: { 'source-a::worker': 'same-id' },
++ sessionOwners: { 'source-a::worker': { name: 'worker' } }
++ }
++ })
++ },
++ groupMemberKey: member => member?.name,
++ requestForBot: async (bot, method, params) => routed.push({ bot, method, params }),
++ sweepBotProfileSessions: async () => undefined
++ }
++ const section = source.slice(start, end).concat('\nglobalThis.__h = { hideOwnedBotSessions };\n')
++ vm.runInNewContext(section, context, { filename: 'h-malformed-owner.js' })
++
++ await context.__h.hideOwnedBotSessions()
++
++ assert.equal(ambient.some(call => call.method === 'session.set_hidden'), false)
++ assert.equal(routed.length, 0)
++})
++
+ test('safety: a stale canonical pointer to an ordinary session is not hidden', async () => {
+ const start = source.indexOf('function hideOwnedBotSessions()')
+ const end = source.indexOf('/** Fetch server-side avatars', start)
+ const calls = []
+ const context = {
+ host: {
+ request: async (method, params) => {
+ calls.push({ method, params })
+ if (method === 'profiles.list') {
+ return {
+ profiles: [{ name: 'default', preferred_session: { id: 'ordinary-1', title: '生产调度会优化' } }]
+ }
+ }
+ return {}
+ }
+ },
+ $botMeta: { get: () => ({ default: { chat: 'ordinary-1' } }) },
- $groupChats: { get: () => ({}) }
++ $groupChats: { get: () => ({}) },
++ $lastRoster: { get: () => [{ name: 'default' }] },
++ backendTargetProfile: (route, name) => route?.targetProfile || name,
++ botConnectionRoute: () => null,
++ botMetaKey: bot => bot.name,
++ requestForBot: (_bot, method, params) => context.host.request(method, params),
++ sweepBotProfileSessions: async () => undefined
+ }
+ const section = source.slice(start, end).concat('\nglobalThis.__h = { hideOwnedBotSessions };\n')
+ vm.runInNewContext(section, context, { filename: 'h-stale.js' })
+ await context.__h.hideOwnedBotSessions()
+
+ assert.equal(calls.some(c => c.method === 'session.set_hidden'), false)
})
test('sweepBotProfileSessions hides Bot-Mode-titled rows per roster bot, and only those', async () => {
@@@ -145,9 -175,11 +298,14 @@@ test('hideOwnedBotSessions chains the o
assert.match(source, /return Promise\.all\(\[known, sweepBotProfileSessions\(\)\.catch\(\(\) => undefined\)\]\)/)
})
- test('the Bots session browser lists with include_hidden', () => {
- // The one session.list consumer that must see the always-hidden rows.
- // (Canonical-chat recovery now goes through profiles.list
+ test('the canonical-chat adoption scan lists with include_hidden', () => {
+ // The one session.list consumer that must see the always-hidden rows:
+ // findExistingCanonicalChat (adopt-before-mint) — canonical Bot Chats are
+ // born hidden, so a visible-only scan would miss the very row whose
+ // existence forbids minting. (Pin recovery goes through profiles.list
// preferred_session_ids, whose resolver already sees hidden rows.)
- assert.match(source, /requestForBot\(owner, 'session\.list',[\s\S]*include_hidden: true/)
- assert.match(source, /include_hidden: true\s*\}\)\s*const rows = res\?\.sessions \?\? \[\]\s*return rows\.find\(row => isCanonicalBotChatHistory\(row\)\)/)
++ assert.match(
++ source,
++ /requestForBot\(bot, 'session\.list',[\s\S]*title: 'Bot Chat',[\s\S]*include_hidden: true[\s\S]*return rows\.find\(row => isCanonicalBotChatHistory\(row\)\)/
++ )
})
diff --cc apps/desktop/src/plugins/hermes-bots/tests/remote-dm-delivery.test.mjs
index 669e0fbc80f,d864d637ce5..24e5fada4b9
--- 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
@@@ -58,7 -58,7 +58,18 @@@ test('remote DM resumes the pinned cano
calls.push([method, params])
if (method === 'profiles.list') {
-- return { profiles: [{ name: 'dixie', ui_meta: { 'hermes-bots': { chat: 'stored-42' } } }] }
++ return {
++ profiles: [{
++ name: 'dixie',
++ ui_meta: { 'hermes-bots': { chat: 'stored-42' } },
++ preferred_session: {
++ id: 'stored-42',
++ resolved_id: 'stored-42',
++ title: 'Bot Chat',
++ message_count: 20
++ }
++ }]
++ }
}
if (method === 'session.resume' && params.session_id === 'stored-42') {
@@@ -83,16 -83,16 +94,158 @@@
assert.ok(!calls.some(([method]) => method === 'session.create'), 'must not mint a fresh session when the pin resumes')
})
++test('remote DM fails closed on transient profile lookup without minting', async () => {
++ const calls = []
++ const ctx = runtime({
++ requestProfile: async (_route, method) => {
++ calls.push(method)
++ if (method === 'profiles.list') throw new Error('gateway reconnecting')
++ if (method === 'session.create') throw new Error('must not mint during an ambiguous lookup')
++ return {}
++ }
++ })
++
++ await assert.rejects(
++ ctx.__dm.ensureRemoteCanonicalChat(
++ { connectionId: 'source-a', mode: 'remote', profile: 'worker', targetProfile: 'backend-worker' },
++ 'worker'
++ ),
++ /gateway reconnecting/
++ )
++ assert.equal(calls.includes('session.create'), false)
++})
++
++test('remote DM fails closed on transient pinned resume without minting', async () => {
++ const calls = []
++ const ctx = runtime({
++ requestProfile: async (_route, method) => {
++ calls.push(method)
++ if (method === 'profiles.list') {
++ return {
++ profiles: [{
++ name: 'backend-worker',
++ ui_meta: { 'hermes-bots': { chat: 'stored-pin' } },
++ preferred_session: { id: 'stored-pin', title: 'Bot Chat', message_count: 10 }
++ }]
++ }
++ }
++ if (method === 'session.resume') throw new Error('resume unavailable')
++ if (method === 'session.create') throw new Error('must not replace a confirmed pin')
++ return {}
++ }
++ })
++
++ await assert.rejects(
++ ctx.__dm.ensureRemoteCanonicalChat(
++ { connectionId: 'source-a', mode: 'remote', profile: 'worker', targetProfile: 'backend-worker' },
++ 'worker'
++ ),
++ /resume unavailable/
++ )
++ assert.equal(calls.includes('session.create'), false)
++})
++
++test('remote DM reuses a pinned title-drifted chat with history', async () => {
++ const calls = []
++ const ctx = runtime({
++ requestProfile: async (_route, method, params) => {
++ calls.push({ method, params })
++ if (method === 'profiles.list') {
++ return {
++ profiles: [{
++ name: 'backend-worker',
++ ui_meta: { 'hermes-bots': { chat: 'stored-pin' } },
++ preferred_session: {
++ id: 'stored-pin',
++ resolved_id: 'stored-tip',
++ title: 'Investigate disk pressure',
++ message_count: 44
++ }
++ }]
++ }
++ }
++ if (method === 'session.resume') {
++ assert.equal(params.session_id, 'stored-tip')
++ return { session_id: 'runtime-tip', session_key: 'stored-pin' }
++ }
++ if (method === 'session.create') throw new Error('must not fork title-drifted history')
++ return {}
++ }
++ })
++
++ const resolved = await ctx.__dm.ensureRemoteCanonicalChat(
++ { connectionId: 'source-a', mode: 'remote', profile: 'worker', targetProfile: 'backend-worker' },
++ 'worker'
++ )
++ assert.equal(resolved.runtime, 'runtime-tip')
++ assert.equal(resolved.stored, 'stored-pin')
++ assert.equal(calls.some(call => call.method === 'session.create'), false)
++})
++
++test('remote DM adopts the exact hidden Bot Chat before minting', async () => {
++ const calls = []
++ const route = { connectionId: 'source-a', mode: 'remote', profile: 'worker', targetProfile: 'backend-worker' }
++ const ctx = runtime({
++ requestProfile: async (capturedRoute, method, params) => {
++ calls.push({ capturedRoute, method, params })
++ if (method === 'profiles.list') return { profiles: [{ name: 'backend-worker', ui_meta: {} }] }
++ if (method === 'session.list') {
++ return { sessions: [{ id: 'existing-chat', resolved_id: 'existing-tip', title: 'Bot Chat' }] }
++ }
++ if (method === 'session.resume') {
++ return { session_id: 'runtime-existing', session_key: 'existing-chat' }
++ }
++ if (method === 'session.create') throw new Error('must adopt before minting')
++ return {}
++ }
++ })
++
++ const resolved = await ctx.__dm.ensureRemoteCanonicalChat(route, 'worker')
++ assert.equal(resolved.runtime, 'runtime-existing')
++ assert.equal(resolved.stored, 'existing-chat')
++ const scan = calls.find(call => call.method === 'session.list')
++ assert.equal(scan.params.title, 'Bot Chat')
++ assert.equal(scan.params.include_hidden, true)
++ assert.equal(calls.some(call => call.method === 'session.create'), false)
++})
++
++test('remote DM persists a newly resolved canonical id through connection-qualified metadata', async () => {
++ const calls = []
++ const route = { connectionId: 'source-a', mode: 'remote', profile: 'worker', targetProfile: 'backend-worker' }
++ const ctx = runtime({
++ requestProfile: async (capturedRoute, method, params) => {
++ calls.push({ capturedRoute, method, params })
++ if (method === 'profiles.list') return { profiles: [{ name: 'backend-worker', ui_meta: {} }] }
++ if (method === 'session.list') return { sessions: [] }
++ if (method === 'session.create') return { session_id: 'runtime-new', stored_session_id: 'stored-new' }
++ return {}
++ }
++ })
++
++ const resolved = await ctx.__dm.ensureRemoteCanonicalChat(route, 'worker')
++ assert.equal(resolved.runtime, 'runtime-new')
++ assert.equal(resolved.stored, 'stored-new')
++ const persisted = calls.find(call => call.method === 'profiles.configure')
++ assert.equal(persisted.capturedRoute.connectionId, 'source-a')
++ assert.equal(persisted.capturedRoute.profile, 'worker')
++ assert.equal(persisted.params.name, 'backend-worker')
++ assert.equal(persisted.params.ui_meta['hermes-bots'].chat, 'stored-new')
++})
++
test('remote DM carries sender attribution and relays the reply', async () => {
const submits = []
const notices = []
const ctx = runtime({
requestProfile: async (route, method, params) => {
if (method === 'profiles.list') {
-- return { profiles: [] }
++ return { profiles: [{ name: 'dixie', ui_meta: {} }] }
+ }
+
- if (method === 'session.resume' && params.session_id === 'Bot Chat' && params.omit_messages) {
++ if (method === 'session.list') {
++ return { sessions: [{ id: 'stored-1', resolved_id: 'stored-1', title: 'Bot Chat' }] }
+ }
+
- if (method === 'session.resume' && params.session_id === 'Bot Chat' && params.omit_messages) {
++ if (method === 'session.resume' && params.session_id === 'stored-1' && params.omit_messages) {
return { session_id: 'runtime-1', session_key: 'stored-1' }
}
diff --cc apps/desktop/src/plugins/hermes-bots/tests/remote-routing-races.test.mjs
index e1739966f73,00000000000..f39e46ec915
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,647 -1,0 +1,625 @@@
+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
++ setPluginStorage: storage => { pluginCtx = { storage } }
+ }
+ `)
+ 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 = [],
+ 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 && 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/sdk/index.ts
index 1582f8a9506,6b83836be6a..c43b66b2cea
--- a/apps/desktop/src/sdk/index.ts
+++ b/apps/desktop/src/sdk/index.ts
@@@ -282,7 -228,12 +284,13 @@@ export interface PluginOpenSessionOptio
intent?: OpenSessionIntent
keepAllProfilesScope?: boolean
profile?: null | string
+ route?: PluginProfileRoute
+ /** A cold profile backend can lose the hydration-timeout race once and still
+ * be fine on a second try. When set, a hydration timeout is retried
+ * internally before it reaches the caller or arms the core stranded-session
+ * overlay ($resumeExhaustedSessionId) — a caller-side retry can't do this
+ * itself because only this SDK layer sees $resumeExhaustedSessionId. */
+ retryHydrationTimeoutOnce?: boolean
}
function waitForFocusedSessionHydration({
@@@ -334,8 -285,7 +344,8 @@@
return
}
- const profileMatches = normalizeProfileKey($activeGatewayProfile.get()) === profile
+ const profileMatches = !requireActiveProfile || normalizeProfileKey($activeGatewayProfile.get()) === profile
+ const connectionMatches = !connectionId || $activeConnectionId.get() === connectionId
const sessionMatches = $selectedStoredSessionId.get() === storedSessionId
const runtimeReady = Boolean($activeSessionId.get())
const historyPainted = Boolean($messages.get().length)
@@@ -510,11 -489,8 +570,14 @@@ export const host =
// A hover-warmed Bot Mode row owns a retained renderer socket. Retire it
// before Electron stops the profile backend so the socket closure cannot
// schedule a reconnect that resurrects the deleted profile.
- retireLocalProfileGateways(name)
- await deleteProfile(name)
+ if (!route || route.mode === 'local') {
+ retireLocalProfileGateways(targetProfile)
+ }
+
- await deleteProfile(targetProfile, route ? { connectionId: route.connectionId, profile: targetProfile } : undefined)
++ await deleteProfile(
++ targetProfile,
++ route ? { connectionId: route.connectionId, profile: route.profile } : undefined
++ )
// The profile rail paints from the shared $profiles cache; without a
// refresh the deleted profile's badge survives and clicking it starts a
@@@ -580,93 -559,151 +646,161 @@@
ensureAgent: async (connectionId: null | string, profile: string): Promise<void> =>
ensureGatewayAgent(connectionId, (profile ?? '').trim() || 'default'),
+ /** Open a stored session the way core surfaces do. A plugin/Bot Mode open
+ * is navigation, not a workspace or chrome API-home switch —
+ * keepAllProfilesScope defaults true so `$activeGatewayProfile` /
+ * Sessions REST stay on the previous (usually launch) backend while the
+ * bot backend is dialed in the background. The bot forever-chat is hidden
+ * and would otherwise look like every session disappeared. Pass false to
+ * also scope chrome onto that profile and collapse the sidebar. */
openSession: async (storedSessionId: string, options: PluginOpenSessionOptions = {}): Promise<void> => {
const generation = ++openSessionGeneration
- const profile = (options.profile ?? '').trim()
+ const ownerRoute = options.route ? { ...options.route } : null
+ const profile = (ownerRoute?.profile ?? options.profile ?? '').trim()
const targetProfile = normalizeProfileKey(profile || $activeGatewayProfile.get())
const expectHistory = options.expectHistory ?? false
+
+ const plan = planPluginOpenSession({
+ activeProfile: $activeGatewayProfile.get(),
+ keepAllProfilesScope: options.keepAllProfilesScope,
+ profile
+ })
+
// Wake-path phase timings. Logged ONLY on a hydration timeout (bridged
// into desktop.log via the renderer-console tap), so a support bundle
// pinpoints WHERE the budget went — profile activation vs hydration —
// instead of leaving us to infer it from process spawn timestamps.
const wakeStartedAt = Date.now()
let profileActiveAt = wakeStartedAt
+ const hydrationTimeoutMs = Math.max(1, options.hydrationTimeoutMs ?? DEFAULT_SESSION_HYDRATION_TIMEOUT_MS)
+ // Which half of the wake a timeout landed in. Only meaningful on the
+ // failure path, where the two phases have different remedies: a stuck dial
+ // is a gateway problem, a slow transcript is a backend-warmup one.
+ let wakePhase: 'activation' | 'hydration' = 'activation'
+ if (ownerRoute) {
- await ensureGatewayAgent(ownerRoute.connectionId, ownerRoute.profile)
+ setSessionOwnerHint(storedSessionId, ownerRoute)
- profileActiveAt = Date.now()
++ }
+
- if (options.keepAllProfilesScope !== false) {
- setShowAllProfiles(true)
+ // Bounded to 2 attempts (never more): a cold profile backend can lose the
+ // hydration-timeout race once and still be fine moments later, but this is
+ // a caller-opt-in retry of the SAME wait, not a backoff loop.
+ const maxAttempts = options.awaitHydration && options.retryHydrationTimeoutOnce ? 2 : 1
+
+ try {
+ // WHICH backend to dial is the plan's call; HOW LONG to wait is the wake
+ // budget's. A workspace switch moves $activeGatewayProfile / chrome REST;
+ // a plain navigation only opens the bot's gateway so session.resume can
+ // hydrate, leaving chrome on the launch backend.
- const dial = plan.switchWorkspace
- ? () => ensureGatewayProfile(plan.switchWorkspace as string)
- : plan.dialWithoutSwitching
- ? () => openGatewayForProfile(plan.dialWithoutSwitching as string)
- : null
++ const dial = ownerRoute
++ ? () => openGatewayForAgent(ownerRoute.connectionId, ownerRoute.profile)
++ : plan.switchWorkspace
++ ? () => ensureGatewayProfile(plan.switchWorkspace as string)
++ : plan.dialWithoutSwitching
++ ? () => openGatewayForProfile(plan.dialWithoutSwitching as string)
++ : null
+
+ if (dial) {
+ // Bounded only on the hydration contract, which is where a budget and a
+ // Retry surface both already exist. A plain open never asked for a
+ // deadline and has nowhere to render one, so it keeps today's
+ // behaviour rather than gaining a rejection its callers cannot handle.
+ await (options.awaitHydration ? awaitProfileActivation(dial, targetProfile, hydrationTimeoutMs) : dial())
+ profileActiveAt = Date.now()
}
- } else if (profile && profile !== $activeGatewayProfile.get()) {
- await ensureGatewayProfile(profile)
- profileActiveAt = Date.now()
- if (options.keepAllProfilesScope !== false) {
- if (plan.showAllProfiles !== null) {
++ if (ownerRoute) {
+ setShowAllProfiles(true)
++ } else if (plan.showAllProfiles !== null) {
+ setShowAllProfiles(plan.showAllProfiles)
}
- }
-
- if (generation !== openSessionGeneration) {
- throw new Error('Session open was superseded by a newer selection.')
- }
- if (options.awaitHydration) {
- // Keep the target-specific overlay visible through transcript hydration,
- // not merely through the gateway/profile activation that precedes it.
- $gatewaySwapTarget.set(targetProfile)
- }
+ wakePhase = 'hydration'
- try {
- openSession(
- storedSessionId,
- (to: string, opts?: { replace?: boolean }) => {
- const target = to.startsWith('#') ? to : `#${to}`
-
- if (opts?.replace) {
- window.location.replace(target)
- } else {
- window.location.hash = target
- }
- },
- options.intent ?? 'in-place'
- )
-
- // Judge the main surface AFTER the open: on a cold start the persisted
- // route can already point at this session while selection has not
- // settled, so a pre-open "already selected" precondition skips the
- // resume exactly when it is needed (#89206 — blank Bot Chat with the
- // roster preview intact). The surface is healthy only when this stored
- // session is selected, a runtime is bound, and the expected transcript
- // is present; anything less gets an explicit sequenced resume request.
- // The route-resume effect only honors the request while the route
- // points at this session, and consumes it alongside any resume the
- // navigation itself triggers, so a redundant request is a no-op.
- const surfaceHealthy =
- $selectedStoredSessionId.get() === storedSessionId &&
- Boolean($activeSessionId.get()) &&
- (!expectHistory || $messages.get().length > 0)
-
- if (options.awaitHydration && !surfaceHealthy) {
- if (ownerRoute) {
- requestSessionResume(storedSessionId, ownerRoute)
- } else {
- requestSessionResume(storedSessionId)
- }
+ if (generation !== openSessionGeneration) {
+ throw new Error('Session open was superseded by a newer selection.')
}
if (options.awaitHydration) {
- await waitForFocusedSessionHydration({
- connectionId: ownerRoute?.connectionId,
- expectHistory,
- generation,
- profile: targetProfile,
- storedSessionId,
- timeoutMs: Math.max(1, options.hydrationTimeoutMs ?? DEFAULT_SESSION_HYDRATION_TIMEOUT_MS)
- })
+ // Keep the target-specific overlay visible through transcript hydration,
+ // not merely through the gateway/profile activation that precedes it.
+ $gatewaySwapTarget.set(targetProfile)
+ }
+
+ // Only the HYDRATION half retries. Activation already failed its own
+ // bounded wait above, and a wedged dial does not get better by dialling
+ // again inside the same wake — that is the Retry surface's job.
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
+ try {
+ openSession(
+ storedSessionId,
+ (to: string, opts?: { replace?: boolean }) => {
+ const target = to.startsWith('#') ? to : `#${to}`
+
+ if (opts?.replace) {
+ window.location.replace(target)
+ } else {
+ window.location.hash = target
+ }
+ },
+ options.intent ?? 'in-place'
+ )
+
+ // Judge the main surface AFTER the open: on a cold start the persisted
+ // route can already point at this session while selection has not
+ // settled, so a pre-open "already selected" precondition skips the
+ // resume exactly when it is needed (#89206 — blank Bot Chat with the
+ // roster preview intact). The surface is healthy only when this stored
+ // session is selected, a runtime is bound, and the expected transcript
+ // is present; anything less gets an explicit sequenced resume request.
+ // The route-resume effect only honors the request while the route
+ // points at this session, and consumes it alongside any resume the
+ // navigation itself triggers, so a redundant request is a no-op.
+ const surfaceHealthy =
+ $selectedStoredSessionId.get() === storedSessionId &&
+ Boolean($activeSessionId.get()) &&
+ (!expectHistory || $messages.get().length > 0)
+
+ if (options.awaitHydration && !surfaceHealthy) {
- requestSessionResume(storedSessionId)
++ requestSessionResume(storedSessionId, ownerRoute || undefined)
+ }
+
+ if (options.awaitHydration) {
+ await waitForFocusedSessionHydration({
++ connectionId: ownerRoute?.connectionId,
+ expectHistory,
+ generation,
+ profile: targetProfile,
+ // A background dial never moves $activeGatewayProfile, so gating
+ // hydration on it would wait for something that is not coming.
- requireActiveProfile: plan.requireActiveProfileForHydration,
++ requireActiveProfile: ownerRoute ? false : plan.requireActiveProfileForHydration,
+ storedSessionId,
+ timeoutMs: hydrationTimeoutMs
+ })
+ }
+
+ break
+ } catch (error) {
+ const retryable =
+ options.awaitHydration &&
+ generation === openSessionGeneration &&
+ attempt < maxAttempts &&
+ error instanceof Error &&
+ error.message.startsWith('Timed out loading ')
+
+ if (!retryable) {
+ throw error
+ }
+
+ // Logged per attempt so a support bundle shows the retry happened at
+ // all; the terminal failure is reported once by the catch below.
+ console.warn('[bot-wake] hydration timed out, retrying', {
+ attempt,
+ hydrationWaitMs: Date.now() - profileActiveAt,
+ profile: targetProfile,
+ storedSessionId
+ })
+ }
}
} catch (error) {
if (
diff --cc apps/desktop/src/sdk/profile-routing.test.ts
index 1f8f44da948,56f28f6cc18..d6a041b9656
--- a/apps/desktop/src/sdk/profile-routing.test.ts
+++ b/apps/desktop/src/sdk/profile-routing.test.ts
@@@ -104,10 -102,18 +104,23 @@@ vi.mock('@/store/gateway', async () =>
const { host } = await import('./index')
const { openSession: openSessionCore } = await import('@/app/open-session')
const { deleteProfile } = await import('@/hermes')
- const { requestGatewayForAgent, requestGatewayForProfile, retireLocalProfileGateways } = await import('@/store/gateway')
- const { $activeGatewayProfile, $gatewaySwapTarget, $profiles, ensureGatewayAgent, ensureGatewayProfile, refreshProfiles } =
- await import('@/store/profile')
-const { openGatewayForProfile, requestGatewayForAgent, requestGatewayForProfile, retireLocalProfileGateways } =
- await import('@/store/gateway')
++const {
++ openGatewayForAgent,
++ openGatewayForProfile,
++ requestGatewayForAgent,
++ requestGatewayForProfile,
++ retireLocalProfileGateways
++} = await import('@/store/gateway')
+
+ const {
+ $activeGatewayProfile,
+ $gatewaySwapTarget,
+ $profiles,
+ ensureGatewayProfile,
+ refreshProfiles,
+ setShowAllProfiles
+ } = await import('@/store/profile')
const { $focusedRuntimeId, $focusedSessionState, $focusedStoredSessionId } = await import('@/store/session-states')
@@@ -234,89 -234,6 +247,89 @@@ describe('connection-aware plugin host
expect(requestGatewayForProfile).not.toHaveBeenCalled()
})
+ it('fails closed when a descriptor omits connection or target profile identity', async () => {
+ await expect(
+ host.requestProfile(
+ { connectionId: '', mode: 'remote', profile: 'worker', targetProfile: 'worker' },
+ 'profiles.configure',
+ {}
+ )
+ ).rejects.toThrow(/connectionId, profile, and targetProfile/)
+ await expect(
+ host.requestProfile(
+ { connectionId: 'source-a', mode: 'remote', profile: 'worker', targetProfile: '' },
+ 'profiles.configure',
+ {}
+ )
+ ).rejects.toThrow(/connectionId, profile, and targetProfile/)
+
+ expect(requestGatewayForAgent).not.toHaveBeenCalled()
+ expect(requestGatewayForProfile).not.toHaveBeenCalled()
+ })
+
+ it('deletes a remote profile through its captured connection without retiring local pools', async () => {
+ const route = {
+ connectionId: 'source-a',
+ mode: 'remote' as const,
+ profile: 'worker',
+ targetProfile: 'backend-worker'
+ }
+ vi.mocked(deleteProfile).mockResolvedValueOnce({ ok: true, path: '/profiles/backend-worker' })
+
+ await host.deleteProfile(route)
+
+ expect(deleteProfile).toHaveBeenCalledWith('backend-worker', {
+ connectionId: 'source-a',
- profile: 'backend-worker'
++ profile: 'worker'
+ })
+ expect(retireLocalProfileGateways).not.toHaveBeenCalled()
+ })
+
+ it('rejects a remote deletion route without a connection id', async () => {
+ await expect(
+ host.deleteProfile({
+ connectionId: '',
+ mode: 'remote',
+ profile: 'worker',
+ targetProfile: 'backend-worker'
+ })
+ ).rejects.toThrow(/connectionId, profile, and targetProfile/)
+
+ expect(deleteProfile).not.toHaveBeenCalled()
+ expect(retireLocalProfileGateways).not.toHaveBeenCalled()
+ })
+
+ it('rejects an alias to backend default before the transport helper runs', async () => {
+ await expect(
+ host.deleteProfile({
+ connectionId: 'source-a',
+ mode: 'remote',
+ profile: 'worker',
+ targetProfile: 'default'
+ })
+ ).rejects.toThrow(/default profile cannot be deleted/i)
+
+ expect(deleteProfile).not.toHaveBeenCalled()
+ })
+
+ it('retires and deletes a local alias by its backend target profile', async () => {
+ const route = {
+ connectionId: 'source-local',
+ mode: 'local' as const,
+ profile: 'worker',
+ targetProfile: 'backend-worker'
+ }
+ vi.mocked(deleteProfile).mockResolvedValueOnce({ ok: true, path: '/profiles/backend-worker' })
+
+ await host.deleteProfile(route)
+
+ expect(retireLocalProfileGateways).toHaveBeenCalledWith('backend-worker')
+ expect(deleteProfile).toHaveBeenCalledWith('backend-worker', {
+ connectionId: 'source-local',
- profile: 'backend-worker'
++ profile: 'worker'
+ })
+ })
+
it('keeps the profile-only request overload as a legacy fallback', async () => {
const result = await host.requestProfile('legacy-worker', 'profiles.list', { include_sessions: true })
@@@ -380,25 -297,8 +393,26 @@@
})
describe('profile-aware plugin session opens', () => {
+ it('captures the full owner route before opening a remote session', async () => {
+ const route = {
+ connectionId: 'source-a',
+ mode: 'remote' as const,
+ profile: 'default',
+ targetProfile: 'backend-default'
+ }
+
+ await host.openSession('remote-chat', { route })
+
- expect(ensureGatewayAgent).toHaveBeenCalledWith('source-a', 'default')
++ expect(openGatewayForAgent).toHaveBeenCalledWith('source-a', 'default')
++ expect(ensureGatewayProfile).not.toHaveBeenCalled()
++ expect(setShowAllProfiles).toHaveBeenCalledWith(true)
++ expect($activeGatewayProfile.get()).toBe('remote-worker')
+ expect(setSessionOwnerHint).toHaveBeenCalledWith('remote-chat', route)
+ expect(openSessionCore).toHaveBeenCalledWith('remote-chat', expect.any(Function), 'in-place')
+ })
+
it('waits until the target Bot Chat runtime and history are on main before resolving', async () => {
- vi.mocked(ensureGatewayProfile).mockImplementationOnce(async (target: null | string | undefined) => {
- $activeGatewayProfile.set(target || 'default')
- })
+ vi.mocked(openGatewayForProfile).mockImplementationOnce(async () => undefined)
let resolved = false
@@@ -467,7 -368,7 +482,7 @@@
// The old pre-open "already selected" precondition skipped this request,
// stranding the pane blank until timeout. It must fire now.
-- expect(requestSessionResume).toHaveBeenCalledWith('cold-bot-chat')
++ expect(requestSessionResume).toHaveBeenCalledWith('cold-bot-chat', undefined)
setMockAtom($selectedStoredSessionId, 'cold-bot-chat')
setMockAtom($activeSessionId, 'runtime-cold')
@@@ -491,7 -392,7 +506,7 @@@
})
await Promise.resolve()
-- expect(requestSessionResume).toHaveBeenCalledWith('bot-chat')
++ expect(requestSessionResume).toHaveBeenCalledWith('bot-chat', undefined)
setMockAtom($activeSessionId, 'runtime-refreshed')
setMockAtom($messages, [{ id: 'history-restored', parts: [], role: 'assistant' }] as never)
diff --cc apps/desktop/src/store/gateway.ts
index 5b723194d9f,05a7920bf5a..dbe576de653
--- a/apps/desktop/src/store/gateway.ts
+++ b/apps/desktop/src/store/gateway.ts
@@@ -600,13 -607,13 +607,15 @@@ export async function requestGatewayFor
connectionId: null | string,
profile: string,
method: string,
-- params: Record<string, unknown> = {}
++ params: Record<string, unknown> = {},
++ timeoutMs?: number,
++ signal?: AbortSignal
): Promise<T> {
const key = normKey(profile)
const scope = registryBackendScopeKey(connectionId, key)
if (scope === key) {
-- return requestGatewayForProfile<T>(key, method, params)
++ return requestGatewayForProfile<T>(key, method, params, timeoutMs, signal)
}
if (!window.hermesDesktop?.getConnectionFor) {
@@@ -632,7 -639,7 +641,9 @@@
await openSecondary(entry)
}
-- return await entry.gateway.request<T>(method, params)
++ return await (timeoutMs === undefined && signal === undefined
++ ? entry.gateway.request<T>(method, params)
++ : entry.gateway.request<T>(method, params, timeoutMs, signal))
} finally {
entry.activeRequests = Math.max(0, entry.activeRequests - 1)
diff --cc apps/desktop/src/store/session-request-router.test.ts
index 6829b32aa6c,7aa4aa3f6ae..5883c8f1693
--- a/apps/desktop/src/store/session-request-router.test.ts
+++ b/apps/desktop/src/store/session-request-router.test.ts
@@@ -234,6 -167,38 +234,67 @@@ describe('requestForSessionProfile', (
expect(secondaryGateways[0].request).toHaveBeenCalledWith('session.resume', { session_id: 'stored-loki-chat' })
})
+ it('forwards timeout and abort signal onto the owning profile socket', async () => {
+ const primary = makePrimary()
+ setPrimaryGateway(primary as never, 'default')
+ installDesktop()
+ await ensureGatewayForProfile('default')
+
+ const ambient = vi.fn(async (method: string, params?: Record<string, unknown>) => ({
+ ambient: true,
+ method,
+ params
+ }))
+
+ const controller = new AbortController()
+
+ await requestForSessionProfile(
+ 'loki',
+ ambient as never,
+ 'prompt.submit',
+ { session_id: 'stored-loki-chat', text: 'hi' },
+ 1_800_000,
+ controller.signal
+ )
+
+ expect(ambient).not.toHaveBeenCalled()
+ expect(secondaryGateways[0].request).toHaveBeenCalledWith(
+ 'prompt.submit',
+ { session_id: 'stored-loki-chat', text: 'hi' },
+ 1_800_000,
+ controller.signal
+ )
+ })
+
++ it('forwards timeout and abort signal onto the owning connection socket', async () => {
++ const primary = makePrimary()
++ setPrimaryGateway(primary as never, 'default')
++ installDesktop()
++ const ambient = vi.fn(async () => ({ ambient: true }))
++ const controller = new AbortController()
++
++ await requestForSessionProfile(
++ {
++ connectionId: 'source-a',
++ profile: 'default',
++ targetProfile: 'backend-default'
++ },
++ ambient as never,
++ 'prompt.submit',
++ { profile: 'default', session_id: 'stored-remote-chat', text: 'hi' },
++ 1_800_000,
++ controller.signal
++ )
++
++ expect(ambient).not.toHaveBeenCalled()
++ expect(secondaryGateways[0].request).toHaveBeenCalledWith(
++ 'prompt.submit',
++ { profile: 'backend-default', session_id: 'stored-remote-chat', text: 'hi' },
++ 1_800_000,
++ controller.signal
++ )
++ })
++
it('keeps the ambient dispatcher when the active route already serves the owner', async () => {
const primary = makePrimary()
setPrimaryGateway(primary as never, 'default')
diff --cc apps/desktop/src/store/session-request-router.ts
index f739ea0bf81,dd55aaf52ce..be59112cfc8
--- a/apps/desktop/src/store/session-request-router.ts
+++ b/apps/desktop/src/store/session-request-router.ts
@@@ -72,24 -39,29 +72,50 @@@ export function sessionRpcNeedsProfileR
* The route is decided at CALL time, not at swap time.
*/
export function requestForSessionProfile<T>(
- ownerProfile: null | string | undefined,
+ ownerProfile: SessionOwnerScope | undefined,
- ambientRequest: <R>(method: string, params?: Record<string, unknown>) => Promise<R>,
+ ambientRequest: <R>(
+ method: string,
+ params?: Record<string, unknown>,
+ timeoutMs?: number,
+ signal?: AbortSignal
+ ) => Promise<R>,
method: string,
- params: Record<string, unknown> = {}
+ params: Record<string, unknown> = {},
+ timeoutMs?: number,
+ signal?: AbortSignal
): Promise<T> {
+ if (isRoute(ownerProfile)) {
+ const connectionId = ownerProfile.connectionId.trim()
+
+ if (!connectionId) {
+ return Promise.reject(new Error('Session owner route is missing connectionId'))
+ }
+
- return requestGatewayForAgent<T>(connectionId, normKey(ownerProfile.profile), method, routeParams(ownerProfile, params))
++ const routedParams = routeParams(ownerProfile, params)
++
++ return timeoutMs === undefined && signal === undefined
++ ? requestGatewayForAgent<T>(connectionId, normKey(ownerProfile.profile), method, routedParams)
++ : requestGatewayForAgent<T>(
++ connectionId,
++ normKey(ownerProfile.profile),
++ method,
++ routedParams,
++ timeoutMs,
++ signal
++ )
+ }
+
if (!sessionRpcNeedsProfileRoute(ownerProfile)) {
- return ambientRequest<T>(method, params)
+ // Forward the extra args only when the caller actually supplied them. The
+ // ambient dispatcher is a plain gateway request whose arity callers assert
+ // on; handing it a trailing `undefined, undefined` on every session RPC
+ // changes the observed call shape for the many callers that never asked
+ // for a deadline (the plugin host bridge in contrib/wiring is the only one
+ // that does).
+ return timeoutMs === undefined && signal === undefined
+ ? ambientRequest<T>(method, params)
+ : ambientRequest<T>(method, params, timeoutMs, signal)
}
- return requestGatewayForProfile<T>(normKey(ownerProfile), method, params)
+ return requestGatewayForProfile<T>(normKey(ownerProfile), method, params, timeoutMs, signal)
}