Skip to content

The agent that grows with you

fix(desktop): route omitted-profile messaging approvals to the list server

brooklyn!6391c3c7e4ab
diff --git a/apps/desktop/src/app/session/hooks/use-session-list-actions.ts b/apps/desktop/src/app/session/hooks/use-session-list-actions.ts
index 0ba7cc82da7..f284f5350a4 100644
--- a/apps/desktop/src/app/session/hooks/use-session-list-actions.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-list-actions.ts
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useLayoutEffect, useRef } from 'react'
-import { listAllProfileSessions, listSidebarSessions, type SessionInfo } from '@/hermes'
+import { getApiRequestConnection, listAllProfileSessions, listSidebarSessions, type SessionInfo } from '@/hermes'
import { sameCronSignature } from '@/lib/session-signatures'
import {
isMessagingSource,
@@ -28,8 +28,10 @@ import {
keepFailedProfileMeta,
mergeSessionPage,
MESSAGING_SECTION_LIMIT,
+ messagingListServerForFetch,
setCorruptSessionStores,
setCronSessions,
+ setMessagingListServer,
setMessagingPlatformTotals,
setMessagingSessions,
setMessagingTruncated,
@@ -37,7 +39,8 @@ import {
setSessionProfilesUsage,
setSessions,
setSessionsLoadError,
- setSessionsLoading
+ setSessionsLoading,
+ stampMessagingRowsWithListServer
} from '@/store/session'
import { $removedSessionIds } from '@/store/session-removal'
import { $sessionTiles, $workingSessionIds, getRecentlySettledSessionIds } from '@/store/session-states'
@@ -72,6 +75,13 @@ function dropTombstoned(sessions: SessionInfo[]): SessionInfo[] {
: sessions
}
+function publishMessagingRows(rows: SessionInfo[], scopeProfile: string): SessionInfo[] {
+ const server = messagingListServerForFetch(scopeProfile, getApiRequestConnection())
+ setMessagingListServer(server)
+
+ return stampMessagingRowsWithListServer(rows, server)
+}
+
// Rows a session refresh must preserve even if the aggregator omits them:
// in-flight first turns (message_count 0), pinned rows aged off the page, the
// actively-viewed chat (its "working" flag clears a beat before the aggregator
@@ -163,7 +173,10 @@ export function useSessionListActions({ profileScope }: UseSessionListActionsArg
// Drop any non-messaging source the broad exclude didn't catch (custom
// sources) — those stay in local recents, not a platform section.
- const rows = dropTombstoned(result.sessions.filter(s => isMessagingSource(s.source)))
+ const rows = publishMessagingRows(
+ dropTombstoned(result.sessions.filter(s => isMessagingSource(s.source))),
+ sessionProfile
+ )
setMessagingSessions(prev => (sameCronSignature(prev, rows) ? prev : rows))
// Hit the cap → at least one platform may have more on disk than loaded,
@@ -221,7 +234,7 @@ export function useSessionListActions({ profileScope }: UseSessionListActionsArg
return
}
- const incoming = dropTombstoned(result.sessions.filter(inPlatform))
+ const incoming = publishMessagingRows(dropTombstoned(result.sessions.filter(inPlatform)), sessionProfile)
setMessagingSessions(prev => [
...prev.filter(s => !inPlatform(s)),
@@ -392,17 +405,19 @@ export function useSessionListActions({ profileScope }: UseSessionListActionsArg
// didn't catch (custom sources stay in local recents), then split per
// platform in the UI.
const messagingErrors = result.messaging.errors ?? result.errors
- setMessagingSessions(prev => {
- const messagingRows = dropTombstoned(
+
+ const messagingRows = publishMessagingRows(
+ dropTombstoned(
carryForwardFailedProfileSessions(
- prev,
+ $messagingSessions.get(),
(result.messaging.sessions ?? []).filter(s => isMessagingSource(s.source)),
messagingErrors
)
- )
+ ),
+ sessionProfile
+ )
- return sameCronSignature(prev, messagingRows) ? prev : messagingRows
- })
+ setMessagingSessions(prev => (sameCronSignature(prev, messagingRows) ? prev : messagingRows))
// Hit the cap → at least one platform may have more on disk than loaded.
setMessagingTruncated(prev =>
messagingErrors?.length ? prev : result.messaging.sessions.length >= MESSAGING_SECTION_LIMIT
diff --git a/apps/desktop/src/store/gateway-switch.ts b/apps/desktop/src/store/gateway-switch.ts
index db332a29fdc..d7703f065da 100644
--- a/apps/desktop/src/store/gateway-switch.ts
+++ b/apps/desktop/src/store/gateway-switch.ts
@@ -16,6 +16,7 @@ import {
setCurrentCwdTransient,
setFreshDraftReady,
setMessages,
+ setMessagingListServer,
setMessagingPlatformTotals,
setMessagingSessions,
setMessagingTruncated,
@@ -201,6 +202,7 @@ export function wipeSessionListsForGatewaySwitch(): void {
invalidateCronJobsRequests()
setCronJobs([])
setMessagingSessions([])
+ setMessagingListServer(null)
setMessagingPlatformTotals({})
setMessagingTruncated(false)
// Clearing $sessionStates automatically clears $workingSessionIds and
diff --git a/apps/desktop/src/store/session-states-runtime-map.test.ts b/apps/desktop/src/store/session-states-runtime-map.test.ts
index c3429a5f29b..2029e313308 100644
--- a/apps/desktop/src/store/session-states-runtime-map.test.ts
+++ b/apps/desktop/src/store/session-states-runtime-map.test.ts
@@ -4,7 +4,15 @@ import { createClientSessionState } from '@/lib/chat-runtime'
import { $connectionsRegistry } from '@/store/connection-registry-state'
import { setPrimaryGateway, setPrimaryGatewayConnection } from '@/store/gateway'
import { $profiles } from '@/store/profile'
-import { _resetSessionOwnerHintsForTests, setSessionOwnerHint, setSessions } from '@/store/session'
+import {
+ _resetSessionOwnerHintsForTests,
+ messagingListServerForFetch,
+ setMessagingListServer,
+ setMessagingSessions,
+ setSessionOwnerHint,
+ setSessions,
+ stampMessagingRowsWithListServer
+} from '@/store/session'
import { isSessionOwnerResolutionError } from '@/store/session-owner-resolution'
import {
$sessionTiles,
@@ -95,6 +103,8 @@ describe('knownOwnerForSession / requestForOwnedSession', () => {
$sessionTiles.set([])
clearAllSessionStates()
setSessions([])
+ setMessagingSessions([])
+ setMessagingListServer(null)
$profiles.set([])
_resetSessionOwnerHintsForTests({ storage: true })
})
@@ -211,4 +221,93 @@ describe('knownOwnerForSession / requestForOwnedSession', () => {
delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop
}
})
+
+ it('routes approval.respond for a messaging row that omits profile to the list server, not ambient or an assumed primary (#108102)', async () => {
+ // Telegram rows from a legacy backend omit `profile`. After restart there is
+ // no tile, hint, or runtime ledger. The list that still contains the row
+ // names the backend that owns it. A non-primary list must keep that
+ // connection; a primary list routes to the primary profile door; an
+ // unrecorded list must not guess primary on a multi-connection install.
+ $profiles.set([{ name: 'default' }, { name: 'omar' }] as never)
+ const primaryRequest = vi.fn(async (method: string, params: unknown) => ({ method, params, via: 'primary' }))
+ setPrimaryGateway({ onEvent: () => () => undefined, request: primaryRequest, state: 'open' } as never, 'default')
+ setPrimaryGatewayConnection({ connectionId: 'local' })
+ const ambient = vi.fn(async () => ({ via: 'ambient' }))
+
+ try {
+ setMessagingListServer({ connectionId: 'homelab', profile: null })
+ setMessagingSessions([makeSessionInfo({ id: 'telegram-remote', source: 'telegram' })])
+
+ expect(knownOwnerForSession('telegram-remote')).toEqual({ connectionId: 'homelab', profile: 'default' })
+
+ await expect(
+ requestForOwnedSession('telegram-remote', ambient as never, 'approval.respond', {
+ choice: 'once',
+ session_id: 'telegram-remote'
+ })
+ ).rejects.toThrow(/cannot dial|registry connections/i)
+ expect(primaryRequest).not.toHaveBeenCalled()
+ expect(ambient).not.toHaveBeenCalled()
+
+ setMessagingListServer({ connectionId: null, profile: null })
+ setMessagingSessions([makeSessionInfo({ id: 'telegram-primary', source: 'telegram' })])
+
+ await expect(
+ requestForOwnedSession('telegram-primary', ambient as never, 'approval.respond', {
+ choice: 'once',
+ session_id: 'telegram-primary'
+ })
+ ).resolves.toEqual({
+ method: 'approval.respond',
+ params: { choice: 'once', session_id: 'telegram-primary' },
+ via: 'primary'
+ })
+ expect(ambient).not.toHaveBeenCalled()
+
+ setMessagingListServer(null)
+ setMessagingSessions([makeSessionInfo({ id: 'telegram-unknown', source: 'telegram' })])
+ primaryRequest.mockClear()
+
+ await expect(
+ requestForOwnedSession('telegram-unknown', ambient as never, 'approval.respond', {
+ choice: 'once',
+ session_id: 'telegram-unknown'
+ })
+ ).rejects.toSatisfy(isSessionOwnerResolutionError)
+ expect(primaryRequest).not.toHaveBeenCalled()
+ expect(ambient).not.toHaveBeenCalled()
+
+ const stamped = stampMessagingRowsWithListServer(
+ [makeSessionInfo({ id: 'telegram-stamped', source: 'telegram' })],
+ { connectionId: 'homelab', profile: null }
+ )
+
+ expect(stamped[0]?.connection_id).toBe('homelab')
+ expect(stamped[0]?.profile).toBeUndefined()
+ setMessagingListServer(null)
+ setMessagingSessions(stamped)
+ expect(knownOwnerForSession('telegram-stamped')).toEqual({ connectionId: 'homelab', profile: 'default' })
+
+ setMessagingListServer({ connectionId: null, profile: null })
+ setMessagingSessions([
+ makeSessionInfo({ connection_id: 'homelab', id: 'telegram-tagged', source: 'telegram' })
+ ])
+ expect(knownOwnerForSession('telegram-tagged')).toEqual({ connectionId: 'homelab', profile: 'default' })
+
+ setSessions([makeSessionInfo({ id: 'fresh-desktop', profile: 'omar', source: 'desktop' })])
+ expect(knownOwnerForSession('fresh-desktop')).toBe('omar')
+
+ setMessagingListServer({ connectionId: 'homelab', profile: null })
+ setSessions([makeSessionInfo({ id: 'fresh-untagged', source: 'desktop' })])
+ expect(knownOwnerForSession('fresh-untagged')).toBeUndefined()
+
+ expect(messagingListServerForFetch('all', 'homelab')).toEqual({ connectionId: 'homelab', profile: null })
+ expect(messagingListServerForFetch('omar', 'local')).toEqual({ connectionId: null, profile: 'omar' })
+ expect(messagingListServerForFetch('', null)).toEqual({ connectionId: null, profile: null })
+ } finally {
+ setPrimaryGateway(null)
+ setMessagingListServer(null)
+ setMessagingSessions([])
+ }
+ })
})
diff --git a/apps/desktop/src/store/session.ts b/apps/desktop/src/store/session.ts
index 76a669339a8..ec7bde884a1 100644
--- a/apps/desktop/src/store/session.ts
+++ b/apps/desktop/src/store/session.ts
@@ -11,6 +11,7 @@ import {
connectionScopeSuffix,
rescopeConnectionScopedStores
} from '@/lib/connection-scoped'
+import { isMessagingSource } from '@/lib/session-source'
import { persistBoolean, persistString, readJson, storedBoolean, storedString, writeJson } from '@/lib/storage'
import type { SessionInfo, UsageStats } from '@/types/hermes'
@@ -214,6 +215,25 @@ export function knownSessionProfile(sessions: readonly SessionInfo[], sessionId:
return typeof owner === 'string' ? owner : (owner?.targetProfile ?? owner?.profile)?.trim() || undefined
}
+function messagingListOwnerForOmittedProfile(session: SessionInfo | undefined): SessionOwnerScope {
+ if (!session || !isMessagingSource(session.source) || !messagingListServer) {
+ return undefined
+ }
+
+ const connectionId = messagingListServer.connectionId?.trim() || ''
+ const profile = messagingListServer.profile?.trim() || 'default'
+
+ // Non-primary list: the connection is the owner. A bare profile would
+ // collapse onto the primary socket.
+ if (connectionId && connectionId !== 'local') {
+ return { connectionId, profile }
+ }
+
+ // Primary pool served this list. Name its profile door; do not fall through
+ // to the ambient request.
+ return profile
+}
+
/**
* The complete known owner of a session: the EXACT route when the row is
* connection-tagged (an optimistic row from a routed create, a foreign
@@ -224,7 +244,10 @@ export function knownSessionProfile(sessions: readonly SessionInfo[], sessionId:
* profile name, so returning only that name silently collapses the route back
* to the local/profile-only path. The exact rungs are what let a session's
* owner be reconstructed after the bounded hint map has evicted it or the app
- * relaunched.
+ * relaunched. A messaging row that omits `profile` is still owned by the
+ * backend that served its list: a non-primary list keeps that connection,
+ * and a primary-pool list names the primary profile door. An unrecorded
+ * list is not assumed to be primary.
*/
export function knownSessionOwner(sessions: readonly SessionInfo[], sessionId: null | string): SessionOwnerScope {
if (!sessionId) {
@@ -250,6 +273,12 @@ export function knownSessionOwner(sessions: readonly SessionInfo[], sessionId: n
return profile
}
+ const served = messagingListOwnerForOmittedProfile(session)
+
+ if (served) {
+ return served
+ }
+
return hint
}
@@ -850,6 +879,64 @@ export const CRON_SECTION_LIMIT = 50
// platform that exceeds this cap gets its own per-platform "load more".
export const $messagingSessions = atom<SessionInfo[]>([])
export const MESSAGING_SECTION_LIMIT = 100
+
+/** The backend that served the current messaging list. Null until a list
+ * publish records it. `connectionId` is null for the primary pool; a
+ * non-primary registry id must be kept. `profile` is null when the client
+ * omitted a named profile on that request. */
+export interface MessagingListServer {
+ connectionId: null | string
+ profile: null | string
+}
+
+let messagingListServer: MessagingListServer | null = null
+
+export function setMessagingListServer(server: MessagingListServer | null): void {
+ messagingListServer = server
+}
+
+export function messagingListServerForFetch(
+ scopeProfile: string,
+ connectionId: null | string | undefined
+): MessagingListServer {
+ const connection = String(connectionId ?? '').trim()
+ const profile = scopeProfile.trim()
+
+ return {
+ connectionId: connection && connection !== 'local' ? connection : null,
+ profile: profile && profile !== 'all' ? profile : null
+ }
+}
+
+/** Keep a non-primary list's connection on messaging rows that arrived without
+ * one. Does not invent a profile and does not tag the primary pool — a bare
+ * primary row already routes through the profile door, and a `local` tag
+ * would pin it to the wrong source once primary is remote. */
+export function stampMessagingRowsWithListServer(
+ rows: readonly SessionInfo[],
+ server: MessagingListServer | null
+): SessionInfo[] {
+ const connectionId = server?.connectionId?.trim() || ''
+
+ if (!connectionId || connectionId === 'local') {
+ return rows as SessionInfo[]
+ }
+
+ let changed = false
+
+ const next = rows.map(row => {
+ if (!isMessagingSource(row.source) || row.connection_id?.trim()) {
+ return row
+ }
+
+ changed = true
+
+ return { ...row, connection_id: connectionId }
+ })
+
+ return changed ? next : (rows as SessionInfo[])
+}
+
// Exact per-platform conversation totals, keyed by source id. Empty until a
// per-platform "load more" fetch resolves it (the combined seed fetch only
// knows the aggregate), so sections fall back to their loaded count.