The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Merge current upstream into fix/remote-bot-routing
Sara Burke336b3216d519
diff --cc apps/desktop/src/api/client.tsindex 00000000000,e996ab01094..8a925be2dd4mode 000000,100644..100644--- a/apps/desktop/src/api/client.ts+++ b/apps/desktop/src/api/client.ts@@@ -1,0 -1,154 +1,154 @@@+ import { JsonRpcGatewayClient } from '@hermes/shared'++ import type { HermesApiRequest } from '@/global'++ // Desktop startup fires a burst of read-only data calls (config, profiles,+ // model info/options, cron) the moment the backend passes readiness. On a+ // profile-heavy or remote install these can each take tens of seconds — e.g.+ // /api/profiles runs list_profiles(), which does a recursive skill-tree walk+ // per profile — so the 15s default (DEFAULT_FETCH_TIMEOUT_MS in hardening.ts)+ // times out a backend that is alive-but-busy, surfacing as a spurious+ // "Timed out connecting to Hermes backend" that hangs the UI (#48504).+ //+ // Give the boot burst a generous per-call timeout instead of raising the+ // global default: interactive/runtime calls and the liveness poll (/api/status)+ // keep the short default so a genuinely-dead backend is still detected fast.+ export const STARTUP_REQUEST_TIMEOUT_MS = 60_000+ const DEFAULT_GATEWAY_REQUEST_TIMEOUT_MS = 30_000+ // prompt.submit is effectively fire-and-forget: turn completion is signaled by+ // stream / message.complete events, NOT by the RPC return. A long turn (MoA+ // presets running references + aggregator in series, deep reasoning, large tool+ // chains) can legitimately take minutes to ACK, so bounding the ack by the+ // generic 30s default surfaces a false "request timed out" toast while the turn+ // is still running and will succeed (issue #55024). Match the backend's+ // agent-turn ceiling (agent.gateway_timeout = 1800s) so the ack timeout only+ // ever fires when the turn itself would have been abandoned server-side.+ export const PROMPT_SUBMIT_REQUEST_TIMEOUT_MS = 1_800_000++ export class HermesGateway extends JsonRpcGatewayClient {+ constructor() {+ super({+ closedErrorMessage: 'Hermes gateway connection closed',+ connectErrorMessage: 'Could not connect to Hermes gateway',+ createRequestId: nextId => nextId,+ notConnectedErrorMessage: 'Hermes gateway is not connected',+ requestTimeoutMs: DEFAULT_GATEWAY_REQUEST_TIMEOUT_MS+ })+ }+ }++ // Profile that profile-scoped REST settings (config/env/skills/tools/model/…)+ // should target. Mirrors $activeGatewayProfile, pushed in from the store via+ // setApiRequestProfile so this module needs no store import (avoids a cycle).+ // Electron main consumes request.profile as request scope. Local calls whose+ // REST handlers accept profile reuse the primary dashboard via ?profile=;+ // unscoped handlers retain a profile backend. Remote overrides still route to+ // their owning backend. Null → primary, so single-profile users are unaffected.+ let _apiProfile: null | string = null++ export function setApiRequestProfile(profile: null | string): void {+ _apiProfile = profile || null+ }++ export function profileScoped(profile?: null | string): { profile?: string } {+ const selected = profile === undefined ? _apiProfile : profile++ return selected ? { profile: selected } : {}+ }++ /** Profile that profile-scoped REST/WS calls should target (null → primary).+ * Read-only twin of setApiRequestProfile for modules (e.g. voice playback)+ * that build their own connection URLs and must stay on the same backend. */+ export function getApiRequestProfile(): null | string {+ return _apiProfile+ }++ // Registry connection serving the active gateway (null → the local pool).+ // Pushed from store/gateway's setActive — the single seam BOTH+ // ensureGatewayProfile and ensureGatewayAgent funnel through — so WS calls+ // that dial their own backend (pluginSocket) resolve it through the SAME+ // source of truth those paths maintain for $connection. That makes the plugin+ // socket follow registry-agent activations too, not just profile switches.+ // Same no-store-import contract as _apiProfile (avoids a cycle).+ let _apiConnectionId: null | string = null++ export function setApiRequestConnection(connectionId: null | string): void {+ _apiConnectionId = connectionId || null+ }++ // Registry connection scope for a REST request. A registered remote gateway+ // owns its own state.db — cron jobs and their run sessions live THERE — so+ // requests for gateway-owned data must carry the connection id for the main+ // process to route them to that host (hermes:api's registry branch). Null+ // resolves to no tag, keeping single-source users byte-identical; explicit+ // 'local' must remain tagged when the legacy primary points elsewhere.+ export function connectionScoped(): { connectionId?: string } {+ return _apiConnectionId ? { connectionId: _apiConnectionId } : {}+ }++ /** Send a REST request to the renderer's active registry source. Request-level+ * routing may override the active source for an explicitly-owned resource.+ *+ * Helpers under `api/` go through here rather than calling the preload bridge+ * directly, so the connection tag cannot be forgotten on a new one — with one+ * exception. A capabilityScoped() helper must NOT: that scope says "the local+ * pool" by omitting `connectionId` entirely, and an absent key cannot override+ * the ambient tag spread underneath it, so a 'local' pin would silently route+ * to whatever remote gateway happened to be active. Those helpers call the+ * bridge directly and own their routing end to end. */+ export function hermesApi<T>(request: HermesApiRequest): Promise<T> {+ return window.hermesDesktop.api<T>({ ...connectionScoped(), ...request })+ }++ // ── Capability scope: (connection, profile) routing for the Capabilities+ // surface (skills / toolsets / MCP / hub / env / toolset config) ────────────+ //+ // A profile is not a machine-global name — it belongs to ONE gateway. The+ // Capabilities surface can be pointed at any (connection, profile) pair+ // (SkillsView's scope selector, Bot Mode's fixedProfile/fixedConnection), so+ // its REST helpers accept either the legacy string form or an explicit scope+ // object:+ //+ // - `undefined` / string → the legacy profile path, PLUS the active registry+ // connection tag (connectionScoped, same contract the cron helpers adopted+ // in #87882). Without the tag, a window activated onto a registered remote+ // gateway read the LOCAL pool's skills/tools/MCP — the wrong machine.+ // - `{ connectionId, profile }` → explicit pin. `''`/`'local'` connection+ // 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 }++ export function capabilityScoped(scope?: ProfileScope): { connectionId?: string; profile?: string } {+ if (scope && typeof scope === 'object') {+ const profile = (scope.profile ?? '').trim()+ const connectionId = (scope.connectionId ?? '').trim()++ return {+ ...(profile ? { profile } : {}),+ ...(connectionId && connectionId !== 'local' ? { connectionId } : {})+ }+ }++ return { ...profileScoped(scope), ...connectionScoped() }+ }++ /** Stable cache-key for a capability scope: `profile` for the local/legacy+ * path, `connectionId::profile` for an explicit remote pin. Mirrors+ * normalizeProfileKey for plain strings so existing keys stay byte-identical. */+ export function profileScopeKey(scope?: ProfileScope): string {+ if (scope && typeof scope === 'object') {+ const profile = (scope.profile ?? '').trim() || 'default'+ const connectionId = (scope.connectionId ?? '').trim()++ return connectionId && connectionId !== 'local' ? `${connectionId}::${profile}` : profile+ }++ return (scope ?? '').trim() || 'default'+ }++ /** Registry connection id that connection-scoped WS calls should target+ * (null → the local pool). Read-only twin of setApiRequestConnection. */+ export function getApiRequestConnection(): null | string {+ return _apiConnectionId+ }diff --cc apps/desktop/src/api/profiles.tsindex 00000000000,52fc0909065..514e367da54mode 000000,100644..100644--- a/apps/desktop/src/api/profiles.ts+++ b/apps/desktop/src/api/profiles.ts@@@ -1,0 -1,89 +1,104 @@@+ import type {+ ProfileCreatePayload,+ ProfileDesktopOverlay,+ ProfileSetupCommand,+ ProfileSoul,+ ProfilesResponse+ } from '@/types/hermes'+-import { hermesApi, STARTUP_REQUEST_TIMEOUT_MS } from './client'++import { capabilityScoped, hermesApi, type ProfileScope, STARTUP_REQUEST_TIMEOUT_MS } from './client'++ export function getProfiles(): Promise<ProfilesResponse> {+ return hermesApi<ProfilesResponse>({+ path: '/api/profiles',+ timeoutMs: STARTUP_REQUEST_TIMEOUT_MS+ })+ }++ export function createProfile(body: ProfileCreatePayload): Promise<{ name: string; ok: boolean; path: string }> {+ return hermesApi<{ name: string; ok: boolean; path: string }>({+ path: '/api/profiles',+ method: 'POST',+ body+ })+ }++ export function renameProfile(name: string, newName: string): Promise<{ name: string; ok: boolean; path: string }> {+ return hermesApi<{ name: string; ok: boolean; path: string }>({+ path: `/api/profiles/${encodeURIComponent(name)}`,+ method: 'PATCH',+ body: { new_name: newName }+ })+ }+-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 hermesApi<{ ok: boolean; path: string }>({- path: `/api/profiles/${encodeURIComponent(name)}`,++ ...capabilityScoped(scope),++ ...(scope && typeof scope === 'object' && scope.connectionId?.trim() === 'local'++ ? { connectionId: 'local' }++ : {}),++ path: `/api/profiles/${encodeURIComponent(normalized)}`,+ method: 'DELETE'+ })+ }++ export function getProfileSoul(name: string): Promise<ProfileSoul> {+ return hermesApi<ProfileSoul>({+ path: `/api/profiles/${encodeURIComponent(name)}/soul`+ })+ }++ export function updateProfileSoul(name: string, content: string): Promise<{ ok: boolean }> {+ return hermesApi<{ ok: boolean }>({+ path: `/api/profiles/${encodeURIComponent(name)}/soul`,+ method: 'PUT',+ body: { content }+ })+ }++ export function getProfileSetupCommand(name: string): Promise<ProfileSetupCommand> {+ return hermesApi<ProfileSetupCommand>({+ path: `/api/profiles/${encodeURIComponent(name)}/setup-command`+ })+ }++ /** Export a profile to a shareable .tar.gz on the backend's filesystem.+ * `extraFiles` stages extra root-level files (desktop.json — the appearance/+ * interface overlay) into the archive alongside the profile's own artifacts. */+ export function exportProfileArchive(+ name: string,+ opts: { extraFiles?: Record<string, string>; output?: string } = {}+ ): Promise<{ archive: string; ok: boolean }> {+ return hermesApi<{ archive: string; ok: boolean }>({+ path: `/api/profiles/${encodeURIComponent(name)}/export`,+ method: 'POST',+ body: { extra_files: opts.extraFiles ?? {}, output: opts.output ?? '' },+ timeoutMs: STARTUP_REQUEST_TIMEOUT_MS+ })+ }++ /** Import a profile .tar.gz as a new profile. Returns the bundled desktop+ * appearance overlay too (when the archive carried one) so the caller can+ * apply theme/layout without another round-trip. */+ export function importProfileArchive(+ archive: string,+ name?: string+ ): Promise<{ desktop: null | ProfileDesktopOverlay; name: string; ok: boolean; path: string }> {+ return hermesApi<{ desktop: null | ProfileDesktopOverlay; name: string; ok: boolean; path: string }>({+ path: '/api/profiles/import',+ method: 'POST',+ body: { archive, name: name || null },+ timeoutMs: STARTUP_REQUEST_TIMEOUT_MS+ })+ }diff --cc apps/desktop/src/api/sessions.tsindex 00000000000,e8f17ac2265..9bd5adfba12mode 000000,100644..100644--- a/apps/desktop/src/api/sessions.ts+++ b/apps/desktop/src/api/sessions.ts@@@ -1,0 -1,465 +1,487 @@@+ import { isMissingRestEndpoint } from '@/lib/gateway-rpc'+ import { recordTranscriptTail } from '@/store/transcript-tail'+ import type {+ PaginatedSessions,+ SessionInfo,+ SessionMessage,+ SessionMessagesResponse,+ SessionSearchResponse+ } from '@/types/hermes'+-import { hermesApi } from './client'++import { capabilityScoped, hermesApi, type ProfileScope } from './client'++ const SESSION_LIST_REQUEST_TIMEOUT_MS = 60_000+++function sessionScoped(scope?: ProfileScope): { connectionId?: string; profile?: string } {++ if (scope === undefined || scope === null) {++ return {}++ }++++ const scoped = capabilityScoped(scope)++++ if (typeof scope === 'object' && scope.connectionId?.trim() === 'local') {++ return { ...scoped, connectionId: 'local' }++ }++++ return scoped++}++++function sessionScopeQuery(scope?: ProfileScope): string {++ const profile = sessionScoped(scope).profile++++ return profile ? `?profile=${encodeURIComponent(profile)}` : ''++}+++ /**+ * Trim a page to its window WITHOUT discarding pinned rows.+ *+ * The list endpoints deliberately back-fill pinned conversations past their+ * LIMIT — a pin means "always reachable", so an aged-out pinned chat is+ * appended after the recency window. A plain `slice(0, limit)` throws exactly+ * those rows away again, which is why pins silently stopped rendering past+ * some count: the sidebar could only ever show the pins that happened to fall+ * inside the most-recent page.+ */+ function pageWindow(sessions: SessionInfo[], limit: number): SessionInfo[] {+ if (sessions.length <= limit) {+ return sessions+ }++ const recent = sessions.slice(0, limit)++ return [...recent, ...sessions.slice(limit).filter(session => session.pinned)]+ }++ export async function listSessions(+ limit = 40,+ minMessages = 0,+ archived: 'exclude' | 'include' | 'only' = 'exclude',+ order: 'created' | 'recent' = 'recent'+ ): Promise<PaginatedSessions> {+ const result = await hermesApi<PaginatedSessions>({+ path:+ `/api/sessions?limit=${limit}&offset=0&min_messages=${Math.max(0, minMessages)}` ++ `&archived=${archived}&order=${order}`,+ timeoutMs: SESSION_LIST_REQUEST_TIMEOUT_MS+ })++ return {+ ...result,+ sessions: pageWindow(result.sessions, limit),+ offset: 0+ }+ }++ // Unified, read-only session list aggregated across ALL profiles. Served by the+ // primary backend straight off each profile's state.db — no per-profile backend+ // is spawned. Single-profile users get the same rows as listSessions(), tagged+ // profile="default".+ // Source scoping lets callers split the unified list into independent slices:+ // recents pass `excludeSources: ['cron']`, the cron-jobs section passes+ // `source: 'cron'`. Without this a burst of (always-newest) cron sessions+ // consumes the whole recents page and starves real conversations.+ export interface SessionSourceFilter {+ source?: string+ excludeSources?: string[]+ }++ export async function listAllProfileSessions(+ limit = 40,+ minMessages = 0,+ archived: 'exclude' | 'include' | 'only' = 'exclude',+ order: 'created' | 'recent' = 'recent',+ profile: 'all' | (string & {}) = 'all',+ filter: SessionSourceFilter = {}+ ): Promise<PaginatedSessions> {+ const sourceParam = filter.source ? `&source=${encodeURIComponent(filter.source)}` : ''++ const excludeParam = filter.excludeSources?.length+ ? `&exclude_sources=${encodeURIComponent(filter.excludeSources.join(','))}`+ : ''++ const result = await hermesApi<PaginatedSessions>({+ path:+ `/api/profiles/sessions?limit=${limit}&offset=0&min_messages=${Math.max(0, minMessages)}` ++ `&archived=${archived}&order=${order}&profile=${encodeURIComponent(profile)}${sourceParam}${excludeParam}`,+ timeoutMs: SESSION_LIST_REQUEST_TIMEOUT_MS+ })++ return {+ ...result,+ sessions: pageWindow(result.sessions, limit),+ offset: 0+ }+ }++ // Batched sidebar slices in one request: recents (scoped to the active profile),+ // cron, and messaging. The backend opens each profile's state.db once and runs+ // all three filtered queries, replacing three separate listAllProfileSessions+ // calls that each reopened + re-counted every profile DB per refresh. Electron+ // splices remote profiles per slice (see interceptSessionRequestForRemote).+ export interface SidebarSessionSlice {+ sessions: SessionInfo[]+ /** Per-profile "the window came back full, more rows exist on disk" flags —+ * what pagination needs, without a COUNT(*) per profile DB per refresh. */+ profiles_truncated?: Record<string, boolean>+ /** Per-profile tokens and spend over every session, not just this window.+ * Absent from the legacy per-slice endpoint, which has no aggregate. */+ profiles_usage?: Record<string, { cost_usd: number; tokens: number }>+ }++ /** Which profiles filled their per-profile window in a returned page. The+ * legacy per-slice endpoint doesn't report this, so derive it from the rows:+ * a profile at (or over) the cap still has more on disk. Pinned rows are+ * discounted — they're back-filled past the LIMIT, so counting them fakes a+ * full page and leaves a "Load more" that can never resolve. */+ function profilesTruncatedFrom(sessions: SessionInfo[], cap: number): Record<string, boolean> {+ const counts = new Map<string, number>()++ for (const session of sessions) {+ const key = session.profile || 'default'++ counts.set(key, (counts.get(key) ?? 0) + (session.pinned ? 0 : 1))+ }++ return Object.fromEntries([...counts].map(([name, count]) => [name, count >= cap]))+ }++ export interface SidebarSessionsResponse {+ recents: SidebarSessionSlice+ cron: SidebarSessionSlice+ messaging: SidebarSessionSlice+ errors?: Array<{ profile: string; error: string }>+ }++ export interface SidebarSessionsRequest {+ recentsProfile: 'all' | (string & {})+ recentsLimit: number+ recentsExclude: string[]+ cronLimit: number+ messagingLimit: number+ messagingExclude: string[]+ }++ // The batched /sidebar endpoint shipped later than the per-slice route, so a+ // newer desktop can meet an older backend that 404s it ("No such API+ // endpoint"). Endpoint-missing is a capability signal, not a transient+ // failure: remember it (per renderer lifetime — a runtime home change reloads+ // the window and re-probes) and serve every subsequent refresh straight from+ // the three proven per-slice calls instead of re-probing a known-dead route+ // once per turn/broadcast.+ let sidebarBatchEndpointMissing = false++ // Capability flags are per-backend facts. A hard re-home reloads the window+ // (module state resets naturally), but a soft gateway switch re-dials in+ // place — the next backend may well have the batched route, so the switch+ // paths call this to re-probe rather than leak the old backend's capability.+ export function resetSidebarBatchCapability() {+ sidebarBatchEndpointMissing = false+ }++ // Compatibility fallback: reassemble the three sidebar slices from the+ // per-slice endpoint, mirroring the batched route's semantics (min_messages=1,+ // archived excluded, recency order; every slice scoped to the caller's profile).+ // Rides the same Electron remote-splice+ // interception as the pre-batching desktop, so remote profiles stay correct.+ async function listSidebarSessionsLegacy(req: SidebarSessionsRequest): Promise<SidebarSessionsResponse> {+ const [recents, cron, messaging] = await Promise.all([+ listAllProfileSessions(req.recentsLimit, 1, 'exclude', 'recent', req.recentsProfile, {+ excludeSources: req.recentsExclude+ }),+ listAllProfileSessions(req.cronLimit, 1, 'exclude', 'recent', req.recentsProfile, { source: 'cron' }),+ listAllProfileSessions(req.messagingLimit, 1, 'exclude', 'recent', req.recentsProfile, {+ excludeSources: req.messagingExclude+ })+ ])++ const errors = [...(recents.errors ?? []), ...(cron.errors ?? []), ...(messaging.errors ?? [])]++ return {+ recents: {+ profiles_truncated: profilesTruncatedFrom(recents.sessions, req.recentsLimit),+ sessions: recents.sessions+ },+ cron: { sessions: cron.sessions },+ messaging: { sessions: messaging.sessions },+ ...(errors.length ? { errors } : {})+ }+ }++ /** The PR each of these sessions opened, recovered from its own transcript —+ * for sessions whose recorded branch can't answer (they started on trunk and+ * did the work in a worktree). Also returns every id it looked at, so the+ * caller can remember a miss and never ask again. */+ export function scanSessionPullRequests(+ ids: string[]+ ): Promise<{ pull_requests: Record<string, { number: number; url: string }>; scanned: string[] }> {+ return hermesApi<{+ pull_requests: Record<string, { number: number; url: string }>+ scanned: string[]+ }>({+ path: '/api/profiles/sessions/pull-requests',+ method: 'POST',+ body: { ids }+ })+ }++ export async function listSidebarSessions(req: SidebarSessionsRequest): Promise<SidebarSessionsResponse> {+ if (sidebarBatchEndpointMissing) {+ return listSidebarSessionsLegacy(req)+ }++ const params = new URLSearchParams({+ recents_profile: req.recentsProfile,+ recents_limit: String(Math.max(1, req.recentsLimit)),+ cron_limit: String(Math.max(1, req.cronLimit)),+ messaging_limit: String(Math.max(1, req.messagingLimit))+ })++ if (req.recentsExclude.length) {+ params.set('recents_exclude', req.recentsExclude.join(','))+ }++ if (req.messagingExclude.length) {+ params.set('messaging_exclude', req.messagingExclude.join(','))+ }++ let result: SidebarSessionsResponse++ try {+ result = await hermesApi<SidebarSessionsResponse>({+ path: `/api/profiles/sessions/sidebar?${params.toString()}`,+ timeoutMs: SESSION_LIST_REQUEST_TIMEOUT_MS+ })+ } catch (err) {+ // Safe to read a 404 as route-missing here: this GET has no path params,+ // so it cannot 404 on a bad id.+ if (!isMissingRestEndpoint(err)) {+ throw err+ }++ // Older backend without the batched route (desktop/runtime version skew).+ sidebarBatchEndpointMissing = true++ return listSidebarSessionsLegacy(req)+ }++ return {+ recents: { ...result.recents, sessions: result.recents?.sessions ?? [] },+ cron: { ...result.cron, sessions: result.cron?.sessions ?? [] },+ messaging: { ...result.messaging, sessions: result.messaging?.sessions ?? [] },+ errors: result.errors+ }+ }++ // Mutations take the owning `profile` so Electron can route them to the correct+ // remote backend or local profile scope. Omit for the current/default profile.+ export function setSessionArchived(id: string, archived: boolean, profile?: string | null): Promise<{ ok: boolean }> {+ return hermesApi<{ ok: boolean }>({+ ...(profile ? { profile } : {}),+ path: `/api/sessions/${encodeURIComponent(id)}`,+ method: 'PATCH',+ body: { archived }+ })+ }++ // Mirror a sidebar pin to the backend "keep" flag so the sessions.auto_archive+ // sweep (which runs backend-side, blind to Desktop localStorage) never hides a+ // pinned chat. Best-effort: the sidebar stays localStorage-driven for its own+ // display; this only feeds the backend policy.+ export function setSessionPinnedRemote(id: string, pinned: boolean, profile?: string | null): Promise<{ ok: boolean }> {+ return hermesApi<{ ok: boolean }>({+ ...(profile ? { profile } : {}),+ path: `/api/sessions/${encodeURIComponent(id)}`,+ method: 'PATCH',+ body: { pinned }+ })+ }++ // Mirror a sidebar unread toggle to the backend read-state watermark+ // (sessions.last_read_at via SessionDB.set_session_read). Same profile+ // routing as the other session mutations: a remote session's row lives only+ // on its remote host, so the owning profile must travel with the request.+ export function setSessionUnreadRemote(id: string, unread: boolean, profile?: string | null): Promise<{ ok: boolean }> {+ return hermesApi<{ ok: boolean }>({+ ...(profile ? { profile } : {}),+ path: `/api/sessions/${encodeURIComponent(id)}`,+ method: 'PATCH',+ body: { unread }+ })+ }++ export function searchSessions(query: string): Promise<SessionSearchResponse> {+ return hermesApi<SessionSearchResponse>({+ path: `/api/sessions/search?q=${encodeURIComponent(query)}`+ })+ }++ // Resolves a single session row by id on one backend (the active profile, or+ // 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 suffix = sessionScopeQuery(profile)++ return hermesApi<SessionInfo>({- ...(profile ? { profile } : {}),++ ...sessionScoped(profile),+ path: `/api/sessions/${encodeURIComponent(id)}${suffix}`+ })+ }++ // Reads another profile's transcript. For a remote profile Electron reroutes+ // this GET to the remote backend (which serves its own state.db); for a local+ // profile the primary opens that profile's state.db via ?profile=. Omit for+ // 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 sessionScope = sessionScoped(profile)++++ if (sessionScope.profile) {++ query.set('profile', sessionScope.profile)+ }++ if (page.limit !== undefined) {+ query.set('limit', String(page.limit))+ }++ if (page.offset !== undefined) {+ query.set('offset', String(page.offset))+ }++ if (page.order) {+ query.set('order', page.order)+ }++ if (page.includeCompacted !== undefined) {+ query.set('include_compacted', String(page.includeCompacted))+ }++ const suffix = query.size ? `?${query.toString()}` : ''++ return hermesApi<SessionMessagesResponse>({- ...(profile ? { profile } : {}),++ ...sessionScope,+ path: `/api/sessions/${encodeURIComponent(id)}/messages${suffix}`+ })+ }++ /**+ * The initial hydration page: enough tail to fill the transcript window a few+ * times over, small enough that opening a long session doesn't ship (and+ * convert) hundreds of rows nobody has scrolled to. Older rows load on demand+ * via `getOlderSessionMessages` when "Show earlier" exhausts the in-memory+ * store (see app/chat/transcript-backfill).+ */+ 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.+ return getSessionMessages(id, profile, {+ limit: LATEST_SESSION_MESSAGES_LIMIT,+ order: 'latest',+ includeCompacted: true+ }).then(page => {+ // Record whether the tail was truncated (page came back full) and where+ // the next older page starts, so "Show earlier" can backfill over REST+ // (app/chat/transcript-backfill). Keyed under both the requested id and+ // the resolved id — callers hold either.+ recordTranscriptTail(id, page, profile)++ if (page.session_id && page.session_id !== id) {+ recordTranscriptTail(page.session_id, page, profile)+ }++ return page+ })+ }++ /**+ * One page of messages OLDER than the `offset` newest rows.+ *+ * Backend semantics (`_handle_session_messages` → `SessionDB.get_messages`+ * with `latest=True`): the offset is measured back from the NEWEST message+ * and the selected page is returned in chronological order. So after a tail+ * hydration of N rows, `getOlderSessionMessages(id, profile, N)` returns the+ * page immediately preceding it, ready to prepend.+ *+ * Legacy backends without pagination support return the full transcript and+ * no `pagination` metadata — callers detect that via the missing field and+ * treat the response as the complete history (see transcript-backfill).+ */+ export function getOlderSessionMessages(+ id: string,- profile: string | null | undefined,++ profile: ProfileScope,+ offset: number,+ limit: number = LATEST_SESSION_MESSAGES_LIMIT+ ): Promise<SessionMessagesResponse> {+ return getSessionMessages(id, profile, { includeCompacted: true, limit, offset, order: 'latest' })+ }++ export async function getAllSessionMessages(+ id: string,- profile?: string | null,++ profile?: ProfileScope,+ options: { maxJsonChars?: number } = {}+ ): Promise<SessionMessagesResponse> {+ const messages: SessionMessage[] = []+ const pageSize = 500+ const maxJsonChars = options.maxJsonChars ?? 32_000_000+ let jsonChars = 0+ let offset = 0+ let resolvedSessionId = id++ while (true) {+ const page = await getSessionMessages(id, profile, {+ limit: pageSize,+ offset,+ order: 'oldest',+ includeCompacted: true+ })++ resolvedSessionId = page.session_id+ jsonChars += (JSON.stringify(page.messages) ?? '').length++ if (jsonChars > maxJsonChars) {+ throw new Error(+ 'Session transcript exceeds the Desktop safe-load limit; use the Web Dashboard export for this session.'+ )+ }++ messages.push(...page.messages)++ // Legacy backends ignore pagination and return the full transcript.+ if (!page.pagination || page.messages.length === 0 || page.messages.length < page.pagination.limit) {+ break+ }++ offset += page.messages.length+ }++ 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 hermesApi<{ ok: boolean }>({- ...(profile ? { profile } : {}),++ ...sessionScoped(profile),+ path: `/api/sessions/${encodeURIComponent(id)}`,+ method: 'DELETE'+ })+ }++ export function renameSession(+ id: string,+ title: string,+ profile?: string | null+ ): Promise<{ ok: boolean; title: string }> {+ return hermesApi<{ ok: boolean; title: string }>({+ ...(profile ? { profile } : {}),+ path: `/api/sessions/${encodeURIComponent(id)}`,+ method: 'PATCH',+ body: { title, ...(profile ? { profile } : {}) }+ })+ }diff --cc apps/desktop/src/app/session/hooks/use-session-actions.test.tsxindex 66c1713eb11,1ab86bcb92e..64f8c47c5b4--- a/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx@@@ -7,6 -7,6 +7,7 @@@ import { afterEach, beforeEach, describimport { $terminalTakeover, setTerminalTakeover } from '@/app/right-sidebar/store'import { noteActiveTreeGroup, revealTreePane } from '@/components/pane-shell/tree/store'import {++ deleteSession,getAllSessionMessages,getLatestSessionMessages,getSession,@@@ -92,19 -80,9 +94,9 @@@ vi.mock('@/components/pane-shell/tree/sconst RUNTIME_SESSION_ID = 'rt-new-001'- function deferred<T>() {- let resolve!: (value: T | PromiseLike<T>) => void-- const promise = new Promise<T>(done => {- resolve = done- })-- return { promise, resolve }- }-type HarnessHandle = Pick<ReturnType<typeof useSessionActions>,-- 'createBackendSessionForSend' | 'selectSidebarItem' | 'startFreshSessionDraft'++ 'createBackendSessionForSend' | 'removeSession' | 'selectSidebarItem' | 'startFreshSessionDraft'>function storedSession(overrides: Partial<SessionInfo> = {}): SessionInfo {@@@ -127,19 -105,19 +119,23 @@@}function Harness({++ activeSessionId = null,navigate = vi.fn(),onReady,-- requestGateway++ requestGateway,++ selectedStoredSessionId = null}: {++ activeSessionId?: null | stringnavigate?: ReturnType<typeof vi.fn>onReady: (handle: HarnessHandle) => voidrequestGateway: <T>(method: string, params?: Record<string, unknown>) => Promise<T>++ selectedStoredSessionId?: null | string}) {const ref = <T,>(value: T): MutableRefObject<T> => ({ current: value })const actions = useSessionActions({-- activeSessionId: null,-- activeSessionIdRef: ref<string | null>(null),++ activeSessionId,++ activeSessionIdRef: ref(activeSessionId),busyRef: ref(false),creatingSessionRef: ref(false),ensureSessionState: () => ({}) as ClientSessionState,@@@ -149,8 -127,8 +145,8 @@@requestGateway,resetViewSync: vi.fn(),runtimeIdByStoredSessionIdRef: ref(new Map<string, string>()),-- selectedStoredSessionId: null,-- selectedStoredSessionIdRef: ref<string | null>(null),++ selectedStoredSessionId,++ selectedStoredSessionIdRef: ref(selectedStoredSessionId),sessionStateByRuntimeIdRef: ref(new Map<string, ClientSessionState>()),syncSessionStateToView: vi.fn(),updateSessionState: () => ({}) as ClientSessionState@@@ -163,6 -141,6 +159,55 @@@return null}++describe('connection-qualified session deletion', () => {++ afterEach(() => {++ cleanup()++ setSessions([])++ vi.restoreAllMocks()++ })++++ it('deletes a registry session through its captured connection owner', async () => {++ const requestGateway = vi.fn().mockResolvedValue({})++ let actions: HarnessHandle | null = null++++ setSessions([++ storedSession({++ connection_id: 'source-a',++ id: 'shared-session',++ profile: 'worker'++ })++ ])++ vi.mocked(deleteSession).mockResolvedValue({ ok: true })++ vi.mocked(requestGatewayForAgent).mockResolvedValue({} as never)++++ render(++ <Harness++ activeSessionId="runtime-shared"++ onReady={value => { actions = value }}++ requestGateway={requestGateway}++ selectedStoredSessionId="shared-session"++ />++ )++ await waitFor(() => expect(actions).not.toBeNull())++++ await act(async () => {++ await actions?.removeSession('shared-session')++ })++++ expect(deleteSession).toHaveBeenCalledWith('shared-session', {++ connectionId: 'source-a',++ profile: 'worker'++ })++ expect(requestGatewayForAgent).toHaveBeenCalledWith(++ 'source-a',++ 'worker',++ 'session.close',++ { session_id: 'runtime-shared' }++ )++ expect(requestGateway).not.toHaveBeenCalledWith('session.close', expect.anything())++ })++})++function StoredIdRotationHarness({activeSessionIdRef,getRoutedStoredSessionId,diff --cc apps/desktop/src/app/session/hooks/use-session-actions/index.tsindex bbe8eb29a44,572c7e1f620..cf9907e69e3--- a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts@@@ -1761,6 -1718,6 +1761,12 @@@ export function useSessionActions(const closingRuntimeId = wasSelected ? activeSessionId : nullconst previousMessages = $messages.get()const previousPinned = $pinnedSessionIds.get()++ const removedOwner: SessionOwnerScope = removed?.connection_id++ ? {++ connectionId: removed.connection_id,++ profile: removed.profile || 'default'++ }++ : removed?.profile// Pins are keyed on the durable lineage-root id; the stored id may be the// live tip after compression. Drop both so the pin can't linger.const removedPinId = removed ? sessionPinId(removed) : storedSessionId@@@ -1783,10 -1740,10 +1789,15 @@@try {if (closingRuntimeId) {-- await requestGateway('session.close', { session_id: closingRuntimeId }).catch(() => undefined)++ await requestForSessionProfile(++ removedOwner,++ requestGateway,++ 'session.close',++ { session_id: closingRuntimeId }++ ).catch(() => undefined)}-- await deleteSession(storedSessionId, removed?.profile)++ await deleteSession(storedSessionId, removedOwner)// A deleted session's cached tail must not resurrect on a recycled id.dropTranscriptTail(storedSessionId)// Only after the RPC lands — the optimistic eviction above can rolldiff --cc apps/desktop/src/hermes.test.tsindex 4b3f588b438,528891697de..0d4f0a2d36b--- a/apps/desktop/src/hermes.test.ts+++ b/apps/desktop/src/hermes.test.ts@@@ -7,7 -7,6 +7,8 @@@ importAUDIO_TRANSCRIBE_MIN_REQUEST_TIMEOUT_MS,audioSpeakRequestTimeoutMs,audioTranscribeRequestTimeoutMs,+ deleteProfile,++ deleteSession,getAllSessionMessages,getCronJobs,getGlobalModelInfo,@@@ -139,6 -137,6 +140,30 @@@ describe('Hermes REST helpers', () =>expect(api).toHaveBeenCalledWith(expect.objectContaining({ connectionId: 'local', path: '/api/profiles' }))})++ it('preserves ambient and explicit-local ownership for session and profile requests', async () => {++ setApiRequestConnection('remote-a')++++ await getSession('ambient-session')++ await getSessionMessages('ambient-session')++ await deleteSession('ambient-session')++++ for (const call of api.mock.calls) {++ expect(call[0]).toEqual(expect.objectContaining({ connectionId: 'remote-a' }))++ }++++ api.mockClear()++ const localScope = { connectionId: 'local', profile: 'worker' }++++ await getSession('local-session', localScope)++ await getSessionMessages('local-session', localScope)++ await deleteSession('local-session', localScope)++ await deleteProfile('worker', localScope)++++ for (const call of api.mock.calls) {++ expect(call[0]).toEqual(expect.objectContaining({ connectionId: 'local', profile: 'worker' }))++ }++ })++it('defaults missing sidebar slices to empty session arrays', async () => {api.mockResolvedValue({})diff --cc apps/desktop/src/store/session.test.tsindex dcf715a3e14,3ebb0c56947..a3518789772--- a/apps/desktop/src/store/session.test.ts+++ b/apps/desktop/src/store/session.test.ts@@@ -51,54 -51,8 +53,37 @@@ importpublishSessionState} from './session-states'- const session = (over: Partial<SessionInfo>): SessionInfo => ({- archived: false,- cwd: null,- ended_at: null,- id: 'live',- input_tokens: 0,- is_active: false,- last_active: 0,- message_count: 0,- model: null,- output_tokens: 0,- preview: null,- source: null,- started_at: 0,- title: null,- tool_call_count: 0,- ...over- })+ const session = (over: Partial<SessionInfo>): SessionInfo => makeSessionInfo({ id: 'live', ...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()