The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): route remote bot actions by connection
Sara Burke9b7ab9d65aed
diff --git a/apps/desktop/electron/connection-registry.ts b/apps/desktop/electron/connection-registry.tsindex c9dcc09b2c8..827127af0bb 100644--- a/apps/desktop/electron/connection-registry.ts+++ b/apps/desktop/electron/connection-registry.ts@@ -255,6 +255,8 @@ export interface RosterAgent {connectionKind: ConnectionKindconnectionLabel: stringprofile: string+ /** Backend profile when the registry route maps the Desktop profile name. */+ targetProfile?: string/** Bare profile name, or `<profile>-<label-slug>` when the profile name* exists on more than one registered source (the @name-device rule). */handle: string@@ -403,6 +405,7 @@ export function buildAgentRoster(connectionKind: connection.kind,connectionLabel: connection.label,profile,+ targetProfile: connection.remoteProfile || profile,handle: agentHandle(profile, connection.label, (counts.get(profile) || 0) > 1)})}diff --git a/apps/desktop/src/app/chat/index.tsx b/apps/desktop/src/app/chat/index.tsxindex 13ed225186d..6e8f149c008 100644--- a/apps/desktop/src/app/chat/index.tsx+++ b/apps/desktop/src/app/chat/index.tsx@@ -32,19 +32,21 @@ import { $petOverlayActive } from '@/store/pet-overlay'import { $activeGatewayProfile, $gatewaySwapTarget, $profiles } from '@/store/profile'import {$contextSuggestions,+ $connection,$freshDraftReady,$gatewayState,$introPersonality,$introSeed,$resumeExhaustedSessionId,$sessions,+ getSessionOwnerHint,resolveComposerSessionKey,sessionMatchesStoredId,sessionPinId,shouldMigrateComposerScope} from '@/store/session'import { 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'@@ -261,10 +263,20 @@ function ChatRuntimeBoundary({const runtimeMessageRepository = useRuntimeMessageRepository(windowedMessages)const storedId = useStore(view.$storedId)+ const connection = useStore($connection)+ const activeProfile = useStore($activeGatewayProfile)// Subscribed (not read imperatively) so the "Show earlier" affordance// appears/retires as tail hydrations and backfill pages record their state.const transcriptTailStates = useStore($transcriptTailBySessionId)- const restBackfillAvailable = Boolean(storedId && transcriptTailStates[storedId]?.possiblyTruncated)+ const connectionId = connection?.connectionId || (connection?.mode === 'local' ? 'local' : '')+ const ownerRoute = storedId+ ? getSessionOwnerHint(storedId, connectionId ? { connectionId, profile: activeProfile } : undefined)+ : undefined+ const tailProfile = ownerRoute+ ? { connectionId: ownerRoute.connectionId, profile: ownerRoute.targetProfile || ownerRoute.profile }+ : undefined+ const tailState = storedId && transcriptTailStates ? transcriptTailState(storedId, tailProfile) : undefined+ const restBackfillAvailable = Boolean(tailState?.possiblyTruncated)const expandWindow = useCallback(() => {// The store window still holds older messages: growing pages is enough.@@ -273,9 +285,15 @@ function ChatRuntimeBoundary({// PREPEND it to the session store before growing, so the grown window has// something older to show. Fire-and-forget: the prepend lands through the// session-state write path and re-renders this boundary.- if (!windowStateRef.current?.window.windowed && runtimeId && storedId && transcriptBackfillAvailable(storedId)) {+ if (+ !windowStateRef.current?.window.windowed &&+ runtimeId &&+ storedId &&+ transcriptBackfillAvailable(storedId, tailProfile)+ ) {void backfillOlderTranscriptPage({storedSessionId: storedId,+ profile: tailProfile,// Stale-response guard: a session switch remounts/re-keys this view;// checking the live atoms (not captured props) discards a page that// resolves after the user moved on — same pattern as isCurrentResume.@@ -291,7 +309,7 @@ function ChatRuntimeBoundary({}setWindowPages(pages => pages + 1)- }, [runtimeId, storedId, view])+ }, [runtimeId, storedId, tailProfile, view])const olderAvailable = windowed || restBackfillAvailablediff --git a/apps/desktop/src/app/chat/transcript-backfill.test.ts b/apps/desktop/src/app/chat/transcript-backfill.test.tsindex 6863ad61b56..5a020b51ef2 100644--- a/apps/desktop/src/app/chat/transcript-backfill.test.ts+++ b/apps/desktop/src/app/chat/transcript-backfill.test.ts@@ -68,6 +68,40 @@ describe('transcript tail bookkeeping', () => {expect(transcriptBackfillAvailable('stored-1')).toBe(false)})++ it('counts the same session id on separate connections as separate entries', () => {+ const page = {+ messages: [row(1, 'tail')],+ pagination: { limit: 120, offset: 0, order: 'latest' as const, returned: 1 }+ }+ const sourceA = { connectionId: 'source-a', profile: 'backend' }+ const sourceB = { connectionId: 'source-b', profile: 'backend' }++ recordTranscriptTail('same-session', page, sourceA)+ recordTranscriptTail('same-session', page, sourceB)++ expect(Object.keys($transcriptTailBySessionId.get())).toHaveLength(2)+ expect(transcriptTailState('same-session', sourceA)?.profile).toEqual(sourceA)+ expect(transcriptTailState('same-session', sourceB)?.profile).toEqual(sourceB)+ expect(transcriptTailState('same-session')).toBeUndefined()+ })++ it('bounds entries and deterministically evicts the oldest scoped identity', () => {+ const page = {+ messages: [row(1, 'tail')],+ pagination: { limit: 120, offset: 0, order: 'latest' as const, returned: 1 }+ }+ const scope = { connectionId: 'source-a', profile: 'backend' }++ for (let index = 0; index < 257; index += 1) {+ recordTranscriptTail(`bounded-${index}`, page, scope)+ }++ expect(Object.keys($transcriptTailBySessionId.get())).toHaveLength(256)+ expect(transcriptTailState('bounded-0', scope)).toBeUndefined()+ expect(transcriptTailState('bounded-1', scope)).toBeDefined()+ expect(transcriptTailState('bounded-256', scope)).toBeDefined()+ })})describe('mergeOlderTranscriptPage', () => {@@ -165,6 +199,34 @@ describe('backfillOlderTranscriptPage', () => {expect(transcriptBackfillAvailable('stored-1')).toBe(false)})+ it('backfills the matching connection when two owners share one session id', async () => {+ const sourceA = { connectionId: 'source-a', profile: 'backend-a' }+ const sourceB = { connectionId: 'source-b', profile: 'backend-b' }+ const page = {+ messages: Array.from({ length: 120 }, (_, index) => row(index, `tail${index}`)),+ pagination: { limit: 120, offset: 0, order: 'latest' as const, returned: 120 }+ }+ recordTranscriptTail('same-session', page, sourceA)+ recordTranscriptTail('same-session', page, sourceB)+ vi.mocked(getOlderSessionMessages).mockResolvedValue({+ messages: [row(1, 'older')],+ pagination: { limit: 120, offset: 120, order: 'latest', returned: 1 },+ session_id: 'same-session'+ } as never)++ await backfillOlderTranscriptPage({+ storedSessionId: 'same-session',+ profile: sourceB,+ isCurrent: () => true,+ applyOlderPage: vi.fn()+ })++ expect(getOlderSessionMessages).toHaveBeenCalledWith('same-session', sourceB, 120)+ expect(transcriptTailState('same-session', sourceA)).toMatchObject({ possiblyTruncated: true })+ expect(transcriptTailState('same-session', sourceB)).toMatchObject({ possiblyTruncated: false })+ expect(transcriptTailState('same-session')).toBeUndefined()+ })+it('keeps backfill available while pages keep coming back full', async () => {truncatedTail()vi.mocked(getOlderSessionMessages).mockResolvedValue({diff --git a/apps/desktop/src/app/chat/transcript-backfill.ts b/apps/desktop/src/app/chat/transcript-backfill.tsindex fb6ff3d3d26..43b41354663 100644--- a/apps/desktop/src/app/chat/transcript-backfill.ts+++ b/apps/desktop/src/app/chat/transcript-backfill.ts@@ -17,11 +17,18 @@import { getOlderSessionMessages } from '@/hermes'import { type ChatMessage, toChatMessages } from '@/lib/chat-messages'-import { recordTranscriptBackfillPage, transcriptTailState } from '@/store/transcript-tail'+import {+ recordTranscriptBackfillPage,+ type TranscriptProfileScope,+ transcriptTailState+} from '@/store/transcript-tail'/** Older rows likely exist beyond what the in-memory store holds. */-export function transcriptBackfillAvailable(storedSessionId: null | string | undefined): boolean {- return Boolean(transcriptTailState(storedSessionId)?.possiblyTruncated)+export function transcriptBackfillAvailable(+ storedSessionId: null | string | undefined,+ profile?: TranscriptProfileScope+): boolean {+ return Boolean(transcriptTailState(storedSessionId, profile)?.possiblyTruncated)}/**@@ -92,6 +99,8 @@ export function graftRefreshedTailOntoBackfill(refreshedTail: ChatMessage[], preexport interface BackfillRequest {/** Durable stored session id — the tail bookkeeping key. */storedSessionId: string+ /** Owner scope captured when the tail was hydrated. */+ profile?: TranscriptProfileScope/** Stale-response guard: called after the fetch resolves; when it reports* false (the user switched sessions mid-flight) the page is discarded and* the bookkeeping is left untouched, mirroring the isCurrentResume()@@ -118,15 +127,16 @@ export function _resetTranscriptBackfillForTests(): void {* for the same session share one fetch.*/export function backfillOlderTranscriptPage(request: BackfillRequest): Promise<boolean> {- const { storedSessionId } = request- const inflight = inflightByStoredSessionId.get(storedSessionId)+ const { profile, storedSessionId } = request+ const inflightKey = JSON.stringify([profile || null, storedSessionId])+ const inflight = inflightByStoredSessionId.get(inflightKey)if (inflight) {return inflight}const run = (async () => {- const tail = transcriptTailState(storedSessionId)+ const tail = transcriptTailState(storedSessionId, profile)if (!tail?.possiblyTruncated) {return false@@ -152,15 +162,15 @@ export function backfillOlderTranscriptPage(request: BackfillRequest): Promise<b// the paging query and returned the FULL transcript one-shot. The merge// below prepends whatever prefix the store is missing, and the recorded// state marks the session fully loaded so the REST action retires.- recordTranscriptBackfillPage(storedSessionId, page)+ recordTranscriptBackfillPage(storedSessionId, page, profile)request.applyOlderPage(toChatMessages(page.messages))return true})().finally(() => {- inflightByStoredSessionId.delete(storedSessionId)+ inflightByStoredSessionId.delete(inflightKey)})- inflightByStoredSessionId.set(storedSessionId, run)+ inflightByStoredSessionId.set(inflightKey, run)return run}diff --git a/apps/desktop/src/app/session/hooks/use-route-resume.test.tsx b/apps/desktop/src/app/session/hooks/use-route-resume.test.tsxindex b2463699868..ca27979e955 100644--- a/apps/desktop/src/app/session/hooks/use-route-resume.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-route-resume.test.tsx@@ -3,6 +3,7 @@ import type { MutableRefObject } from 'react'import { afterEach, describe, expect, it, vi } from 'vitest'import { $resumeExhaustedSessionId, setResumeExhaustedSessionId } from '@/store/session'+import type { SessionProfileRoute } from '@/store/session-request-router'import { markSelectionRestore } from '@/store/session-states'import { useRouteResume } from './use-route-resume'@@ -20,10 +21,10 @@ interface HarnessProps {freshDraftReady: booleangatewayState: stringlocationPathname: string- resumeSession: (sessionId: string, focus: boolean) => Promise<unknown>+ resumeSession: (sessionId: string, focus: boolean, ownerRoute?: SessionProfileRoute) => Promise<unknown>resumeFailedSessionId?: null | stringresumeExhaustedSessionId?: null | string- sessionResumeRequest?: null | { sequence: number; sessionId: string }+ sessionResumeRequest?: null | { ownerRoute?: SessionProfileRoute; sequence: number; sessionId: string }routedSessionId: null | stringruntimeIdByStoredSessionIdRef: MutableRefObject<Map<string, string>>selectedStoredSessionId: null | string@@ -343,6 +344,58 @@ describe('useRouteResume', () => {expect(resumeSession).toHaveBeenCalledTimes(1)expect(resumeSession).toHaveBeenCalledWith('session-1', true)})++ it('does not reuse a stale plugin owner route after pathname navigation', () => {+ const resumeSession = vi.fn(async () => undefined)+ const startFreshSessionDraft = vi.fn()+ const activeSessionIdRef: MutableRefObject<null | string> = { current: 'runtime-1' }+ const creatingSessionRef = { current: false }+ const runtimeIdByStoredSessionIdRef = { current: new Map([['session-1', 'runtime-1']]) }+ const selectedStoredSessionIdRef: MutableRefObject<null | string> = { current: 'session-1' }+ const ownerRoute: SessionProfileRoute = {+ connectionId: 'source-a',+ mode: 'remote',+ profile: 'worker',+ targetProfile: 'backend-worker'+ }+ const request = { ownerRoute, sequence: 1, sessionId: 'session-1' }+ const props = {+ activeSessionId: 'runtime-1',+ activeSessionIdRef,+ creatingSessionRef,+ currentView: 'chat',+ freshDraftReady: false,+ gatewayState: 'open',+ resumeSession,+ runtimeIdByStoredSessionIdRef,+ selectedStoredSessionId: 'session-1',+ selectedStoredSessionIdRef,+ sessionResumeRequest: request,+ startFreshSessionDraft+ }++ const { rerender } = render(+ <RouteResumeHarness+ {...props}+ locationPathname="/session-1"+ routedSessionId="session-1"+ />+ )++ expect(resumeSession).toHaveBeenCalledWith('session-1', true, ownerRoute)+ resumeSession.mockClear()++ rerender(+ <RouteResumeHarness+ {...props}+ locationPathname="/session-2"+ routedSessionId="session-2"+ />+ )++ expect(resumeSession).toHaveBeenCalledTimes(1)+ expect(resumeSession).toHaveBeenCalledWith('session-2', true)+ })})describe('useRouteResume bounded auto-retry after a failed resume', () => {diff --git a/apps/desktop/src/app/session/hooks/use-route-resume.ts b/apps/desktop/src/app/session/hooks/use-route-resume.tsindex 597f72bb2cf..af51055dec2 100644--- a/apps/desktop/src/app/session/hooks/use-route-resume.ts+++ b/apps/desktop/src/app/session/hooks/use-route-resume.ts@@ -2,6 +2,7 @@ import { type MutableRefObject, useEffect, useRef } from 'react'import { isNewChatRoute } from '@/app/routes'import { type SessionResumeRequest, setResumeExhaustedSessionId } from '@/store/session'+import type { SessionProfileRoute } from '@/store/session-request-router'import { markSelectionRestore } from '@/store/session-states'interface RouteResumeOptions {@@ -12,7 +13,7 @@ interface RouteResumeOptions {freshDraftReady: booleangatewayState: string | undefinedlocationPathname: string- resumeSession: (sessionId: string, focus: boolean) => Promise<unknown>+ resumeSession: (sessionId: string, focus: boolean, ownerRoute?: SessionProfileRoute) => Promise<unknown>// Stored-session id whose most recent resume failed terminally (set by// useSessionActions, mirrored from $resumeFailedSessionId). While this equals// routedSessionId the window would otherwise latch on the loader forever, so@@ -177,7 +178,13 @@ export function useRouteResume({}bootResumeRef.current = false- void resumeSession(routedSessionId, true)+ const ownerRoute =+ sessionResumeRequest?.sessionId === routedSessionId ? sessionResumeRequest.ownerRoute : undefined+ if (ownerRoute) {+ void resumeSession(routedSessionId, true, ownerRoute)+ } else {+ void resumeSession(routedSessionId, true)+ }}returndiff --git a/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsxindex 5a0c89a754a..66c1713eb11 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx@@ -15,7 +15,14 @@ import {} from '@/hermes'import { createClientSessionState } from '@/lib/chat-runtime'import { clearSessionDraft, stashSessionDraft, takeSessionDraft } from '@/store/composer'-import { $activeGatewayProfile, $newChatProfile, ensureGatewayProfile } from '@/store/profile'+import {+ $activeGatewayProfile,+ $newChatProfile,+ $newChatRoute,+ ensureGatewayProfile+} from '@/store/profile'+import { requestGatewayForAgent } from '@/store/gateway'+import type { SessionProfileRoute } from '@/store/session-request-router'import { $projectScope, $projectTree, ALL_PROJECTS } from '@/store/projects'import {$activeSessionId,@@ -68,9 +75,15 @@ vi.mock('@/hermes', async importOriginal => ({vi.mock('@/store/profile', async importOriginal => ({...(await importOriginal<Record<string, unknown>>()),+ ensureGatewayAgent: vi.fn().mockResolvedValue(undefined),ensureGatewayProfile: vi.fn().mockResolvedValue(undefined)}))+vi.mock('@/store/gateway', async importOriginal => ({+ ...(await importOriginal<Record<string, unknown>>()),+ requestGatewayForAgent: vi.fn()+}))+vi.mock('@/components/pane-shell/tree/store', async importOriginal => ({...(await importOriginal<Record<string, unknown>>()),noteActiveTreeGroup: vi.fn(),@@ -477,6 +490,7 @@ describe('createBackendSessionForSend profile routing', () => {afterEach(() => {cleanup()$newChatProfile.set(null)+ $newChatRoute.set(null)$activeGatewayProfile.set('default')$projectScope.set(ALL_PROJECTS)$projectTree.set([])@@ -534,6 +548,40 @@ describe('createBackendSessionForSend profile routing', () => {expect(params).toMatchObject({ cwd: '/remote/worktree' })})+ it('keeps a route-aware New Chat pinned when foreground activation changes before Send', async () => {+ const route = {+ connectionId: 'source-a',+ mode: 'remote' as const,+ profile: 'default',+ targetProfile: 'backend-default'+ }+ const ambientRequest = vi.fn(async () => ({}) as never)+ vi.mocked(requestGatewayForAgent).mockResolvedValueOnce({+ session_id: RUNTIME_SESSION_ID,+ stored_session_id: null+ } as never)++ $newChatProfile.set(route.profile)+ $newChatRoute.set({ ...route })+ $activeGatewayProfile.set('other-connection-profile')++ let handle: HarnessHandle | null = null+ render(<Harness onReady={value => (handle = value)} requestGateway={ambientRequest} />)+ await waitFor(() => expect(handle).not.toBeNull())++ await act(async () => {+ await handle!.createBackendSessionForSend()+ })++ expect(requestGatewayForAgent).toHaveBeenCalledWith(+ 'source-a',+ 'default',+ 'session.create',+ expect.objectContaining({ profile: 'backend-default', source: 'desktop' })+ )+ expect(ambientRequest).not.toHaveBeenCalledWith('session.create', expect.anything())+ })+it('freezes the visible selector state before profile readiness and sends fast: false explicitly', async () => {const profileReady = deferred<void>()vi.mocked(ensureGatewayProfile).mockReturnValueOnce(profileReady.promise)@@ -618,7 +666,13 @@ function ResumeHarness({sessionStateByRuntimeIdRef}: {onStateUpdate?: (sessionId: string, state: ClientSessionState) => void- onReady: (resume: (storedSessionId: string, replaceRoute?: boolean) => Promise<unknown>) => void+ onReady: (+ resume: (+ storedSessionId: string,+ replaceRoute?: boolean,+ ownerRoute?: SessionProfileRoute+ ) => Promise<unknown>+ ) => voidrequestGateway: <T>(method: string, params?: Record<string, unknown>) => Promise<T>runtimeIdByStoredSessionIdRef?: MutableRefObject<Map<string, string>>selectedStoredSessionId?: string | null@@ -1700,9 +1754,110 @@ describe('resumeSession warm-cache mapping integrity', () => {setResumeFailedSessionId(null)setMessages([])setSessions([])+ vi.mocked(getSession).mockReset()+ vi.mocked(getLatestSessionMessages).mockReset().mockResolvedValue({ messages: [] } as never)+ vi.mocked(requestGatewayForAgent).mockReset()vi.restoreAllMocks()})+ it('pins metadata, transcript, resume, activate, and usage to the captured connection', async () => {+ const ownerRoute: SessionProfileRoute = {+ connectionId: 'source-a',+ mode: 'remote',+ profile: 'default',+ targetProfile: 'backend-default'+ }+ const runtimeIdByStoredSessionIdRef: MutableRefObject<Map<string, string>> = {+ current: new Map([['stored-warm', 'runtime-warm']])+ }+ const sessionStateByRuntimeIdRef: MutableRefObject<Map<string, ClientSessionState>> = {+ current: new Map([['runtime-warm', clientState('stored-warm')]])+ }+ // Same-name rows without a source tag are not authoritative for an+ // explicit owner. Metadata must be re-read from the captured connection.+ setSessions([storedSession({ id: 'stored-warm', profile: 'default' })])+ vi.mocked(getSession).mockImplementation(async id => storedSession({ id, profile: 'default' }))+ vi.mocked(getLatestSessionMessages).mockImplementation(async id => ({ messages: [], session_id: id }) as never)+ vi.mocked(requestGatewayForAgent).mockImplementation(async (_connectionId, _profile, method, params) => {+ if (method === 'session.activate') {+ throw new Error('Method not found')+ }++ if (method === 'session.usage') {+ return { input: 1, output: 2, total: 3 } as never+ }++ if (method === 'session.resume') {+ return {+ info: {},+ messages: [],+ resumed: params?.session_id,+ session_id: 'runtime-cold'+ } as never+ }++ return {} as never+ })++ const ambientRequest = vi.fn(async () => ({}) as never)+ let resume: null | ((+ storedSessionId: string,+ replaceRoute?: boolean,+ ownerRoute?: SessionProfileRoute+ ) => Promise<unknown>) = null+ render(+ <ResumeHarness+ onReady={ready => (resume = ready)}+ requestGateway={ambientRequest}+ runtimeIdByStoredSessionIdRef={runtimeIdByStoredSessionIdRef}+ sessionStateByRuntimeIdRef={sessionStateByRuntimeIdRef}+ />+ )+ await waitFor(() => expect(resume).not.toBeNull())++ await resume!('stored-warm', true, ownerRoute)+ await resume!('stored-cold', true, ownerRoute)+ await resume!('stored-cold', true, {+ connectionId: 'source-b',+ mode: 'remote',+ profile: 'default',+ targetProfile: 'backend-b'+ })++ const restScope = { connectionId: 'source-a', profile: 'backend-default' }+ expect(getSession).toHaveBeenCalledWith('stored-warm', restScope)+ expect(getSession).toHaveBeenCalledWith('stored-cold', restScope)+ expect(getLatestSessionMessages).toHaveBeenCalledWith('stored-warm', restScope)+ expect(getLatestSessionMessages).toHaveBeenCalledWith('stored-cold', restScope)+ expect(getSession).toHaveBeenCalledWith('stored-cold', {+ connectionId: 'source-b',+ profile: 'backend-b'+ })+ expect(getLatestSessionMessages).toHaveBeenCalledWith('stored-cold', {+ connectionId: 'source-b',+ profile: 'backend-b'+ })+ expect(requestGatewayForAgent).toHaveBeenCalledWith(+ 'source-a',+ 'default',+ 'session.activate',+ expect.objectContaining({ session_id: 'runtime-warm' })+ )+ expect(requestGatewayForAgent).toHaveBeenCalledWith(+ 'source-a',+ 'default',+ 'session.usage',+ { session_id: 'runtime-warm' }+ )+ expect(requestGatewayForAgent).toHaveBeenCalledWith(+ 'source-a',+ 'default',+ 'session.resume',+ expect.objectContaining({ session_id: 'stored-cold' })+ )+ expect(ambientRequest).not.toHaveBeenCalled()+ })+it('rejects a cross-wired runtime mapping and falls through to a full resume', async () => {// A recycled runtime id ('rt-recycled') is mapped to 'stored-A', but its// cached state actually belongs to a DIFFERENT session ('stored-B') — thediff --git a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts b/apps/desktop/src/app/session/hooks/use-session-actions/index.tsindex 572c7e1f620..bbe8eb29a44 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts@@ -14,12 +14,14 @@ import { normalizeChoices, setClarifyRequest } from '@/store/clarify'import { migrateSessionDraft } from '@/store/composer'import { clearQueuedPrompts, migrateQueuedPrompts } from '@/store/composer-queue'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,ensureGatewayAgent,ensureGatewayProfile,normalizeProfileKey@@ -64,11 +66,12 @@ import {setSelectedStoredSessionId,setSessions,setSessionStartedAt,+ getSessionOwnerHint,setTurnStartedAt,setWorkspaceCwdOwner,setYoloActive} from '@/store/session'-import { requestForSessionProfile } from '@/store/session-request-router'+import { requestForSessionProfile, type SessionOwnerScope, type SessionProfileRoute } from '@/store/session-request-router'import {$sessionTiles,closeSessionTile,@@ -188,7 +191,10 @@ function reconcileAuthoritativeMessages(// A no-op for single-profile/local-pooled users (a backend resolves its own launch// profile to None). The sticky UI model/effort/fast ride as per-session overrides,// never the profile default (that lives in Settings → Model).-async function desktopSessionCreateParams(cwd: string): Promise<Record<string, unknown>> {+async function desktopSessionCreateParams(+ cwd: string,+ capturedRoute = $newChatRoute.get()+): Promise<Record<string, unknown>> {// Treat Send as the linearization point for the visible selector state. The// profile handshake below can yield long enough for background config/model// refreshes to finish; reading atoms afterward would silently create the@@ -200,14 +206,19 @@ async function desktopSessionCreateParams(cwd: string): Promise<Record<string, uprovider: $currentProvider.get().trim()}- const profile = $newChatProfile.get() ?? normalizeProfileKey($activeGatewayProfile.get())- await ensureGatewayProfile(profile)+ const profile = capturedRoute?.profile || $newChatProfile.get() || normalizeProfileKey($activeGatewayProfile.get())++ if (capturedRoute) {+ await ensureGatewayAgent(capturedRoute.connectionId, profile)+ } else {+ await ensureGatewayProfile(profile)+ }return {cols: 96,source: 'desktop',...(cwd && { cwd }),- ...(profile ? { profile } : {}),+ ...(profile ? { profile: capturedRoute?.targetProfile || profile } : {}),...(selection.model? { model: selection.model, ...(selection.provider ? { provider: selection.provider } : {}) }: {}),@@ -458,8 +469,16 @@ export function useSessionActions({? workspaceTarget.trim(): $currentCwd.get().trim() || resolveNewSessionCwd()- const params = await desktopSessionCreateParams(cwd)- const created = await requestGateway<SessionCreateResponse>('session.create', params)+ const capturedRoute = $newChatRoute.get()+ const params = await desktopSessionCreateParams(cwd, capturedRoute)+ const created = capturedRoute+ ? await requestGatewayForAgent<SessionCreateResponse>(+ capturedRoute.connectionId,+ capturedRoute.profile,+ 'session.create',+ params+ )+ : await requestGateway<SessionCreateResponse>('session.create', params)const stored = created.stored_session_id ?? null// Only a genuine move to a DIFFERENT chat mid-create should orphan the@@ -574,8 +593,16 @@ export function useSessionActions({// Fresh tile → the caller's workspace when one was named (the sidebar// "+" on a project/worktree lane), else the resolved new-session cwd// (project scope → configured default).- const params = await desktopSessionCreateParams((options?.cwd || resolveNewSessionCwd()).trim())- const created = await requestGateway<SessionCreateResponse>('session.create', params)+ const capturedRoute = $newChatRoute.get()+ const params = await desktopSessionCreateParams((options?.cwd || resolveNewSessionCwd()).trim(), capturedRoute)+ const created = capturedRoute+ ? await requestGatewayForAgent<SessionCreateResponse>(+ capturedRoute.connectionId,+ capturedRoute.profile,+ 'session.create',+ params+ )+ : await requestGateway<SessionCreateResponse>('session.create', params)const stored = created.stored_session_idif (!stored) {@@ -639,7 +666,7 @@ export function useSessionActions({}, [navigate, selectedStoredSessionId])const resumeSession = useCallback(- async (storedSessionId: string, replaceRoute = false) => {+ async (storedSessionId: string, replaceRoute = false, capturedOwner?: SessionProfileRoute) => {const requestId = resumeRequestRef.current + 1resumeRequestRef.current = requestIdconst resumedSameSelectedSession = selectedStoredSessionIdRef.current === storedSessionId@@ -730,7 +757,8 @@ export function useSessionActions({// gateway call (no-op when it's already on that profile / single-profile).// resolveStoredSession finds the row by id (cheap), so an uncached pasted// id loads as fast as a sidebar click instead of hanging on a list scan.- const storedForProfile = await resolveStoredSession(storedSessionId)+ const ownerRoute = capturedOwner || getSessionOwnerHint(storedSessionId)+ const storedForProfile = await resolveStoredSession(storedSessionId, ownerRoute)const sessionProfile = storedForProfile?.profileif (resumeRequestRef.current !== requestId) {@@ -740,8 +768,16 @@ 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.- if (storedForProfile?.connection_id) {- await ensureGatewayAgent(storedForProfile.connection_id, sessionProfile || 'default')+ 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')} else {await ensureGatewayProfile(sessionProfile)}@@ -759,7 +795,14 @@ export function useSessionActions({// own backend is healthy one port over (#89206: local pool AND SSH).// requestForSessionProfile re-resolves the route at each call.const requestForSession = <T>(method: string, params: Record<string, unknown> = {}): Promise<T> =>- requestForSessionProfile<T>(sessionProfile, requestGateway, method, params)+ requestForSessionProfile<T>(sessionOwner, requestGateway, method, params)++ const sessionRestScope = ownerRoute+ ? {+ connectionId: ownerRoute.connectionId,+ profile: ownerRoute.targetProfile || ownerRoute.profile+ }+ : sessionProfile// Re-check after the profile-resolve / gateway-swap awaits above: the// cache may have changed, and takeWarmCache re-validates belongs-to and@@ -808,7 +851,7 @@ export function useSessionActions({// prefetch. Watch mirrors stay live-only by design.const persistedTranscriptPromise = isWatchWindow()? null- : getLatestSessionMessages(storedSessionId, sessionProfile).catch(() => null)+ : getLatestSessionMessages(storedSessionId, sessionRestScope).catch(() => null)setFreshDraftReady(false)clearNotifications()@@ -1101,7 +1144,7 @@ export function useSessionActions({// max(prefetch, resume) instead of their sum. The prefetch paints the// transcript as soon as it lands; the RPC binds the runtime id.// Watch windows skip the prefetch — lazy resume attaches the live mirror.- const prefetchPromise = watchWindow ? null : getLatestSessionMessages(storedSessionId, sessionProfile)+ const prefetchPromise = watchWindow ? null : getLatestSessionMessages(storedSessionId, sessionRestScope)let resumeRuntimeBaselineMessages: ChatMessage[] = []@@ -1360,7 +1403,7 @@ export function useSessionActions({let fallbackError: unknown = nulltry {- const fallback = await getLatestSessionMessages(storedSessionId, sessionProfile)+ const fallback = await getLatestSessionMessages(storedSessionId, sessionRestScope)if (!isCurrentResume()) {returndiff --git a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts b/apps/desktop/src/app/session/hooks/use-session-actions/utils.tsindex 198db855d83..6346ee136a6 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts@@ -27,6 +27,7 @@ import {setWorkspaceCwdOwner,setYoloActive} from '@/store/session'+import type { SessionProfileRoute } from '@/store/session-request-router'// Re-exported for the many session-actions/tile call sites that already import// it from here; the canonical definition lives in @/store/session.@@ -1292,11 +1293,41 @@ function upsertResolvedSession(session: SessionInfo, storedSessionId: string) {])}-export async function resolveStoredSession(storedSessionId: string): Promise<SessionInfo | undefined> {+export async function resolveStoredSession(+ storedSessionId: string,+ ownerRoute?: SessionProfileRoute+): Promise<SessionInfo | undefined> {const cached = [...$sessions.get(), ...$cronSessions.get(), ...$messagingSessions.get()].find(session =>sessionMatchesStoredId(session, storedSessionId))+ if (ownerRoute) {+ const scope = {+ connectionId: ownerRoute.connectionId,+ profile: ownerRoute.targetProfile || ownerRoute.profile+ }+ const cachedOwnerMatches = cached &&+ cached.connection_id === ownerRoute.connectionId &&+ (!cached.profile || normalizeProfileKey(cached.profile) === normalizeProfileKey(ownerRoute.profile))++ if (cached && cachedOwnerMatches) {+ return cached+ }++ try {+ const session = await getSession(storedSessionId, scope)+ session.profile = normalizeProfileKey(ownerRoute.profile)+ session.connection_id = ownerRoute.connectionId+ upsertResolvedSession(session, storedSessionId)++ return session+ } catch {+ // An explicit owner is fail-closed. Probing the ambient or another+ // profile would turn a stale route into a cross-connection open.+ return undefined+ }+ }+// A row with no owning profile can't route a resume when more than one// profile exists — a resume without a profile lands on whichever gateway is// active (#67603 family, cross-profile open asymmetry). Treat such a hit asdiff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.tsindex 55be4019271..a407043fc6a 100644--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@ -834,6 +834,7 @@ export interface DesktopRosterAgent {connectionKind: DesktopConnectionKindconnectionLabel: stringprofile: string+ targetProfile?: stringhandle: string}diff --git a/apps/desktop/src/hermes.test.ts b/apps/desktop/src/hermes.test.tsindex 43c6fa052ce..1cf3a795312 100644--- a/apps/desktop/src/hermes.test.ts+++ b/apps/desktop/src/hermes.test.ts@@ -7,6 +7,7 @@ import {AUDIO_TRANSCRIBE_MIN_REQUEST_TIMEOUT_MS,audioSpeakRequestTimeoutMs,audioTranscribeRequestTimeoutMs,+ deleteProfile,getAllSessionMessages,getCronJobs,getGlobalModelInfo,@@ -16,6 +17,7 @@ import {getLatestSessionMessages,getOlderSessionMessages,getProfiles,+ getSession,getSessionMessages,getStatus,LATEST_SESSION_MESSAGES_LIMIT,@@ -358,6 +360,42 @@ describe('Hermes REST helpers', () => {})})+ it('pins session metadata and transcripts to an explicit connection scope', async () => {+ api.mockResolvedValue({ messages: [], session_id: 'session-1' })+ const scope = { connectionId: 'source-a', profile: 'backend-default' }++ await getSession('session-1', scope)+ await getSessionMessages('session-1', scope)++ expect(api).toHaveBeenNthCalledWith(1, {+ connectionId: 'source-a',+ path: '/api/sessions/session-1?profile=backend-default',+ profile: 'backend-default'+ })+ expect(api).toHaveBeenNthCalledWith(2, {+ connectionId: 'source-a',+ path: '/api/sessions/session-1/messages?profile=backend-default',+ profile: 'backend-default'+ })+ })++ it('scopes profile deletion and rejects default before Electron dispatch', async () => {+ api.mockResolvedValue({ ok: true, path: '/profiles/worker' })++ await deleteProfile('backend-worker', { connectionId: 'source-a', profile: 'backend-worker' })+ await expect(+ deleteProfile('worker', { connectionId: 'source-a', profile: 'default' })+ ).rejects.toThrow(/default profile cannot be deleted/i)++ expect(api).toHaveBeenCalledOnce()+ expect(api).toHaveBeenCalledWith({+ connectionId: 'source-a',+ method: 'DELETE',+ path: '/api/profiles/backend-worker',+ profile: 'backend-worker'+ })+ })+it('hydrates the latest transcript with a small tail page (120, latest, compacted rows included)', async () => {api.mockResolvedValue({messages: [],diff --git a/apps/desktop/src/hermes.ts b/apps/desktop/src/hermes.tsindex 296e33c20fe..e8cf3e78221 100644--- a/apps/desktop/src/hermes.ts+++ b/apps/desktop/src/hermes.ts@@ -311,7 +311,21 @@ function connectionScoped(): { connectionId?: string } {// ids mean the local pool and deliberately DROP the ambient connection// tag, so a local-profile pick made while a remote gateway is active still// routes to the local machine.-export type ProfileScope = null | string | { connectionId?: null | string; profile?: null | string }+export type ProfileScope = undefined | null | string | { connectionId?: null | string; profile?: null | string }++function sessionScoped(scope?: ProfileScope): { connectionId?: string; profile?: string } {+ if (scope === undefined || scope === null) {+ return {}+ }++ return capabilityScoped(scope)+}++function sessionScopeQuery(scope?: ProfileScope): string {+ const profile = sessionScoped(scope).profile++ return profile ? `?profile=${encodeURIComponent(profile)}` : ''+}function capabilityScoped(scope?: ProfileScope): { connectionId?: string; profile?: string } {if (scope && typeof scope === 'object') {@@ -773,11 +787,12 @@ export function searchSessions(query: string): Promise<SessionSearchResponse> {// the given `profile`). The backend resolves exact ids and unique prefixes and// 404s when the id isn't on that profile — so a cheap by-id lookup replaces the// cross-profile list scan when locating an unknown id's owner.-export function getSession(id: string, profile?: string | null): Promise<SessionInfo> {- const suffix = profile ? `?profile=${encodeURIComponent(profile)}` : ''+export function getSession(id: string, profile?: ProfileScope): Promise<SessionInfo> {+ const scoped = sessionScoped(profile)+ const suffix = sessionScopeQuery(profile)return window.hermesDesktop.api<SessionInfo>({- ...(profile ? { profile } : {}),+ ...scoped,path: `/api/sessions/${encodeURIComponent(id)}${suffix}`})}@@ -788,13 +803,15 @@ export function getSession(id: string, profile?: string | null): Promise<Session// the current/default profile.export function getSessionMessages(id: string,- profile?: string | null,+ profile?: ProfileScope,page: { limit?: number; offset?: number; order?: 'latest' | 'oldest'; includeCompacted?: boolean } = {}): Promise<SessionMessagesResponse> {const query = new URLSearchParams()- if (profile) {- query.set('profile', profile)+ const scoped = sessionScoped(profile)++ if (scoped.profile) {+ query.set('profile', scoped.profile)}if (page.limit !== undefined) {@@ -816,7 +833,7 @@ export function getSessionMessages(const suffix = query.size ? `?${query.toString()}` : ''return window.hermesDesktop.api<SessionMessagesResponse>({- ...(profile ? { profile } : {}),+ ...scoped,path: `/api/sessions/${encodeURIComponent(id)}/messages${suffix}`})}@@ -830,7 +847,7 @@ export function getSessionMessages(*/export const LATEST_SESSION_MESSAGES_LIMIT = 120-export function getLatestSessionMessages(id: string, profile?: string | null): Promise<SessionMessagesResponse> {+export function getLatestSessionMessages(id: string, profile?: ProfileScope): Promise<SessionMessagesResponse> {// includeCompacted: durable display history must include rows preserved by// in-place compaction (active=0, compacted=1); without them the transcript// silently ends at the compaction boundary and earlier turns are unreachable.@@ -868,7 +885,7 @@ export function getLatestSessionMessages(id: string, profile?: string | null): P*/export function getOlderSessionMessages(id: string,- profile: string | null | undefined,+ profile: ProfileScope,offset: number,limit: number = LATEST_SESSION_MESSAGES_LIMIT): Promise<SessionMessagesResponse> {@@ -877,7 +894,7 @@ export function getOlderSessionMessages(export async function getAllSessionMessages(id: string,- profile?: string | null,+ profile?: ProfileScope,options: { maxJsonChars?: number } = {}): Promise<SessionMessagesResponse> {const messages: SessionMessage[] = []@@ -917,9 +934,9 @@ export async function getAllSessionMessages(return { session_id: resolvedSessionId, messages }}-export function deleteSession(id: string, profile?: string | null): Promise<{ ok: boolean }> {+export function deleteSession(id: string, profile?: ProfileScope): Promise<{ ok: boolean }> {return window.hermesDesktop.api<{ ok: boolean }>({- ...(profile ? { profile } : {}),+ ...sessionScoped(profile),path: `/api/sessions/${encodeURIComponent(id)}`,method: 'DELETE'})@@ -1771,9 +1788,21 @@ export function renameProfile(name: string, newName: string): Promise<{ name: st})}-export function deleteProfile(name: string): Promise<{ ok: boolean; path: string }> {+export function deleteProfile(name: string, scope?: ProfileScope): Promise<{ ok: boolean; path: string }> {+ const normalized = name.trim()+ const scopedProfile = scope && typeof scope === 'object' ? scope.profile?.trim() : undefined++ if (!normalized) {+ return Promise.reject(new Error('Profile name required'))+ }++ if (normalized.toLowerCase() === 'default' || scopedProfile?.toLowerCase() === 'default') {+ return Promise.reject(new Error('The default profile cannot be deleted.'))+ }+return window.hermesDesktop.api<{ ok: boolean; path: string }>({- path: `/api/profiles/${encodeURIComponent(name)}`,+ ...capabilityScoped(scope),+ path: `/api/profiles/${encodeURIComponent(normalized)}`,method: 'DELETE'})}diff --git a/apps/desktop/src/lib/session-link-title.test.ts b/apps/desktop/src/lib/session-link-title.test.tsindex 5efa8ba3efd..4f753c33312 100644--- a/apps/desktop/src/lib/session-link-title.test.ts+++ b/apps/desktop/src/lib/session-link-title.test.ts@@ -84,9 +84,11 @@ describe('fetchSessionLinkTitle', () => {})it('keeps separate cache entries per profile', async () => {- vi.mocked(getSession).mockImplementation(async (id, profile) =>- makeSession({ id, profile: profile ?? 'default', title: profile === 'work' ? 'Work chat' : 'Home chat' })- )+ vi.mocked(getSession).mockImplementation(async (id, scope) => {+ const profile = typeof scope === 'string' ? scope : scope?.profile || 'default'++ return makeSession({ id, profile, title: profile === 'work' ? 'Work chat' : 'Home chat' })+ })await expect(fetchSessionLinkTitle('default/20260101_abc123')).resolves.toBe('Home chat')await expect(fetchSessionLinkTitle('work/20260101_abc123')).resolves.toBe('Work chat')diff --git a/apps/desktop/src/plugins/hermes-bots/plugin.js b/apps/desktop/src/plugins/hermes-bots/plugin.jsindex 1f5257f18c3..cab453ae274 100644--- a/apps/desktop/src/plugins/hermes-bots/plugin.js+++ b/apps/desktop/src/plugins/hermes-bots/plugin.js@@ -86,6 +86,12 @@ const ID = 'hermes-bots'const ROSTER_KEY = [ID, 'roster']const ROUTINES_KEY = [ID, 'routines']const NAME_RE = /^[a-z0-9][a-z0-9_-]{0,63}$/+const BOT_META_V1_KEY = 'bot-meta'+const BOT_META_V2_KEY = 'bot-meta-v2'+const BOT_META_MIGRATION_KEY = 'bot-meta-v2-migrated'+let botMetaV2Active = false+let botMetaV2Commit = Promise.resolve()+const migratedLocalRoutes = new Map()/** Captured in register() so components can reach plugin storage. */let pluginCtx = null@@ -126,9 +132,10 @@ function trackInboundActivity(roster) {watermarksSeeded = truefor (const bot of roster) {+ const key = botSelectionKey(bot)const ts = bot.last_session?.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@@ -136,22 +143,22 @@ function trackInboundActivity(roster) {// Activity in the bot the user is currently looking at is already// visible — never badge the open chat.- if ($selectedBot.get() === bot.name) {+ if ($selectedBot.get() === key) {continue}- $botUnread.set({ ...$botUnread.get(), [bot.name]: true })+ $botUnread.set({ ...$botUnread.get(), [key]: true })// Roster-hidden bots stay quiet: the unread flag above accumulates// silently (unhiding reveals the badge) but a hidden bot never toasts.- if ($botMeta.get()[bot.name]?.hidden) {+ if (botRosterMeta(bot, $botMeta.get())?.hidden) {continue}// 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 inbound = /^Message from/i.test(preview)@@ -214,14 +221,61 @@ function handleSessionsGatewayTransition() {* { [botName]: { shape, color, title } } */const $botMeta = atom({})-async function saveBotMeta(name, patch) {- const prevMeta = $botMeta.get()[name] || {}- const next = { ...$botMeta.get(), [name]: { ...prevMeta, ...patch } }+function commitBotMetaV2(storage, snapshot) {+ const commit = botMetaV2Commit.then(async () => {+ if (typeof storage?.remove !== 'function' || typeof storage?.set !== 'function') {+ throw new Error('bot metadata v2 storage is unavailable')+ }++ try {+ await storage.remove(BOT_META_MIGRATION_KEY)+ await storage.set(BOT_META_V2_KEY, snapshot)+ await storage.set(BOT_META_MIGRATION_KEY, true)+ } catch (error) {+ await Promise.allSettled(+ [BOT_META_MIGRATION_KEY, BOT_META_V2_KEY].map(key => storage.remove(key))+ )+ throw error+ }+ })++ botMetaV2Commit = commit.catch(() => undefined)++ return commit+}++function botOwner(owner) {+ if (typeof owner === 'string') {+ const name = owner.trim()+ const route = migratedLocalRoutes.get(name)++ return {+ bot: route ? { name, sourceScoped: true, route } : { name },+ name,+ key: route ? botRouteKey(route) : name,+ route: route || null+ }+ }++ const name = String(owner?.name || '').trim()+ const route = botConnectionRoute(owner)++ return { bot: owner, name, key: route ? botRouteKey(route) : name, route }+}++async function saveBotMeta(owner, patch) {+ const { bot, key, name, route } = botOwner(owner)+ const prevMeta = $botMeta.get()[key] || {}+ const next = { ...$botMeta.get(), [key]: { ...prevMeta, ...patch } }$botMeta.set(next)// Local plugin storage: instant, and the fallback for older gateways.+ let localPersistence = Promise.resolve()try {- Promise.resolve(pluginCtx?.storage?.set?.('bot-meta', next)).catch(() => undefined)+ const persisted = route || botMetaV2Active+ ? commitBotMetaV2(pluginCtx?.storage, next)+ : Promise.resolve(pluginCtx?.storage?.set?.(BOT_META_V1_KEY, next))+ localPersistence = persisted.catch(() => undefined)} catch {/* storage unavailable — look persists for this window only */}@@ -236,8 +290,10 @@ async function saveBotMeta(name, patch) {// the list call — so pfps follow the profile across machines too.let serverRequest = nulltry {- const { image, pet, ...rest } = next[name] || {}- serverRequest = Promise.resolve(host.request('profiles.configure', { name, ui_meta: { 'hermes-bots': rest } }))+ const { image, pet, ...rest } = next[key] || {}+ const request = route ? requestForBot(bot, 'profiles.configure', { name, ui_meta: { 'hermes-bots': rest } }) :+ host.request('profiles.configure', { name, ui_meta: { 'hermes-bots': rest } })+ serverRequest = Promise.resolve(request)} catch {/* older/unavailable gateway — the local fallback remains saved */}@@ -251,8 +307,12 @@ async function saveBotMeta(name, patch) {if ('image' in patch && patch.image !== (prevMeta.image ?? null)) {try {const req = patch.image- ? host.request('profiles.set_asset', { name, asset: 'avatar', data: patch.image })- : host.request('profiles.set_asset', { name, asset: 'avatar', clear: true })+ ? (route+ ? requestForBot(bot, 'profiles.set_asset', { name, asset: 'avatar', data: patch.image })+ : host.request('profiles.set_asset', { name, asset: 'avatar', data: patch.image }))+ : (route+ ? requestForBot(bot, 'profiles.set_asset', { name, asset: 'avatar', clear: true })+ : host.request('profiles.set_asset', { name, asset: 'avatar', clear: true }))req.catch(() => undefined)} catch {/* older gateway */@@ -282,9 +342,147 @@ async function saveBotMeta(name, patch) {}}+ await localPersistence+return { serverPersisted: serverOutcome === 'persisted', serverOutcome }}+/** Migrate name-keyed appearance state only when the live registry proves+ * there is one local source. A v1 name cannot identify a machine in a+ * multi-source desktop, so the conservative result there is to retain v1 as+ * rollback data and leave remote rows unpainted. */+function hydrateBotMeta(snapshot, remap = null) {+ const next = { ...snapshot }++ for (const [key, meta] of Object.entries($botMeta.get())) {+ const target = remap?.get(key) || key+ next[target] = { ...(next[target] || {}), ...meta }+ }++ $botMeta.set(next)++ return next+}++async function migrateBotMeta(storage = pluginCtx?.storage) {+ let v1 = null+ let v2 = null+ let v2Committed = false++ try {+ ;[v1, v2, v2Committed] = await Promise.all([+ storage?.get?.(BOT_META_V1_KEY),+ storage?.get?.(BOT_META_V2_KEY),+ storage?.get?.(BOT_META_MIGRATION_KEY)+ ])+ } catch {+ return false+ }++ if (v2Committed === true && v2 && typeof v2 === 'object' && !Array.isArray(v2)) {+ hydrateBotMeta(v2)+ botMetaV2Active = true++ return true+ }++ if (!v1 || typeof v1 !== 'object' || Array.isArray(v1) || typeof host.agents !== 'function') {+ if (v1 && typeof v1 === 'object' && !Array.isArray(v1)) {+ hydrateBotMeta(v1)+ }++ return false+ }++ let union+ let routes++ try {+ union = await host.agents()+ routes = typeof host.profileRoutes === 'function' ? await host.profileRoutes() : []+ } catch {+ hydrateBotMeta(v1)++ return false+ }++ const sources = Array.isArray(union?.sources) ? union.sources : []+ const localAgents = (union?.agents || []).filter(agent => agent?.connectionKind === 'local')+ const soleLocal = sources.length === 1+ ? sources[0]?.kind === 'local'+ : sources.length === 0 && localAgents.length > 0 && (union?.agents || []).every(agent => agent?.connectionKind === 'local')++ if (!soleLocal) {+ hydrateBotMeta(v1)++ return false+ }++ const migrated = {}+ const pendingLocalRoutes = new Map()++ for (const [name, meta] of Object.entries(v1)) {+ const route = (routes || []).find(candidate => candidate?.mode === 'local' && candidate?.profile === name) ||+ (() => {+ const agent = localAgents.find(candidate => candidate.profile === name)++ return agent+ ? {+ connectionId: agent.connectionId,+ mode: 'local',+ profile: name,+ targetProfile: agent.targetProfile || name+ }+ : null+ })()++ if (!route?.connectionId) {+ // A missing route makes the topology proof unusable for this key. Keep+ // the v1 record intact rather than guessing a local/remote projection.+ hydrateBotMeta(v1)++ return false+ }++ const captured = {+ connectionId: route.connectionId,+ mode: 'local',+ profile: name,+ targetProfile: route.targetProfile || name+ }+ migrated[botRouteKey(captured)] = meta+ pendingLocalRoutes.set(name, captured)+ }++ const remap = new Map(+ [...pendingLocalRoutes].map(([name, route]) => [name, botRouteKey(route)])+ )+ const hydrated = { ...migrated }++ for (const [key, meta] of Object.entries($botMeta.get())) {+ const target = remap.get(key) || key+ hydrated[target] = { ...(hydrated[target] || {}), ...meta }+ }++ try {+ await commitBotMetaV2(storage, hydrated)+ } catch {+ botMetaV2Active = false+ hydrateBotMeta(v1)++ return false+ }++ migratedLocalRoutes.clear()+ for (const [name, route] of pendingLocalRoutes) {+ migratedLocalRoutes.set(name, route)+ }+ hydrateBotMeta(hydrated)+ botMetaV2Active = true++ return true+}+// ── hidden bots (right-click → Hide Bot) ────────────────────────────────────// Hiding is a ROSTER-DISPLAY concern only: a hidden bot keeps working —// @mentions still resolve, group-chat membership is untouched, its name@@ -318,14 +516,19 @@ function fallbackSelectionAfterHide(name) {const meta = $botMeta.get()const visible = $lastRoster.get()- .filter(bot => !bot.remoteSource && bot.name !== name && !meta[bot.name]?.hidden)+ .filter(bot => botSelectionKey(bot) !== name && !botRosterMeta(bot, meta)?.hidden)if (visible.length) {- $selectedBot.set(visible[0].name)+ $selectedBot.set(botSelectionKey(visible[0]))return}- if (name !== 'default' && !meta.default?.hidden) {+ const defaultBot = $lastRoster.get().find(bot => isDefaultBot(bot) && !botRosterMeta(bot, meta)?.hidden)+ if (defaultBot && botSelectionKey(defaultBot) !== name) {+ $selectedBot.set(botSelectionKey(defaultBot))+ } else if (!$lastRoster.get().some(isDefaultBot)) {+ // Legacy sole-local rosters can transiently omit the default row. Keep the+ // historic fallback rather than leaving Routines attached to a hidden bot.$selectedBot.set('default')}}@@ -339,19 +542,26 @@ function fallbackSelectionAfterHide(name) {* 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 canonical = Object.values($botMeta.get())- .map(m => m && m.chat)+ const roster = $lastRoster.get()+ const canonical = Object.entries($botMeta.get())+ .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)- const ids = [...new Set([...canonical, ...rooms])]-- const known = Promise.all(- ids.map(sid =>+ .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))- )+ ])return Promise.all([known, sweepBotProfileSessions().catch(() => undefined)])}@@ -391,7 +601,12 @@ async function sweepBotProfileSessions() {// back to the active gateway's own profile list (local bots; remote// sources get covered by the next sweep once the roster cache exists).try {- const res = await host.request('profiles.list', {})+ const route = await activeBotRoute()+ const res = await requestForBot(+ route ? { name: route.profile, sourceScoped: true, route } : { name: 'default' },+ 'profiles.list',+ {}+ )roster = Array.isArray(res?.profiles) ? res.profiles : []} catch {return@@ -437,18 +652,22 @@ const avatarPushInflight = new Set()* cross-machine roster art, so local-only images are a bug, not a state. */function pushLocalAvatars(roster) {for (const bot of roster) {- if (bot.has_avatar || avatarPushInflight.has(bot.name)) {+ const key = botMetaKey(bot)++ if (bot.has_avatar || avatarPushInflight.has(key)) {continue}- const image = $botMeta.get()[bot.name]?.image+ const image = $botMeta.get()[key]?.imageif (image && typeof image === 'string' && image.startsWith('data:')) {- avatarPushInflight.add(bot.name)- host- .request('profiles.set_asset', { name: bot.name, asset: 'avatar', data: image })+ avatarPushInflight.add(key)+ const request = bot.sourceScoped+ ? requestForBot(bot, 'profiles.set_asset', { name: bot.name, asset: 'avatar', data: image })+ : host.request('profiles.set_asset', { name: bot.name, asset: 'avatar', data: image })+ Promise.resolve(request).then(() => queryClient.invalidateQueries({ queryKey: ['hermes-bots', 'roster'] }))- .catch(() => avatarPushInflight.delete(bot.name))+ .catch(() => avatarPushInflight.delete(key))continue}@@ -461,16 +680,17 @@ function pushLocalAvatars(roster) {continue}- avatarPushInflight.add(bot.name)+ avatarPushInflight.add(key)rasterizeSvgToPng(svg, 160).then(png =>png- ? host- .request('profiles.set_asset', { name: bot.name, asset: 'avatar', data: png })+ ? (bot.sourceScoped+ ? requestForBot(bot, 'profiles.set_asset', { name: bot.name, asset: 'avatar', data: png })+ : host.request('profiles.set_asset', { name: bot.name, asset: 'avatar', data: png })).then(() => queryClient.invalidateQueries({ queryKey: ['hermes-bots', 'roster'] })): Promise.reject(new Error('rasterize failed')))- .catch(() => avatarPushInflight.delete(bot.name))+ .catch(() => avatarPushInflight.delete(key))}}@@ -529,37 +749,36 @@ function pullServerAvatars(roster) {pushLocalAvatars(roster)for (const bot of roster) {- if (!bot.has_avatar || avatarFetchInflight.has(bot.name)) {+ const key = botMetaKey(bot)++ if (!bot.has_avatar || avatarFetchInflight.has(key)) {continue}- if ($botMeta.get()[bot.name]?.image) {+ if ($botMeta.get()[key]?.image) {continue}- avatarFetchInflight.add(bot.name)- host- .request('profiles.get_asset', { name: bot.name, asset: 'avatar' })+ avatarFetchInflight.add(key)+ const assetRequest = bot.sourceScoped+ ? requestForBot(bot, 'profiles.get_asset', { name: bot.name, asset: 'avatar' })+ : host.request('profiles.get_asset', { name: bot.name, asset: 'avatar' })+ Promise.resolve(assetRequest).then(res => {if (res?.found && res.data) {const current = $botMeta.get()- const mine = current[bot.name] || {}+ const mine = current[key] || {}// A 160px raster of the vector face is only for inter-agent// notices. Do not park it on the roster or the live face dies.if (isBackfilledFacePng(res.data) && mine.imageKind !== 'photo' && !mine.pet) {return}- $botMeta.set({ ...current, [bot.name]: { ...mine, image: res.data } })-- try {- Promise.resolve(pluginCtx?.storage?.set?.('bot-meta', $botMeta.get())).catch(() => undefined)- } catch {- /* no storage */- }+ $botMeta.set({ ...current, [key]: { ...mine, image: res.data } })+ persistBotMetaSnapshot($botMeta.get(), Boolean(bot.sourceScoped))}}).catch(() => undefined)- .finally(() => avatarFetchInflight.delete(bot.name))+ .finally(() => avatarFetchInflight.delete(key))}}@@ -577,7 +796,8 @@ function mergeServerMeta(roster) {for (const bot of roster) {const server = bot.ui_meta?.['hermes-bots']if (server && typeof server === 'object') {- const mine = next[bot.name] || {}+ const key = botMetaKey(bot)+ const mine = next[key] || {}const merged = { ...mine, ...server }// Local-only fields survive the server overlay.@@ -607,8 +827,8 @@ function mergeServerMeta(roster) {delete merged.group}- if (JSON.stringify(next[bot.name] || null) !== JSON.stringify(merged)) {- next[bot.name] = merged+ if (JSON.stringify(next[key] || null) !== JSON.stringify(merged)) {+ next[key] = mergedchanged = true}}@@ -620,7 +840,7 @@ function mergeServerMeta(roster) {// Persist server reconciliation so a relaunch cannot rehydrate stale// local fields that the server intentionally removed.try {- Promise.resolve(pluginCtx?.storage?.set?.('bot-meta', next)).catch(() => undefined)+ persistBotMetaSnapshot(next, roster.some(bot => bot.sourceScoped))} catch {/* storage unavailable — reconciliation lasts for this window only */}@@ -630,7 +850,10 @@ function mergeServerMeta(roster) {/** Clone a bot: profile (config/skills/SOUL/memory via clone_from) + look.* Name is "<base>-2", "-3", … — first free slot against the live roster. */async function duplicateBot(bot, roster) {+ await ensureBotMetadata(bot)const base = bot.name+ const ownerRoute = botConnectionRoute(bot)+ const ownerKey = ownerRoute ? botRouteKey(ownerRoute) : nulllet name = nullfor (let n = 2; n < 100; n++) {// Truncate the BASE, never the suffix — slicing the joined string chops@@ -638,7 +861,7 @@ async function duplicateBot(bot, roster) {// base forever (#19).const suffix = `-${n}`const candidate = base.slice(0, 64 - suffix.length) + suffix- if (!roster.some(b => b.name === candidate)) {+ if (!roster.some(b => b.name === candidate && (!ownerKey || botMetaKey(b)?.startsWith(`${ownerRoute.connectionId}::`)))) {name = candidatebreak}@@ -648,7 +871,7 @@ async function duplicateBot(bot, roster) {throw new Error('No free name for the duplicate.')}- await host.request('profiles.create', {+ await requestForBot(bot, 'profiles.create', {name,clone_from: base,description: bot.description || ''@@ -657,10 +880,10 @@ async function duplicateBot(bot, roster) {// Same look: avatar shape/color/image and a "(copy)" title so the two// are tellable apart in the roster until the user renames. Do not copy// chat or created. Those belong to the original bot.- const meta = $botMeta.get()[base]+ const meta = $botMeta.get()[botMetaKey(bot)]if (meta) {const { chat, created, ...look } = meta- saveBotMeta(name, {+ await saveBotMeta({ ...bot, name, route: ownerRoute, sourceScoped: Boolean(ownerRoute) }, {...look,title: meta.title ? `${meta.title} (copy)` : ''})@@ -681,13 +904,25 @@ async function duplicateBot(bot, roster) {* renderer's socket reconnect respawns it mid-delete, resurrecting the* directory (hermes-agent#52279). That is the "can't delete a bot" error. */async function deleteBot(bot) {+ const route = botConnectionRoute(bot)++ if (isDefaultBot(bot) || String(route?.targetProfile || '').toLowerCase() === 'default') {+ throw new Error('The default profile cannot be deleted.')+ }+if (typeof host.deleteProfile === 'function') {- await host.deleteProfile(bot.name)+ if (route) {+ await host.deleteProfile(route)+ } else {+ await host.deleteProfile(bot.name)+ }} else {- // Older desktop without the SDK verb — best effort via the CLI.- const result = await host.request('cli.exec', {+ // Older desktop without the SDK verb — source-scoped rows fail closed.+ const result = await (route ? requestForBot(bot, 'cli.exec', {argv: ['profile', 'delete', bot.name, '--yes']- })+ }) : host.request('cli.exec', {+ argv: ['profile', 'delete', bot.name, '--yes']+ }))if (result?.blocked || result?.code !== 0) {throw new Error(result?.hint || result?.output || `Could not delete profile ${bot.name}.`)@@ -695,23 +930,27 @@ async function deleteBot(bot) {}const meta = { ...$botMeta.get() }- delete meta[bot.name]+ delete meta[botMetaKey(bot)]$botMeta.set(meta)try {- await Promise.resolve(pluginCtx?.storage?.set?.('bot-meta', meta))+ if (route) {+ await commitBotMetaV2(pluginCtx?.storage, meta)+ } else {+ await Promise.resolve(pluginCtx?.storage?.set?.(BOT_META_V1_KEY, meta))+ }} catch {/* profile is deleted; stale local appearance is harmless if storage fails */}const unread = { ...$botUnread.get() }- delete unread[bot.name]+ delete unread[botSelectionKey(bot)]$botUnread.set(unread)- rosterWatermarks.delete(bot.name)- avatarFetchInflight.delete(bot.name)- avatarPushInflight.delete(bot.name)+ rosterWatermarks.delete(botSelectionKey(bot))+ avatarFetchInflight.delete(botMetaKey(bot))+ avatarPushInflight.delete(botMetaKey(bot))- if ($selectedBot.get() === bot.name) {+ if ($selectedBot.get() === botSelectionKey(bot)) {$selectedBot.set('default')}@@ -2605,16 +2844,43 @@ let serverInjectsProtocol = false* (preferred_session), so a row's preview can describe the same session its* click opens (hermes-agent#88200). Unknown params are ignored by older* gateways, which simply omit the field. */-function preferredSessionIds(allMeta) {+function preferredSessionIds(allMeta, activeRoute = null) {const pins = {}- for (const [name, meta] of Object.entries(allMeta || {})) {+ for (const [key, meta] of Object.entries(allMeta || {})) {if (meta?.chat) {- pins[name] = meta.chat+ const name = key.includes('::')+ ? (activeRoute && key === botRouteKey(activeRoute) ? activeRoute.profile : null)+ : key++ if (name) {+ pins[name] = meta.chat+ }}}return pins}+async function activeBotRoute() {+ if (typeof host.profileRoutes !== 'function') {+ return null+ }++ const profile = String(host.state.profile?.get?.() || 'default').trim() || 'default'+ const connectionId = String(+ host.state.connectionId?.get?.() ||+ (typeof host.activeConnectionId === 'function' ? host.activeConnectionId() : '') ||+ 'local'+ ).trim() || 'local'+ const routes = await host.profileRoutes()+ const route = routes.find(candidate => candidate?.connectionId === connectionId && candidate?.profile === profile)++ if (!route && typeof host.agents === 'function') {+ throw new Error(`No route for active bot ${connectionId}::${profile}`)+ }++ return route || null+}+function useRoster() {const activeConnectionId = useValue(host.state.connectionId)@@ -2623,8 +2889,13 @@ function useRoster() {queryFn: async () => {// 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 } : {})@@ -2665,8 +2936,9 @@ function useRoster() {* already returned: they only ANNOTATE the rich rows (handle, connection* fields); rich fields stay authoritative and they are NOT duplicated.* Rows from other sources become new roster entries tagged with their- * source label so BotRow can badge them and route open/warm through- * ensureAgent/warmAgent. Pure — exercised directly by the tests. */+ * source label so BotRow can badge them, warm the captured agent, and route+ * every open directly through that descriptor. Pure — exercised directly by+ * the tests. */function mergeMultiSourceRoster(local, union, activeConnectionId, previous = []) {const localProfiles = Array.isArray(local?.profiles) ? local.profiles : []const agents = Array.isArray(union?.agents) ? union.agents : []@@ -2756,6 +3028,13 @@ function mergeMultiSourceRoster(local, union, activeConnectionId, previous = [])row.connectionId = agent.connectionIdrow.connectionKind = agent.connectionKindrow.connectionLabel = agent.connectionLabel+ row.targetProfile = agent.targetProfile || profile+ row.route = {+ connectionId,+ mode: agent.connectionKind === 'local' ? 'local' : 'remote',+ profile,+ targetProfile: agent.targetProfile || profile+ }row.sourceScoped = truecontinue}@@ -2772,6 +3051,13 @@ function mergeMultiSourceRoster(local, union, activeConnectionId, previous = [])connectionId,connectionKind: agent.connectionKind,connectionLabel: agent.connectionLabel,+ targetProfile: agent.targetProfile || profile,+ route: {+ connectionId,+ mode: agent.connectionKind === 'local' ? 'local' : 'remote',+ profile,+ targetProfile: agent.targetProfile || profile+ },remoteSource: true,sourceScoped: true})@@ -2849,6 +3135,26 @@ function isActiveRosterBot(bot, active) {return botName === activeName}+function botSelectionKey(bot) {+ return bot?.sourceScoped || bot?.remoteSource ? botRosterKey(bot) : bot?.name+}++function isDefaultBot(bot) {+ const route = botConnectionRoute(bot)++ return String(route?.profile || bot?.name || '').trim().toLowerCase() === 'default'+}++function newBotChat(bot) {+ if (typeof host.newChat !== 'function') {+ host.navigate?.('/')++ return+ }++ host.newChat(bot?.sourceScoped || bot?.remoteSource ? botConnectionRoute(bot) : bot?.name)+}+/** Resolve @handles in prose against the Bot Mode roster (local + Connections).* Skips the bot already speaking in this chat. Unique bare names match;* duplicate names require the @name-device handle. */@@ -2926,10 +3232,11 @@ const REMOTE_DM_POLL_MS = 2000* minting a fresh "Bot Chat" per mention. */async function ensureRemoteCanonicalChat(route, profile) {let pinned = null+ const backendProfile = route.targetProfile || profiletry {const listed = await host.requestProfile(route, 'profiles.list', {})- const owner = listed?.profiles?.find(p => p.name === profile)+ const owner = listed?.profiles?.find(p => p.name === backendProfile)pinned = owner?.ui_meta?.['hermes-bots']?.chat || null} catch {/* older remote gateway — title lookup below still works */@@ -2943,7 +3250,7 @@ async function ensureRemoteCanonicalChat(route, profile) {try {const res = await host.requestProfile(route, 'session.resume', {session_id: target,- profile,+ profile: backendProfile,omit_messages: true})@@ -2956,7 +3263,7 @@ async function ensureRemoteCanonicalChat(route, profile) {}const created = await host.requestProfile(route, 'session.create', {- profile,+ profile: backendProfile,title: 'Bot Chat',// Bot Mode sessions are always hidden from the global sidebar.hidden: true@@ -2969,6 +3276,7 @@ async function ensureRemoteCanonicalChat(route, profile) {* member turn: wait for a NEW assistant message after `before`, or time out. */async function pollRemoteDmReply(route, profile, sessionRef, before) {const deadline = Date.now() + REMOTE_DM_TIMEOUT_MS+ const backendProfile = route.targetProfile || profilewhile (Date.now() < deadline) {await new Promise(resolve => setTimeout(resolve, REMOTE_DM_POLL_MS))@@ -2976,7 +3284,10 @@ async function pollRemoteDmReply(route, profile, sessionRef, before) {let state = nulltry {- state = await host.requestProfile(route, 'session.resume', { session_id: sessionRef, profile })+ state = await host.requestProfile(route, 'session.resume', {+ session_id: sessionRef,+ profile: backendProfile+ })} catch {continue}@@ -3029,7 +3340,7 @@ async function deliverRemoteRosterMentions(bots, userText, sender) {continue}- const route = { connectionId, mode: 'remote', profile, targetProfile: profile }+ const route = botConnectionRoute(bot)const label = bot.connectionLabel || connectionIdtry {@@ -3043,7 +3354,10 @@ async function deliverRemoteRosterMentions(bots, userText, sender) {let before = 0try {- const pre = await host.requestProfile(route, 'session.resume', { session_id: stored || runtime, profile })+ const pre = await host.requestProfile(route, 'session.resume', {+ session_id: stored || runtime,+ profile: route.targetProfile || profile+ })before = Array.isArray(pre?.messages) ? pre.messages.length : pre?.message_count || 0} catch {/* lazy session — zero messages */@@ -3091,33 +3405,106 @@ function botRosterKey(bot) {return `${bot?.connectionId || 'legacy'}::${bot?.name || 'default'}`}+function botRouteKey(route) {+ return `${route.connectionId}::${route.profile}`+}++function botMetaKey(bot) {+ const route = botConnectionRoute(bot)++ return route ? botRouteKey(route) : bot?.name+}++function persistBotMetaSnapshot(value, scoped = false) {+ try {+ const persisted = scoped+ ? commitBotMetaV2(pluginCtx?.storage, value)+ : Promise.resolve(pluginCtx?.storage?.set?.(BOT_META_V1_KEY, value))++ return persisted.catch(() => undefined)+ } catch {+ return Promise.resolve()+ }+}+// ── cross-connection routing ─────────────────────────────────────────────────// A bot from another registered connection (remoteSource rows) is reached// through host.requestProfile with a route descriptor; local bots keep the// active-gateway door. Feature-detected: older desktops without// requestProfile simply have no remote routes (callers fall back / disable).-/** Route descriptor for a bot on another connection, or null for the local /- * active source (or when the desktop can't route). */+/** Immutable owner descriptor for every source-scoped row. The active+ * gateway is presentation state and is never consulted here. */function botConnectionRoute(bot) {- const id = String(bot?.connectionId || '').trim()-- if (!bot?.remoteSource || !id || id === 'local' || typeof host.requestProfile !== 'function') {+ if (!bot?.sourceScoped && !bot?.remoteSource) {return null}- const profile = String(bot?.name || '').trim() || 'default'+ const candidate = bot.route || {+ connectionId: bot.connectionId,+ mode: bot.connectionKind === 'local' ? 'local' : 'remote',+ profile: bot.name,+ targetProfile: bot.targetProfile || bot.name+ }+ const connectionId = String(candidate?.connectionId || '').trim()+ const profile = String(candidate?.profile || bot?.name || '').trim() || 'default'+ const targetProfile = String(candidate?.targetProfile || profile).trim() || profile- return { connectionId: id, mode: 'remote', profile, targetProfile: profile }+ if (!connectionId) {+ throw new Error(`Bot ${profile} has no connection owner`)+ }++ return Object.freeze({+ connectionId,+ mode: candidate.mode === 'local' || connectionId === 'local' ? 'local' : 'remote',+ profile,+ targetProfile+ })}-/** Gateway RPC on the bot's OWN source: requestProfile for remote rows,- * the active gateway for local ones. Never activates/foregrounds. */+function scopedBotParams(route, method, params) {+ const logical = route.profile+ const target = route.targetProfile || logical+ let next = params++ if (Object.prototype.hasOwnProperty.call(params, 'profile')) {+ next = { ...next, profile: target }+ }++ if (method.startsWith('profiles.') && method !== 'profiles.create' && params.name === logical) {+ next = { ...next, name: target }+ }++ if (params.clone_from === logical) {+ next = { ...next, clone_from: target }+ }++ if (method === 'cli.exec' && Array.isArray(params.argv)) {+ next = { ...next, argv: params.argv.map(arg => arg === logical ? target : arg) }+ }++ return next+}++function botBackendProfileScope(route, fallbackProfile = 'default') {+ if (!route) {+ return fallbackProfile+ }++ return { connectionId: route.connectionId, profile: route.targetProfile || route.profile }+}++/** Gateway RPC on the bot's OWN source. Source-scoped rows always use the+ * explicit descriptor, including a registered local source. */async function requestForBot(bot, method, params = {}) {const route = botConnectionRoute(bot)if (route) {- return host.requestProfile(route, method, params)+ if (typeof host.requestProfile !== 'function') {+ throw new Error(`Cannot route ${method} for ${route.connectionId}::${route.profile}`)+ }++ return host.requestProfile(route, method, scopedBotParams(route, method, params))}return host.request(method, params)@@ -3128,7 +3515,7 @@ async function requestForBot(bot, method, params = {}) {* 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}// Bot metadata is scoped to the active gateway until the server exposes a@@ -3136,7 +3523,13 @@ function groupMemberKey(member) {// another source: two `default` agents must not borrow each other's title,// pin, avatar, group, unread state, or canonical-chat pointer.function botRosterMeta(bot, metaByName) {- return bot?.remoteSource ? null : metaByName?.[bot?.name]+ if (bot?.sourceScoped || bot?.remoteSource) {+ const route = botConnectionRoute(bot)++ return route ? metaByName?.[botRouteKey(route)] : null+ }++ return metaByName?.[bot?.name]}function showsHandle(name, meta, bot) {@@ -3163,16 +3556,19 @@ function showsHandle(name, meta, bot) {const canonicalCreations = new Map()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')}+ const { name, route } = botOwner(owner)+const hasAuthoritativeCount =typeof summary?.message_count === 'number' && Number.isFinite(summary.message_count)const expectHistory = hasAuthoritativeCount ? summary.message_count > 0 : trueawait host.openSession(storedId, {+ ...(route ? { route } : {}),profile: name,intent: 'main',awaitHydration: true,@@ -3186,15 +3582,16 @@ async function openStoredBotChat(name, storedId, summary) {* 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. */-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 res = await host.request('session.create', {+ const res = await requestForBot(bot, 'session.create', {profile: name,title: 'Bot Chat',// Always born hidden from the global sidebar — Bot Mode sessions are@@ -3207,7 +3604,7 @@ function createCanonicalChat(name) {const runtime = res?.session_idif (sid) {- saveBotMeta(name, { chat: sid })+ saveBotMeta(owner, { chat: sid })}// Mount the session view FIRST, then send the kickoff — submitting into@@ -3216,7 +3613,7 @@ function createCanonicalChat(name) {if (sid && typeof host.openSession === 'function') {try {- await host.openSession(sid, { profile: name, intent: 'main' })+ await host.openSession(sid, { ...(route ? { route } : {}), profile: name, intent: 'main' })opened = true} catch {// The stored row may not exist until the kickoff persists it. Retry@@ -3228,10 +3625,10 @@ function createCanonicalChat(name) {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' })+ await host.openSession(sid, { ...(route ? { route } : {}), profile: name, intent: 'main' })}} catch {// The chat already exists. Keep the pin so the next click@@ -3240,9 +3637,9 @@ function createCanonicalChat(name) {}return sid || null- })().finally(() => canonicalCreations.delete(name))+ })().finally(() => canonicalCreations.delete(key))- canonicalCreations.set(name, run)+ canonicalCreations.set(key, run)return run}@@ -3260,16 +3657,18 @@ function createCanonicalChat(name) {* session.list window, which misjudged real hidden pins as gone;* - transient lookup failures keep the pin: try the stored id as-is, and* only a rejected open enters recovery. */-async function openBotCanonicalChat(name, pinned, history) {+async function openBotCanonicalChat(owner, pinned, history) {+ const { bot, name } = botOwner(owner)+if (!pinned) {// Grandfather: adopt the conversation the row already previews.const adoptId = history?.idif (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@@ -3278,7 +3677,7 @@ async function openBotCanonicalChat(name, pinned, history) {let preferredlet lookupFailed = falsetry {- const res = await host.request('profiles.list', {+ const res = await requestForBot(bot, 'profiles.list', {include_sessions: true,preferred_session_ids: { [name]: pinned }})@@ -3296,12 +3695,12 @@ async function openBotCanonicalChat(name, pinned, history) {// 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) {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@@ -3316,41 +3715,23 @@ async function openBotCanonicalChat(name, pinned, history) {// recovery): re-anchor on the previewed session when there is one.const recoveryId = history?.idif (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) {- if (!bot.sourceScoped) {+ if (!bot.sourceScoped || pinnedChat) {return pinnedChat}- if (typeof host.ensureAgent !== 'function') {- throw new Error('Update Hermes Desktop to chat with agents on other connections.')- }-- await host.ensureAgent(bot.connectionId, bot.name)-- if (!bot.remoteSource) {- return pinnedChat- }-- const liveId = String(typeof host.activeConnectionId === 'function' ? host.activeConnectionId() || '' : '').trim()- const targetId = String(bot.connectionId || '').trim()-- if (targetId && targetId !== 'local' && liveId !== targetId) {- throw new Error(`Still on ${liveId || 'this device'}, not ${bot.connectionLabel || targetId}`)- }-- // Thin rows deliberately omit metadata from the active source. Once their- // owner is active, recover that source's canonical-chat pointer so- // same-named agents never reuse or overwrite each other's pin.+ // Thin rows deliberately omit metadata. Read it on the captured owner+ // route; activation is a UI concern and cannot authorize this RPC.try {- const refreshed = await host.request('profiles.list', {})+ const refreshed = await requestForBot(bot, 'profiles.list', {})const owner = refreshed?.profiles?.find(profile => profile.name === bot.name)return owner?.ui_meta?.['hermes-bots']?.chat || null@@ -3360,6 +3741,24 @@ async function prepareBotSource(bot, pinnedChat) {}}+async function ensureBotMetadata(bot) {+ if (!bot?.sourceScoped) {+ return botRosterMeta(bot, $botMeta.get()) || {}+ }++ const result = await requestForBot(bot, 'profiles.list', {})+ const row = (result?.profiles || []).find(profile => profile?.name === bot.name)+ const server = row?.ui_meta?.['hermes-bots']++ if (server && typeof server === 'object') {+ const key = botMetaKey(bot)+ $botMeta.set({ ...$botMeta.get(), [key]: { ...($botMeta.get()[key] || {}), ...server } })+ persistBotMetaSnapshot($botMeta.get(), true)+ }++ return botRosterMeta(bot, $botMeta.get()) || {}+}+function displayName(bot, meta) {// Only THIN rows from another source trade the friendly name for their// connection label — the active gateway's own default must keep reading@@ -3509,7 +3908,7 @@ function groupLastActivity(room) {* Prefers the LIVE roster row for a stored descriptor when present. */function groupChatMemberBots(group, roster, metaByName) {const local = (roster || []).filter(- bot => !bot.remoteSource && botGroups(botRosterMeta(bot, metaByName)).includes(group)+ bot => botGroups(botRosterMeta(bot, metaByName)).includes(group))const stored = ($groupChats.get()[group] || {}).members || []const seated = new Set(local.map(botRosterKey))@@ -3533,15 +3932,20 @@ function groupChatMemberBots(group, roster, metaByName) {* source's row may become remote after a connection switch, so retaining it* here is what keeps the same room intact across machines. */function durableGroupChatMembers(bots) {- return (bots || []).map(bot => ({- name: bot.name,- handle: bot.handle || bot.name,- connectionId: bot.connectionId,- connectionKind: bot.connectionKind,- connectionLabel: bot.connectionLabel,- remoteSource: true,- sourceScoped: true- }))+ return (bots || []).map(bot => {+ const route = botConnectionRoute(bot)++ return {+ name: bot.name,+ handle: bot.handle || bot.name,+ connectionId: bot.connectionId,+ connectionKind: bot.connectionKind,+ connectionLabel: bot.connectionLabel,+ ...(route ? { route, targetProfile: route.targetProfile } : {}),+ remoteSource: true,+ sourceScoped: Boolean(route)+ }+ })}/** Existing group names, alphabetical — feeds the Manage-groups dialog. */@@ -3862,12 +4266,12 @@ async function disbandGroupChat(group, members) {// best-effort profiles.configure per member), so a flaky gateway can't// strand the disband halfway with the room log already gone.for (const member of members) {- if (!member?.name || member.remoteSource) {+ if (!member?.name) {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))}}@@ -3935,14 +4339,14 @@ async function renameGroupChat(oldName, newName, members) {// list (syncs cross-machine via ui_meta). Remote members' seating lives in// the room record we just moved.for (const member of members || []) {- if (!member?.name || member.remoteSource) {+ if (!member?.name) {continue}- const meta = $botMeta.get()[member.name] || {}+ const meta = botRosterMeta(member, $botMeta.get()) || {}const groups = [...new Set(botGroups(meta).map(g => (g === oldName ? next : g)))]- await saveBotMeta(member.name, { groups, group: groups[0] || null })+ await saveBotMeta(member, { groups, group: groups[0] || null })}// Persist the re-keyed map (updateGroupChat writes the whole durable map).@@ -4643,7 +5047,8 @@ function BotRow({ bot, onDelete, onEdit, onGroup }) {const meta = botRosterMeta(bot, useValue($botMeta))const groups = botGroups(meta)const last = bot.last_session- const isActive = !bot.remoteSource && bot.name === activeProfile+ const activeConnectionId = String(host.state.connectionId?.get?.() || 'local').trim()+ const isActive = isActiveRosterBot(bot, { name: activeProfile, connectionId: activeConnectionId })const { shape, color, image } = botAppearance(bot.name, meta)// Keep user photos/pets. Drop the 160px SVG backfill so the math face can move.const photo = Boolean(image && !isBackfilledFacePng(image))@@ -4656,7 +5061,7 @@ function BotRow({ bot, onDelete, onEdit, onGroup }) {// 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])+ 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.// Preview identity must match click identity (#88200): when the backend@@ -4698,28 +5103,18 @@ function BotRow({ bot, onDelete, onEdit, onGroup }) {const open = async () => {const generation = ++botOpenGenerationhaptic('tap')- $selectedBot.set(bot.name)-- if (bot.remoteSource) {- const handle = botHandle(bot.name, bot)- host.notify?.({- kind: 'info',- title: displayName(bot),- message: `Stay in this chat and @${handle} to message them. Gateway stays on this device.`- })- return- }+ $selectedBot.set(botSelectionKey(bot))let pinnedChat = meta?.chat- if (!bot.remoteSource && $botUnread.get()[bot.name]) {+ if ($botUnread.get()[botSelectionKey(bot)]) {const next = { ...$botUnread.get() }- delete next[bot.name]+ delete next[botSelectionKey(bot)]$botUnread.set(next)}- // Activate the owner first so every canonical-chat RPC lands on the- // backend that owns this bot's state database.+ // Refresh through the immutable owner route. Foreground activation is+ // presentation state and is never routing authority for this open.try {pinnedChat = await prepareBotSource(bot, pinnedChat)} catch (error) {@@ -4733,7 +5128,7 @@ function BotRow({ bot, onDelete, onEdit, onGroup }) {}try {- const id = await openBotCanonicalChat(bot.name, pinnedChat, previewSession)+ const id = await openBotCanonicalChat(bot, pinnedChat, previewSession)if (generation === botOpenGeneration && id) {return@@ -4752,7 +5147,7 @@ function BotRow({ bot, onDelete, onEdit, onGroup }) {if (typeof host.newChat === 'function') {// Older gateway without profile-scoped session.create — plain draft.- host.newChat(bot.name)+ newBotChat(bot)} else {host.navigate('/')}@@ -4862,14 +5257,6 @@ function BotRow({ bot, onDelete, onEdit, onGroup }) {]})- // Thin rows from another source are navigation targets only. Their profile- // metadata is not loaded yet, so edit/delete/pin/group actions would mutate- // whichever backend happens to be active. A normal click activates the- // owner; the refreshed rich row then exposes the full context menu.- if (bot.remoteSource) {- return row- }-return jsxs(ContextMenu, {children: [jsx(ContextMenuTrigger, { asChild: true, children: row }),@@ -4877,32 +5264,34 @@ function BotRow({ bot, onDelete, onEdit, onGroup }) {children: [jsx(ContextMenuItem, {onSelect: () => {- const pinned = Boolean($botMeta.get()[bot.name]?.pinned)- saveBotMeta(bot.name, { pinned: !pinned })- host.notify({- kind: 'info',- message: `${displayName(bot, meta)} ${pinned ? 'unpinned' : 'pinned to top'}`- })+ void ensureBotMetadata(bot).then(current => {+ const pinned = Boolean(current.pinned)+ void saveBotMeta(bot, { pinned: !pinned })+ host.notify({+ kind: 'info',+ message: `${displayName(bot, current)} ${pinned ? 'unpinned' : 'pinned to top'}`+ })+ }).catch(error => host.notifyError?.(error, 'Could not load bot metadata'))},children: meta?.pinned ? 'Unpin' : 'Pin to top'}),jsx(ContextMenuItem, {onSelect: () => {- const hidden = Boolean($botMeta.get()[bot.name]?.hidden)- // `hidden: false` (not null) so unhide round-trips through the- // server ui_meta merge the same way the local merge sees it.- saveBotMeta(bot.name, { hidden: !hidden })+ void ensureBotMetadata(bot).then(current => {+ const hidden = Boolean(current.hidden)+ void saveBotMeta(bot, { hidden: !hidden })- if (!hidden) {- fallbackSelectionAfterHide(bot.name)- }+ if (!hidden) {+ fallbackSelectionAfterHide(botSelectionKey(bot))+ }- host.notify({- kind: 'info',- message: hidden- ? `${displayName(bot, meta)} is back in the roster`- : `${displayName(bot, meta)} hidden — use the eye button in the Bots header to see hidden bots`- })+ host.notify({+ kind: 'info',+ message: hidden+ ? `${displayName(bot, current)} is back in the roster`+ : `${displayName(bot, current)} hidden — use the eye button in the Bots header to see hidden bots`+ })+ }).catch(error => host.notifyError?.(error, 'Could not load bot metadata'))},children: meta?.hidden ? 'Unhide Bot' : 'Hide Bot'}),@@ -4911,17 +5300,18 @@ function BotRow({ bot, onDelete, onEdit, onGroup }) {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)}…` })- duplicateBot(bot, $lastRoster.get().filter(candidate => !candidate.remoteSource))+ duplicateBot(bot, $lastRoster.get()).then(name => {queryClient.invalidateQueries({ queryKey: ROSTER_KEY })host.notify({ kind: 'success', message: `Created ${name} — full copy of ${bot.name}` })@@ -4933,16 +5323,16 @@ function BotRow({ bot, onDelete, onEdit, onGroup }) {jsx(ContextMenuSeparator, {}),jsx(ContextMenuItem, {onSelect: () => {- $selectedBot.set(bot.name)+ $selectedBot.set(botSelectionKey(bot))if (typeof host.newChat === 'function') {- host.newChat(bot.name)+ newBotChat(bot)}},children: 'New chat with this agent'}),- bot.is_default ? null : jsx(ContextMenuSeparator, {}),- bot.is_default+ isDefaultBot(bot) ? null : jsx(ContextMenuSeparator, {}),+ isDefaultBot(bot)? null: jsx(ContextMenuItem, {onSelect: () => onDelete(bot),@@ -4957,10 +5347,16 @@ function BotRow({ bot, onDelete, onEdit, onGroup }) {// ── model picker (provider/model dropdowns via model.options) ───────────────-function useModelOptions() {+function useModelOptions(bot = null) {+ const route = botConnectionRoute(bot)+return useQuery({- queryKey: [ID, 'model-options'],- queryFn: () => host.request('model.options', { include_unconfigured: true, explicit_only: false, refresh: true }),+ queryKey: [ID, 'model-options', route ? botRouteKey(route) : 'active'],+ queryFn: () => requestForBot(bot, 'model.options', {+ include_unconfigured: true,+ explicit_only: false,+ refresh: true+ }),staleTime: 120000,retry: false})@@ -4971,8 +5367,8 @@ function useModelOptions() {* same data the core model picker shows. `value = {provider, model}`;* onChange receives the merged patch.*/-function ModelPicker({ value, onChange, placeholderModel = 'gateway default' }) {- const { data, isLoading, error } = useModelOptions()+function ModelPicker({ bot = null, value, onChange, placeholderModel = 'gateway default' }) {+ const { data, isLoading, error } = useModelOptions(bot)// Hooks are ALWAYS declared up front, before any conditional return.// Declaring them after a return trips React error #310.@@ -5164,12 +5560,15 @@ function AdvancedProfileConfig({ bot, state, setState }) {const [loaded, setLoaded] = useState(false)const [unsupported, setUnsupported] = useState(false)const [skillFilter, setSkillFilter] = useState('')+ const botRoute = botConnectionRoute(bot)+ const backendProfile = botRoute?.targetProfile || botRoute?.profile || bot.name+ const backendScope = botBackendProfileScope(botRoute, bot.name)if (!loaded) {setLoaded(true)Promise.all([- host.request('profiles.describe', { name: bot }),- host.request('mcp.catalog', { profile: bot }).catch(() => null)+ requestForBot(bot, 'profiles.describe', { name: bot.name }),+ requestForBot(bot, 'mcp.catalog', { profile: bot.name }).catch(() => null)]).then(([res, cat]) => {const configured = res.mcp_servers || []@@ -5251,11 +5650,12 @@ function AdvancedProfileConfig({ bot, state, setState }) {// Render THAT instead of the checkbox stand-ins; writes go straight to the// bot's backend, so the dirty-section staging below only carries// model + SOUL on these builds. Older builds keep the full checklist UI.- if (SkillsView) {+ if (SkillsView && (!botRoute || skillsViewRoutesConnections)) {return jsxs('div', {className: 'grid gap-4',children: [jsx(ModelPicker, {+ bot,value: { provider: state.provider, model: state.model },onChange: patch => setState(prev => ({ ...prev, dirtyModel: true, ...patch }))}),@@ -5264,7 +5664,11 @@ function AdvancedProfileConfig({ bot, state, setState }) {jsx('div', {className: 'overflow-hidden rounded-md border border-(--ui-stroke-secondary)',style: { height: 460, minHeight: 300, resize: 'vertical', overflow: 'auto' },- children: jsx(SkillsView, { embedded: true, fixedProfile: bot })+ children: jsx(SkillsView, {+ embedded: true,+ fixedProfile: backendProfile,+ ...(botRoute ? { fixedConnection: botRoute.connectionId } : {})+ })})),labeled(@@ -5279,10 +5683,36 @@ function AdvancedProfileConfig({ bot, state, setState }) {})}+ if (bot?.sourceScoped && botRoute?.mode === 'remote' && !skillsViewRoutesConnections) {+ return jsxs('div', {+ className: 'grid gap-4',+ children: [+ jsx(ModelPicker, {+ bot,+ value: { provider: state.provider, model: state.model },+ onChange: patch => setState(prev => ({ ...prev, dirtyModel: true, ...patch }))+ }),+ jsx('div', {+ className: 'rounded-md border border-(--ui-stroke-secondary) px-3 py-2 text-xs text-(--ui-text-tertiary)',+ children: 'Remote capabilities require a newer desktop. Model and SOUL changes remain staged until you save.'+ }),+ labeled(+ 'SOUL.md (persona + agent-messaging protocol)',+ jsx(Textarea, {+ className: 'min-h-28 font-mono text-xs leading-5',+ value: state.soul,+ onChange: event => setState(prev => ({ ...prev, dirtySoul: true, soul: event.target.value }))+ })+ )+ ]+ })+ }+return jsxs('div', {className: 'grid gap-4',children: [jsx(ModelPicker, {+ bot,value: { provider: state.provider, model: state.model },onChange: patch => setState(prev => ({ ...prev, dirtyModel: true, ...patch }))}),@@ -5303,7 +5733,7 @@ function AdvancedProfileConfig({ bot, state, setState }) {children: jsx(CheckList, { items: visibleSkills, onToggle: toggleSkill, columns: 2 })}),jsx(HubSkillsSection, {- forProfile: bot,+ forProfile: backendScope,onInstalled: name =>setState(prev =>prev.skills.some(s => s.name === name)@@ -5345,7 +5775,7 @@ function AdvancedProfileConfig({ bot, state, setState }) {ToolsetConfigPanel? jsx('div', {className: 'mt-1.5 border-t border-(--ui-stroke-secondary) pt-1.5',- children: jsx(ToolsetConfigPanel, { toolset: tset.name, profile: bot })+ children: jsx(ToolsetConfigPanel, { toolset: tset.name, profile: backendScope })}): null]@@ -5368,7 +5798,7 @@ function AdvancedProfileConfig({ bot, state, setState }) {children: McpTab && typeof host.getGateway === 'function'? jsx('div', {style: { minHeight: 220, maxHeight: 360 },- children: jsx(McpTab, { gateway: host.getGateway(), profile: bot })+ children: jsx(McpTab, { gateway: host.getGateway(), profile: backendScope })}): mcpList.length === 0? jsx('div', {@@ -5404,7 +5834,7 @@ function AdvancedProfileConfig({ bot, state, setState }) {: null,needsSetup? jsx(McpSetupButton, {- profile: bot,+ profile: backendScope,entry: m,onDone: () => toggleMcp(m.name, true)})@@ -5722,11 +6152,11 @@ function emptyAdvancedState() {/** Persist only the dirty sections of the advanced editor. */async function applyAdvancedConfig(bot, state) {- const payload = { name: bot }+ const payload = { name: bot.name }const applied = {}if (state.dirtySoul) {- payload.soul = ensureMessagingProtocol(state.soul, bot, $lastRoster.get())+ payload.soul = ensureMessagingProtocol(state.soul, bot.name, $lastRoster.get())}if (state.dirtyModel) {@@ -5738,8 +6168,8 @@ async function applyAdvancedConfig(bot, state) {payload.provider = provider} else if (!model && !provider) {try {- const result = await host.request('cli.exec', {- argv: ['--profile', bot, 'config', 'unset', 'model']+ const result = await requestForBot(bot, 'cli.exec', {+ argv: ['--profile', bot.name, 'config', 'unset', 'model']})applied.model = result?.blocked !== true && result?.code === 0} catch {@@ -5769,7 +6199,7 @@ async function applyAdvancedConfig(bot, state) {return { ok: Object.values(applied).every(Boolean), applied }}- const result = await host.request('profiles.configure', payload)+ const result = await requestForBot(bot, 'profiles.configure', payload)const merged = { ...applied, ...(result?.applied || {}) }return { ...result, ok: Object.values(merged).every(Boolean), applied: merged }@@ -5792,7 +6222,7 @@ function labeled(label, control) {function EditProfileDialog({ bot, open, onClose }) {const metaAll = useValue($botMeta)- const meta = bot ? metaAll[bot.name] : null+ const meta = bot ? botRosterMeta(bot, metaAll) : nullconst appearance = bot ? botAppearance(bot.name, meta) : { shape: 'circle', color: AVATAR_COLORS[3] }const [shape, setShape] = useState(appearance.shape)const [color, setColor] = useState(appearance.color)@@ -5805,7 +6235,7 @@ function EditProfileDialog({ bot, open, onClose }) {// Re-seed local state each time a different bot opens the dialog.const [seedKey, setSeedKey] = useState(null)- const currentKey = bot ? `${bot.name}:${open}` : null+ const currentKey = bot ? `${botSelectionKey(bot)}:${open}` : nullif (currentKey !== seedKey) {setSeedKey(currentKey)if (bot && open) {@@ -5831,7 +6261,7 @@ function EditProfileDialog({ bot, open, onClose }) {setBusy(true)let advancedFailed = false- const persistence = await saveBotMeta(bot.name, {+ const persistence = await saveBotMeta(bot, {shape,color,image,@@ -5854,7 +6284,7 @@ function EditProfileDialog({ bot, open, onClose }) {const desc = description.trim()if (desc !== (bot.description || '').trim()) {try {- await host.request('cli.exec', {+ await requestForBot(bot, 'cli.exec', {argv: ['profile', 'describe', bot.name, '--text', desc]})queryClient.invalidateQueries({ queryKey: ROSTER_KEY })@@ -5865,7 +6295,7 @@ function EditProfileDialog({ bot, open, onClose }) {if (adv.loaded && (adv.dirtyModel || adv.dirtySoul || adv.dirtySkills || adv.dirtyToolsets || adv.dirtyMcp)) {try {- const res = await applyAdvancedConfig(bot.name, adv)+ const res = await applyAdvancedConfig(bot, adv)const failed = Object.entries(res?.applied || {}).filter(([, ok]) => !ok)if (failed.length) {@@ -5947,7 +6377,7 @@ function EditProfileDialog({ bot, open, onClose }) {advanced? jsx('div', {className: 'rounded-md border border-(--ui-stroke-secondary) p-3',- children: jsx(AdvancedProfileConfig, { bot: bot.name, state: adv, setState: setAdv })+ children: jsx(AdvancedProfileConfig, { bot, state: adv, setState: setAdv })}): null]@@ -6841,13 +7271,15 @@ function isLegacyDelegatedRoutine(job) {return Boolean(routineBot(job) && typeof preview === 'string' && preview.startsWith(LEGACY_DELEGATED_ROUTINE_PREFIX))}-async function loadRoutines(profile) {+async function loadRoutines(owner) {+ const bot = typeof owner === 'string' ? { name: owner } : owner+ const profile = String(bot?.name || '').trim()// profile scopes cron.manage to that bot's own cron store (core RPC gained an// optional `profile` param). Older gateways ignore the unknown param and// return the launch-profile store — the [bot:] tag filter in selectRoutineJobs// remains the graceful fallback there.const scope = profile ? { profile } : {}- const data = await host.request('cron.manage', { action: 'list', include_disabled: true, ...scope })+ const data = await requestForBot(bot, 'cron.manage', { action: 'list', include_disabled: true, ...scope })const jobs = Array.isArray(data?.jobs) ? data.jobs : []const activeLegacyJobs = jobs.filter(job => isLegacyDelegatedRoutine(job) && job.enabled !== false && job.state !== 'paused'@@ -6860,8 +7292,7 @@ async function loadRoutines(profile) {// actually paused, and the next poll retries the rest.const pauses = await Promise.all(activeLegacyJobs.map(job =>- host- .request('cron.manage', { action: 'pause', name: job.job_id, ...scope })+ requestForBot(bot, 'cron.manage', { action: 'pause', name: job.job_id, ...scope }).then(() => true).catch(() => false))@@ -6878,10 +7309,14 @@ async function loadRoutines(profile) {}}-function useRoutines(profile) {+function useRoutines(owner) {+ const bot = typeof owner === 'string' ? { name: owner } : owner+ const route = botConnectionRoute(bot)+ const key = route ? botRosterKey(bot) : bot?.name || ''+return useQuery({- queryKey: [...ROUTINES_KEY, profile || ''],- queryFn: () => loadRoutines(profile),+ queryKey: [...ROUTINES_KEY, key],+ queryFn: () => loadRoutines(bot),refetchInterval: 20000,staleTime: 8000})@@ -6891,9 +7326,13 @@ function routineCreateTarget(owner, activeBot) {return owner || activeBot}-async function invalidateRoutineOwner(profile) {+async function invalidateRoutineOwner(owner) {+ const bot = typeof owner === 'string' ? { name: owner } : owner+ const route = botConnectionRoute(bot)+ const key = route ? botRosterKey(bot) : bot?.name || ''+await queryClient.invalidateQueries({- queryKey: [...ROUTINES_KEY, profile || ''],+ queryKey: [...ROUTINES_KEY, key],exact: true})}@@ -7001,7 +7440,8 @@ function scheduleLabel(schedule) {return schedule || ''}-function RoutineRow({ job, profile }) {+function RoutineRow({ job, owner }) {+ const profile = typeof owner === 'string' ? owner : owner?.nameconst [busy, setBusy] = useState(false)// Optimistic overlay: null = trust server state. Set immediately on// toggle so the switch responds even before the refetch lands.@@ -7026,8 +7466,8 @@ function RoutineRow({ job, profile }) {}try {- await host.request('cron.manage', { action, name: job.job_id, ...(profile ? { profile } : {}) })- await invalidateRoutineOwner(profile)+ await requestForBot(owner, 'cron.manage', { action, name: job.job_id, ...(profile ? { profile } : {}) })+ await invalidateRoutineOwner(owner)} catch (err) {setPendingActive(null)host.notifyError(err, 'Cronjob update failed')@@ -7310,6 +7750,7 @@ function CreateRoutineDialog({ bot, open, onClose }) {const [busy, setBusy] = useState(false)const [error, setError] = useState(null)const activeProfile = useValue(host.state.profile)+ const profile = typeof bot === 'string' ? bot : bot?.nameconst schedule = composeSchedule(sched)const reset = () => {@@ -7343,12 +7784,12 @@ function CreateRoutineDialog({ bot, open, onClose }) {sched.freq !== 'once' && sched.freq !== 'advanced' && String(sched.repeatN || '').trim()? Math.max(1, parseInt(sched.repeatN, 10) || 1): null- await host.request('cron.manage', {+ await requestForBot(bot, 'cron.manage', {action: 'add',- name: `[bot:${bot}] ${title}`,+ name: `[bot:${profile}] ${title}`,schedule: schedule.trim(),- prompt: routinePrompt(bot, title, task, activeProfile),- ...(bot ? { profile: bot } : {}),+ prompt: routinePrompt(profile, title, task, activeProfile),+ ...(profile ? { profile } : {}),...(repeatN ? { repeat: repeatN } : {}),...(continuity ? { continuity: true } : {})})@@ -7377,7 +7818,7 @@ function CreateRoutineDialog({ bot, open, onClose }) {children: [jsx(DialogTitle, { children: 'New Cronjob' }),jsx(DialogDescription, {- children: `A recurring task ${displayName({ name: bot }, $botMeta.get()[bot])} runs on a schedule. Runs land in its own chat history.`+ children: `A recurring task ${displayName(typeof bot === 'string' ? { name: bot } : bot, botRosterMeta(bot, $botMeta.get()))} runs on a schedule. Runs land in its own chat history.`})]}),@@ -7452,16 +7893,25 @@ function RoutinesPane() {// The tile maps to the bot you're chatting with: the live gateway profile// is the truth once a chat opens; $selectedBot covers the gap between a// roster click and the profile swap landing.- const bot = (gatewayProfile || selected || 'default').trim() || 'default'- const meta = useValue($botMeta)[bot]+ const roster = $lastRoster.get()+ const selectedBot = roster.find(bot => botSelectionKey(bot) === selected)+ const activeBot = roster.find(bot =>+ isActiveRosterBot(bot, {+ name: gatewayProfile,+ connectionId: String(host.state.connectionId?.get?.() || host.activeConnectionId?.() || 'local')+ })+ )+ const owner = selectedBot || activeBot || { name: (gatewayProfile || selected || 'default').trim() || 'default' }+ const bot = owner.name+ const meta = botRosterMeta(owner, useValue($botMeta))const { shape, color, image } = botAppearance(bot, meta)- const { data, error, isLoading, refetch } = useRoutines(bot)+ const { data, error, isLoading, refetch } = useRoutines(owner)const [createOpen, setCreateOpen] = useState(false)const [createOwner, setCreateOwner] = useState(null)const createTarget = routineCreateTarget(createOwner, bot)const openCreate = () => {- setCreateOwner(bot)+ setCreateOwner(owner)setCreateOpen(true)}@@ -7573,7 +8023,7 @@ function RoutinesPane() {className: 'min-h-0 flex-1',children: jsx('div', {className: 'grid gap-1.5 px-2.5 py-2',- children: jobs.map(job => jsx(RoutineRow, { job, profile: bot }, job.job_id))+ children: jobs.map(job => jsx(RoutineRow, { job, owner }, job.job_id))})}),jsx(CreateRoutineDialog, {@@ -7596,7 +8046,7 @@ const PROFILE_SESSION_LIST_LIMIT = 200function openBotSessionsWorkspace(bot) {if (bot?.name && NAME_RE.test(bot.name)) {- $botSessionsWorkspace.set(bot.name)+ $botSessionsWorkspace.set(botSelectionKey(bot))}}@@ -7609,21 +8059,33 @@ function filterProfileSessions(sessions, query) {)}-function useProfileSessions(botName, gatewayGeneration) {+function useProfileSessions(bot, gatewayGeneration) {+ const owner = typeof bot === 'string' ? { name: bot } : bot+ const profile = String(owner?.name || '')+ const route = botConnectionRoute(owner)+ const key = route ? botRosterKey(owner) : profile+return useQuery({- queryKey: [ID, 'profile-sessions', botName, gatewayGeneration],- enabled: Boolean(botName),+ queryKey: [ID, 'profile-sessions', key, gatewayGeneration],+ enabled: Boolean(profile),// include_hidden: this browser exists precisely to see the profile's own// (always-hidden) Bot Mode sessions alongside its regular ones.- queryFn: () => host.request('session.list', { profile: botName, limit: PROFILE_SESSION_LIST_LIMIT, include_hidden: true }),+ queryFn: () => requestForBot(owner, 'session.list', {+ profile: route?.targetProfile || profile,+ limit: PROFILE_SESSION_LIST_LIMIT,+ include_hidden: true+ }),refetchInterval: 8000,staleTime: 4000,retry: false})}-async function openProfileSession(botName, session, gatewayGeneration) {- const profile = String(botName || '')+async function openProfileSession(bot, session, gatewayGeneration) {+ const owner = typeof bot === 'string' ? { name: bot } : bot+ const profile = String(owner?.name || '')+ const route = botConnectionRoute(owner)+ const selectionKey = route ? botRosterKey(owner) : profileconst id = String(session?.id || '')if (!NAME_RE.test(profile) || !id || gatewayGeneration !== $sessionsGatewayGeneration.get()) returnif (typeof host.openSession !== 'function') {@@ -7638,16 +8100,21 @@ async function openProfileSession(botName, session, gatewayGeneration) {typeof session?.message_count === 'number' && Number.isFinite(session.message_count)const expectHistory = hasAuthoritativeCount ? session.message_count > 0 : Boolean(session?.preview)- await host.openSession(id, { profile, awaitHydration: true, expectHistory })+ await host.openSession(id, {+ ...(route ? { route } : {}),+ profile,+ awaitHydration: true,+ expectHistory+ })if (gatewayGeneration !== $sessionsGatewayGeneration.get()) return- $botSelectedSessions.set({ ...$botSelectedSessions.get(), [profile]: id })+ $botSelectedSessions.set({ ...$botSelectedSessions.get(), [selectionKey]: id })}-function ProfileSessionRow({ session, botName, active, gatewayGeneration }) {+function ProfileSessionRow({ session, bot, active, gatewayGeneration }) {return jsxs('button', {type: 'button','aria-current': active ? 'page' : undefined,- onClick: () => void openProfileSession(botName, session, gatewayGeneration).catch(err => host.notifyError(err, 'Could not open session')),+ onClick: () => void openProfileSession(bot, session, gatewayGeneration).catch(err => host.notifyError(err, 'Could not open session')),className: cn('flex w-full flex-col gap-0.5 overflow-hidden rounded-md px-2 py-1.5 text-left transition-colors','hover:bg-(--chrome-action-hover)',@@ -7668,13 +8135,13 @@ function ProfileSessionRow({ session, botName, active, gatewayGeneration }) {function ProfileSessionsWorkspace({ bot }) {const gatewayGeneration = useValue($sessionsGatewayGeneration)- const { data, isLoading, error } = useProfileSessions(bot.name, gatewayGeneration)+ const { data, isLoading, error } = useProfileSessions(bot, gatewayGeneration)const selectedByProfile = useValue($botSelectedSessions)const [query, setQuery] = useState('')const sourceSessions = data?.sessions || []const sessions = filterProfileSessions(sourceSessions, query)const inventoryBounded = sourceSessions.length >= PROFILE_SESSION_LIST_LIMIT- const selectedId = selectedByProfile[bot.name] || ''+ const selectedId = selectedByProfile[botSelectionKey(bot)] || ''const header = jsxs('div', {className: 'flex items-center gap-2 px-2.5 pt-2.5 pb-2',@@ -7687,7 +8154,7 @@ function ProfileSessionsWorkspace({ bot }) {}),jsx('div', {className: 'min-w-0 flex-1 truncate text-sm font-semibold',- children: `${displayName(bot, $botMeta.get()[bot.name])} sessions`+ children: `${displayName(bot, botRosterMeta(bot, $botMeta.get()))} sessions`})]})@@ -7728,7 +8195,7 @@ function ProfileSessionsWorkspace({ bot }) {children: sessions.length? sessions.map(session => jsx(ProfileSessionRow, {session,- botName: bot.name,+ bot,active: selectedId === session.id,gatewayGeneration}, session.id))@@ -7771,7 +8238,7 @@ function ActiveNowStrip({ roster, activeProfile, gatewayState, metaByName, onOpechildren: 'Active now'}),...active.map(bot => {- const meta = metaByName?.[bot.name]+ const meta = botRosterMeta(bot, metaByName)const { shape, color, image } = botAppearance(bot.name, meta)const photo = Boolean(image && !isBackfilledFacePng(image))const label = displayName(bot, meta)@@ -7810,16 +8277,16 @@ function ActiveNowStrip({ roster, activeProfile, gatewayState, metaByName, onOpefunction GroupDialog({ bot, onClose }) {const meta = useValue($botMeta)const [name, setName] = useState('')- const current = botGroups(meta[bot?.name])+ const current = botGroups(botRosterMeta(bot, meta))const groups = knownGroups(meta)const setMembership = (group, enabled) => {- saveBotMeta(bot.name, groupMembershipPatch(meta[bot.name], group, enabled))+ void saveBotMeta(bot, groupMembershipPatch(botRosterMeta(bot, meta), group, enabled))host.notify({kind: 'info',message: enabled- ? `${displayName(bot, meta[bot.name])} added to “${group}”`- : `${displayName(bot, meta[bot.name])} removed from “${group}”`+ ? `${displayName(bot, botRosterMeta(bot, meta))} added to “${group}”`+ : `${displayName(bot, botRosterMeta(bot, meta))} removed from “${group}”`})}@@ -7891,7 +8358,7 @@ function GroupDialog({ bot, onClose }) {variant: 'ghost',size: 'sm',className: 'justify-self-start',- onClick: () => saveBotMeta(bot.name, { groups: [], group: null }),+ onClick: () => void saveBotMeta(bot, { groups: [], group: null }),children: 'Remove from all groups'}): null@@ -8125,9 +8592,7 @@ function CreateGroupChatDialog({ open, roster, onClose, onCreated }) {}for (const bot of selected) {- if (!bot.remoteSource) {- void saveBotMeta(bot.name, groupMembershipPatch(botRosterMeta(bot, allMeta), groupName, true))- }+ void saveBotMeta(bot, groupMembershipPatch(botRosterMeta(bot, allMeta), groupName, true))}// Persist every machine identity, including today's active source. That@@ -9311,7 +9776,7 @@ function BotsPane() {const showHidden = useValue($showHiddenBots)const unreadByName = useValue($botUnread)const hiddenBots = roster.filter(bot => isBotHidden(bot, allMeta))- const hiddenUnread = hiddenBots.some(bot => !bot.remoteSource && unreadByName[bot.name])+ const hiddenUnread = hiddenBots.some(bot => unreadByName[botSelectionKey(bot)])const visibleRoster = showHidden ? roster : roster.filter(bot => !isBotHidden(bot, allMeta))const filteredRoster = filterBots(visibleRoster, allMeta, query)// Group chats are first-class roster rows (Discord-style): one standalone@@ -9352,7 +9817,7 @@ function BotsPane() {const staleNotice = error && !live && roster.length? 'Roster refresh failed — showing the last good list.' + (gatewayUp ? '' : ' Waiting for the gateway to reconnect…'): null- const sessionsWorkspaceBot = roster.find(bot => bot.name === sessionsWorkspaceName)+ const sessionsWorkspaceBot = roster.find(bot => botSelectionKey(bot) === sessionsWorkspaceName)if (sessionsWorkspaceBot) {return jsx(ProfileSessionsWorkspace, { bot: sessionsWorkspaceBot })@@ -9459,21 +9924,11 @@ function BotsPane() {onOpen: bot => {const generation = ++botOpenGenerationhaptic('tap')- $selectedBot.set(bot.name)-- if (bot.remoteSource) {- const handle = botHandle(bot.name, bot)- host.notify?.({- kind: 'info',- title: displayName(bot),- message: `Stay in this chat and @${handle} to message them. Gateway stays on this device.`- })- return- }+ $selectedBot.set(botSelectionKey(bot))- if ($botUnread.get()[bot.name]) {+ if ($botUnread.get()[botSelectionKey(bot)]) {const next = { ...$botUnread.get() }- delete next[bot.name]+ delete next[botSelectionKey(bot)]$botUnread.set(next)}@@ -9494,7 +9949,7 @@ function BotsPane() {try {const id = await openBotCanonicalChat(- bot.name,+ bot,pinnedChat,bot.preferred_session || bot.last_session)@@ -9515,7 +9970,7 @@ function BotsPane() {}if (typeof host.newChat === 'function') {- host.newChat(bot.name)+ newBotChat(bot)} else {host.navigate('/')}@@ -9750,25 +10205,10 @@ export default {document.head.appendChild(style)}- // Hydrate persisted avatars/titles. Storage may be sync, async, or- // absent depending on shell version — normalize through Promise.resolve- // inside a try so a storage quirk can NEVER fail the plugin load.- try {- Promise.resolve(ctx.storage?.get?.('bot-meta'))- .then(value => {- if (value && typeof value === 'object' && !Array.isArray(value)) {- const live = $botMeta.get()- const next = { ...value }- for (const name of Object.keys(live)) {- next[name] = { ...(value[name] || {}), ...live[name] }- }- $botMeta.set(next)- }- })- .catch(() => undefined)- } catch {- /* no storage on this shell — defaults stay */- }+ // Hydrate persisted avatars/titles. Migration writes v2 only after a+ // provable sole-local topology and deliberately leaves v1 untouched for+ // one-version rollback.+ void migrateBotMeta(ctx.storage).catch(() => undefined)// Bot Mode sessions are always hidden now — the old "hide Bot Chats"// pref is gone (its stored key is simply ignored). The reconciliation@@ -9826,7 +10266,12 @@ export default {// clock before its onDispose hook — these kept firing until app restart).const unbindProfileListener = host.state.profile.listen(profile => {if (profile && typeof profile === 'string') {- $selectedBot.set(profile)+ const connectionId = String(+ host.state.connectionId?.get?.() ||+ (typeof host.activeConnectionId === 'function' ? host.activeConnectionId() : '') ||+ ''+ ).trim()+ $selectedBot.set(connectionId ? `${connectionId}::${profile}` : profile)}})const unbindGatewayListener = host.state.gateway.listen(handleSessionsGatewayTransition)diff --git a/apps/desktop/src/plugins/hermes-bots/tests/activity-toasts.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/activity-toasts.test.mjsindex cd89ff4942d..2937ac82972 100644--- a/apps/desktop/src/plugins/hermes-bots/tests/activity-toasts.test.mjs+++ b/apps/desktop/src/plugins/hermes-bots/tests/activity-toasts.test.mjs@@ -27,6 +27,8 @@ function loadTracker(toastsEnabled) {let value = {}return { get: () => value, set: next => { value = next } }})(),+ botRosterMeta: (bot, meta) => meta?.[bot.name] || null,+ botSelectionKey: bot => bot.name,displayName: bot => bot.name}const section = sourcediff --git a/apps/desktop/src/plugins/hermes-bots/tests/bot-delete.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/bot-delete.test.mjsindex 872ad062788..c79ae659531 100644--- a/apps/desktop/src/plugins/hermes-bots/tests/bot-delete.test.mjs+++ b/apps/desktop/src/plugins/hermes-bots/tests/bot-delete.test.mjs@@ -10,6 +10,7 @@ function load({ sdkDeleteProfile = false } = {}) {const sdkDeletes = []const invalidations = []const stored = []+ const storageOps = []const values = new Map()const atom = initial => {const slot = { get: () => values.get(slot), set: value => values.set(slot, value) }@@ -28,8 +29,8 @@ function load({ sdkDeleteProfile = false } = {}) {},...(sdkDeleteProfile? {- deleteProfile: async name => {- sdkDeletes.push(name)+ deleteProfile: async profile => {+ sdkDeletes.push(profile)}}: {}),@@ -52,11 +53,15 @@ function load({ sdkDeleteProfile = false } = {}) {context.plugin.register({storage: {get: () => null,- set: (key, value) => stored.push({ key, value })+ remove: key => storageOps.push({ op: 'remove', key }),+ set: (key, value) => {+ stored.push({ key, value })+ storageOps.push({ op: 'set', key, value })+ }},register: () => undefined})- return { context, requests, sdkDeletes, invalidations, stored }+ return { context, requests, sdkDeletes, invalidations, stored, storageOps }}test('unit: deleting a bot prefers the SDK deleteProfile (teardown-routed REST path)', async () => {@@ -68,6 +73,75 @@ test('unit: deleting a bot prefers the SDK deleteProfile (teardown-routed REST passert.equal(requests.filter(r => r.method === 'cli.exec').length, 0)})+test('unit: source-scoped deletion preserves the route targetProfile', async () => {+ const { context, sdkDeletes } = load({ sdkDeleteProfile: true })+ const route = {+ connectionId: 'source-a',+ mode: 'remote',+ profile: 'worker',+ targetProfile: 'backend-worker'+ }++ await context.__delete.deleteBot({ name: 'worker', sourceScoped: true, route })++ assert.deepEqual(JSON.parse(JSON.stringify(sdkDeletes)), [route])+})++test('unit: source-scoped deletion commits bot-meta-v2 atomically', async () => {+ const { context, storageOps } = load({ sdkDeleteProfile: true })+ const route = {+ connectionId: 'source-a',+ mode: 'remote',+ profile: 'worker',+ targetProfile: 'backend-worker'+ }+ const key = 'source-a::worker'+ context.__delete.$botMeta.set({+ [key]: { title: 'Worker' },+ 'source-a::writer': { title: 'Writer' }+ })++ await context.__delete.deleteBot({+ name: 'worker',+ sourceScoped: true,+ route+ })++ assert.deepEqual(+ JSON.parse(JSON.stringify(storageOps.slice(-3))),+ [+ { op: 'remove', key: 'bot-meta-v2-migrated' },+ {+ op: 'set',+ key: 'bot-meta-v2',+ value: { 'source-a::writer': { title: 'Writer' } }+ },+ { op: 'set', key: 'bot-meta-v2-migrated', value: true }+ ]+ )+})++test('unit: an alias targeting backend default is rejected before deletion', async () => {+ const { context, sdkDeletes, requests } = load({ sdkDeleteProfile: true })++ await assert.rejects(+ context.__delete.deleteBot({+ name: 'worker',+ sourceScoped: true,+ route: {+ connectionId: 'source-a',+ mode: 'remote',+ profile: 'worker',+ targetProfile: 'default'+ }+ }),+ /default profile cannot be deleted/i+ )++ assert.deepEqual(sdkDeletes, [])+ assert.equal(requests.some(request => request.method === 'cli.exec'), false)+})+test('unit: older desktop without host.deleteProfile falls back to the non-interactive profile CLI command', async () => {const { context, requests } = load()@@ -101,7 +175,7 @@ test('integration: a deleted bot is removed from plugin-local state and the rosttest('regression: the bot context menu exposes a destructive delete action and confirmation', () => {assert.match(pluginSource, /ContextMenuItem, \{[\s\S]*?variant: 'destructive'[\s\S]*?children: 'Delete'/)- assert.match(pluginSource, /bot\.is_default \? null : jsx\(ContextMenuSeparator/)+ assert.match(pluginSource, /isDefaultBot\(bot\) \? null : jsx\(ContextMenuSeparator/)assert.match(pluginSource, /ConfirmDialog/)assert.match(pluginSource, /title: 'Delete bot and profile\?'/)assert.match(pluginSource, /This will permanently delete the bot[\s\S]*?and its associated Hermes profile at[\s\S]*?This cannot be undone\./)diff --git a/apps/desktop/src/plugins/hermes-bots/tests/bot-meta-hydrate.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/bot-meta-hydrate.test.mjsindex a0d89bbdf2b..4da93318b08 100644--- a/apps/desktop/src/plugins/hermes-bots/tests/bot-meta-hydrate.test.mjs+++ b/apps/desktop/src/plugins/hermes-bots/tests/bot-meta-hydrate.test.mjs@@ -70,8 +70,7 @@ test('regression: a slow load still keeps looks from disk under a new pin', asynruntime.saveBotMeta('researcher', { chat: 'sess-just-created' })resolveStorage({ researcher: { title: 'Research', shape: 'cloud', color: '#38bdf8' } })await pending- await Promise.resolve()- await Promise.resolve()+ await new Promise(resolve => setTimeout(resolve, 0))assert.equal(runtime.$botMeta.get().researcher.chat, 'sess-just-created')assert.equal(runtime.$botMeta.get().researcher.shape, 'cloud')diff --git a/apps/desktop/src/plugins/hermes-bots/tests/bot-meta-persistence.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/bot-meta-persistence.test.mjsindex 9be4b6e8854..9451b72a57a 100644--- a/apps/desktop/src/plugins/hermes-bots/tests/bot-meta-persistence.test.mjs+++ b/apps/desktop/src/plugins/hermes-bots/tests/bot-meta-persistence.test.mjs@@ -91,7 +91,7 @@ test('a rejected configure request is unsupported, not failed', async () => {})test('Edit Profile waits for persistence and reports a local-only save', () => {- assert.match(pluginSource, /const persistence = await saveBotMeta\(bot\.name,/)+ assert.match(pluginSource, /const persistence = await saveBotMeta\(bot,/)assert.match(pluginSource, /Saved look locally; remote persistence failed/)// The toast fires only on an explicit remote failure — never on the// documented older-gateway fallback.diff --git 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.mjsindex dc468d1f65b..8df1b70b05a 100644--- 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,6 +12,8 @@ function loadCanonicalCreation({ openSession, request }) {const context = {host: { openSession, request },saveBotMeta: (name, patch) => saved.push({ name, patch }),+ 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 --git a/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-empty-recovery.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-empty-recovery.test.mjsindex 76a93ffa410..b3a8439a3b5 100644--- a/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-empty-recovery.test.mjs+++ b/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-empty-recovery.test.mjs@@ -19,6 +19,8 @@ function loadCanonicalRecovery({ openSession, request }) {}},saveBotMeta: (name, patch) => saved.push({ name, patch }),+ 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 --git a/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-identity.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-identity.test.mjsindex 92776344e5a..de8c7b4ed41 100644--- a/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-identity.test.mjs+++ b/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-identity.test.mjs@@ -20,6 +20,8 @@ function loadOpenPath({ openSession, request }) {}},saveBotMeta: (name, patch) => saved.push({ name, patch: JSON.parse(JSON.stringify(patch)) }),+ 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 --git a/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-pin.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-pin.test.mjsindex b2796ba933b..388862eeca1 100644--- a/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-pin.test.mjs+++ b/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-pin.test.mjs@@ -27,6 +27,8 @@ function loadOpenPath({ openSession, request }) {}},saveBotMeta: (name, patch) => saved.push({ name, patch: JSON.parse(JSON.stringify(patch)) }),+ 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 --git a/apps/desktop/src/plugins/hermes-bots/tests/cross-connection-bots.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/cross-connection-bots.test.mjsindex 876e0a19661..af97687327c 100644--- a/apps/desktop/src/plugins/hermes-bots/tests/cross-connection-bots.test.mjs+++ b/apps/desktop/src/plugins/hermes-bots/tests/cross-connection-bots.test.mjs@@ -51,20 +51,20 @@ function runtime() {.replace(/^import .* from 'react\/jsx-runtime'\r?\n/m, '').replace('export default {', 'globalThis.plugin = {').concat(- '\nglobalThis.__x = { botConnectionRoute, requestForBot, groupMemberKey, parseGroupChatMentions, resolveGroupResponders, formatGroupChatLine, buildGroupChatTurnPrompt };\n'+ '\nglobalThis.__x = { botConnectionRoute, scopedBotParams, botBackendProfileScope, requestForBot, groupMemberKey, parseGroupChatMentions, resolveGroupResponders, formatGroupChatLine, buildGroupChatTurnPrompt };\n')vm.runInNewContext(code, context, { filename: 'plugin.js' })return context}-test('botConnectionRoute: remote rows get a route descriptor, local rows do not', () => {+test('botConnectionRoute: every source-scoped row gets an immutable route', () => {const ctx = runtime()const { botConnectionRoute } = ctx.__xassert.equal(botConnectionRoute({ name: 'writer', connectionId: 'local' }), null)assert.equal(botConnectionRoute({ name: 'writer' }), null)- // remoteSource is required — an annotated ACTIVE row keeps the active door.- assert.equal(botConnectionRoute({ name: 'writer', connectionId: 'spark', sourceScoped: true }), null)+ const active = botConnectionRoute({ name: 'writer', connectionId: 'spark', sourceScoped: true })+ assert.equal(Object.isFrozen(active), true)const route = botConnectionRoute({ name: 'dixie', connectionId: 'mac-mini', remoteSource: true })assert.deepEqual(JSON.parse(JSON.stringify(route)), {@@ -75,7 +75,7 @@ test('botConnectionRoute: remote rows get a route descriptor, local rows do not'})})-test('requestForBot: remote members go through requestProfile, local through host.request', async () => {+test('requestForBot: source-scoped members go through requestProfile', async () => {const ctx = runtime()const calls = []ctx.host.request = async (method, params) => {@@ -90,13 +90,65 @@ test('requestForBot: remote members go through requestProfile, local through hosconst { requestForBot } = ctx.__xawait requestForBot({ name: 'local-bot' }, 'session.create', { title: 'x' })+ await requestForBot({ name: 'local-bot', connectionId: 'local', sourceScoped: true }, 'session.create', { title: 'x' })await requestForBot({ name: 'dixie', connectionId: 'mac-mini', remoteSource: true }, 'prompt.submit', { text: 'hi' })assert.equal(calls[0][0], 'active')assert.equal(calls[0][1], 'session.create')assert.equal(calls[1][0], 'routed')- assert.equal(calls[1][1], 'mac-mini')- assert.equal(calls[1][2], 'prompt.submit')+ assert.equal(calls[1][1], 'local')+ assert.equal(calls[2][0], 'routed')+ assert.equal(calls[2][1], 'mac-mini')+ assert.equal(calls[2][2], 'prompt.submit')+})++test('requestForBot: non-identity aliases translate every backend profile RPC shape', async () => {+ const ctx = runtime()+ const calls = []+ ctx.host.requestProfile = async (route, method, params) => {+ calls.push({ route, method, params })+ return {}+ }+ const bot = {+ name: 'worker',+ sourceScoped: true,+ route: {+ connectionId: 'remote-a',+ mode: 'remote',+ profile: 'worker',+ targetProfile: 'backend-worker'+ }+ }++ await ctx.__x.requestForBot(bot, 'profiles.describe', { name: 'worker' })+ await ctx.__x.requestForBot(bot, 'profiles.configure', { name: 'worker', soul: 'x' })+ await ctx.__x.requestForBot(bot, 'profiles.create', { name: 'worker-2', clone_from: 'worker' })+ await ctx.__x.requestForBot(bot, 'session.create', { profile: 'worker', title: 'Bot Chat' })+ await ctx.__x.requestForBot(bot, 'cli.exec', { argv: ['--profile', 'worker', 'config', 'unset', 'model'] })+ await ctx.__x.requestForBot(bot, 'cli.exec', { argv: ['profile', 'describe', 'worker', '--text', 'x'] })++ assert.deepEqual(JSON.parse(JSON.stringify(calls.map(call => call.params))), [+ { name: 'backend-worker' },+ { name: 'backend-worker', soul: 'x' },+ { name: 'worker-2', clone_from: 'backend-worker' },+ { profile: 'backend-worker', title: 'Bot Chat' },+ { argv: ['--profile', 'backend-worker', 'config', 'unset', 'model'] },+ { argv: ['profile', 'describe', 'backend-worker', '--text', 'x'] }+ ])+ assert.equal(calls.every(call => call.route.profile === 'worker'), true)+})++test('advanced capability scope keeps Desktop identity separate from backend targetProfile', () => {+ const scope = runtime().__x.botBackendProfileScope({+ connectionId: 'remote-a',+ profile: 'worker',+ targetProfile: 'backend-worker'+ })++ assert.deepEqual(JSON.parse(JSON.stringify(scope)), {+ connectionId: 'remote-a',+ profile: 'backend-worker'+ })})test('groupMemberKey: local members keep bare names (persisted-room compat), remote members are source-qualified', () => {diff --git a/apps/desktop/src/plugins/hermes-bots/tests/embed-real-capabilities.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/embed-real-capabilities.test.mjsindex 8ee211ab021..8faf9e677e6 100644--- a/apps/desktop/src/plugins/hermes-bots/tests/embed-real-capabilities.test.mjs+++ b/apps/desktop/src/plugins/hermes-bots/tests/embed-real-capabilities.test.mjs@@ -18,12 +18,18 @@ test('resolves optional Capabilities components from the SDK namespace', () => {test('AdvancedProfileConfig embeds ToolsetConfigPanel per toolset, scoped to the bot profile', () => {// Rendered only when the SDK export exists (older builds: just the toggle).assert.match(source, /ToolsetConfigPanel\s*\n?\s*\?\s*jsx\('div'/)- assert.match(source, /jsx\(ToolsetConfigPanel, \{ toolset: tset\.name, profile: bot \}\)/)+ assert.match(source, /jsx\(ToolsetConfigPanel, \{ toolset: tset\.name, profile: backendScope \}\)/)})test('AdvancedProfileConfig embeds the real McpTab with a live gateway + profile, feature-detected', () => {assert.match(source, /McpTab && typeof host\.getGateway === 'function'/)- assert.match(source, /jsx\(McpTab, \{ gateway: host\.getGateway\(\), profile: bot \}\)/)+ assert.match(source, /jsx\(McpTab, \{ gateway: host\.getGateway\(\), profile: backendScope \}\)/)+})++test('AdvancedProfileConfig scopes SkillsView to the connection and backend target profile', () => {+ assert.match(source, /const botRoute = botConnectionRoute\(bot\)/)+ assert.match(source, /fixedProfile: backendProfile/)+ assert.match(source, /fixedConnection: botRoute\.connectionId/)})test('older-build fallback: the checkbox MCP list + inline McpSetupButton is still present', () => {diff --git a/apps/desktop/src/plugins/hermes-bots/tests/embed-skills-view.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/embed-skills-view.test.mjsindex 7269f515dd0..272cf75f7db 100644--- a/apps/desktop/src/plugins/hermes-bots/tests/embed-skills-view.test.mjs+++ b/apps/desktop/src/plugins/hermes-bots/tests/embed-skills-view.test.mjs@@ -1,6 +1,7 @@import assert from 'node:assert/strict'import { readFileSync } from 'node:fs'import test from 'node:test'+import vm from 'node:vm'// Newer desktop builds export the WHOLE core Capabilities surface (SkillsView,// hermes-agent#87317). The bot editor's Advanced section must render it pinned@@ -10,14 +11,118 @@ import test from 'node:test'const source = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')+function loadAdvanced(SkillsView, sdkComponents = {}) {+ const values = new Map()+ const atom = initial => {+ const slot = {+ get: () => values.get(slot),+ set: value => values.set(slot, value),+ listen: () => undefined+ }+ values.set(slot, initial)+ return slot+ }+ const jsx = (type, props = {}) => ({ type, props })+ const stateValues = [true, false, '']+ const routed = []+ let gatewayReads = 0+ let query+ const context = {+ atom,+ Checkbox: 'Checkbox',+ GlyphSpinner: 'GlyphSpinner',+ Input: 'Input',+ ScrollArea: 'ScrollArea',+ Textarea: 'Textarea',+ document: { createElement: () => ({}), getElementById: () => null, head: { appendChild: () => undefined } },+ host: {+ getGateway: () => {+ gatewayReads += 1+ return 'ambient-gateway'+ },+ request: async (...args) => routed.push(['ambient', ...args]),+ requestProfile: async (...args) => routed.push(['profile', ...args]),+ state: {+ gateway: { get: () => 'open', listen: () => undefined },+ profile: { get: () => 'default', listen: () => undefined }+ }+ },+ jsx,+ jsxs: jsx,+ queryClient: { invalidateQueries: () => undefined },+ sdk: { SkillsView, ...sdkComponents },+ useQuery: options => {+ query = options+ return { data: { providers: [] }, isLoading: false, error: null }+ },+ useState: initial => [stateValues.length ? stateValues.shift() : initial, () => undefined],+ 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(/^import .* from 'react'\r?\n/m, '')+ .replace(/^import .* from 'react\/jsx-runtime'\r?\n/m, '')+ .replace('export default {', 'globalThis.plugin = {')+ .concat('\nglobalThis.__AdvancedProfileConfig = AdvancedProfileConfig; globalThis.__useModelOptions = useModelOptions;')+ vm.runInNewContext(code, context, { filename: 'plugin.js' })++ return { context, gatewayReads: () => gatewayReads, query: () => query, routed }+}++function descendants(node) {+ if (!node || typeof node !== 'object') return []+ const children = Array.isArray(node.props?.children) ? node.props.children : [node.props?.children]+ return [node, ...children.flatMap(descendants)]+}++const remoteBot = {+ connectionId: 'remote-a',+ name: 'default',+ remoteSource: true,+ route: {+ connectionId: 'remote-a',+ mode: 'remote',+ profile: 'default',+ targetProfile: 'backend-default'+ },+ sourceScoped: true,+ targetProfile: 'backend-default'+}++const localBot = {+ connectionId: 'local',+ name: 'default',+ remoteSource: false,+ route: {+ connectionId: 'local',+ mode: 'local',+ profile: 'default',+ targetProfile: 'default'+ },+ sourceScoped: true,+ targetProfile: 'default'+}++const advancedState = {+ loaded: true,+ provider: '',+ model: '',+ soul: '',+ skills: [],+ toolsets: [],+ mcp: [{ name: 'remote-mcp', enabled: false, fromCatalog: true, installed: false, requires: ['TOKEN'] }]+}+test('resolves SkillsView as an optional SDK namespace export', () => {assert.match(source, /import \* as sdk from '@hermes\/plugin-sdk'/)assert.match(source, /const SkillsView = typeof sdk === 'undefined' \? undefined : sdk\.SkillsView/)})test('Edit Profile renders the pinned Capabilities surface when the export exists', () => {- assert.match(source, /if \(SkillsView\) \{/)- assert.match(source, /jsx\(SkillsView, \{ embedded: true, fixedProfile: bot \}\)/)+ assert.match(source, /if \(SkillsView && \(!botRoute \|\| skillsViewRoutesConnections\)\) \{/)+ assert.match(source, /fixedProfile: backendProfile/)+ assert.match(source, /fixedConnection: botRoute\.connectionId/)})test('New Agent gains a Capabilities tab that materializes the profile first', () => {@@ -43,3 +148,80 @@ test('older-build fallback keeps the checklist UI intact', () => {assert.match(source, /jsx\(CheckList, \{ items: visibleSkills/)assert.match(source, /jsx\(HubSkillsSection, \{/)})++test('older SkillsView builds fail closed for remote Edit Profile', () => {+ function OldSkillsView() {}+ function McpTab() {}+ function ToolsetConfigPanel() {}+ const runtime = loadAdvanced(OldSkillsView, { McpTab, ToolsetConfigPanel })+ const tree = runtime.context.__AdvancedProfileConfig({+ bot: remoteBot,+ state: advancedState,+ setState: () => undefined+ })+ const nodes = descendants(tree)++ assert.equal(nodes.some(node => node.type === OldSkillsView), false)+ assert.equal(nodes.some(node => node.type?.name === 'ModelPicker'), true)+ assert.equal(nodes.some(node => node.type === 'Textarea'), true)+ assert.equal(nodes.some(node => node.type?.name === 'HubSkillsSection'), false)+ assert.equal(nodes.some(node => node.type?.name === 'McpSetupButton'), false)+ assert.equal(nodes.some(node => node.type === McpTab), false)+ assert.equal(nodes.some(node => node.type === ToolsetConfigPanel), false)+ assert.equal(runtime.gatewayReads(), 0)++ for (const node of nodes) {+ node.props?.onClick?.()+ node.props?.onCheckedChange?.(true)+ }++ assert.equal(runtime.routed.some(call => call[0] === 'ambient'), false)+ assert.equal(runtime.gatewayReads(), 0)+})++test('older SkillsView builds keep local capability fallback unchanged', () => {+ function OldSkillsView() {}+ function McpTab() {}+ function ToolsetConfigPanel() {}+ const runtime = loadAdvanced(OldSkillsView, { McpTab, ToolsetConfigPanel })+ const tree = runtime.context.__AdvancedProfileConfig({+ bot: localBot,+ state: { ...advancedState, toolsets: [{ name: 'local-tools', enabled: true }] },+ setState: () => undefined+ })+ const nodes = descendants(tree)++ assert.equal(nodes.some(node => node.type?.name === 'HubSkillsSection'), true)+ assert.equal(nodes.some(node => node.type === McpTab), true)+ assert.equal(nodes.some(node => node.type === ToolsetConfigPanel), true)+ assert.equal(runtime.gatewayReads(), 1)+})++test('connection-aware SkillsView receives separate connection and backend profile', () => {+ function RoutedSkillsView() {}+ RoutedSkillsView.supportsFixedConnection = true+ const runtime = loadAdvanced(RoutedSkillsView)+ const tree = runtime.context.__AdvancedProfileConfig({+ bot: remoteBot,+ state: advancedState,+ setState: () => undefined+ })+ const view = descendants(tree).find(node => node.type === RoutedSkillsView)++ assert.equal(view.props.fixedConnection, 'remote-a')+ assert.equal(view.props.fixedProfile, 'backend-default')+})++test('Edit Profile model options use the captured non-identity Bot route', async () => {+ const runtime = loadAdvanced(undefined)+ runtime.context.__useModelOptions(remoteBot)++ await runtime.query().queryFn()++ assert.deepEqual(JSON.parse(JSON.stringify(runtime.routed)), [[+ 'profile',+ remoteBot.route,+ 'model.options',+ { include_unconfigured: true, explicit_only: false, refresh: true }+ ]])+})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/hide-bot-chats.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/hide-bot-chats.test.mjsindex fda52c1c068..412f0344f7c 100644--- a/apps/desktop/src/plugins/hermes-bots/tests/hide-bot-chats.test.mjs+++ b/apps/desktop/src/plugins/hermes-bots/tests/hide-bot-chats.test.mjs@@ -28,6 +28,8 @@ function loadCreate() {}},saveBotMeta: () => {},+ 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')@@ -63,6 +65,9 @@ test('hideOwnedBotSessions sweeps canonical chats AND room member sessions', asy}},$botMeta: { get: () => ({ alpha: { chat: 'chat-a' }, beta: { chat: 'chat-b' }, gamma: {} }) },+ $lastRoster: { get: () => [{ name: 'alpha' }, { name: 'beta' }] },+ 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' } },@@ -144,5 +149,5 @@ 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// preferred_session_ids, whose resolver already sees hidden rows.)- assert.match(source, /session\.list', \{ profile: botName, limit: PROFILE_SESSION_LIST_LIMIT, include_hidden: true \}/)+ assert.match(source, /requestForBot\(owner, 'session\.list',[\s\S]*include_hidden: true/)})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/hide-bots.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/hide-bots.test.mjsindex 9a1bb6e0d9c..8539e716f69 100644--- a/apps/desktop/src/plugins/hermes-bots/tests/hide-bots.test.mjs+++ b/apps/desktop/src/plugins/hermes-bots/tests/hide-bots.test.mjs@@ -204,7 +204,7 @@ test('shape: revealed hidden rows are dimmed and flagged with the eye-closed glyassert.match(botRow, /meta\?\.hidden && 'opacity-60'/)assert.match(botRow, /name: 'eye-closed'/)assert.match(botRow, /children: meta\?\.hidden \? 'Unhide Bot' : 'Hide Bot'/)- assert.match(botRow, /saveBotMeta\(bot\.name, \{ hidden: !hidden \}\)/)+ assert.match(botRow, /saveBotMeta\(bot, \{ hidden: !hidden \}\)/)})test('shape: hiding never filters mentions, group flows, or the meta/activity sweeps', () => {diff --git a/apps/desktop/src/plugins/hermes-bots/tests/model-inherit.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/model-inherit.test.mjsindex f36c5cc09e5..1e539cdd543 100644--- a/apps/desktop/src/plugins/hermes-bots/tests/model-inherit.test.mjs+++ b/apps/desktop/src/plugins/hermes-bots/tests/model-inherit.test.mjs@@ -10,6 +10,7 @@ function loadApplyAdvancedConfig(request) {const end = source.indexOf('// ── edit profile dialog', start)const context = {host: { request },+ requestForBot: (_bot, method, params) => request(method, params),ensureMessagingProtocol: soul => soul,$lastRoster: { get: () => [] }}@@ -45,7 +46,7 @@ test('regression: selecting Inherit explicitly clears the profile model assignmereturn { code: 0, blocked: false, output: 'Unset model' }})- const result = await apply('ops', state({ dirtyModel: true }))+ const result = await apply({ name: 'ops' }, state({ dirtyModel: true }))assert.deepEqual(JSON.parse(JSON.stringify(calls)), [{@@ -64,7 +65,7 @@ test('integration: model clearing and other dirty sections report a merged resulreturn { ok: true, applied: { soul: true } }})- const result = await apply('ops', state({ dirtyModel: true, dirtySoul: true, soul: '# Ops' }))+ const result = await apply({ name: 'ops' }, state({ dirtyModel: true, dirtySoul: true, soul: '# Ops' }))assert.equal(calls[0].method, 'cli.exec')assert.deepEqual(JSON.parse(JSON.stringify(calls[1])), {@@ -80,7 +81,7 @@ test('integration: model clearing and other dirty sections report a merged resultest('regression: a rejected model clear is reported as a failed section', async () => {const apply = loadApplyAdvancedConfig(async () => ({ code: 1, blocked: false, output: 'Config key not set' }))- const result = await apply('ops', state({ dirtyModel: true }))+ const result = await apply({ name: 'ops' }, state({ dirtyModel: true }))assert.deepEqual(JSON.parse(JSON.stringify(result)), { ok: false, applied: { model: false } })})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/multi-source-roster.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/multi-source-roster.test.mjsindex f097e95326d..ee0ae378a50 100644--- a/apps/desktop/src/plugins/hermes-bots/tests/multi-source-roster.test.mjs+++ b/apps/desktop/src/plugins/hermes-bots/tests/multi-source-roster.test.mjs@@ -230,24 +230,27 @@ test('default rows use source identity without borrowing another source title',const { __botRosterKey: key, __botRosterMeta: metaFor, __displayName: name } = runtime()const remote = {name: 'default',- connectionId: 'personal',+ connectionId: 'other',connectionLabel: 'Personal',remoteSource: true,sourceScoped: true}- const active = { ...remote, remoteSource: undefined }- const metadata = { default: { title: 'Active workspace' } }+ const active = { ...remote, connectionId: 'personal', remoteSource: undefined }+ const metadata = {+ default: { title: 'Legacy local only' },+ 'personal::default': { title: 'Active workspace' }+ }- assert.equal(metaFor(remote, metadata), null)+ assert.equal(metaFor(remote, metadata), undefined)assert.equal(name(remote, metaFor(remote, metadata)), 'Personal')- assert.equal(key(remote), 'personal::default')+ assert.equal(key(remote), 'other::default')// The ACTIVE gateway's own default is the user's main agent — annotation// (sourceScoped + connection fields) must NOT rename it to a connection// label. Titled: the title wins. Untitled: it stays "Hermes". Regression:// remote-gateway desktops showed the main agent as an IP-derived label// with no shortname (Aug 17 2026 report).- assert.equal(name(active, metadata.default), 'Active workspace')+ assert.equal(name(active, metadata['personal::default']), 'Active workspace')assert.equal(name(active, undefined), 'Hermes')})@@ -264,7 +267,14 @@ test('filterBots: matches the source device name for remote rows', () => {const { __filterBots: filterBots } = runtime()const roster = [{ name: 'research' },- { name: 'research', remoteSource: true, connectionLabel: 'Homelab', handle: 'research-homelab' }+ {+ name: 'research',+ connectionId: 'homelab',+ connectionLabel: 'Homelab',+ handle: 'research-homelab',+ remoteSource: true,+ sourceScoped: true+ }]const hits = filterBots(roster, {}, 'homelab')diff --git a/apps/desktop/src/plugins/hermes-bots/tests/profile-prewarm.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/profile-prewarm.test.mjsindex 4c7db313fa9..e2d6c201978 100644--- a/apps/desktop/src/plugins/hermes-bots/tests/profile-prewarm.test.mjs+++ b/apps/desktop/src/plugins/hermes-bots/tests/profile-prewarm.test.mjs@@ -56,6 +56,11 @@ function renderBotRow(input = 'alpha') {// #49 session-aware-row helpers referenced inside BotRow.previewKind: () => ({ fromBot: false, sender: null }),generatedSessionTitle: () => null,+ isActiveRosterBot: () => false,+ isBackfilledFacePng: () => false,+ botSelectionKey: value => value.sourceScoped ? `${value.connectionId}::${value.name}` : value.name,+ isDefaultBot: value => value.name === 'default',+ newBotChat: () => undefined,openBotCanonicalChat: async (...args) => {opened.push(args)return 'stored-chat'@@ -121,7 +126,7 @@ test('behavior: pointer entry prewarms only the hovered bot', () => {assert.deepEqual(warmed, ['alpha'])})-test('behavior: a remote Connections row stays in this chat instead of hopping SSH', async () => {+test('behavior: a remote Connections row opens through its captured route without activation authority', async () => {const { ensured, opened, row, warmed } = renderBotRow({connectionId: 'work',connectionLabel: 'Work',@@ -135,10 +140,11 @@ test('behavior: a remote Connections row stays in this chat instead of hopping Sawait row.props.onClick()assert.deepEqual(ensured, [])- assert.deepEqual(opened, [])+ assert.equal(opened.length, 1)+ assert.equal(opened[0][0].connectionId, 'work')})-test('behavior: remote default does not open this-device chat when the source did not activate', async () => {+test('behavior: remote default never opens the same-name local chat', async () => {const bot = {connectionId: 'mac-mini',connectionLabel: 'Mac Mini',@@ -182,6 +188,11 @@ test('behavior: remote default does not open this-device chat when the source dihaptic: () => undefined,previewKind: () => ({ fromBot: false, sender: null }),generatedSessionTitle: () => null,+ isActiveRosterBot: () => false,+ isBackfilledFacePng: () => false,+ botSelectionKey: value => value.sourceScoped ? `${value.connectionId}::${value.name}` : value.name,+ isDefaultBot: value => value.name === 'default',+ newBotChat: () => undefined,openBotCanonicalChat: async (...args) => {opened.push(args)return 'this-device-chat'@@ -217,6 +228,7 @@ test('behavior: remote default does not open this-device chat when the source diawait row.props.onClick()assert.deepEqual(ensured, [])- assert.deepEqual(opened, [])+ assert.equal(opened.length, 1)+ assert.equal(opened[0][0].connectionId, 'mac-mini')assert.equal(errors.length, 0)})diff --git 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.mjsindex d864d637ce5..d27c25967ea 100644--- a/apps/desktop/src/plugins/hermes-bots/tests/remote-dm-delivery.test.mjs+++ b/apps/desktop/src/plugins/hermes-bots/tests/remote-dm-delivery.test.mjs@@ -127,6 +127,61 @@ test('remote DM carries sender attribution and relays the reply', async () => {)})+test('remote DM preserves a non-identity targetProfile through list, resume, create, and submit', async () => {+ const calls = []+ let submitted = false+ const ctx = runtime({+ requestProfile: async (route, method, params) => {+ calls.push({ route, method, params })++ if (method === 'profiles.list') {+ return { profiles: [{ name: 'backend-worker', ui_meta: {} }] }+ }++ if (method === 'session.resume' && params.omit_messages) {+ throw new Error('not found')+ }++ if (method === 'session.create') {+ return { session_id: 'runtime-1', stored_session_id: 'stored-1' }+ }++ if (method === 'prompt.submit') {+ submitted = true+ return {}+ }++ if (method === 'session.resume') {+ return submitted+ ? { messages: [{ role: 'assistant', content: 'done' }], inflight: false, running: false }+ : { messages: [] }+ }++ return {}+ }+ })+ const route = {+ connectionId: 'remote-a',+ mode: 'remote',+ profile: 'worker',+ targetProfile: 'backend-worker'+ }++ await ctx.__dm.deliverRemoteRosterMentions(+ [{ name: 'worker', connectionId: 'remote-a', remoteSource: true, route }],+ 'ping',+ { name: 'Hermes', handle: 'hermes' }+ )++ assert.equal(calls.length > 0, true)+ assert.equal(calls.every(call => call.route.profile === 'worker'), true)+ assert.equal(calls.every(call => call.route.targetProfile === 'backend-worker'), true)+ for (const call of calls.filter(call => ['session.resume', 'session.create'].includes(call.method))) {+ assert.equal(call.params.profile, 'backend-worker')+ }+ assert.equal(calls.find(call => call.method === 'prompt.submit')?.params.session_id, 'runtime-1')+})+test('source contract: DM poll shares the group-turn shape (bounded, new-assistant-message)', () => {assert.match(pluginSource, /const REMOTE_DM_TIMEOUT_MS = /)assert.match(pluginSource, /pollRemoteDmReply/)diff --git 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.mjsnew file mode 100644index 00000000000..2ac69d87fa1--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/tests/remote-routing-races.test.mjs@@ -0,0 +1,521 @@+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,+ groupMemberKey,+ migrateBotMeta,+ migratedLocalRoutes,+ newBotChat,+ openBotCanonicalChat,+ openProfileSession,+ persistBotMetaSnapshot,+ requestForBot,+ saveBotMeta,+ setPluginStorage: storage => { pluginCtx = { storage } },+ useProfileSessions+ }+ `)+ vm.runInNewContext(code, context, { filename: 'plugin.js' })+ return {+ context,+ calls,+ host,+ setActiveConnection: value => {+ activeConnectionId = value+ }+ }+}++const remoteBot = {+ connectionId: 'remote-a',+ connectionLabel: 'Remote A',+ name: 'default',+ remoteSource: true,+ route: { connectionId: 'remote-a', mode: 'remote', profile: 'default', targetProfile: 'remote-default' },+ sourceScoped: true,+ targetProfile: 'remote-default'+}++function recordingStorage(initial, failSetKey = null, failRemoveKeys = []) {+ const values = new Map(Object.entries(initial))+ const operations = []+ const failedRemovals = new Set(failRemoveKeys)++ return {+ operations,+ get: async key => values.get(key) ?? null,+ set: async (key, value) => {+ operations.push(['set', key, value])+ if (key === failSetKey) {+ 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('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 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 --git a/apps/desktop/src/plugins/hermes-bots/tests/roster-groups.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/roster-groups.test.mjsindex f4a58bdcefb..f275ce93d21 100644--- a/apps/desktop/src/plugins/hermes-bots/tests/roster-groups.test.mjs+++ b/apps/desktop/src/plugins/hermes-bots/tests/roster-groups.test.mjs@@ -128,14 +128,22 @@ test('groupChatMemberBots: seats local meta members plus stored remote descriptotest('durableGroupChatMembers: retains active and remote source identities', () => {const { durableGroupChatMembers } = load()const members = durableGroupChatMembers([- { name: 'default', handle: 'noah', connectionId: 'noah', connectionKind: 'remote', connectionLabel: 'Noah' },+ {+ name: 'default',+ handle: 'noah',+ connectionId: 'noah',+ connectionKind: 'remote',+ connectionLabel: 'Noah',+ sourceScoped: true+ },{name: 'default',handle: 'maya',connectionId: 'maya',connectionKind: 'remote',connectionLabel: 'Maya',- remoteSource: true+ remoteSource: true,+ sourceScoped: true}])@@ -149,6 +157,8 @@ test('durableGroupChatMembers: retains active and remote source identities', ()connectionId: 'noah',connectionKind: 'remote',connectionLabel: 'Noah',+ route: { connectionId: 'noah', mode: 'remote', profile: 'default', targetProfile: 'default' },+ targetProfile: 'default',remoteSource: true,sourceScoped: true},@@ -158,6 +168,8 @@ test('durableGroupChatMembers: retains active and remote source identities', ()connectionId: 'maya',connectionKind: 'remote',connectionLabel: 'Maya',+ route: { connectionId: 'maya', mode: 'remote', profile: 'default', targetProfile: 'default' },+ targetProfile: 'default',remoteSource: true,sourceScoped: true}diff --git a/apps/desktop/src/plugins/hermes-bots/tests/routine-owner.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/routine-owner.test.mjsindex f0e09041b06..3ebf4308276 100644--- a/apps/desktop/src/plugins/hermes-bots/tests/routine-owner.test.mjs+++ b/apps/desktop/src/plugins/hermes-bots/tests/routine-owner.test.mjs@@ -66,7 +66,7 @@ test('routine mutation invalidates only its immutable owner cache', async () =>test('source contract: row mutations invalidate the profile that owned the request', () => {assert.match(pluginSource,- /function RoutineRow\(\{ job, profile \}\)[\s\S]*await host\.request\('cron\.manage', \{ action, name: job\.job_id, \.\.\.\(profile \? \{ profile \} : \{\}\) \}\)[\s\S]*await invalidateRoutineOwner\(profile\)/+ /function RoutineRow\(\{ job, owner \}\)[\s\S]*await requestForBot\(owner, 'cron\.manage',[\s\S]*await invalidateRoutineOwner\(owner\)/)assert.doesNotMatch(pluginSource, /function RoutineRow\(\{ job, onChanged, profile \}\)/)})@@ -74,10 +74,10 @@ test('source contract: row mutations invalidate the profile that owned the requetest('source contract: create mutations and dialog state retain one owner', () => {assert.match(pluginSource,- /function CreateRoutineDialog\(\{ bot, open, onClose \}\)[\s\S]*await host\.request\('cron\.manage', \{[\s\S]*\.\.\.\(bot \? \{ profile: bot \} : \{\}\)[\s\S]*await invalidateRoutineOwner\(bot\)/+ /function CreateRoutineDialog\(\{ bot, open, onClose \}\)[\s\S]*await requestForBot\(bot, 'cron\.manage',[\s\S]*\.\.\.\(profile \? \{ profile \} : \{\}\)[\s\S]*await invalidateRoutineOwner\(bot\)/)assert.match(pluginSource, /const \[createOwner, setCreateOwner\] = useState\(null\)/)- assert.match(pluginSource, /const openCreate = \(\) => \{[\s\S]*setCreateOwner\(bot\)[\s\S]*setCreateOpen\(true\)/)+ assert.match(pluginSource, /const openCreate = \(\) => \{[\s\S]*setCreateOwner\(owner\)[\s\S]*setCreateOpen\(true\)/)assert.match(pluginSource, /const createTarget = routineCreateTarget\(createOwner, bot\)/)// key must be the jsx() THIRD argument (a `key:` prop is silently ignored// by the react/jsx-runtime and the dialog would keep stale per-bot state).diff --git a/apps/desktop/src/plugins/hermes-bots/tests/routine-prompt.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/routine-prompt.test.mjsindex 79e094d81fe..ed2de91bf4b 100644--- a/apps/desktop/src/plugins/hermes-bots/tests/routine-prompt.test.mjs+++ b/apps/desktop/src/plugins/hermes-bots/tests/routine-prompt.test.mjs@@ -160,12 +160,12 @@ test('robustness: routine input rejects NUL before cron creation', () => {assert.match(__routines.routineInputError('Normal title', 'Bad\0instruction'), /NUL.*U\+0000/)assert.match(pluginSource,- /const inputError = routineInputError\(title, task\)[\s\S]*if \(inputError\)[\s\S]*setError\(inputError\)[\s\S]*return[\s\S]*host\.request\('cron\.manage'/+ /const inputError = routineInputError\(title, task\)[\s\S]*if \(inputError\)[\s\S]*setError\(inputError\)[\s\S]*return[\s\S]*requestForBot\(bot, 'cron\.manage'/)})test('regression: Create Cronjob passes the active profile to routinePrompt', () => {- assert.match(pluginSource, /prompt: routinePrompt\(bot, title, task, activeProfile\)/)+ assert.match(pluginSource, /prompt: routinePrompt\(profile, title, task, activeProfile\)/)const { __routines } = load()const instruction = 'Keep "quoted" output intact'assert.equal(__routines.routinePrompt('ops', 'Check', instruction, 'ops'), instruction)diff --git a/apps/desktop/src/plugins/hermes-bots/tests/routines-profile-scope.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/routines-profile-scope.test.mjsindex bac16adc8c3..fd4e52b9613 100644--- a/apps/desktop/src/plugins/hermes-bots/tests/routines-profile-scope.test.mjs+++ b/apps/desktop/src/plugins/hermes-bots/tests/routines-profile-scope.test.mjs@@ -19,13 +19,13 @@ test('loadRoutines forwards a profile scope to cron.manage list + pause', () =>})test('useRoutines is bot-keyed so switching bots refetches', () => {- assert.match(source, /queryKey: \[\.\.\.ROUTINES_KEY, profile \|\| ''\]/)- assert.match(source, /queryFn: \(\) => loadRoutines\(profile\)/)+ assert.match(source, /queryKey: \[\.\.\.ROUTINES_KEY, key\]/)+ assert.match(source, /queryFn: \(\) => loadRoutines\(bot\)/)})test('RoutineRow toggle and create forward the profile scope', () => {// RoutineRow pause/resume- assert.match(source, /action, name: job\.job_id, \.\.\.\(profile \? \{ profile \} : \{\}\)/)+ assert.match(source, /requestForBot\(owner, 'cron\.manage', \{ action, name: job\.job_id, \.\.\.\(profile \? \{ profile \} : \{\}\) \}\)/)// create- assert.match(source, /\.\.\.\(bot \? \{ profile: bot \} : \{\}\)/)+ assert.match(source, /requestForBot\(bot, 'cron\.manage',[\s\S]*\.\.\.\(profile \? \{ profile \} : \{\}\)/)})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/session-workspace.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/session-workspace.test.mjsindex 8d2d1c03b85..e65c68e462e 100644--- a/apps/desktop/src/plugins/hermes-bots/tests/session-workspace.test.mjs+++ b/apps/desktop/src/plugins/hermes-bots/tests/session-workspace.test.mjs@@ -132,19 +132,19 @@ test('sessions workspace: an in-flight open cannot restore selection after gatewassert.deepEqual(plain(runtime.__sessions.$botSelectedSessions.get()), {})})-test('source contract: bot rows and Active now activate the owner before canonical chat', () => {+test('source contract: Bot opens capture the owner route without activation authority', () => {assert.match(pluginSource, /async function prepareBotSource\(bot, pinnedChat\)/)- assert.match(pluginSource, /await host\.ensureAgent\(bot\.connectionId, bot\.name\)/)- assert.match(pluginSource, /host\.request\('profiles\.list', \{\}\)/)- assert.match(pluginSource, /const open = async \(\) => \{[\s\S]*await prepareBotSource\(bot, pinnedChat\)[\s\S]*openBotCanonicalChat\(bot\.name, pinnedChat, previewSession\)/)- assert.match(pluginSource, /onOpen: bot => \{[\s\S]*await prepareBotSource\(bot, pinnedChat\)[\s\S]*bot\.preferred_session \|\| bot\.last_session/)+ assert.doesNotMatch(pluginSource, /await host\.ensureAgent\(bot\.connectionId, bot\.name\)/)+ assert.match(pluginSource, /const refreshed = await requestForBot\(bot, 'profiles\.list', \{\}\)/)+ assert.match(pluginSource, /openBotCanonicalChat\(bot, pinnedChat, previewSession\)/)+ assert.match(pluginSource, /newBotChat\(bot\)/)assert.match(pluginSource, /openBotSessionsWorkspace\(bot\)[\s\S]*children: 'Sessions'/)})test('source contract: workspaces disclose the bounded recent-session inventory', () => {- assert.match(pluginSource, /queryKey: \[ID, 'profile-sessions', botName, gatewayGeneration\]/)- assert.match(pluginSource, /enabled: Boolean\(botName\)/)- assert.match(pluginSource, /host\.request\('session\.list', \{ profile: botName, limit: PROFILE_SESSION_LIST_LIMIT, include_hidden: true \}\)/)+ assert.match(pluginSource, /queryKey: \[ID, 'profile-sessions', key, gatewayGeneration\]/)+ assert.match(pluginSource, /enabled: Boolean\(profile\)/)+ assert.match(pluginSource, /requestForBot\(owner, 'session\.list'/)assert.match(pluginSource, /Showing the \$\{PROFILE_SESSION_LIST_LIMIT\} most recent sessions\./)assert.match(pluginSource, /No matching sessions in the \$\{PROFILE_SESSION_LIST_LIMIT\} most recent\./)assert.doesNotMatch(pluginSource, /children: 'Activate profile'/)diff --git a/apps/desktop/src/sdk/index.ts b/apps/desktop/src/sdk/index.tsindex 6ffdd1b2974..3332a731649 100644--- a/apps/desktop/src/sdk/index.ts+++ b/apps/desktop/src/sdk/index.ts@@ -50,6 +50,7 @@ import {$profiles,ensureGatewayAgent,ensureGatewayProfile,+ newSessionInAgent,newSessionInProfile,normalizeProfileKey,refreshProfiles,@@ -65,6 +66,7 @@ import {$gatewayState,$messages,$selectedStoredSessionId,+ setSessionOwnerHint,requestSessionResume,setResumeExhaustedSessionId} from '@/store/session'@@ -147,6 +149,10 @@ async function requestPluginProfile<T>(params: Record<string, unknown>): Promise<T> {if (typeof route !== 'string') {+ if (!route.connectionId.trim() || !route.profile.trim() || !route.targetProfile.trim()) {+ throw new Error('Profile route must include connectionId, profile, and targetProfile')+ }+return requestGatewayForAgent<T>(route.connectionId, route.profile, method, params)}@@ -201,22 +207,25 @@ const $activeConnectionId = computed($connection, connection => {const DEFAULT_SESSION_HYDRATION_TIMEOUT_MS = 20_000let openSessionGeneration = 0-interface PluginOpenSessionOptions {+export interface PluginOpenSessionOptions {awaitHydration?: booleanexpectHistory?: booleanhydrationTimeoutMs?: numberintent?: OpenSessionIntentkeepAllProfilesScope?: booleanprofile?: null | string+ route?: PluginProfileRoute}function waitForFocusedSessionHydration({+ connectionId,expectHistory,generation,profile,storedSessionId,timeoutMs}: {+ connectionId?: stringexpectHistory: booleangeneration: numberprofile: string@@ -258,6 +267,7 @@ function waitForFocusedSessionHydration({}const profileMatches = normalizeProfileKey($activeGatewayProfile.get()) === profile+ const connectionMatches = !connectionId || $activeConnectionId.get() === connectionIdconst sessionMatches = $selectedStoredSessionId.get() === storedSessionIdconst runtimeReady = Boolean($activeSessionId.get())const historyPainted = Boolean($messages.get().length)@@ -276,12 +286,13 @@ function waitForFocusedSessionHydration({// surface is real rather than a stuck loader.const hydrated = expectHistory ? historyPainted : runtimeReady- if (profileMatches && sessionMatches && hydrated) {+ if (profileMatches && connectionMatches && sessionMatches && hydrated) {finish()}}unbinds.push($activeGatewayProfile.listen(check))+ unbinds.push($activeConnectionId.listen(check))unbinds.push($selectedStoredSessionId.listen(check))unbinds.push($activeSessionId.listen(check))unbinds.push($messages.listen(check))@@ -387,27 +398,48 @@ export const host = {* entirely. When the deleted profile was the live gateway's, the app is* re-homed to the default profile — same semantics as the core dialog.* Rejects with the backend's error when the delete fails. */- deleteProfile: async (profile: string): Promise<void> => {- const name = (profile ?? '').trim()+ deleteProfile: async (profile: string | PluginProfileRoute): Promise<void> => {+ const route =+ typeof profile === 'string'+ ? null+ : {+ ...profile,+ connectionId: String(profile.connectionId || '').trim(),+ profile: String(profile.profile || '').trim(),+ targetProfile: String(profile.targetProfile || '').trim()+ }+ const name = typeof profile === 'string' ? profile.trim() : route?.profile || ''++ if (route && (!route.connectionId || !route.profile || !route.targetProfile)) {+ throw new Error('deleteProfile: route requires connectionId, profile, and targetProfile')+ }++ const targetProfile = route?.targetProfile || nameif (!name) {throw new Error('deleteProfile: profile name required')}- if (normalizeProfileKey(name) === 'default') {+ if (normalizeProfileKey(targetProfile) === 'default') {throw new Error('The default profile cannot be deleted.')}// Capture before the delete; re-home after so our write is the last one// (mirrors DeleteProfileDialog — a refreshActiveProfile racing the dying// backend can't clobber the pill back to the deleted profile).- const wasActive = normalizeProfileKey(name) === normalizeProfileKey($activeGatewayProfile.get())+ const wasActive = route+ ? route.connectionId === ($activeConnectionId.get() || '') &&+ normalizeProfileKey(route.profile) === normalizeProfileKey($activeGatewayProfile.get())+ : normalizeProfileKey(name) === normalizeProfileKey($activeGatewayProfile.get())// 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)// The profile rail paints from the shared $profiles cache; without a// refresh the deleted profile's badge survives and clicking it starts a@@ -475,7 +507,8 @@ export const host = {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// Wake-path phase timings. Logged ONLY on a hydration timeout (bridged@@ -485,7 +518,15 @@ export const host = {const wakeStartedAt = Date.now()let profileActiveAt = wakeStartedAt- if (profile && profile !== $activeGatewayProfile.get()) {+ if (ownerRoute) {+ await ensureGatewayAgent(ownerRoute.connectionId, ownerRoute.profile)+ setSessionOwnerHint(storedSessionId, ownerRoute)+ profileActiveAt = Date.now()++ if (options.keepAllProfilesScope !== false) {+ setShowAllProfiles(true)+ }+ } else if (profile && profile !== $activeGatewayProfile.get()) {await ensureGatewayProfile(profile)profileActiveAt = Date.now()@@ -535,11 +576,16 @@ export const host = {(!expectHistory || $messages.get().length > 0)if (options.awaitHydration && !surfaceHealthy) {- requestSessionResume(storedSessionId)+ if (ownerRoute) {+ requestSessionResume(storedSessionId, ownerRoute)+ } else {+ requestSessionResume(storedSessionId)+ }}if (options.awaitHydration) {await waitForFocusedSessionHydration({+ connectionId: ownerRoute?.connectionId,expectHistory,generation,profile: targetProfile,@@ -632,8 +678,13 @@ export const host = {/** Start a fresh chat draft, optionally pointed at another profile (its* backend spins up in the background — same door the sidebar's per-profile* "+" uses). */- newChat: (profile?: null | string): void => {- newSessionInProfile((profile ?? '').trim() || $activeGatewayProfile.get())+ newChat: (profile?: null | string | PluginProfileRoute): void => {+ if (profile && typeof profile !== 'string') {+ newSessionInAgent({ ...profile })+ } else {+ newSessionInProfile((profile ?? '').trim() || $activeGatewayProfile.get())+ }+window.location.hash = '#/'},diff --git a/apps/desktop/src/sdk/profile-routing.test.ts b/apps/desktop/src/sdk/profile-routing.test.tsindex 26ca655169b..68a83d45237 100644--- a/apps/desktop/src/sdk/profile-routing.test.ts+++ b/apps/desktop/src/sdk/profile-routing.test.ts@@ -29,6 +29,7 @@ vi.mock('@/store/session', async () => {$messages: atom([]),$selectedStoredSessionId: atom(null),requestSessionResume: vi.fn(),+ setSessionOwnerHint: vi.fn(),setResumeExhaustedSessionId: vi.fn()}})@@ -63,6 +64,7 @@ vi.mock('@/store/profile', async () => {$profiles: profiles,ensureGatewayAgent: vi.fn(),ensureGatewayProfile: vi.fn(),+ newSessionInAgent: vi.fn(),newSessionInProfile: vi.fn(),normalizeProfileKey: (value: null | string | undefined) => (value ?? '').trim() || 'default',refreshProfiles: vi.fn(async () => profiles.get()),@@ -101,13 +103,19 @@ 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, ensureGatewayProfile, refreshProfiles } =+const { $activeGatewayProfile, $gatewaySwapTarget, $profiles, ensureGatewayAgent, ensureGatewayProfile, refreshProfiles } =await import('@/store/profile')const { $focusedRuntimeId, $focusedSessionState, $focusedStoredSessionId } = await import('@/store/session-states')-const { $activeSessionId, $messages, $selectedStoredSessionId, requestSessionResume, setResumeExhaustedSessionId } =- await import('@/store/session')+const {+ $activeSessionId,+ $messages,+ $selectedStoredSessionId,+ requestSessionResume,+ setSessionOwnerHint,+ setResumeExhaustedSessionId+} = await import('@/store/session')const setMockAtom = <T>(store: unknown, value: T) => (store as { set(next: T): void }).set(value)@@ -223,6 +231,89 @@ describe('connection-aware plugin host APIs', () => {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'+ })+ 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'+ })+ })+it('keeps the profile-only request overload as a legacy fallback', async () => {const result = await host.requestProfile('legacy-worker', 'profiles.list', { include_sessions: true })@@ -286,6 +377,21 @@ describe('connection-aware plugin host APIs', () => {})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(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')diff --git a/apps/desktop/src/store/profile.ts b/apps/desktop/src/store/profile.tsindex 6e23a7b07f2..e354321227f 100644--- a/apps/desktop/src/store/profile.ts+++ b/apps/desktop/src/store/profile.ts@@ -192,6 +192,16 @@ export const $activeGatewayProfile = atom<string>('default')// Profile for the NEXT new chat (chosen via the new-chat picker). null = primary// / default, so single-profile users are unaffected.export const $newChatProfile = atom<string | null>(null)+export interface AgentProfileRoute {+ connectionId: string+ mode?: 'local' | 'remote'+ profile: string+ targetProfile?: string+}++// A draft remembers the source it was created for. The active gateway may+// change before the first Send; the draft's owner must not change with it.+export const $newChatRoute = atom<AgentProfileRoute | null>(null)// Bumped whenever the open session should be dropped for a fresh new-session// draft: a profile switch/create (below), or deleting the project that owns the@@ -517,6 +527,7 @@ export function selectProfile(name: string): void {const switching = $showAllProfiles.get() || target !== normalizeProfileKey($activeGatewayProfile.get())$showAllProfiles.set(false)$newChatProfile.set(target)+ $newChatRoute.set(null)if (switching) {requestFreshSession()@@ -534,10 +545,32 @@ export function selectProfile(name: string): void {export function newSessionInProfile(name: string): void {const target = normalizeProfileKey(name)$newChatProfile.set(target)+ $newChatRoute.set(null)requestFreshSession()void ensureGatewayProfile(target)}+/** Start a draft owned by a specific registry agent. Foreground activation is+ * only a presentation step; the route stays attached to the draft for the+ * eventual session.create request. */+export function newSessionInAgent(route: AgentProfileRoute): void {+ const captured = {+ ...route,+ connectionId: route.connectionId.trim(),+ profile: normalizeProfileKey(route.profile),+ ...(route.targetProfile ? { targetProfile: normalizeProfileKey(route.targetProfile) } : {})+ }++ if (!captured.connectionId) {+ throw new Error('Agent profile route is missing connectionId')+ }++ $newChatProfile.set(captured.profile)+ $newChatRoute.set(captured)+ requestFreshSession()+ void ensureGatewayAgent(captured.connectionId, captured.profile)+}+export function setShowAllProfiles(value: boolean): void {$showAllProfiles.set(value)}diff --git a/apps/desktop/src/store/session-request-router.test.ts b/apps/desktop/src/store/session-request-router.test.tsindex f6f3ef89a87..6829b32aa6c 100644--- a/apps/desktop/src/store/session-request-router.test.ts+++ b/apps/desktop/src/store/session-request-router.test.ts@@ -60,6 +60,11 @@ function installDesktop(): void {getConnection: vi.fn(async (profile: null | string) =>profile ? { port: 5151, profile, token: 'secondary-token' } : { port: 4242, token: 'primary-token' }),+ getConnectionFor: vi.fn(async ({ connectionId, profile }: { connectionId: string; profile: string }) => ({+ port: connectionId === 'source-a' ? 6161 : 6262,+ profile,+ token: `${connectionId}-token`+ })),touchBackend: vi.fn(async () => undefined)}}@@ -139,6 +144,68 @@ describe('sessionRpcNeedsProfileRoute', () => {})describe('requestForSessionProfile', () => {+ it('keeps concurrent same-name requests pinned while foreground activation changes', async () => {+ const primary = makePrimary()+ setPrimaryGateway(primary as never, 'default')+ installDesktop()+ await ensureGatewayForProfile('other')+ const desktop = (window as unknown as {+ hermesDesktop: { getConnectionFor: ReturnType<typeof vi.fn> }+ }).hermesDesktop+ const ambient = vi.fn(async () => ({ ambient: true }))+ const routeA = {+ connectionId: 'source-a',+ profile: 'default',+ targetProfile: 'backend-a'+ }+ const routeB = {+ connectionId: 'source-b',+ profile: 'default',+ targetProfile: 'backend-b'+ }++ const fromA = requestForSessionProfile(routeA, ambient as never, 'session.resume', {+ profile: 'default',+ session_id: 'stored-a'+ })+ routeA.connectionId = 'source-b'+ routeA.targetProfile = 'mutated-after-dispatch'+ await ensureGatewayForProfile('default')+ const fromB = requestForSessionProfile(routeB, ambient as never, 'session.resume', {+ profile: 'default',+ session_id: 'stored-b'+ })++ await Promise.all([fromA, fromB])++ expect(desktop.getConnectionFor).toHaveBeenCalledWith({ connectionId: 'source-a', profile: 'default' })+ expect(desktop.getConnectionFor).toHaveBeenCalledWith({ connectionId: 'source-b', profile: 'default' })+ expect(secondaryGateways).toHaveLength(3)+ expect(secondaryGateways[1].request).toHaveBeenCalledWith('session.resume', {+ profile: 'backend-a',+ session_id: 'stored-a'+ })+ expect(secondaryGateways[2].request).toHaveBeenCalledWith('session.resume', {+ profile: 'backend-b',+ session_id: 'stored-b'+ })+ expect(ambient).not.toHaveBeenCalled()+ })++ it('rejects an explicit route without a connection instead of using ambient state', async () => {+ const ambient = vi.fn(async () => ({ ambient: true }))++ await expect(+ requestForSessionProfile(+ { connectionId: '', profile: 'default', targetProfile: 'backend-default' },+ ambient as never,+ 'session.resume',+ { session_id: 'stored-a' }+ )+ ).rejects.toThrow(/missing connectionId/i)+ expect(ambient).not.toHaveBeenCalled()+ })+it("dispatches on the owning profile's own socket when the active route moved off it (#89206)", async () => {const primary = makePrimary()setPrimaryGateway(primary as never, 'default')diff --git a/apps/desktop/src/store/session-request-router.ts b/apps/desktop/src/store/session-request-router.tsindex 8c67a529163..f739ea0bf81 100644--- a/apps/desktop/src/store/session-request-router.ts+++ b/apps/desktop/src/store/session-request-router.ts@@ -1,4 +1,18 @@-import { activeGatewayProfileKey, requestGatewayForProfile } from '@/store/gateway'+import {+ activeGatewayConnectionId,+ activeGatewayProfileKey,+ requestGatewayForAgent,+ requestGatewayForProfile+} from '@/store/gateway'++export interface SessionProfileRoute {+ connectionId: string+ mode?: 'local' | 'remote'+ profile: string+ targetProfile?: string+}++export type SessionOwnerScope = undefined | null | string | SessionProfileRoute// ── Session-scoped RPC routing (the #89206 class) ───────────────────────────// A session-scoped RPC (session.resume / session.activate / session.usage)@@ -15,6 +29,17 @@ import { activeGatewayProfileKey, requestGatewayForProfile } from '@/store/gatewconst normKey = (profile: null | string | undefined): string => (profile ?? '').trim() || 'default'+const isRoute = (owner: SessionOwnerScope): owner is SessionProfileRoute =>+ Boolean(owner && typeof owner === 'object' && 'connectionId' in owner)++function routeParams(route: SessionProfileRoute, params: Record<string, unknown>): Record<string, unknown> {+ if (!route.targetProfile || !Object.prototype.hasOwnProperty.call(params, 'profile')) {+ return params+ }++ return { ...params, profile: route.targetProfile }+}+/*** True when a session-scoped RPC must be pinned to `ownerProfile`'s own* socket because the active gateway currently serves a different profile.@@ -22,9 +47,17 @@ const normKey = (profile: null | string | undefined): string => (profile ?? '').* (the pre-multi-profile behavior) rather than guessing.*/export function sessionRpcNeedsProfileRoute(- ownerProfile: null | string | undefined,- activeProfile: string = activeGatewayProfileKey()+ ownerProfile: SessionOwnerScope | undefined,+ activeProfile: string = activeGatewayProfileKey(),+ activeConnectionId: null | string = activeGatewayConnectionId()): boolean {+ if (isRoute(ownerProfile)) {+ // A descriptor is an immutable ownership claim. Even an explicitly local+ // route must not collapse to the ambient request: another connection can+ // expose the same profile name, and activation is UI state only.+ return Boolean(ownerProfile.connectionId.trim())+ }+if (ownerProfile == null || !String(ownerProfile).trim()) {return false}@@ -39,11 +72,21 @@ export function sessionRpcNeedsProfileRoute(* 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>,method: string,params: Record<string, unknown> = {}): 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))+ }+if (!sessionRpcNeedsProfileRoute(ownerProfile)) {return ambientRequest<T>(method, params)}diff --git a/apps/desktop/src/store/session.test.ts b/apps/desktop/src/store/session.test.tsindex ab7961dc038..dcf715a3e14 100644--- a/apps/desktop/src/store/session.test.ts+++ b/apps/desktop/src/store/session.test.ts@@ -27,6 +27,7 @@ import {commitWorkspaceCwdForSelectedSession,getRememberedRoute,getRememberedSessionId,+ getSessionOwnerHint,mergeSessionPage,rememberedSessionProfile,resolveComposerSessionKey,@@ -36,6 +37,7 @@ import {setCurrentCwdTransient,setRememberedRoute,setRememberedSessionId,+ setSessionOwnerHint,setSelectedStoredSessionId,setSessions,shouldMigrateComposerScope,@@ -68,6 +70,35 @@ const session = (over: Partial<SessionInfo>): SessionInfo => ({...over})+describe('session owner hints', () => {+ it('keeps identical session ids separate across connection and profile owners', () => {+ const sourceA = { connectionId: 'source-a', mode: 'remote' as const, profile: 'worker', targetProfile: 'backend-a' }+ const sourceB = { connectionId: 'source-b', mode: 'remote' as const, profile: 'worker', targetProfile: 'backend-b' }++ setSessionOwnerHint('same-session', sourceA)+ setSessionOwnerHint('same-session', sourceB)++ expect(getSessionOwnerHint('same-session', sourceA)).toEqual(sourceA)+ expect(getSessionOwnerHint('same-session', sourceB)).toEqual(sourceB)+ expect(getSessionOwnerHint('same-session')).toBeUndefined()+ })++ it('bounds owner hints and evicts the oldest scoped identity', () => {+ for (let index = 0; index < 257; index += 1) {+ setSessionOwnerHint(`bounded-${index}`, {+ connectionId: 'bounded-source',+ mode: 'remote',+ profile: 'worker',+ targetProfile: 'backend-worker'+ })+ }++ const scope = { connectionId: 'bounded-source', profile: 'worker' }+ expect(getSessionOwnerHint('bounded-0', scope)).toBeUndefined()+ expect(getSessionOwnerHint('bounded-256', scope)).toMatchObject({ connectionId: 'bounded-source' })+ })+})+describe('computed $attentionSessionIds', () => {beforeEach(() => {clearAllSessionStates()diff --git a/apps/desktop/src/store/session.ts b/apps/desktop/src/store/session.tsindex eff88f92fbd..9532c42f429 100644--- a/apps/desktop/src/store/session.ts+++ b/apps/desktop/src/store/session.ts@@ -9,6 +9,7 @@ import { activeConnectionScopeSuffix, rescopeConnectionScopedStores } from '@/liimport { persistBoolean, persistString, storedBoolean, storedString } from '@/lib/storage'import { syncCronModelImpactConnection } from '@/store/cron-model-impact-scope'import type { SessionInfo, UsageStats } from '@/types/hermes'+import type { SessionProfileRoute } from './session-request-router'import { clearUnreadOnOpen } from './session-unread-remote'@@ -599,11 +600,63 @@ export const $awaitingResponse = atom(false)// Null whenever the active route has a healthy (or in-flight) resume.export const $resumeFailedSessionId = atom<string | null>(null)export interface SessionResumeRequest {+ ownerRoute?: SessionProfileRoutesequence: numbersessionId: string}let sessionResumeRequestSequence = 0export const $sessionResumeRequest = atom<SessionResumeRequest | null>(null)+const SESSION_OWNER_HINT_LIMIT = 256+const sessionOwnerHints = new Map<string, { id: string; route: SessionProfileRoute }>()++function sessionOwnerHintKey(sessionId: string, route: Pick<SessionProfileRoute, 'connectionId' | 'profile'>): string {+ return JSON.stringify([route.connectionId.trim(), route.profile.trim() || 'default', sessionId])+}++export function setSessionOwnerHint(sessionId: string, route: SessionProfileRoute): void {+ const id = sessionId.trim()+ const normalized = {+ ...route,+ connectionId: route.connectionId.trim(),+ profile: route.profile.trim() || 'default',+ ...(route.targetProfile ? { targetProfile: route.targetProfile.trim() || 'default' } : {})+ }++ if (!id || !normalized.connectionId) {+ return+ }++ const key = sessionOwnerHintKey(id, normalized)+ sessionOwnerHints.delete(key)+ sessionOwnerHints.set(key, { id, route: normalized })++ while (sessionOwnerHints.size > SESSION_OWNER_HINT_LIMIT) {+ const oldest = sessionOwnerHints.keys().next().value++ if (oldest === undefined) {+ break+ }++ sessionOwnerHints.delete(oldest)+ }+}++export function getSessionOwnerHint(+ sessionId: string,+ scope?: Pick<SessionProfileRoute, 'connectionId' | 'profile'>+): SessionProfileRoute | undefined {+ const id = sessionId.trim()++ if (scope) {+ const entry = sessionOwnerHints.get(sessionOwnerHintKey(id, scope))++ return entry ? { ...entry.route } : undefined+ }++ const matches = [...sessionOwnerHints.values()].filter(entry => entry.id === id)++ return matches.length === 1 ? { ...matches[0].route } : undefined+}// Stored-session id whose resume has EXHAUSTED its bounded auto-retries (the// terminal-failure latch above kept failing through all MAX_RESUME_RETRIES// attempts). Distinct from $resumeFailedSessionId, which is armed *during* the@@ -778,14 +831,22 @@ export const setMessages = (next: Updater<ChatMessage[]>) => updateAtom($messageexport const setFreshDraftReady = (next: Updater<boolean>) => updateAtom($freshDraftReady, next)export const setResumeFailedSessionId = (next: Updater<string | null>) => updateAtom($resumeFailedSessionId, next)-export const requestSessionResume = (sessionId: string) => {+export const requestSessionResume = (sessionId: string, ownerRoute?: SessionProfileRoute) => {const id = sessionId.trim()if (!id) {return}- $sessionResumeRequest.set({ sequence: ++sessionResumeRequestSequence, sessionId: id })+ if (ownerRoute) {+ setSessionOwnerHint(id, ownerRoute)+ }++ $sessionResumeRequest.set({+ ...(ownerRoute ? { ownerRoute: { ...ownerRoute } } : {}),+ sequence: ++sessionResumeRequestSequence,+ sessionId: id+ })}export const setResumeExhaustedSessionId = (next: Updater<string | null>) => updateAtom($resumeExhaustedSessionId, next)diff --git a/apps/desktop/src/store/transcript-tail.ts b/apps/desktop/src/store/transcript-tail.tsindex fc1794743ac..c87e615d92e 100644--- a/apps/desktop/src/store/transcript-tail.ts+++ b/apps/desktop/src/store/transcript-tail.ts@@ -25,14 +25,60 @@ export interface TranscriptTailState {possiblyTruncated: boolean/** Owning profile captured at hydration time, so a later backfill routes* its REST read to the same backend that served the tail. */+ profile?: TranscriptProfileScope+}++export type TranscriptProfileScope = null | string | {+ connectionId?: null | stringprofile?: null | string}export const $transcriptTailBySessionId = atom<Record<string, TranscriptTailState>>({})+const TRANSCRIPT_TAIL_LIMIT = 256+let transcriptTailOrder: string[] = []type TailPage = Pick<SessionMessagesResponse, 'messages' | 'pagination'>-function tailStateFromPage(page: TailPage, profile?: null | string): TranscriptTailState {+function normalizedScope(profile?: TranscriptProfileScope): { connectionId: string; profile: string } | null {+ if (typeof profile === 'string') {+ return { connectionId: '', profile: profile.trim() || 'default' }+ }++ if (!profile) {+ return null+ }++ return {+ connectionId: String(profile.connectionId || '').trim(),+ profile: String(profile.profile || '').trim() || 'default'+ }+}++function transcriptTailKey(storedSessionId: string, profile?: TranscriptProfileScope): string {+ const scope = normalizedScope(profile)++ return scope ? JSON.stringify([scope.connectionId, scope.profile, storedSessionId]) : storedSessionId+}++function matchingTailEntries(+ storedSessionId: string+): Array<[string, TranscriptTailState]> {+ return Object.entries($transcriptTailBySessionId.get()).filter(([key]) => {+ if (key === storedSessionId) {+ return true+ }++ try {+ const parsed = JSON.parse(key)++ return Array.isArray(parsed) && parsed.length === 3 && parsed[2] === storedSessionId+ } catch {+ return false+ }+ })+}++function tailStateFromPage(page: TailPage, profile?: TranscriptProfileScope): TranscriptTailState {const pagination = page.pagination// No pagination metadata is a legacy backend that ignored the paging query@@ -48,37 +94,94 @@ function tailStateFromPage(page: TailPage, profile?: null | string): TranscriptT}}+function setTranscriptTailEntry(key: string, state: TranscriptTailState): void {+ const current = $transcriptTailBySessionId.get()+ const existing = new Set(Object.keys(current))+ transcriptTailOrder = transcriptTailOrder.filter(candidate => candidate !== key && existing.has(candidate))+ transcriptTailOrder.push(key)++ const next = { ...current, [key]: state }++ while (transcriptTailOrder.length > TRANSCRIPT_TAIL_LIMIT) {+ const oldest = transcriptTailOrder.shift()++ if (oldest !== undefined) {+ delete next[oldest]+ }+ }++ $transcriptTailBySessionId.set(next)+}+/** Record the outcome of a tail hydration (`getLatestSessionMessages`). */-export function recordTranscriptTail(storedSessionId: string, page: TailPage, profile?: null | string): void {+export function recordTranscriptTail(storedSessionId: string, page: TailPage, profile?: TranscriptProfileScope): void {if (!storedSessionId) {return}- const current = $transcriptTailBySessionId.get()- $transcriptTailBySessionId.set({ ...current, [storedSessionId]: tailStateFromPage(page, profile) })+ const key = transcriptTailKey(storedSessionId, profile)+ setTranscriptTailEntry(key, tailStateFromPage(page, profile))}/** Advance the bookkeeping after one older backfill page landed. */-export function recordTranscriptBackfillPage(storedSessionId: string, page: TailPage): void {+export function recordTranscriptBackfillPage(+ storedSessionId: string,+ page: TailPage,+ profile?: TranscriptProfileScope+): void {const current = $transcriptTailBySessionId.get()- const previous = current[storedSessionId]- $transcriptTailBySessionId.set({- ...current,- [storedSessionId]: tailStateFromPage(page, previous?.profile)- })+ const selected: Array<[string, TranscriptTailState | undefined]> = profile === undefined+ ? matchingTailEntries(storedSessionId)+ : [[transcriptTailKey(storedSessionId, profile), current[transcriptTailKey(storedSessionId, profile)]]]++ if (selected.length !== 1) {+ return+ }++ const [key, previous] = selected[0]++ if (!previous) {+ return+ }++ setTranscriptTailEntry(key, tailStateFromPage(page, previous.profile))}-export function transcriptTailState(storedSessionId: null | string | undefined): TranscriptTailState | undefined {- return storedSessionId ? $transcriptTailBySessionId.get()[storedSessionId] : undefined+export function transcriptTailState(+ storedSessionId: null | string | undefined,+ profile?: TranscriptProfileScope+): TranscriptTailState | undefined {+ if (!storedSessionId) {+ return undefined+ }++ if (profile !== undefined) {+ return $transcriptTailBySessionId.get()[transcriptTailKey(storedSessionId, profile)]+ }++ const matches = matchingTailEntries(storedSessionId)++ return matches.length === 1 ? matches[0][1] : undefined}-export function clearTranscriptTail(storedSessionId: string): void {+export function clearTranscriptTail(storedSessionId: string, profile?: TranscriptProfileScope): void {const current = $transcriptTailBySessionId.get()+ const keys = profile === undefined+ ? matchingTailEntries(storedSessionId).map(([key]) => key)+ : [transcriptTailKey(storedSessionId, profile)]- if (!(storedSessionId in current)) {+ if (keys.length === 0) {return}- const { [storedSessionId]: _dropped, ...rest } = current- $transcriptTailBySessionId.set(rest)+ const next = { ...current }++ for (const key of keys) {+ delete next[key]+ }++ const removed = new Set(keys)+ transcriptTailOrder = transcriptTailOrder.filter(key => !removed.has(key))++ $transcriptTailBySessionId.set(next)}