The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): show every profile's sessions in the sidebar
Brooklyn Nicholson771b214516d7
diff --git a/apps/desktop/src/app/chat/close-tab.test.ts b/apps/desktop/src/app/chat/close-tab.test.tsindex 880e2edbbed..219f20df6d4 100644--- a/apps/desktop/src/app/chat/close-tab.test.ts+++ b/apps/desktop/src/app/chat/close-tab.test.ts@@ -1,3 +1,4 @@+import { atom } from 'nanostores'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'const closeFocusedSessionTab = vi.fn(() => false)@@ -17,7 +18,11 @@ vi.mock('@/store/session-states', () => ({}))vi.mock('@/store/profile', () => ({- requestFreshSession: () => requestFreshSession()+ // The layout store reads the sidebar's profile scope; this suite only cares+ // about the fresh-session call.+ $showAllProfiles: atom(false),+ requestFreshSession: () => requestFreshSession(),+ setShowAllProfiles: () => {}}))import { $previewTabs, closeRightRail, openPreview, type PreviewTarget } from '@/store/preview'diff --git a/apps/desktop/src/app/chat/sidebar/chrome.tsx b/apps/desktop/src/app/chat/sidebar/chrome.tsxindex 5adf70a20e2..3d422ab3c87 100644--- a/apps/desktop/src/app/chat/sidebar/chrome.tsx+++ b/apps/desktop/src/app/chat/sidebar/chrome.tsx@@ -1,8 +1,13 @@+import { useStore } from '@nanostores/react'import type * as React from 'react'import { Codicon } from '@/components/ui/codicon'+import { DisclosureCaret } from '@/components/ui/disclosure-caret'import { RowButton } from '@/components/ui/row-button'+import { Tip } from '@/components/ui/tooltip'+import { compactNumber } from '@/lib/format'import { cn } from '@/lib/utils'+import { $sidebarRowMeta } from '@/store/layout'// Shared, content-agnostic sidebar chrome — used by both the flat session// sections and the project/workspace tree, so it lives outside either to keep@@ -118,6 +123,90 @@ export function SidebarRowLabel({ className, ...props }: React.ComponentProps<'sreturn <span className={cn(rowLabel, className)} {...props} />}+/** What a group's sessions add up to, for the Show options that count something. */+export interface SidebarGroupTotals {+ costUsd: number+ tokens: number+}++/**+ * Header for a group of sessions that hangs its rows underneath — a project, a+ * profile. Row-shaped rather than caption-shaped (that's {@link SidebarDateDivider},+ * for groupings that only separate), so a group header lines up with the session+ * rows it heads. `toggle` omitted keeps the caret's space with nothing to reveal.+ */+export function SidebarGroupRow({+ actions,+ className,+ label,+ lead,+ toggle,+ totals,+ ...props+}: React.ComponentProps<'div'> & {+ actions?: React.ReactNode+ label: React.ReactNode+ lead: React.ReactNode+ toggle?: { ariaLabel: string; onToggle: () => void; open: boolean }+ totals?: SidebarGroupTotals+}) {+ const rowMeta = useStore($sidebarRowMeta)++ const facts = [+ totals && rowMeta.includes('tokens') && totals.tokens > 0 ? compactNumber(totals.tokens) : null,+ // Sub-cent spend rounds to "$0.00", which reads as a bug rather than as a+ // cheap group — below a cent the header says nothing at all.+ totals && rowMeta.includes('cost') && totals.costUsd >= 0.01 ? `$${totals.costUsd.toFixed(2)}` : null+ ].filter(Boolean) as string[]++ return (+ <SidebarRowShell+ actions={+ // The controls overlay the figures rather than sitting beside them: in+ // flow they hold their width open at all times, which reads as a gap+ // torn between the total and the row's edge. Same trade the session row+ // makes with its kebab and age — you read the number or you act on the+ // group, never both at once.+ facts.length ? (+ <div className="relative flex items-center">+ <span className="min-w-9 whitespace-nowrap text-right text-[0.625rem] leading-none text-(--ui-text-tertiary) transition-opacity group-hover/workspace:opacity-0">+ {facts.join(' · ')}+ </span>+ {actions ? <div className="absolute right-0 flex items-center">{actions}</div> : null}+ </div>+ ) : (+ actions+ )+ }+ className={cn('group/workspace', className)}+ {...props}+ >+ <SidebarRowCluster className="min-w-0 flex-1">+ {lead}+ {label}+ {toggle ? (+ <Tip label={toggle.ariaLabel}>+ <button+ aria-label={toggle.ariaLabel}+ className="flex flex-1 items-center self-stretch bg-transparent p-0"+ data-row-actions+ onClick={toggle.onToggle}+ type="button"+ >+ <DisclosureCaret+ className="shrink-0 text-(--ui-text-tertiary) opacity-0 transition group-hover/workspace:opacity-100"+ open={toggle.open}+ />+ </button>+ </Tip>+ ) : (+ <span className="flex-1" />+ )}+ </SidebarRowCluster>+ </SidebarRowShell>+ )+}+/** Dot ↔ grabber swap for dnd-kit reorder rows. */export function SidebarRowGrab({ariaLabel,diff --git a/apps/desktop/src/app/chat/sidebar/filter-menu.tsx b/apps/desktop/src/app/chat/sidebar/filter-menu.tsxindex 2bb1e247c8b..f7019c3a8f7 100644--- a/apps/desktop/src/app/chat/sidebar/filter-menu.tsx+++ b/apps/desktop/src/app/chat/sidebar/filter-menu.tsx@@ -26,6 +26,7 @@ import {$sidebarGrouping,$sidebarOrdering,$sidebarPrFilter,+ $sidebarProfileFilter,$sidebarProjectFilter,$sidebarRowMeta,$sidebarShowArchived,@@ -41,10 +42,19 @@ import {type SidebarOrdering,type SidebarRowMeta,toggleSidebarPrFilter,+ toggleSidebarProfileFilter,toggleSidebarProjectFilter,toggleSidebarRowMeta,toggleSidebarStatusFilter} from '@/store/layout'+import {+ $profiles,+ $showAllProfiles,+ normalizeProfileKey,+ requestProfileCreate,+ toggleShowAllProfiles+} from '@/store/profile'+import { runImportProfileFlow } from '@/store/profile-share'import { $projectTree } from '@/store/projects'import type { PullRequestBucket } from '@/store/pull-requests'import { $unreadFinishedSessionIds, markAllSessionsRead } from '@/store/session'@@ -62,7 +72,8 @@ interface Option<T extends string = string> {const GROUPINGS: Option<SidebarGrouping>[] = [{ icon: 'clock', id: 'date', label: 'Updated' },{ icon: 'root-folder', id: 'project', label: 'Project' },- { icon: 'pulse', id: 'status', label: 'Status' }+ { icon: 'pulse', id: 'status', label: 'Status' },+ { icon: 'account', id: 'profile', label: 'Profile' }]const ORDERINGS: Option<SidebarOrdering>[] = [@@ -141,6 +152,10 @@ export function SidebarFilterMenu({ className }: { className?: string }) {const rowMeta = useStore($sidebarRowMeta)const statusFilter = useStore($sidebarStatusFilter)const projectFilter = useStore($sidebarProjectFilter)+ const profileFilter = useStore($sidebarProfileFilter)+ const showAllProfiles = useStore($showAllProfiles)+ const profileNames = useStore($profiles).map(profile => normalizeProfileKey(profile.name))+ const narrowsByProfile = showAllProfiles && profileNames.length > 1const prFilter = useStore($sidebarPrFilter)const showArchived = useStore($sidebarShowArchived)const filtersActive = useStore($sidebarFiltersActive)@@ -287,6 +302,32 @@ export function SidebarFilterMenu({ className }: { className?: string }) {</DropdownMenuSub>)}+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>Profile</DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="max-h-80 overflow-y-auto">+ {/* Scoped to one profile the rail is already the filter, so the+ per-profile boxes only appear where they can narrow something.+ The actions below stand on their own. */}+ {narrowsByProfile && (+ <>+ {profileNames.map(name => (+ <OptionCheckbox+ checked={profileFilter.includes(name)}+ key={name}+ onCheck={() => toggleSidebarProfileFilter(name)}+ option={{ icon: 'account', id: name, label: name }}+ />+ ))}+ <DropdownMenuSeparator />+ </>+ )}+ <DropdownMenuItem onSelect={requestProfileCreate}>{t.profiles.newProfile}</DropdownMenuItem>+ <DropdownMenuItem onSelect={() => void runImportProfileFlow()}>+ {t.profiles.importProfile}+ </DropdownMenuItem>+ </DropdownMenuSubContent>+ </DropdownMenuSub>+{projects.length > 1 && (<DropdownMenuSub><DropdownMenuSubTrigger>Project</DropdownMenuSubTrigger>@@ -308,6 +349,19 @@ export function SidebarFilterMenu({ className }: { className?: string }) {</DropdownMenuSub>)}+ {/* Off by default: one profile's sessions are what the rail selected.+ Nothing to widen to until a second profile exists — but stay+ visible while it's on, or deleting your way back down to one+ profile would strand the sidebar in a mode nothing can leave (the+ rail hides its switcher at one profile too). */}+ {(profileNames.length > 1 || showAllProfiles) && (+ <OptionCheckbox+ checked={showAllProfiles}+ onCheck={toggleShowAllProfiles}+ option={{ id: 'all-profiles', label: t.profiles.allProfiles }}+ />+ )}+<OptionCheckboxchecked={showArchived}onCheck={() => setSidebarShowArchived(!showArchived)}diff --git a/apps/desktop/src/app/chat/sidebar/index.tsx b/apps/desktop/src/app/chat/sidebar/index.tsxindex d22f84e0bc2..05a0f2f811e 100644--- a/apps/desktop/src/app/chat/sidebar/index.tsx+++ b/apps/desktop/src/app/chat/sidebar/index.tsx@@ -26,7 +26,7 @@ import { useContributions } from '@/contrib/react/use-contributions'import { searchSessions, type SessionInfo, type SessionSearchResult } from '@/hermes'import { useI18n } from '@/i18n'import { comboTokens } from '@/lib/keybinds/combo'-import { profileColor } from '@/lib/profile-color'+import { resolveProfileColor } from '@/lib/profile-color'import { sessionMatchesSearch } from '@/lib/session-search'import { normalizeSessionSource, sessionSourceLabel } from '@/lib/session-source'import { cn } from '@/lib/utils'@@ -44,6 +44,7 @@ import {$sidebarPinsOpen,$sidebarPrDataWanted,$sidebarPrFilter,+ $sidebarProfileFilter,$sidebarProjectFilter,$sidebarProjectOrderIds,$sidebarRecentsOpen,@@ -69,7 +70,14 @@ import {toggleSidebarMessagingOpen,unpinSession} from '@/store/layout'-import { $newChatProfile, $profiles, $profileScope, ALL_PROFILES, normalizeProfileKey } from '@/store/profile'+import {+ $newChatProfile,+ $profileColors,+ $profiles,+ $profileScope,+ ALL_PROFILES,+ normalizeProfileKey+} from '@/store/profile'import {$activeProjectId,$projects,@@ -110,9 +118,10 @@ import {sessionPinId,setCurrentCwd} from '@/store/session'-import { $sessionDotStateById, sessionStatusBucket, sessionStatusRank } from '@/store/session-dot-state'+import { $sessionDotStateById, sessionStatusBucket } from '@/store/session-dot-state'import { $focusedStoredSessionId, $workingSessionIds, type SplitDir } from '@/store/session-states'-import { $archivedSessions, loadArchivedSessions, sessionCostUsd } from '@/store/sidebar-archive'+import { $archivedSessions, loadArchivedSessions } from '@/store/sidebar-archive'+import { $sidebarSessionRankIds } from '@/store/sidebar-sort'import {type AppView,@@ -256,7 +265,6 @@ interface ChatSidebarProps extends React.ComponentProps<typeof Sidebar> {currentView: AppViewonNavigate: (item: SidebarNavItem) => voidonLoadMoreSessions: () => Promise<void> | void- onLoadMoreProfileSessions?: (profile: string) => Promise<void> | voidonLoadMoreMessaging?: (platform: string) => Promise<void> | voidonResumeSession: (sessionId: string) => voidonDeleteSession: (sessionId: string) => void@@ -273,7 +281,6 @@ export function ChatSidebar({currentView,onNavigate,onLoadMoreSessions,- onLoadMoreProfileSessions,onLoadMoreMessaging,onResumeSession,onDeleteSession,@@ -319,6 +326,7 @@ export function ChatSidebar({const ordering = useStore($sidebarOrdering)const statusFilter = useStore($sidebarStatusFilter)const projectFilter = useStore($sidebarProjectFilter)+ const profileFilter = useStore($sidebarProfileFilter)const prFilter = useStore($sidebarPrFilter)const prDataWanted = useStore($sidebarPrDataWanted)const prBranchOverrides = useStore($prBranchBySession)@@ -327,6 +335,9 @@ export function ChatSidebar({const showArchived = useStore($sidebarShowArchived)const archivedSessions = useStore($archivedSessions)const dotStates = useStore($sessionDotStateById)+ // The active sort key as an id order. The flat list applies it within its+ // dividers; groups apply it to their own lanes.+ const sortOrderIds = useStore($sidebarSessionRankIds)const agentsGrouped = grouping === 'project'const pinnedSessionIds = useStore($pinnedSessionIds)const pinsOpen = useStore($sidebarPinsOpen)@@ -344,6 +355,7 @@ export function ChatSidebar({const sessionsLoading = useStore($sessionsLoading)const sessionProfilesTruncated = useStore($sessionProfilesTruncated)const profiles = useStore($profiles)+ const profileColors = useStore($profileColors)const profileScope = useStore($profileScope)// Only surface the profile switcher when more than one profile exists, so// single-profile users see the unchanged sidebar.@@ -373,7 +385,6 @@ export function ChatSidebar({const [serverMatches, setServerMatches] = useState<SessionSearchResult[]>([])const [searchPending, setSearchPending] = useState(false)const [newSessionKbdFlash, setNewSessionKbdFlash] = useState(false)- const [profileLoadMorePending, setProfileLoadMorePending] = useState<Record<string, boolean>>({})const [messagingLoadMorePending, setMessagingLoadMorePending] = useState<Record<string, boolean>>({})const [recentsLoadMorePending, setRecentsLoadMorePending] = useState(false)const messagingOpenIds = useStore($sidebarMessagingOpenIds)@@ -440,6 +451,12 @@ export function ChatSidebar({return false}+ // Narrowing to a few of the profiles on screen. Scoped to one profile the+ // list is already that profile's, so a stale selection can't blank it.+ if (showAllProfiles && profileFilter.length && !profileFilter.includes(normalizeProfileKey(session.profile))) {+ return false+ }+if (prFilter.length) {const key = sessionPrKey(session)@@ -452,10 +469,14 @@ export function ChatSidebar({// lands in the lane the user picked it from.return !projectFilter.length || projectFilter.includes(liveSessionProjectId(session, projects) ?? '')},- [statusFilter, projectFilter, prFilter, pullRequests, projects, dotStates]+ [statusFilter, projectFilter, profileFilter, showAllProfiles, prFilter, pullRequests, projects, dotStates])- const filtersNarrow = statusFilter.length > 0 || projectFilter.length > 0 || prFilter.length > 0+ const filtersNarrow =+ statusFilter.length > 0 ||+ projectFilter.length > 0 ||+ prFilter.length > 0 ||+ (showAllProfiles && profileFilter.length > 0)const visibleSessions = useMemo(() => (filtersNarrow ? scopedSessions.filter(sessionMatchesFilters) : scopedSessions),@@ -634,7 +655,7 @@ export function ChatSidebar({// Workspace grouping is a `project -> repo -> lane -> sessions` tree computed// authoritatively on the backend (projects.tree). Parents reorder via// workspaceParentOrderIds; worktrees within a parent via workspaceOrderIds.- const worktreeGroupingActive = agentsGrouped && !showAllProfiles && !showArchived+ const worktreeGroupingActive = agentsGrouped && !showArchivedconst gatewayReady = gatewayState === 'open'// The backend project tree is a structural snapshot, NOT a per-message feed.@@ -651,6 +672,18 @@ export function ChatSidebar({if (worktreeGroupingActive) {void refreshProjects()++ // The all-profiles tree is served off every profile's databases at once+ // and deliberately leaves discovery out — a repo with no sessions is the+ // same repo in every profile, so scanning here would multiply empty lanes+ // by the profile count and write the result into profiles the user isn't+ // driving.+ if (showAllProfiles) {+ void refreshProjectTree()++ return+ }+// Paint the list from the fast tree fetch (explicit projects + repos from// existing sessions / the backend cache) FIRST, then kick off the heavy// home-dir git crawl so newly-discovered repos fold in afterward — instead@@ -667,7 +700,7 @@ export function ChatSidebar({const warm = window.setTimeout(() => void refreshProjectTree(), PROJECT_TREE_WARM_MS)return () => window.clearTimeout(warm)- }, [worktreeGroupingActive, profileScope, gatewayReady])+ }, [worktreeGroupingActive, showAllProfiles, profileScope, gatewayReady])// Sessions the branch join can't answer for get one look at their own// transcript — a `gh pr create` in there names the PR outright. Backfills@@ -768,6 +801,12 @@ export function ChatSidebar({void refreshProjects()void refreshProjectTree()+ // Discovery stays off while browsing every profile, for the reason the+ // first fetch leaves it out.+ if (showAllProfiles) {+ return+ }+const now = Date.now()if (now - lastScanAt >= SCAN_THROTTLE_MS) {@@ -783,7 +822,7 @@ export function ChatSidebar({window.removeEventListener('focus', onActive)document.removeEventListener('visibilitychange', onActive)}- }, [worktreeGroupingActive, gatewayReady])+ }, [worktreeGroupingActive, showAllProfiles, gatewayReady])// Apply the persisted repo + worktree orders to a project's repo subtrees.const orderRepos = useCallback(@@ -801,10 +840,6 @@ export function ChatSidebar({// state on top: dismissed auto-projects, persisted repo/lane order, and the// overview sort. Membership is the backend tree's — never re-derived here.const projectModel = useMemo<SidebarProjectTree[]>(() => {- if (showAllProfiles) {- return []- }-const sorted = sortProjectsForOverview(filterVisibleProjects(projectTree, dismissedAutoProjects)// A filtered-out project drops its whole lane, header included — hiding@@ -830,7 +865,6 @@ export function ChatSidebar({// keep their sorted position rather than jumping the hand-picked list.return orderProjectsByIds(sorted, projectOrderIds)}, [- showAllProfiles,projectTree,dismissedAutoProjects,orderRepos,@@ -1020,8 +1054,14 @@ export function ChatSidebar({// session shows under its project instantly (and with its working arc),// matching the flat Recents list. Keyed by project id for the rows.const overviewPreviews = useMemo<Record<string, SessionInfo[]>>(- () => overlayLivePreviews(projectOverview ?? [], agentSessions, projects, PROJECT_PREVIEW_COUNT, removedSessionIds),- [projectOverview, agentSessions, projects, removedSessionIds]+ () =>+ overlayLivePreviews(projectOverview ?? [], agentSessions, projects, PROJECT_PREVIEW_COUNT, {+ removed: removedSessionIds,+ // Rank before the trim, so "3 priciest in this project" isn't "3 most+ // recent, priciest first".+ rankIds: sortOrderIds+ }),+ [projectOverview, agentSessions, projects, removedSessionIds, sortOrderIds])const onEnterProject = useCallback(@@ -1070,11 +1110,6 @@ export function ChatSidebar({[])- const loadMoreForProfileGroup = useCallback(- (profile: string) => runKeyedLoad(profile, onLoadMoreProfileSessions, setProfileLoadMorePending),- [onLoadMoreProfileSessions, runKeyedLoad]- )-const loadMoreForMessaging = useCallback((platform: string) => runKeyedLoad(platform, onLoadMoreMessaging, setMessagingLoadMorePending),[onLoadMoreMessaging, runKeyedLoad]@@ -1146,10 +1181,14 @@ export function ChatSidebar({.sort((a, b) => sessionTime(b.sessions[0]) - sessionTime(a.sessions[0]))}, [messagingSessions, messagingPlatformTotals, messagingTruncated, isPinnedSession])- // ALL-profiles view: one collapsible group per profile, color on the header+ // Grouping by profile: one collapsible group per profile, color on the header// (not on every row). Default profile floats to the top, the rest alpha.+ // Only reachable while the sidebar is showing every profile — scoped to one,+ // it would draw a single group around the whole list.+ const profileGrouped = showAllProfiles && grouping === 'profile'+const profileGroups = useMemo<SidebarSessionGroup[] | undefined>(() => {- if (!showAllProfiles) {+ if (!profileGrouped) {return undefined}@@ -1159,7 +1198,7 @@ export function ChatSidebar({const key = normalizeProfileKey(session.profile)const group = groups.get(key) ?? {- color: profileColor(key),+ color: resolveProfileColor(key, profileColors),id: key,label: key,mode: 'profile',@@ -1172,25 +1211,11 @@ export function ChatSidebar({groups.set(key, group)}- return (- [...groups.values()]- .map(group => ({- ...group,- loadingMore: Boolean(profileLoadMorePending[group.id]),- onLoadMore: onLoadMoreProfileSessions ? () => loadMoreForProfileGroup(group.id) : undefined,- 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)))+ // default (root) first, then the rest alphabetically.+ return [...groups.values()].sort((a, b) =>+ a.id === 'default' ? -1 : b.id === 'default' ? 1 : a.label.localeCompare(b.label))- }, [- showAllProfiles,- agentSessions,- loadMoreForProfileGroup,- onLoadMoreProfileSessions,- profileLoadMorePending,- sessionProfilesTruncated- ])+ }, [profileGrouped, agentSessions, profileColors])// The flat Sessions list always shows ALL recent sessions; Projects is a// parallel grouped view, not a filter on this one — nothing is hidden here.@@ -1268,31 +1293,7 @@ export function ChatSidebar({// state-based keys stay bucketed, where they read correctly per day.const rankedGlobally = ordering === 'cost' || ordering === 'tokens'- // Every sort key but `updated` is expressed as an id order applied within- // whatever dividers are on — so a bucketed key ranks rows inside each day,- // and a globally-ranked one (which has no dividers left) ranks the lot.- // `updated` is the natural order the list already arrives in, so it needs no- // ids at all.- const sortOrderIds = useMemo(() => {- const rank: null | ((session: SessionInfo) => number) =- ordering === 'status'- ? session => sessionStatusRank(dotStates[session.id])- : ordering === 'created'- ? session => -session.started_at- : ordering === 'tokens'- ? session => -(session.input_tokens + session.output_tokens)- : ordering === 'cost'- ? session => -sessionCostUsd(session)- : null-- if (!rank) {- return undefined- }-- return [...agentSessions].sort((a, b) => rank(a) - rank(b)).map(session => session.id)- }, [ordering, agentSessions, dotStates])-- const displayAgentGroups = showAllProfiles ? profileGroups : undefined+ const displayAgentGroups = profileGroups// The recents list owns its own (virtualized) scroll container only when it's a// long flat list. In that case it must keep its scroller even in short mode, so@@ -1550,11 +1551,8 @@ export function ChatSidebar({activeSessionId={activeSidebarSessionId}collapsible={!inProject}contentClassName={cn(- 'flex min-h-0 flex-1 flex-col pb-1.75',+ 'flex min-h-0 flex-1 flex-col gap-px pb-1.75',SCROLL_Y,- // Separate profile sections clearly in the ALL view; rows inside- // each group keep their own tight gap-px rhythm.- showAllProfiles ? 'gap-3' : 'gap-px',// Flatten into the single scroll when compact — unless this is the// virtualized long list, which must keep its own scroller.!recentsVirtualizes && COMPACT_FLAT@@ -1576,10 +1574,10 @@ export function ChatSidebar({)}footer={- // Hide "load more" only when workspace-grouped (those groups page- // themselves). ALL-profiles now pages per-profile from each profile- // header; the global footer only applies to non-ALL views.- !showAllProfiles && !agentsGrouped && !showSessionSkeletons && hasMoreSessions ? (+ // Hidden only when workspace-grouped — those groups page+ // themselves. Profile groups don't: this one footer fetches the+ // next page, which grows every profile at once.+ !agentsGrouped && !showSessionSkeletons && hasMoreSessions ? (<SidebarLoadMoreRowloading={sessionsLoading || recentsLoadMorePending}onClick={() => void onLoadMoreRecents()}@@ -1651,7 +1649,7 @@ export function ChatSidebar({</Tip>) : null}<div className="grid size-6 place-items-center">- {!showAllProfiles ? <SidebarFilterMenu className={HEADER_NAV_BTN} /> : null}+ <SidebarFilterMenu className={HEADER_NAV_BTN} /></div></div>)@@ -1670,7 +1668,10 @@ export function ChatSidebar({onBranchSession={onBranchSession}onDeleteSession={onDeleteSession}onEnterProject={onEnterProject}- onNewSessionInWorkspace={showAllProfiles ? undefined : onNewSessionInWorkspace}+ // Unlike reorder below, this stays on across profiles: a folder+ // is a folder, and the new session lands in the active profile+ // — the same one the composer would have started it in.+ onNewSessionInWorkspace={onNewSessionInWorkspace}onReorderProjects={showAllProfiles ? undefined : reorderProjects}onReorderSessions={showAllProfiles ? undefined : reorderSessions}onResumeSession={onResumeSession}diff --git a/apps/desktop/src/app/chat/sidebar/projects/overview-row.test.tsx b/apps/desktop/src/app/chat/sidebar/projects/overview-row.test.tsxindex 66303462994..896643636d8 100644--- a/apps/desktop/src/app/chat/sidebar/projects/overview-row.test.tsx+++ b/apps/desktop/src/app/chat/sidebar/projects/overview-row.test.tsx@@ -1,4 +1,4 @@-import { cleanup, render, screen } from '@testing-library/react'+import { cleanup, fireEvent, render, screen } from '@testing-library/react'import type { ReactNode } from 'react'import { afterEach, describe, expect, it, vi } from 'vitest'@@ -71,11 +71,19 @@ describe('ProjectOverviewRow', () => {expect(screen.queryByRole('button', { name: 'Show Test D sessions' })).toBeNull()})- it('drops the "new session" add button on Home, which has no folder to start in', () => {- const home = { id: '__no_project__', isNoProject: true, label: 'Home' } as unknown as SidebarProjectTree+ it('offers the "new session" add button on Home, which starts one with no folder', () => {+ const home = {+ id: '__no_project__',+ isNoProject: true,+ label: 'Home',+ path: null+ } as unknown as SidebarProjectTree- render(<ProjectOverviewRow onNewSession={vi.fn()} project={home} />)+ const onNewSession = vi.fn()- expect(screen.queryByRole('button', { name: 'New session in Home' })).toBeNull()+ render(<ProjectOverviewRow onNewSession={onNewSession} project={home} />)+ fireEvent.click(screen.getByRole('button', { name: 'New session in Home' }))++ expect(onNewSession).toHaveBeenCalledWith(null)})})diff --git a/apps/desktop/src/app/chat/sidebar/projects/overview-row.tsx b/apps/desktop/src/app/chat/sidebar/projects/overview-row.tsxindex aedd2e6e09e..155d477e1ee 100644--- a/apps/desktop/src/app/chat/sidebar/projects/overview-row.tsx+++ b/apps/desktop/src/app/chat/sidebar/projects/overview-row.tsx@@ -2,16 +2,14 @@ import type * as React from 'react'import { useRef } from 'react'import { Codicon } from '@/components/ui/codicon'-import { DisclosureCaret } from '@/components/ui/disclosure-caret'-import { Tip } from '@/components/ui/tooltip'import type { SessionInfo } from '@/hermes'import { useI18n } from '@/i18n'import { cn } from '@/lib/utils'import {SIDEBAR_LEAD_ICON_SIZE,+ SidebarGroupRow,SidebarRowBody,- SidebarRowCluster,SidebarRowGrab,SidebarRowLabel,SidebarRowLead,@@ -113,18 +111,30 @@ export function ProjectOverviewRow({)const shell = (- <SidebarRowShell+ <SidebarGroupRowactions={<>- {/* Home has no folder to start a chat in — the sidebar's own "New- session" is that button — and no record to rename or delete. */}- {onNewSession && !project.isNoProject && (+ {/* Home is a bucket, not a record, so there's nothing to rename or+ delete — but it still starts sessions: a null path is the "no+ folder" chat. New session sits outermost: it's the one you reach+ for. */}+ {!project.isNoProject && <ProjectMenu anchorRef={rowRef} isActive={isActive} project={project} />}+ {onNewSession && (<WorkspaceAddButton label={s.newSessionIn(project.label)} onClick={() => onNewSession(project.path)} />)}- {!project.isNoProject && <ProjectMenu anchorRef={rowRef} isActive={isActive} project={project} />}</>}- className={cn('group/workspace', dragging && 'cursor-grabbing bg-(--ui-sidebar-surface-background)')}+ className={cn(dragging && 'cursor-grabbing bg-(--ui-sidebar-surface-background)')}+ label={+ <SidebarRowLink+ aria-label={s.projects.enter(project.label)}+ labelClassName={cn('hover:text-foreground hover:underline', isActive && 'text-foreground')}+ onClick={() => onEnter?.(project.id)}+ >+ {project.label}+ </SidebarRowLink>+ }+ lead={lead}// The label is grab surface too, not just the lead's grabber — same// listeners, minus the controls that keep their own gestures. A project// row has no rival drag (its title navigates on CLICK), so the sortable@@ -138,36 +148,13 @@ export function ProjectOverviewRow({dragHandleProps?.onPointerDown?.(event)}}ref={rowRef}- >- <SidebarRowCluster className="min-w-0 flex-1">- {lead}- <SidebarRowLink- aria-label={s.projects.enter(project.label)}- labelClassName={cn('hover:text-foreground hover:underline', isActive && 'text-foreground')}- onClick={() => onEnter?.(project.id)}- >- {project.label}- </SidebarRowLink>- {preview.length > 0 ? (- <Tip label={s.projects.toggle(project.label, !open)}>- <button- aria-label={s.projects.toggle(project.label, !open)}- className="flex flex-1 items-center self-stretch bg-transparent p-0"- data-row-actions- onClick={toggleOpen}- type="button"- >- <DisclosureCaret- className="shrink-0 text-(--ui-text-tertiary) opacity-0 transition group-hover/workspace:opacity-100"- open={open}- />- </button>- </Tip>- ) : (- <span className="flex-1" />- )}- </SidebarRowCluster>- </SidebarRowShell>+ toggle={+ preview.length > 0+ ? { ariaLabel: s.projects.toggle(project.label, !open), onToggle: toggleOpen, open }+ : undefined+ }+ totals={{ costUsd: project.totalCostUsd ?? 0, tokens: project.totalTokens ?? 0 }}+ />)return (diff --git a/apps/desktop/src/app/chat/sidebar/projects/workspace-group.tsx b/apps/desktop/src/app/chat/sidebar/projects/workspace-group.tsxindex 5c05869b5a7..33f83827548 100644--- a/apps/desktop/src/app/chat/sidebar/projects/workspace-group.tsx+++ b/apps/desktop/src/app/chat/sidebar/projects/workspace-group.tsx@@ -1,19 +1,24 @@+import { useStore } from '@nanostores/react'import type * as React from 'react'import { useState } from 'react'import { Codicon } from '@/components/ui/codicon'+import { ProfileGlyph } from '@/components/ui/profile-glyph'import type { SessionInfo } from '@/hermes'import { useI18n } from '@/i18n'import { displayPath } from '@/lib/display-path'+import { useStoreSelector } from '@/lib/use-session-slice'import { setWorkspaceNodeOpen } from '@/store/layout'import { notifyError } from '@/store/notifications'-import { newSessionInProfile } from '@/store/profile'+import { newSessionInProfile, selectProfile } from '@/store/profile'import { switchBranchInRepo } from '@/store/projects'+import { $sessionProfilesUsage } from '@/store/session'+import { $sidebarSessionRankIds } from '@/store/sidebar-sort'-import { SidebarRowStack } from '../chrome'-import { SidebarLoadMoreRow } from '../load-more-row'+import { SidebarGroupRow, SidebarRowLead, SidebarRowLink, SidebarRowStack } from '../chrome'+import { rankSessions } from '../order'-import { SIDEBAR_GROUP_PAGE, useWorkspaceNodeOpen } from './model'+import { PROJECT_PREVIEW_COUNT, SIDEBAR_GROUP_PAGE, useWorkspaceNodeOpen } from './model'import type { SidebarSessionGroup } from './workspace-groups'import {WorkspaceAddButton,@@ -36,6 +41,10 @@ export function SidebarWorkspaceGroup({ group, renderRows, onNewSession, onRemovconst { t } = useI18n()const s = t.sidebarconst isProfileGroup = group.mode === 'profile'+ // Totals for the whole profile, not the loaded page — a selector so a refresh+ // that leaves this profile's spend unchanged doesn't repaint its header.+ const usage = useStoreSelector($sessionProfilesUsage, all => all[group.id])+ const rankIds = useStore($sidebarSessionRankIds)// Empty worktree/branch lanes start collapsed — they only show a "No sessions// yet" placeholder, so defaulting them open just adds noise. Profile lanes and// lanes that already hold sessions default open.@@ -43,21 +52,18 @@ export function SidebarWorkspaceGroup({ group, renderRows, onNewSession, onRemovconst [open, toggleOpen] = useWorkspaceNodeOpen(group.id, defaultOpen)const [visibleCount, setVisibleCount] = useState(SIDEBAR_GROUP_PAGE)- const loadedCount = group.sessions.length- const visibleSessions = group.sessions.slice(0, visibleCount)- // 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+ // A lane ranks by whatever the sort key says before it trims itself, so the+ // rows it hides are the ones the sort ranked last.+ const sessions = rankSessions(group.sessions, rankIds)+ // A profile previews the same handful a project does, and clicking its label+ // is how you see the rest. Workspace groups page within what's loaded.+ const visibleSessions = sessions.slice(0, isProfileGroup ? PROJECT_PREVIEW_COUNT : visibleCount)+ const hiddenCount = isProfileGroup ? 0 : sessions.length - visibleSessions.lengthconst nextCount = Math.min(SIDEBAR_GROUP_PAGE, hiddenCount)- // Leading glyph: profile color dot, a home mark for the repo's primary- // checkout (labeled by its live branch), or a branch/kanban mark otherwise.- const leadingIcon = group.color ? (- <span aria-hidden="true" className="size-2 shrink-0 rounded-full" style={{ backgroundColor: group.color }} />- ) : (+ // Leading glyph: a home mark for the repo's primary checkout (labeled by its+ // live branch), a branch/kanban mark otherwise.+ const leadingIcon = (<CodiconclassName="shrink-0 text-(--ui-text-tertiary)"name={group.isKanban ? 'checklist' : group.isHome ? 'home' : 'git-branch'}@@ -65,18 +71,6 @@ export function SidebarWorkspaceGroup({ group, renderRows, onNewSession, onRemov/>)- // Reveal already-loaded rows first; only hit the backend when the next page- // crosses what's been fetched for this profile.- const handleProfileLoadMore = () => {- const target = visibleCount + SIDEBAR_GROUP_PAGE-- setVisibleCount(target)-- if (target > loadedCount && group.hasMore) {- group.onLoadMore?.()- }- }-const handleNewSession = async () => {// Reveal the lane the new session targets — an empty worktree/branch lane// starts collapsed, so without this the session lands in a folder the user@@ -109,33 +103,67 @@ export function SidebarWorkspaceGroup({ group, renderRows, onNewSession, onRemovonNewSession(group.path)}+ // Profile groups start a fresh session in that profile but keep the+ // all-profiles browse view; workspace groups seed the new session's cwd.+ // Main checkout lanes are branch-targeted.+ const addButton = (onNewSession || isProfileGroup) && (+ <WorkspaceAddButton label={s.newSessionIn(group.label)} onClick={() => void handleNewSession()} />+ )+return (<SidebarRowStack>- <WorkspaceContextMenu onRemove={onRemove} path={group.path}>- <WorkspaceHeader- action={- (onNewSession || isProfileGroup || onRemove) && (- <div className="flex items-center">- {(onNewSession || isProfileGroup) && (- <WorkspaceAddButton- label={s.newSessionIn(group.label)}- // Profile groups start a fresh session in that profile but keep- // the all-profiles browse view; workspace groups seed the new- // session's cwd. Main checkout lanes are branch-targeted.- onClick={() => void handleNewSession()}- />- )}- {onRemove && <WorkspaceMenu onRemove={onRemove} path={group.path} />}- </div>- )+ {isProfileGroup ? (+ // A profile heads its sessions the way a project does, so it takes the+ // project row's shape rather than the tree caption the lanes below use.+ <SidebarGroupRow+ actions={addButton}+ // Clicking a profile scopes the sidebar to it, the way clicking a+ // project enters that project. Capitalized to sit level with the+ // project labels it alternates with (`Home`, and whatever the user+ // named theirs) — profile keys are stored lowercase.+ label={+ <SidebarRowLink+ aria-label={t.profiles.switchToProfile(group.label)}+ labelClassName="capitalize hover:text-foreground hover:underline"+ onClick={() => selectProfile(group.id)}+ >+ {group.label}+ </SidebarRowLink>}- icon={leadingIcon}- label={group.label}- onToggle={toggleOpen}- open={open}- title={group.path ? displayPath(group.path) : undefined}+ lead={+ <SidebarRowLead>+ {/* Fills the lead cell like a project's icon does: the glyph's own+ 16px would sit 2px proud of the 14px column. */}+ <ProfileGlyph+ className="size-full"+ color={group.color ?? null}+ isDefault={group.id === 'default'}+ name={group.label}+ />+ </SidebarRowLead>+ }+ toggle={{ ariaLabel: s.projects.toggle(group.label, !open), onToggle: toggleOpen, open }}+ totals={{ costUsd: usage?.cost_usd ?? 0, tokens: usage?.tokens ?? 0 }}/>- </WorkspaceContextMenu>+ ) : (+ <WorkspaceContextMenu onRemove={onRemove} path={group.path}>+ <WorkspaceHeader+ action={+ (onNewSession || onRemove) && (+ <div className="flex items-center">+ {addButton}+ {onRemove && <WorkspaceMenu onRemove={onRemove} path={group.path} />}+ </div>+ )+ }+ icon={leadingIcon}+ label={group.label}+ onToggle={toggleOpen}+ open={open}+ title={group.path ? displayPath(group.path) : undefined}+ />+ </WorkspaceContextMenu>+ )}{open && (<>{visibleSessions.length === 0 ? (@@ -143,20 +171,13 @@ export function SidebarWorkspaceGroup({ group, renderRows, onNewSession, onRemov) : (renderRows(visibleSessions))}- {hiddenCount > 0 &&- (isProfileGroup ? (- <SidebarLoadMoreRow- loading={Boolean(group.loadingMore)}- onClick={handleProfileLoadMore}- step={nextCount}- />- ) : (- <WorkspaceShowMoreButton- count={nextCount}- label={group.label}- onClick={() => setVisibleCount(count => count + SIDEBAR_GROUP_PAGE)}- />- ))}+ {hiddenCount > 0 && (+ <WorkspaceShowMoreButton+ count={nextCount}+ label={group.label}+ onClick={() => setVisibleCount(count => count + SIDEBAR_GROUP_PAGE)}+ />+ )}</>)}</SidebarRowStack>diff --git a/apps/desktop/src/app/chat/sidebar/projects/workspace-groups.test.ts b/apps/desktop/src/app/chat/sidebar/projects/workspace-groups.test.tsindex 7fb7166f9b6..b2a893af583 100644--- a/apps/desktop/src/app/chat/sidebar/projects/workspace-groups.test.ts+++ b/apps/desktop/src/app/chat/sidebar/projects/workspace-groups.test.ts@@ -855,11 +855,26 @@ describe('overlayLivePreviews', () => {]})- const previews = overlayLivePreviews([project], [], [], 3, new Set(['gone']))+ const previews = overlayLivePreviews([project], [], [], 3, { removed: new Set(['gone']) })expect(previews['/www/app'].map(s => s.id)).toEqual(['old'])})+ it('ranks by the active sort key before trimming, so the preview is its top rows', () => {+ const project = projectNode({+ id: '/www/app',+ previewSessions: [+ makeSession('/www/app', { id: 'newest', last_active: 9, started_at: 9 }),+ makeSession('/www/app', { id: 'cheap', last_active: 8, started_at: 8 }),+ makeSession('/www/app', { id: 'priciest', last_active: 1, started_at: 1 })+ ]+ })++ const previews = overlayLivePreviews([project], [], [], 2, { rankIds: ['priciest', 'newest', 'cheap'] })++ expect(previews['/www/app'].map(s => s.id)).toEqual(['priciest', 'newest'])+ })+it('previews a detached session under Home, which no cwd could place', () => {const previews = overlayLivePreviews([homeNode([])], [makeSession(null, { id: 'fresh' })], [], 3)diff --git a/apps/desktop/src/app/chat/sidebar/projects/workspace-groups.ts b/apps/desktop/src/app/chat/sidebar/projects/workspace-groups.tsindex 55f36bf99f9..353e9d4ad70 100644--- a/apps/desktop/src/app/chat/sidebar/projects/workspace-groups.ts+++ b/apps/desktop/src/app/chat/sidebar/projects/workspace-groups.ts@@ -2,6 +2,8 @@ import type { HermesGitWorktree } from '@/global'import type { ProjectInfo, SessionInfo } from '@/hermes'import { normalize } from '@/lib/text'+import { rankSessions } from '../order'+// Session grouping is now computed authoritatively on the backend// (`tui_gateway/project_tree.py`, exposed via `projects.tree` /// `projects.project_sessions`). The desktop is a thin renderer: this module@@ -26,14 +28,8 @@ export interface SidebarSessionGroup {// worktrees (`<repo>/.worktrees/t_*`) into one row, so a heavy board doesn't// spray hundreds of throwaway branch lanes across the sidebar.isKanban?: boolean- loadingMore?: booleanmode?: 'profile' | 'source' | 'workspace'- onLoadMore?: () => voidsourceId?: string- /** 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`). */@@ -62,6 +58,10 @@ export interface SidebarProjectTree {isNoProject?: booleanrepos: SidebarWorkspaceTree[]sessionCount: number+ // Tokens and spend over the same sessions `sessionCount` counts, summed by+ // the backend — the tree only carries a preview of the rows themselves.+ totalTokens?: number+ totalCostUsd?: number// Max activity timestamp across the project's sessions (overview sort key).lastActive?: number// Up to N most-recent sessions for the overview preview (set by `projects.tree`).@@ -700,13 +700,19 @@ export function overlayLiveLanes(return { ...project, repos, sessionCount: repos.reduce((n, repo) => n + repo.sessionCount, 0) }}+interface PreviewOverlayOptions {+ removed?: ReadonlySet<string>+ /** The active sort key as an id order; recency when empty. */+ rankIds?: string[]+}+/** Merge live sessions into per-project overview previews, keyed by project id. */export function overlayLivePreviews(projects: SidebarProjectTree[],live: SessionInfo[],explicitProjects: ProjectInfo[],limit: number,- removed: ReadonlySet<string> = new Set()+ { removed = NO_REMOVED, rankIds }: PreviewOverlayOptions = {}): Record<string, SessionInfo[]> {const byProject = new Map<string, SessionInfo[]>()@@ -746,7 +752,9 @@ export function overlayLivePreviews(}}- out[node.id] = [...map.values()].sort((a, b) => sessionRecency(b) - sessionRecency(a)).slice(0, limit)+ const pool = [...map.values()].sort((a, b) => sessionRecency(b) - sessionRecency(a))++ out[node.id] = rankSessions(pool, rankIds).slice(0, limit)}return outdiff --git a/apps/desktop/src/app/contrib/latest-actions.test.ts b/apps/desktop/src/app/contrib/latest-actions.test.tsindex 9ff335054f3..f719e8438a6 100644--- a/apps/desktop/src/app/contrib/latest-actions.test.ts+++ b/apps/desktop/src/app/contrib/latest-actions.test.ts@@ -38,7 +38,6 @@ function makeSidebarActions(): SidebarActions {onBranchSession: vi.fn(),onDeleteSession: vi.fn(),onLoadMoreMessaging: vi.fn(),- onLoadMoreProfileSessions: vi.fn(),onLoadMoreSessions: vi.fn(),onManageCronJob: vi.fn(),onNavigate: vi.fn(),@@ -100,12 +99,10 @@ describe('latestActions adapters', () => {const sidebar = makeSidebarActions()sidebar.onLoadMoreMessaging = undefined- sidebar.onLoadMoreProfileSessions = undefinedconst adaptedSidebar = latestSidebarActions(sidebar)expect(adaptedSidebar.onLoadMoreMessaging).toBeUndefined()- expect(adaptedSidebar.onLoadMoreProfileSessions).toBeUndefined()})it('still late-binds a PRESENT optional handler to the latest closure', async () => {diff --git a/apps/desktop/src/app/contrib/latest-actions.ts b/apps/desktop/src/app/contrib/latest-actions.tsindex 7d191208a27..41fa4949d89 100644--- a/apps/desktop/src/app/contrib/latest-actions.ts+++ b/apps/desktop/src/app/contrib/latest-actions.ts@@ -61,7 +61,6 @@ export function latestSidebarActions(actions: SidebarActions): SidebarActions {onBranchSession: (...args) => actions.onBranchSession(...args),onDeleteSession: (...args) => actions.onDeleteSession(...args),onLoadMoreMessaging: latestOptional(() => actions.onLoadMoreMessaging),- onLoadMoreProfileSessions: latestOptional(() => actions.onLoadMoreProfileSessions),onLoadMoreSessions: (...args) => actions.onLoadMoreSessions(...args),onManageCronJob: (...args) => actions.onManageCronJob(...args),onNavigate: (...args) => actions.onNavigate(...args),diff --git a/apps/desktop/src/app/contrib/types.ts b/apps/desktop/src/app/contrib/types.tsindex 1e2c60ac776..44c29f46853 100644--- a/apps/desktop/src/app/contrib/types.ts+++ b/apps/desktop/src/app/contrib/types.ts@@ -15,7 +15,6 @@ export type SidebarActions = Pick<| 'onBranchSession'| 'onDeleteSession'| 'onLoadMoreMessaging'- | 'onLoadMoreProfileSessions'| 'onLoadMoreSessions'| 'onManageCronJob'| 'onNavigate'diff --git a/apps/desktop/src/app/contrib/wiring.tsx b/apps/desktop/src/app/contrib/wiring.tsxindex 37c04bd9083..356a38cd77e 100644--- a/apps/desktop/src/app/contrib/wiring.tsx+++ b/apps/desktop/src/app/contrib/wiring.tsx@@ -251,7 +251,6 @@ export function ContribWiring({ children }: { children: ReactNode }) {const {loadMoreMessagingForPlatform,loadMoreSessions,- loadMoreSessionsForProfile,refreshCronJobs,refreshMessagingSessions,refreshSessions@@ -879,7 +878,6 @@ export function ContribWiring({ children }: { children: ReactNode }) {onDismissError: dismissError,onEdit: editMessage,onLoadMoreMessaging: loadMoreMessagingForPlatform,- onLoadMoreProfileSessions: loadMoreSessionsForProfile,onLoadMoreSessions: loadMoreSessions,onManageCronJob: jobId => {setCronFocusJobId(jobId)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.tsindex ba2e560b475..8e26f770d21 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@@ -32,6 +32,7 @@ import {setMessagingSessions,setMessagingTruncated,setSessionProfilesTruncated,+ setSessionProfilesUsage,setSessions,setSessionsLoading} from '@/store/session'@@ -223,6 +224,19 @@ export function useSessionListActions({ profileScope }: UseSessionListActionsArg? prev: next})+ // Same identity gate: these totals only move when a session bills, and+ // a fresh object every refresh would repaint every profile header.+ setSessionProfilesUsage(prev => {+ const next = recents.profiles_usage ?? {}+ const prevKeys = Object.keys(prev)++ return prevKeys.length === Object.keys(next).length &&+ prevKeys.every(+ key => prev[key]?.tokens === next[key]?.tokens && prev[key]?.cost_usd === next[key]?.cost_usd+ )+ ? prev+ : next+ })// Cron section: latest N cron sessions (kept so a pinned cron run still// resolves via sessionByAnyId), signature-gated like above.@@ -282,37 +296,9 @@ export function useSessionListActions({ profileScope }: UseSessionListActionsArg[refreshSessions])- // ALL-profiles view pages one profile at a time: fetch that profile's next- // page and merge it in place, leaving every other profile's rows untouched.- const loadMoreSessionsForProfile = useCallback(async (profile: string) => {- const key = normalizeProfileKey(profile)- const inKey = (s: SessionInfo) => normalizeProfileKey(s.profile) === key- const loaded = $sessions.get().filter(inKey).length-- const result = await listAllProfileSessions(loaded + SIDEBAR_SESSIONS_PAGE_SIZE, 1, 'exclude', 'recent', key, {- excludeSources: SIDEBAR_EXCLUDED_SOURCES- })-- const keep = sessionsToKeep(key)-- setSessions(prev => [- ...prev.filter(s => !inKey(s)),- ...mergeSessionPage(prev.filter(inKey), result.sessions, keep)- ])-- // A full window back means the profile still has more on disk — but pinned- // rows arrive as a back-fill PAST the limit, so counting them fakes a full- // page and the "Load more" never goes away (it re-fetches the same rows- // forever). Only unpinned rows count toward the window.- const unpinned = result.sessions.filter(s => !s.pinned).length- const truncated = unpinned >= loaded + SIDEBAR_SESSIONS_PAGE_SIZE- setSessionProfilesTruncated(prev => ({ ...prev, [key]: truncated }))- }, [])-return {loadMoreMessagingForPlatform,loadMoreSessions,- loadMoreSessionsForProfile,refreshCronJobs,refreshMessagingSessions,refreshSessionsdiff --git a/apps/desktop/src/hermes.ts b/apps/desktop/src/hermes.tsindex 83c5d06cfac..24a31273317 100644--- a/apps/desktop/src/hermes.ts+++ b/apps/desktop/src/hermes.ts@@ -462,6 +462,9 @@ export interface SidebarSessionSlice {/** 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. Thediff --git a/apps/desktop/src/store/gateway-switch.ts b/apps/desktop/src/store/gateway-switch.tsindex 19928dc64f6..0338f06bc4c 100644--- a/apps/desktop/src/store/gateway-switch.ts+++ b/apps/desktop/src/store/gateway-switch.ts@@ -17,6 +17,7 @@ import {setMessagingTruncated,setSelectedStoredSessionId,setSessionProfilesTruncated,+ setSessionProfilesUsage,setSessions,setSessionsLoading} from '@/store/session'@@ -50,6 +51,7 @@ export function wipeSessionListsForGatewaySwitch(): void {resetSessionPinMirror()setSessions([])setSessionProfilesTruncated({})+ setSessionProfilesUsage({})setCronSessions([])setMessagingSessions([])setMessagingPlatformTotals({})diff --git a/apps/desktop/src/store/layout-sidebar-view.test.ts b/apps/desktop/src/store/layout-sidebar-view.test.tsnew file mode 100644index 00000000000..bb05bd78b95--- /dev/null+++ b/apps/desktop/src/store/layout-sidebar-view.test.ts@@ -0,0 +1,67 @@+import { beforeEach, describe, expect, it } from 'vitest'++import {+ $sidebarGrouping,+ $sidebarOrdering,+ $sidebarRowMeta,+ $sidebarViewCustomized,+ resetSidebarView,+ setSidebarGrouping,+ setSidebarOrdering,+ toggleSidebarRowMeta,+ toggleSidebarStatusFilter+} from './layout'+import { $showAllProfiles } from './profile'++beforeEach(() => {+ $showAllProfiles.set(false)+ resetSidebarView()+})++describe('the sidebar as it ships', () => {+ it('groups by date, sorts by recency, and pins the timestamp', () => {+ expect($sidebarGrouping.get()).toBe('date')+ expect($sidebarOrdering.get()).toBe('updated')+ expect($sidebarRowMeta.get()).toEqual(['updated'])+ })++ it('offers no reset until something actually moves off the defaults', () => {+ expect($sidebarViewCustomized.get()).toBe(false)++ toggleSidebarRowMeta('tokens')++ expect($sidebarViewCustomized.get()).toBe(true)+ })++ it('is what reset puts back — every knob, not just the filters', () => {+ setSidebarGrouping('project')+ setSidebarOrdering('cost')+ toggleSidebarRowMeta('updated')+ toggleSidebarRowMeta('cost')+ toggleSidebarStatusFilter('working')++ resetSidebarView()++ expect($sidebarGrouping.get()).toBe('date')+ expect($sidebarOrdering.get()).toBe('updated')+ expect($sidebarRowMeta.get()).toEqual(['updated'])+ expect($sidebarViewCustomized.get()).toBe(false)+ })++ it('resets to the all-profiles default while that scope is on', () => {+ $showAllProfiles.set(true)+ setSidebarGrouping('status')++ resetSidebarView()++ expect($sidebarGrouping.get()).toBe('profile')+ expect($sidebarViewCustomized.get()).toBe(false)+ })++ it('turns all-profiles on when the user groups by profile, since that is the ask', () => {+ setSidebarGrouping('profile')++ expect($showAllProfiles.get()).toBe(true)+ expect($sidebarGrouping.get()).toBe('profile')+ })+})diff --git a/apps/desktop/src/store/layout.ts b/apps/desktop/src/store/layout.tsindex 52d04795fd2..ad8dd4abab0 100644--- a/apps/desktop/src/store/layout.ts+++ b/apps/desktop/src/store/layout.ts@@ -8,6 +8,7 @@ import { type Codec, Codecs, persistentAtom } from '@/lib/persisted'import { arraysEqual, insertUniqueId, readKey } from '@/lib/storage'import { $paneStates, ensurePaneRegistered, setPaneOpen, setPaneWidthOverride, togglePane } from './panes'+import { $showAllProfiles, setShowAllProfiles } from './profile'import type { PullRequestBucket } from './pull-requests'import type { SessionStatusBucket } from './session-dot-state'@@ -33,11 +34,13 @@ const SIDEBAR_MESSAGING_OPEN_STORAGE_KEY = 'hermes.desktop.sidebarMessagingOpen'const SIDEBAR_SESSION_ORDER_STORAGE_KEY = 'hermes.desktop.sessionOrder'const SIDEBAR_SESSION_ORDER_MANUAL_STORAGE_KEY = 'hermes.desktop.sessionOrder.manual'const SIDEBAR_GROUPING_STORAGE_KEY = 'hermes.desktop.sidebarGrouping'+const SIDEBAR_ALL_PROFILES_GROUPING_STORAGE_KEY = 'hermes.desktop.sidebarGrouping.allProfiles'const SIDEBAR_SORT_KEY_STORAGE_KEY = 'hermes.desktop.sidebarSortKey'const SIDEBAR_ROW_META_STORAGE_KEY = 'hermes.desktop.sidebarRowMeta'const SIDEBAR_STATUS_FILTER_STORAGE_KEY = 'hermes.desktop.sidebarStatusFilter'const SIDEBAR_SHOW_ARCHIVED_STORAGE_KEY = 'hermes.desktop.sidebarShowArchived'const SIDEBAR_PROJECT_FILTER_STORAGE_KEY = 'hermes.desktop.sidebarProjectFilter'+const SIDEBAR_PROFILE_FILTER_STORAGE_KEY = 'hermes.desktop.sidebarProfileFilter'const SIDEBAR_PR_FILTER_STORAGE_KEY = 'hermes.desktop.sidebarPrFilter'const SIDEBAR_WORKSPACE_ORDER_STORAGE_KEY = 'hermes.desktop.workspaceOrder'const SIDEBAR_WORKSPACE_PARENT_ORDER_STORAGE_KEY = 'hermes.desktop.workspaceParentOrder'@@ -201,8 +204,9 @@ export const $sidebarMessagingOpenIds = persistentAtom(export const $sidebarAgentsGrouped = persistentAtom(SIDEBAR_AGENTS_GROUPED_STORAGE_KEY, false, Codecs.bool)/** How the recents list is divided. `date` is the sidebar's long-standing- * default (Today / Yesterday / Last week dividers). */-export type SidebarGrouping = 'date' | 'project' | 'status'+ * default (Today / Yesterday / Last week dividers). `profile` only means+ * anything while the sidebar is showing every profile at once. */+export type SidebarGrouping = 'date' | 'profile' | 'project' | 'status'/** What ranks rows within whatever grouping is active. */export type SidebarOrdering = 'cost' | 'created' | 'manual' | 'status' | 'tokens' | 'updated'/** The sort keys the menu offers; `manual` is entered by dragging, not picked. */@@ -239,13 +243,44 @@ const $sidebarFlatGrouping = persistentAtom<SidebarGrouping>(oneOf(['date', 'status'], 'date'))+// All-profiles keeps its own grouping. The two scopes want different answers —+// one profile's chats read best by day, everyone's read best by owner — and a+// shared atom would either drag `profile` into a scope where it means nothing+// or reset the choice every time the user flips the rail.+const $sidebarAllProfilesGrouping = persistentAtom<SidebarGrouping>(+ SIDEBAR_ALL_PROFILES_GROUPING_STORAGE_KEY,+ 'profile',+ oneOf(['date', 'profile', 'status'], 'profile')+)++/** What the active scope groups by before the user touches anything. */+export const $sidebarDefaultGrouping: ReadableAtom<SidebarGrouping> = computed([$showAllProfiles], showAll =>+ showAll ? 'profile' : 'date'+)++// The sidebar as it ships. Declared once so the atoms below, "Reset to+// defaults" and the "has this view been customized?" check can't drift apart —+// they used to inline the same literals in three places.+const SIDEBAR_DEFAULT_ORDERING: SidebarOrdering = 'updated'+const SIDEBAR_DEFAULT_ROW_META: SidebarRowMeta[] = ['updated']+const $sidebarSortKey = persistentAtom<SidebarSortKey>(SIDEBAR_SORT_KEY_STORAGE_KEY,'updated',oneOf(SIDEBAR_SORT_KEYS, 'updated'))-export const $sidebarRowMeta = persistentAtom<SidebarRowMeta[]>(SIDEBAR_ROW_META_STORAGE_KEY, [], listOf(ROW_META))+export const $sidebarRowMeta = persistentAtom<SidebarRowMeta[]>(+ SIDEBAR_ROW_META_STORAGE_KEY,+ SIDEBAR_DEFAULT_ROW_META,+ listOf(ROW_META)+)++/** Order-insensitive: the menu appends in click order, so ['tokens','updated']+ * and ['updated','tokens'] are the same view. */+function sameRowMeta(a: SidebarRowMeta[], b: SidebarRowMeta[]): boolean {+ return a.length === b.length && a.every(id => b.includes(id))+}// Archived sessions are a separate backend query (`archived: 'only'`), so this// flag both filters the list and drives the fetch.@@ -265,6 +300,14 @@ export const $sidebarProjectFilter = persistentAtom(Codecs.stringArray)+// Profile names, as `normalizeProfileKey` reports them. Only bites while the+// sidebar is showing every profile — scoped to one, the scope is the filter.+export const $sidebarProfileFilter = persistentAtom(+ SIDEBAR_PROFILE_FILTER_STORAGE_KEY,+ [] as string[],+ Codecs.stringArray+)+// Whether a session's branch has a PR, and in what state. Fetched per repo via// `gh` (see store/pull-requests), so this is empty on backends without a local// checkout — the menu hides the submenu rather than offering a dead filter.@@ -275,8 +318,8 @@ export const $sidebarPrFilter = persistentAtom<PullRequestBucket[]>()export const $sidebarGrouping: ReadableAtom<SidebarGrouping> = computed(- [$sidebarAgentsGrouped, $sidebarFlatGrouping],- (grouped, grouping) => (grouped ? 'project' : grouping)+ [$sidebarAgentsGrouped, $sidebarFlatGrouping, $sidebarAllProfilesGrouping, $showAllProfiles],+ (grouped, flat, allProfiles, showAll) => (grouped ? 'project' : showAll ? allProfiles : flat))// A hand-dragged order outranks any sort key — dragging IS how you pick manual,@@ -287,17 +330,21 @@ export const $sidebarOrdering: ReadableAtom<SidebarOrdering> = computed()export const $sidebarFiltersActive: ReadableAtom<boolean> = computed(- [$sidebarStatusFilter, $sidebarProjectFilter, $sidebarPrFilter, $sidebarShowArchived],- (statuses, projects, prs, archived) => statuses.length > 0 || projects.length > 0 || prs.length > 0 || archived+ [$sidebarStatusFilter, $sidebarProjectFilter, $sidebarProfileFilter, $sidebarPrFilter, $sidebarShowArchived],+ (statuses, projects, profiles, prs, archived) =>+ statuses.length > 0 || projects.length > 0 || profiles.length > 0 || prs.length > 0 || archived)/** Anything at all moved off the shipped view — what makes a reset worth* offering. Broader than `$sidebarFiltersActive`, which only knows about what* hides rows, not about how they're grouped, sorted or labelled. */export const $sidebarViewCustomized: ReadableAtom<boolean> = computed(- [$sidebarGrouping, $sidebarOrdering, $sidebarRowMeta, $sidebarFiltersActive],- (grouping, ordering, rowMeta, filtersActive) =>- grouping !== 'date' || ordering !== 'updated' || rowMeta.length > 0 || filtersActive+ [$sidebarGrouping, $sidebarDefaultGrouping, $sidebarOrdering, $sidebarRowMeta, $sidebarFiltersActive],+ (grouping, defaultGrouping, ordering, rowMeta, filtersActive) =>+ grouping !== defaultGrouping ||+ ordering !== SIDEBAR_DEFAULT_ORDERING ||+ !sameRowMeta(rowMeta, SIDEBAR_DEFAULT_ROW_META) ||+ filtersActive)// When true, the sessions sidebar moves to the right and the file browser +@@ -494,9 +541,27 @@ export function setSidebarAgentsGrouped(grouped: boolean) {export function setSidebarGrouping(grouping: SidebarGrouping) {setSidebarAgentsGrouped(grouping === 'project')- if (grouping !== 'project') {- $sidebarFlatGrouping.set(grouping)+ if (grouping === 'project') {+ return+ }++ // Grouping by owner is a request to see every owner, so it turns the+ // all-profiles view on rather than drawing one group around one profile.+ // (The flat scope's atom can't hold 'profile' at all.)+ if (grouping === 'profile') {+ setShowAllProfiles(true)+ $sidebarAllProfilesGrouping.set(grouping)++ return+ }++ if ($showAllProfiles.get()) {+ $sidebarAllProfilesGrouping.set(grouping)++ return}++ $sidebarFlatGrouping.set(grouping)}export function setSidebarOrdering(ordering: SidebarOrdering) {@@ -535,6 +600,10 @@ export function toggleSidebarProjectFilter(projectId: string) {toggleIn($sidebarProjectFilter, projectId)}+export function toggleSidebarProfileFilter(profile: string) {+ toggleIn($sidebarProfileFilter, profile)+}+export function toggleSidebarPrFilter(bucket: PullRequestBucket) {toggleIn($sidebarPrFilter, bucket)}@@ -542,17 +611,17 @@ export function toggleSidebarPrFilter(bucket: PullRequestBucket) {function clearSidebarFilters() {$sidebarStatusFilter.set([])$sidebarProjectFilter.set([])+ $sidebarProfileFilter.set([])$sidebarPrFilter.set([])$sidebarShowArchived.set(false)}-/** Every knob the filter menu owns, back to the sidebar as it ships: date- * groups, newest first, no extra row metadata, no filters. Ordering goes- * through its setter so a hand-dragged sequence is dropped along with it. */+/** Every knob the filter menu owns, back to the sidebar as it ships. Ordering+ * goes through its setter so a hand-dragged sequence is dropped along with it. */export function resetSidebarView() {- setSidebarGrouping('date')- setSidebarOrdering('updated')- $sidebarRowMeta.set([])+ setSidebarGrouping($sidebarDefaultGrouping.get())+ setSidebarOrdering(SIDEBAR_DEFAULT_ORDERING)+ $sidebarRowMeta.set(SIDEBAR_DEFAULT_ROW_META)clearSidebarFilters()}diff --git a/apps/desktop/src/store/projects.ts b/apps/desktop/src/store/projects.tsindex 5d7a0a222d6..a810eb7b0ee 100644--- a/apps/desktop/src/store/projects.ts+++ b/apps/desktop/src/store/projects.ts@@ -16,7 +16,7 @@ import { persistentAtom } from '@/lib/persisted'import { $gateway, activeGateway, ensureActiveGatewayOpen } from '@/store/gateway'import { setSidebarAgentsGrouped } from '@/store/layout'import { notify } from '@/store/notifications'-import { $activeGatewayProfile, requestFreshSession } from '@/store/profile'+import { $activeGatewayProfile, $profileScope, ALL_PROFILES, requestFreshSession } from '@/store/profile'import {$selectedStoredSessionId,$sessions,@@ -392,8 +392,33 @@ interface ProjectTreePayload {scoped_session_ids: string[]}+const PROJECT_TREE_PREVIEW_LIMIT = 3+// The all-profiles fan-out reads one database per profile, so it is allowed the+// same headroom as the cross-profile session list rather than the interactive+// default.+const PROJECT_TREE_REQUEST_TIMEOUT_MS = 60_000+let projectTreeRefreshGeneration = 0+function applyProjectTreePayload(res: ProjectTreePayload): void {+ const scoped = new Set(res.scoped_session_ids ?? [])+ $projectTree.set(res.projects ?? [])+ $activeProjectId.set(res.active_id ?? null)+ const tombstones = $removedSessionIds.get()++ if (tombstones.size) {+ // Keep a tombstone while the backend still lists the id (delete pending on+ // its side) OR while its mutation is still in flight locally — dropping it+ // early flashes the row back until the RPC lands.+ const inFlight = $sessionMutationsInFlight.get()+ const pending = new Set([...tombstones].filter(id => scoped.has(id) || inFlight.has(id)))++ if (pending.size !== tombstones.size) {+ $removedSessionIds.set(pending)+ }+ }+}+async function refreshProjectTreeOn(gateway: HermesGateway): Promise<void> {const generation = ++projectTreeRefreshGeneration@@ -403,30 +428,14 @@ async function refreshProjectTreeOn(gateway: HermesGateway): Promise<void> {try {const res = await gatewayRequestOn<ProjectTreePayload>(gateway, 'projects.tree', {- preview_limit: 3+ preview_limit: PROJECT_TREE_PREVIEW_LIMIT})if (generation !== projectTreeRefreshGeneration || activeGateway() !== gateway) {return}- const scoped = new Set(res.scoped_session_ids ?? [])- $projectTree.set(res.projects ?? [])- $activeProjectId.set(res.active_id ?? null)- const tombstones = $removedSessionIds.get()-- if (tombstones.size) {- // Keep a tombstone while the backend still lists the id (delete pending on- // its side) OR while its mutation is still in flight locally — dropping it- // early flashes the row back until the RPC lands.- const inFlight = $sessionMutationsInFlight.get()- const pending = new Set([...tombstones].filter(id => scoped.has(id) || inFlight.has(id)))-- if (pending.size !== tombstones.size) {- $removedSessionIds.set(pending)- }- }-+ applyProjectTreePayload(res)markProjectsRpcSuccess()} catch (err) {if (activeGateway() === gateway) {@@ -443,6 +452,12 @@ async function refreshProjectTreeOn(gateway: HermesGateway): Promise<void> {// sessions + the scoped-session-id set). Best-effort: a failure leaves the// cached tree intact so the sidebar doesn't flicker.export async function refreshProjectTree(): Promise<void> {+ if ($profileScope.get() === ALL_PROFILES) {+ await refreshProjectTreeAcrossProfiles()++ return+ }+try {const { gateway } = await activeProjectsContext()await refreshProjectTreeOn(gateway)@@ -451,6 +466,37 @@ export async function refreshProjectTree(): Promise<void> {}}+// The grouped sidebar in all-profiles mode. `projects.tree` answers for one+// backend's own profile, so it can only ever describe a slice of this view;+// the REST fan-out reads every profile's databases directly instead of asking+// us to hold a backend open per profile just to draw lanes.+async function refreshProjectTreeAcrossProfiles(): Promise<void> {+ const generation = ++projectTreeRefreshGeneration+ $projectTreeLoading.set(true)++ try {+ const res = await window.hermesDesktop.api<ProjectTreePayload>({+ path: `/api/profiles/projects/tree?preview_limit=${PROJECT_TREE_PREVIEW_LIMIT}`,+ timeoutMs: PROJECT_TREE_REQUEST_TIMEOUT_MS+ })++ // A profile switch mid-flight leaves this payload describing the wrong+ // scope; the newer refresh owns the tree.+ if (generation !== projectTreeRefreshGeneration || $profileScope.get() !== ALL_PROFILES) {+ return+ }++ applyProjectTreePayload(res)+ markProjectsRpcSuccess()+ } catch (err) {+ markProjectsRpcFailure(err)+ } finally {+ if (generation === projectTreeRefreshGeneration) {+ $projectTreeLoading.set(false)+ }+ }+}+// Fully hydrated lanes (repo -> lane -> session rows) for one project, fetched// when the user enters it. Same backend grouping as `projects.tree`, so ids and// membership match exactly.@@ -617,7 +663,10 @@ export async function scanAndRecordRepos(force = false): Promise<void> {}state.completedSignature = signature- await refreshProjectTreeOn(context.gateway)+ // Scope-aware on purpose: the scan records into one profile, but folding+ // its result back in through the active scope keeps an all-profiles tree+ // from being overwritten by the scanned profile's own.+ await refreshProjectTree()} catch {state.completedSignature = undefined} finally {diff --git a/apps/desktop/src/store/session-pin-sync.test.ts b/apps/desktop/src/store/session-pin-sync.test.tsindex 494650ad7e6..634b2b09be6 100644--- a/apps/desktop/src/store/session-pin-sync.test.ts+++ b/apps/desktop/src/store/session-pin-sync.test.ts@@ -7,6 +7,9 @@ const patch = vi.fn<(id: string, pinned: boolean, profile?: null | string) => Pr)vi.mock('@/hermes', () => ({+ // The layout store reaches the profile store, which sets the request profile+ // at import time; this suite only cares about the pin call.+ setApiRequestProfile: () => {},setSessionPinnedRemote: (id: string, pinned: boolean, profile?: null | string) => patch(id, pinned, profile)}))diff --git a/apps/desktop/src/store/session.ts b/apps/desktop/src/store/session.tsindex a8024c0739f..794e7be61e4 100644--- a/apps/desktop/src/store/session.ts+++ b/apps/desktop/src/store/session.ts@@ -482,6 +482,16 @@ export const $messagingTruncated = atom<boolean>(false)// "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>>({})++/** Tokens and spend per profile across ALL its sessions, not just the loaded+ * page — summed in SQL so a profile group's header total doesn't move when the+ * window does. Keyed by profile name. */+export interface ProfileUsage {+ cost_usd: number+ tokens: number+}++export const $sessionProfilesUsage = atom<Record<string, ProfileUsage>>({})export const $sessionsLoading = atom(true)export const $activeSessionId = atom<string | null>(null)export const $selectedStoredSessionId = atom<string | null>(null)@@ -594,6 +604,8 @@ export const setMessagingPlatformTotals = (next: Updater<Record<string, number>>export const setMessagingTruncated = (next: Updater<boolean>) => updateAtom($messagingTruncated, next)export const setSessionProfilesTruncated = (next: Updater<Record<string, boolean>>) =>updateAtom($sessionProfilesTruncated, next)+export const setSessionProfilesUsage = (next: Updater<Record<string, ProfileUsage>>) =>+ updateAtom($sessionProfilesUsage, 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>) =>