Skip to content

The agent that grows with you

refactor(sidebar): drop session counts and the COUNT(*) that fed them

Brooklyn Nicholson0f7492f43aa3
diff --git a/apps/desktop/src/app/chat/sidebar/chrome.tsx b/apps/desktop/src/app/chat/sidebar/chrome.tsx
index 2a0f728503a..36d97e03f2c 100644
--- a/apps/desktop/src/app/chat/sidebar/chrome.tsx
+++ b/apps/desktop/src/app/chat/sidebar/chrome.tsx
@@ -8,10 +8,6 @@ import { cn } from '@/lib/utils'
// sections and the project/workspace tree, so it lives outside either to keep
// imports one-directional (no index <-> projects cycle).
-/** `loaded/total` when there's more on the server, else just the loaded count. */
-export const countLabel = (loaded: number, total: number): string =>
- total > loaded ? `${loaded}/${total}` : String(loaded)
-
/** The muted count chip next to a section/workspace label. */
export function SidebarCount({ children }: { children: React.ReactNode }) {
return <span className="text-[0.6875rem] font-medium text-(--ui-text-quaternary)">{children}</span>
diff --git a/apps/desktop/src/app/chat/sidebar/index.tsx b/apps/desktop/src/app/chat/sidebar/index.tsx
index 91dec1e2d58..c1f00e5777c 100644
--- a/apps/desktop/src/app/chat/sidebar/index.tsx
+++ b/apps/desktop/src/app/chat/sidebar/index.tsx
@@ -89,10 +89,9 @@ import {
$messagingPlatformTotals,
$messagingSessions,
$messagingTruncated,
- $sessionProfileTotals,
+ $sessionProfilesTruncated,
$sessions,
$sessionsLoading,
- $sessionsTotal,
sessionPinId,
setCurrentCwd
} from '@/store/session'
@@ -108,7 +107,6 @@ import {
} from '../../routes'
import type { SidebarNavItem } from '../../types'
-import { countLabel } from './chrome'
import { SidebarCronJobsSection } from './cron-jobs-section'
import { SidebarLoadMoreRow } from './load-more-row'
import { orderByIds, reconcileOrderIds, resolveManualSessionOrderIds, sameIds } from './order'
@@ -300,8 +298,7 @@ export function ChatSidebar({
const messagingPlatformTotals = useStore($messagingPlatformTotals)
const messagingTruncated = useStore($messagingTruncated)
const sessionsLoading = useStore($sessionsLoading)
- const sessionsTotal = useStore($sessionsTotal)
- const sessionProfileTotals = useStore($sessionProfileTotals)
+ const sessionProfilesTruncated = useStore($sessionProfilesTruncated)
const workingSessionIds = useStore($workingSessionIds)
const profiles = useStore($profiles)
const profileScope = useStore($profileScope)
@@ -937,7 +934,7 @@ export function ChatSidebar({
...group,
loadingMore: Boolean(profileLoadMorePending[group.id]),
onLoadMore: onLoadMoreProfileSessions ? () => loadMoreForProfileGroup(group.id) : undefined,
- totalCount: Math.max(group.sessions.length, sessionProfileTotals[group.id] ?? 0)
+ hasMore: Boolean(sessionProfilesTruncated[group.id])
}))
// default (root) first, then the rest alphabetically.
.sort((a, b) => (a.id === 'default' ? -1 : b.id === 'default' ? 1 : a.label.localeCompare(b.label)))
@@ -948,7 +945,7 @@ export function ChatSidebar({
loadMoreForProfileGroup,
onLoadMoreProfileSessions,
profileLoadMorePending,
- sessionProfileTotals
+ sessionProfilesTruncated
])
// The flat Sessions list always shows ALL recent sessions; Projects is a
@@ -956,22 +953,16 @@ export function ChatSidebar({
const displayAgentSessions = agentSessions
// Pagination is scope-aware. In "All profiles" mode it tracks the global
- // unified set. When scoped to one profile it must compare that profile's own
- // loaded rows against that profile's total — otherwise a huge default profile
- // keeps "Load more" stuck on while you browse a small one (the aggregator's
- // total sums every profile). Per-profile totals come from the aggregator
- // (children excluded); fall back to the global total / loaded count.
+ // unified set; scoped to one profile it tracks that profile's own truncation
+ // flag — otherwise a huge default profile keeps "Load more" stuck on while
+ // you browse a small one. The backend reports whether its page was capped
+ // rather than an exact count, so no COUNT(*) runs per refresh.
const loadedSessionCount = showAllProfiles ? sessions.length : visibleSessions.length
- const scopedProfileTotal = showAllProfiles ? undefined : sessionProfileTotals[profileScope]
- const knownSessionTotal = Math.max(
- showAllProfiles ? sessionsTotal : (scopedProfileTotal ?? loadedSessionCount),
- loadedSessionCount
- )
-
- const hasMoreSessions = knownSessionTotal > loadedSessionCount
+ const hasMoreSessions = showAllProfiles
+ ? Object.values(sessionProfilesTruncated).some(Boolean)
+ : Boolean(sessionProfilesTruncated[profileScope])
- const recentsMeta = countLabel(displayAgentSessions.length, knownSessionTotal)
const displayRecentsCountRef = useRef(0)
const loadedRecentsCountRef = useRef(0)
displayRecentsCountRef.current = displayAgentSessions.length
@@ -1390,9 +1381,7 @@ export function ChatSidebar({
reposScanning && !projectsSkeletonVisible ? (
<GlyphSpinner ariaLabel={s.loading} className="text-[0.6875rem] text-(--ui-text-quaternary)" />
) : undefined
- ) : (
- recentsMeta
- )
+ ) : undefined
}
liveSessions={inProject ? agentSessions : undefined}
onArchiveSession={onArchiveSession}
@@ -1458,7 +1447,7 @@ export function ChatSidebar({
platformName={group.label}
/>
}
- labelMeta={countLabel(group.sessions.length, group.total)}
+ labelMeta={String(shownSessions.length)}
onArchiveSession={onArchiveSession}
onDeleteSession={onDeleteSession}
onResumeSession={onResumeSession}
diff --git a/apps/desktop/src/app/chat/sidebar/projects/workspace-group.tsx b/apps/desktop/src/app/chat/sidebar/projects/workspace-group.tsx
index bcbefafa672..bb0ae30cff1 100644
--- a/apps/desktop/src/app/chat/sidebar/projects/workspace-group.tsx
+++ b/apps/desktop/src/app/chat/sidebar/projects/workspace-group.tsx
@@ -9,7 +9,7 @@ import { notifyError } from '@/store/notifications'
import { newSessionInProfile } from '@/store/profile'
import { switchBranchInRepo } from '@/store/projects'
-import { countLabel, SidebarRowStack } from '../chrome'
+import { SidebarRowStack } from '../chrome'
import { SidebarLoadMoreRow } from '../load-more-row'
import { SIDEBAR_GROUP_PAGE, useWorkspaceNodeOpen } from './model'
@@ -37,11 +37,13 @@ export function SidebarWorkspaceGroup({ group, renderRows, onNewSession, onRemov
const [visibleCount, setVisibleCount] = useState(SIDEBAR_GROUP_PAGE)
const loadedCount = group.sessions.length
- // Profile groups know their on-disk total (children excluded); workspace
- // groups only ever page within what's already loaded.
- const totalCount = isProfileGroup ? Math.max(group.totalCount ?? loadedCount, loadedCount) : loadedCount
const visibleSessions = group.sessions.slice(0, visibleCount)
- const hiddenCount = Math.max(0, totalCount - visibleSessions.length)
+ // Profile groups can have more rows on the server than are loaded — the
+ // aggregator reports `hasMore` so the lane can offer another page without
+ // pricing an exact total per refresh. Workspace groups only ever page within
+ // what's already loaded.
+ const hiddenLoaded = Math.max(0, loadedCount - visibleSessions.length)
+ const hiddenCount = isProfileGroup && group.hasMore ? Math.max(hiddenLoaded, 1) : hiddenLoaded
const nextCount = Math.min(SIDEBAR_GROUP_PAGE, hiddenCount)
// Leading glyph: profile color dot, a home mark for the repo's primary
@@ -63,7 +65,7 @@ export function SidebarWorkspaceGroup({ group, renderRows, onNewSession, onRemov
setVisibleCount(target)
- if (target > loadedCount && loadedCount < totalCount) {
+ if (target > loadedCount && group.hasMore) {
group.onLoadMore?.()
}
}
@@ -119,7 +121,7 @@ export function SidebarWorkspaceGroup({ group, renderRows, onNewSession, onRemov
</div>
)
}
- count={isProfileGroup ? countLabel(visibleSessions.length, totalCount) : group.sessions.length}
+ count={visibleSessions.length}
icon={leadingIcon}
label={group.label}
onToggle={toggleOpen}
diff --git a/apps/desktop/src/app/chat/sidebar/projects/workspace-groups.ts b/apps/desktop/src/app/chat/sidebar/projects/workspace-groups.ts
index 17a085113dd..a55fdce8191 100644
--- a/apps/desktop/src/app/chat/sidebar/projects/workspace-groups.ts
+++ b/apps/desktop/src/app/chat/sidebar/projects/workspace-groups.ts
@@ -30,7 +30,10 @@ export interface SidebarSessionGroup {
mode?: 'profile' | 'source' | 'workspace'
onLoadMore?: () => void
sourceId?: string
- totalCount?: number
+ /** Profile lanes only: the backend page was capped, so more rows exist on
+ * disk than were loaded. Replaces the old exact `totalCount`, which cost a
+ * COUNT(*) per profile on every sidebar refresh just to render `n/total`. */
+ hasMore?: boolean
}
/** A repo node: holds its branch/worktree lanes (`repo -> lane -> sessions`). */
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
index b0202e722a4..4dbcfa6000e 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
@@ -53,7 +53,6 @@ import {
setSelectedStoredSessionId,
setSessions,
setSessionStartedAt,
- setSessionsTotal,
setTurnStartedAt,
setYoloActive
} from '@/store/session'
@@ -1293,9 +1292,6 @@ export function useSessionActions({
// the delete RPC is in flight, so a racing refresh can't flash it back.
tombstoneSessions(removedIds)
beginSessionMutation(removedIds)
- // Keep $sessionsTotal in sync so the sidebar's "Load N more" footer
- // doesn't keep claiming the removed row is still on the server.
- setSessionsTotal(prev => Math.max(0, prev - 1))
$pinnedSessionIds.set(previousPinned.filter(id => id !== storedSessionId && id !== removedPinId))
// Tear down before awaiting so the route effect can't resume the
@@ -1330,7 +1326,6 @@ export function useSessionActions({
} catch (err) {
if (removed) {
setSessions(prev => [removed, ...prev])
- setSessionsTotal(prev => prev + 1)
}
untombstoneSessions(removedIds)
@@ -1393,10 +1388,6 @@ export function useSessionActions({
setSessions(prev => prev.filter(session => !sessionMatchesStoredId(session, storedSessionId)))
tombstoneSessions(archivedIds)
beginSessionMutation(archivedIds)
- // Archived sessions are hidden by the listSessions(min_messages=1) query
- // on the next refresh, so they count as "removed" for the load-more
- // footer math.
- setSessionsTotal(prev => Math.max(0, prev - 1))
$pinnedSessionIds.set(previousPinned.filter(id => id !== storedSessionId && id !== archivedPinId))
if (wasSelected) {
@@ -1419,7 +1410,6 @@ export function useSessionActions({
} catch (err) {
if (archived) {
setSessions(prev => [archived, ...prev.filter(session => !sessionMatchesStoredId(session, storedSessionId))])
- setSessionsTotal(prev => prev + 1)
}
untombstoneSessions(archivedIds)
diff --git a/apps/desktop/src/app/session/hooks/use-session-list-actions.test.tsx b/apps/desktop/src/app/session/hooks/use-session-list-actions.test.tsx
index b5c3ef07217..7ca89984ddf 100644
--- a/apps/desktop/src/app/session/hooks/use-session-list-actions.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-session-list-actions.test.tsx
@@ -43,13 +43,13 @@ const row = (id: string, over: Partial<SessionInfo> = {}): SessionInfo =>
// separate listAllProfileSessions calls (each of which reopened every profile
// DB) — #66377-adjacent perf work from the desktop audit canvas.
const sidebar = (
- recents: { sessions: SessionInfo[]; total?: number; profile_totals?: Record<string, number> },
+ recents: { sessions: SessionInfo[]; profiles_truncated?: Record<string, boolean> },
cron: SessionInfo[] = [],
messaging: SessionInfo[] = []
): SidebarSessionsResponse => ({
- recents: { sessions: recents.sessions, total: recents.total, profile_totals: recents.profile_totals },
+ recents: { sessions: recents.sessions, profiles_truncated: recents.profiles_truncated },
cron: { sessions: cron },
- messaging: { sessions: messaging, total: messaging.length }
+ messaging: { sessions: messaging }
})
const listSidebarSessions = vi.fn()
@@ -90,7 +90,7 @@ afterEach(() => {
describe('refreshSessions identity + loading hygiene', () => {
it('keeps the previous $sessions array when the refresh is content-identical', async () => {
const rows = [row('a'), row('b')]
- listSidebarSessions.mockResolvedValue(sidebar({ sessions: rows, total: 2, profile_totals: { default: 2 } }))
+ listSidebarSessions.mockResolvedValue(sidebar({ sessions: rows }))
const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))
@@ -103,7 +103,7 @@ describe('refreshSessions identity + loading hygiene', () => {
// Second refresh returns fresh (but equal) row objects, as the API does.
listSidebarSessions.mockResolvedValue(
- sidebar({ sessions: [row('a'), row('b')], total: 2, profile_totals: { default: 2 } })
+ sidebar({ sessions: [row('a'), row('b')] })
)
await act(async () => {
@@ -114,7 +114,7 @@ describe('refreshSessions identity + loading hygiene', () => {
})
it('swaps the array when rows actually changed', async () => {
- listSidebarSessions.mockResolvedValue(sidebar({ sessions: [row('a')], total: 1, profile_totals: {} }))
+ listSidebarSessions.mockResolvedValue(sidebar({ sessions: [row('a')] }))
const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))
await act(async () => {
@@ -124,7 +124,7 @@ describe('refreshSessions identity + loading hygiene', () => {
const first = $sessions.get()
listSidebarSessions.mockResolvedValue(
- sidebar({ sessions: [row('a', { last_active: 2000, title: 'Renamed' })], total: 1, profile_totals: {} })
+ sidebar({ sessions: [row('a', { last_active: 2000, title: 'Renamed' })] })
)
await act(async () => {
@@ -136,7 +136,7 @@ describe('refreshSessions identity + loading hygiene', () => {
})
it('does not flicker the loading flag over a populated list', async () => {
- listSidebarSessions.mockResolvedValue(sidebar({ sessions: [row('a')], total: 1, profile_totals: {} }))
+ listSidebarSessions.mockResolvedValue(sidebar({ sessions: [row('a')] }))
const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))
await act(async () => {
@@ -162,9 +162,7 @@ describe('refreshSessions identity + loading hygiene', () => {
removed.ids = new Set(['b', 'root-c'])
listSidebarSessions.mockResolvedValue(
sidebar({
- sessions: [row('a'), row('b'), row('c', { _lineage_root_id: 'root-c' } as Partial<SessionInfo>)],
- total: 3,
- profile_totals: {}
+ sessions: [row('a'), row('b'), row('c', { _lineage_root_id: 'root-c' } as Partial<SessionInfo>)]
})
)
@@ -178,7 +176,7 @@ describe('refreshSessions identity + loading hygiene', () => {
})
it('still shows loading for the initial (empty-list) fetch', async () => {
- listSidebarSessions.mockResolvedValue(sidebar({ sessions: [row('a')], total: 1, profile_totals: {} }))
+ listSidebarSessions.mockResolvedValue(sidebar({ sessions: [row('a')] }))
const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))
const loadingStates: boolean[] = []
@@ -200,7 +198,7 @@ describe('refreshSessions batches slices into one request', () => {
const messaging = [row('m1', { source: 'telegram', title: 'tg chat' })]
listSidebarSessions.mockResolvedValue(
- sidebar({ sessions: recents, total: 2, profile_totals: { default: 2 } }, cron, messaging)
+ sidebar({ sessions: recents }, cron, messaging)
)
const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))
@@ -220,7 +218,7 @@ describe('refreshSessions batches slices into one request', () => {
})
it('forwards the active profile scope + section limits to the batched call', async () => {
- listSidebarSessions.mockResolvedValue(sidebar({ sessions: [], total: 0, profile_totals: {} }))
+ listSidebarSessions.mockResolvedValue(sidebar({ sessions: [] }))
const { result } = renderHook(() => useSessionListActions({ profileScope: 'work' }))
await act(async () => {
@@ -238,7 +236,7 @@ describe('refreshSessions batches slices into one request', () => {
it('scopes the cron-jobs fetch to the active profile (all → unified view)', async () => {
const { getCronJobs } = await import('@/hermes')
- listSidebarSessions.mockResolvedValue(sidebar({ sessions: [], total: 0, profile_totals: {} }))
+ listSidebarSessions.mockResolvedValue(sidebar({ sessions: [] }))
const scoped = renderHook(() => useSessionListActions({ profileScope: 'work' }))
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 a9457322629..611484e0d73 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
@@ -23,10 +23,9 @@ import {
setMessagingPlatformTotals,
setMessagingSessions,
setMessagingTruncated,
- setSessionProfileTotals,
+ setSessionProfilesTruncated,
setSessions,
- setSessionsLoading,
- setSessionsTotal
+ setSessionsLoading
} from '@/store/session'
import { $workingSessionIds, getRecentlySettledSessionIds } from '@/store/session-states'
@@ -202,9 +201,13 @@ export function useSessionListActions({ profileScope }: UseSessionListActionsArg
return sameCronSignature(prev, next) ? prev : next
})
- setSessionsTotal(typeof recents.total === 'number' ? recents.total : recents.sessions.length)
- setSessionProfileTotals(prev => {
- const next = recents.profile_totals ?? {}
+ // "Is there another page?" instead of an exact total: the backend
+ // reports which profiles filled their window, which costs nothing on
+ // top of the rows it already read (the old exact totals ran a COUNT(*)
+ // per profile DB on every refresh). Reference-stable when unchanged so
+ // the sidebar's group memos don't recompute per refresh.
+ setSessionProfilesTruncated(prev => {
+ const next = recents.profiles_truncated ?? {}
const prevKeys = Object.keys(prev)
return prevKeys.length === Object.keys(next).length && prevKeys.every(key => prev[key] === next[key])
@@ -258,8 +261,9 @@ export function useSessionListActions({ profileScope }: UseSessionListActionsArg
...mergeSessionPage(prev.filter(inKey), result.sessions, keep)
])
- const total = result.profile_totals?.[key] ?? result.total ?? result.sessions.length
- setSessionProfileTotals(prev => ({ ...prev, [key]: Math.max(total, result.sessions.length) }))
+ // A full window back means the profile still has more on disk.
+ const truncated = result.sessions.length >= loaded + SIDEBAR_SESSIONS_PAGE_SIZE
+ setSessionProfilesTruncated(prev => ({ ...prev, [key]: truncated }))
}, [])
return {
diff --git a/apps/desktop/src/hermes.test.ts b/apps/desktop/src/hermes.test.ts
index f829471c5a3..6b477574236 100644
--- a/apps/desktop/src/hermes.test.ts
+++ b/apps/desktop/src/hermes.test.ts
@@ -150,8 +150,9 @@ describe('Hermes REST helpers', () => {
// Slices reassembled from the legacy per-slice route with the same
// scoping: recents on the caller's profile, cron + messaging cross-profile.
expect(result.recents.sessions.map(s => s.id)).toEqual(['recent-1'])
- expect(result.recents.total).toBe(7)
- expect(result.recents.profile_totals).toEqual({ default: 7 })
+ // One row back against a 30-row window: the profile is fully loaded, so
+ // the legacy path must not claim there's another page.
+ expect(result.recents.profiles_truncated).toEqual({ default: false })
expect(result.cron.sessions.map(s => s.id)).toEqual(['cron-1'])
expect(result.messaging.sessions.map(s => s.id)).toEqual(['msg-1'])
diff --git a/apps/desktop/src/hermes.ts b/apps/desktop/src/hermes.ts
index 27a9e234680..5d19debb428 100644
--- a/apps/desktop/src/hermes.ts
+++ b/apps/desktop/src/hermes.ts
@@ -420,8 +420,24 @@ export async function listAllProfileSessions(
// splices remote profiles per slice (see interceptSessionRequestForRemote).
export interface SidebarSessionSlice {
sessions: SessionInfo[]
- total?: number
- profile_totals?: Record<string, number>
+ /** 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>
+}
+
+/** 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. */
+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) + 1)
+ }
+
+ return Object.fromEntries([...counts].map(([name, count]) => [name, count >= cap]))
}
export interface SidebarSessionsResponse {
@@ -494,7 +510,10 @@ async function listSidebarSessionsLegacy(req: SidebarSessionsRequest): Promise<S
const errors = [...(recents.errors ?? []), ...(cron.errors ?? []), ...(messaging.errors ?? [])]
return {
- recents: { profile_totals: recents.profile_totals, sessions: recents.sessions, total: recents.total },
+ recents: {
+ profiles_truncated: profilesTruncatedFrom(recents.sessions, req.recentsLimit),
+ sessions: recents.sessions
+ },
cron: { sessions: cron.sessions },
messaging: { sessions: messaging.sessions },
...(errors.length ? { errors } : {})
diff --git a/apps/desktop/src/store/gateway-switch.test.ts b/apps/desktop/src/store/gateway-switch.test.ts
index 4ee362a4bab..5473287c9fc 100644
--- a/apps/desktop/src/store/gateway-switch.test.ts
+++ b/apps/desktop/src/store/gateway-switch.test.ts
@@ -5,15 +5,15 @@ import {
$cronSessions,
$freshDraftReady,
$messagingSessions,
+ $sessionProfilesTruncated,
$sessions,
$sessionsLoading,
- $sessionsTotal,
setCronSessions,
setFreshDraftReady,
setMessagingSessions,
setSessions,
setSessionsLoading,
- setSessionsTotal
+ setSessionProfilesTruncated
} from '@/store/session'
import { $stalledSessionIds } from '@/store/session-states'
@@ -27,7 +27,7 @@ describe('wipeSessionListsForGatewaySwitch', () => {
beforeEach(() => {
$gatewaySwitching.set(false)
setSessions([{ id: 's1', title: 'old', profile: 'default' } as never])
- setSessionsTotal(1)
+ setSessionProfilesTruncated({ default: true })
setCronSessions([{ id: 'c1', title: 'cron', profile: 'default' } as never])
setMessagingSessions([{ id: 'm1', title: 'tg', profile: 'default' } as never])
$stalledSessionIds.set(['s1'])
@@ -50,7 +50,7 @@ describe('wipeSessionListsForGatewaySwitch', () => {
wipeSessionListsForGatewaySwitch()
expect($sessions.get()).toEqual([])
- expect($sessionsTotal.get()).toBe(0)
+ expect($sessionProfilesTruncated.get()).toEqual({})
expect($cronSessions.get()).toEqual([])
expect($messagingSessions.get()).toEqual([])
expect($stalledSessionIds.get()).toEqual([])
diff --git a/apps/desktop/src/store/gateway-switch.ts b/apps/desktop/src/store/gateway-switch.ts
index 291b803283a..7b1a9c338c8 100644
--- a/apps/desktop/src/store/gateway-switch.ts
+++ b/apps/desktop/src/store/gateway-switch.ts
@@ -13,10 +13,9 @@ import {
setMessagingSessions,
setMessagingTruncated,
setSelectedStoredSessionId,
- setSessionProfileTotals,
setSessions,
- setSessionsLoading,
- setSessionsTotal
+ setSessionProfilesTruncated,
+ setSessionsLoading
} from '@/store/session'
import { clearAllSessionStates } from '@/store/session-states'
@@ -42,8 +41,7 @@ export function wipeSessionListsForGatewaySwitch(): void {
// "batched sidebar endpoint missing" capability verdict across the switch.
resetSidebarBatchCapability()
setSessions([])
- setSessionsTotal(0)
- setSessionProfileTotals({})
+ setSessionProfilesTruncated({})
setCronSessions([])
setMessagingSessions([])
setMessagingPlatformTotals({})
diff --git a/apps/desktop/src/store/session.ts b/apps/desktop/src/store/session.ts
index 31ea5ff832a..340770936d0 100644
--- a/apps/desktop/src/store/session.ts
+++ b/apps/desktop/src/store/session.ts
@@ -270,7 +270,6 @@ export function mergeSessionPage(
export const $connection = atom<HermesConnection | null>(null)
export const $gatewayState = atom<ConnectionState>('idle')
export const $sessions = atom<SessionInfo[]>([])
-export const $sessionsTotal = atom<number>(0)
// Cron-job sessions (source === 'cron') are fetched as their own list so the
// scheduler's always-newest sessions never crowd recents out of the page
// budget. Powers the collapsed "Cron jobs" sidebar section.
@@ -294,11 +293,13 @@ export const $messagingPlatformTotals = atom<Record<string, number>>({})
// True when the combined seed fetch hit MESSAGING_SECTION_LIMIT, so at least
// one platform may have more rows on disk than were loaded.
export const $messagingTruncated = atom<boolean>(false)
-// Listable conversation count per profile (children excluded), keyed by profile
-// name. Lets the sidebar scope its "Load more" footer to the active profile so a
-// huge default profile doesn't keep "Load more" visible while browsing a small
-// one. Empty for single-profile users (fall back to $sessionsTotal).
-export const $sessionProfileTotals = atom<Record<string, number>>({})
+// Whether a profile's last session page was CAPPED by the request limit, keyed
+// by profile name — i.e. more rows exist on disk than were loaded. Replaces the
+// old exact per-profile totals: rendering `loaded/total` in the sidebar cost a
+// COUNT(*) per profile DB on every refresh and only ever confused people, while
+// "is there another page?" is what pagination actually needs and comes free
+// from the row count the query already returned.
+export const $sessionProfilesTruncated = atom<Record<string, boolean>>({})
export const $sessionsLoading = atom(true)
export const $activeSessionId = atom<string | null>(null)
export const $selectedStoredSessionId = atom<string | null>(null)
@@ -376,14 +377,13 @@ export const $sessionPickerOpen = atom(false)
export const setConnection = (next: Updater<HermesConnection | null>) => updateAtom($connection, next)
export const setGatewayState = (next: Updater<ConnectionState>) => updateAtom($gatewayState, next)
export const setSessions = (next: Updater<SessionInfo[]>) => updateAtom($sessions, next)
-export const setSessionsTotal = (next: Updater<number>) => updateAtom($sessionsTotal, next)
export const setCronSessions = (next: Updater<SessionInfo[]>) => updateAtom($cronSessions, next)
export const setMessagingSessions = (next: Updater<SessionInfo[]>) => updateAtom($messagingSessions, next)
export const setMessagingPlatformTotals = (next: Updater<Record<string, number>>) =>
updateAtom($messagingPlatformTotals, next)
export const setMessagingTruncated = (next: Updater<boolean>) => updateAtom($messagingTruncated, next)
-export const setSessionProfileTotals = (next: Updater<Record<string, number>>) =>
- updateAtom($sessionProfileTotals, next)
+export const setSessionProfilesTruncated = (next: Updater<Record<string, boolean>>) =>
+ updateAtom($sessionProfilesTruncated, next)
export const setSessionsLoading = (next: Updater<boolean>) => updateAtom($sessionsLoading, next)
export const setActiveSessionId = (next: Updater<string | null>) => updateAtom($activeSessionId, next)
export const setActiveSessionStoredIdRotation = (next: Updater<ActiveSessionStoredIdRotation | null>) =>
diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.py
index 5ae0010ca47..9f7933286f2 100644
--- a/hermes_cli/web_server.py
+++ b/hermes_cli/web_server.py
@@ -5076,8 +5076,7 @@ def get_profiles_sessions_sidebar(
recents_rows: List[Dict[str, Any]] = []
cron_rows: List[Dict[str, Any]] = []
messaging_rows: List[Dict[str, Any]] = []
- recents_total = 0
- recents_profile_totals: Dict[str, int] = {}
+ recents_truncated: Dict[str, bool] = {}
errors: List[Dict[str, str]] = []
now = time.time()
@@ -5116,18 +5115,13 @@ def get_profiles_sessions_sidebar(
continue
try:
if recents_scope == "all" or name == recents_scope:
- recents_rows.extend(
- _tag(_slice(db, exclude=recents_exclude_list, cap=recents_cap), name)
- )
- rtotal = db.session_count(
- exclude_sources=recents_exclude_list or None,
- min_message_count=1,
- include_archived=False,
- archived_only=False,
- exclude_children=True,
- )
- recents_total += rtotal
- recents_profile_totals[name] = rtotal
+ profile_rows = _slice(db, exclude=recents_exclude_list, cap=recents_cap)
+ # A full window means more rows remain on disk. That is all the
+ # sidebar's "load more" needs, and unlike an exact COUNT(*) per
+ # profile per refresh it costs nothing beyond the rows already
+ # read.
+ recents_truncated[name] = len(profile_rows) >= recents_cap
+ recents_rows.extend(_tag(profile_rows, name))
cron_rows.extend(_tag(_slice(db, source="cron", cap=cron_cap), name))
messaging_rows.extend(
_tag(_slice(db, exclude=messaging_exclude_list, cap=messaging_cap), name)
@@ -5146,8 +5140,7 @@ def get_profiles_sessions_sidebar(
return {
"recents": {
"sessions": _window(recents_rows, recents_cap),
- "total": recents_total,
- "profile_totals": recents_profile_totals,
+ "profiles_truncated": recents_truncated,
},
"cron": {"sessions": _window(cron_rows, cron_cap)},
"messaging": {
diff --git a/tests/hermes_cli/test_web_server.py b/tests/hermes_cli/test_web_server.py
index 070c86943d2..24ef3d0f8c4 100644
--- a/tests/hermes_cli/test_web_server.py
+++ b/tests/hermes_cli/test_web_server.py
@@ -2186,7 +2186,9 @@ class TestWebServerEndpoints:
assert row["profile"] == "default"
assert row["is_default_profile"] is True
assert isinstance(data.get("errors"), list)
- assert data["recents"]["total"] >= 1
+ # Pagination reports "was this window capped?" per profile, not an exact
+ # COUNT(*) — one row against a 20-row cap means nothing more to load.
+ assert data["recents"]["profiles_truncated"]["default"] is False
def test_sessions_endpoint_reads_requested_profile(self):
"""The machine dashboard's global profile switcher must retarget