Skip to content

The agent that grows with you

feat(desktop): sidebar filter menu

Brooklyn Nicholson83b8ca1e12c5
diff --git a/apps/desktop/src/app/chat/session-status-dot.tsx b/apps/desktop/src/app/chat/session-status-dot.tsx
index ab808866a8b..22dbae7ee3c 100644
--- a/apps/desktop/src/app/chat/session-status-dot.tsx
+++ b/apps/desktop/src/app/chat/session-status-dot.tsx
@@ -83,6 +83,11 @@ const DOT_VARIANTS: Record<SessionDotState, DotVariant> = {
}
}
+/** The dot a state paints, for surfaces that describe a status rather than
+ * render a session — the sidebar's status filter, say. Idle carries no color
+ * of its own (it inherits the project's), so callers supply one. */
+export const sessionDotClassName = (state: SessionDotState): string => DOT_VARIANTS[state].className
+
export interface SessionStatusDotProps {
/** The STORED session id — the key every live-state atom (working /
* attention / stalled / unread / background) is keyed by, on BOTH surfaces:
diff --git a/apps/desktop/src/app/chat/sidebar/chrome.tsx b/apps/desktop/src/app/chat/sidebar/chrome.tsx
index d931c323de8..5adf70a20e2 100644
--- a/apps/desktop/src/app/chat/sidebar/chrome.tsx
+++ b/apps/desktop/src/app/chat/sidebar/chrome.tsx
@@ -36,7 +36,7 @@ export function SidebarRowStack({ className, ...props }: React.ComponentProps<'d
/** Nested rows (session previews, worktree bodies). */
export function SidebarRowNest({ className, ...props }: React.ComponentProps<'div'>) {
- return <SidebarRowStack className={cn('pb-1 pl-4', className)} {...props} />
+ return <SidebarRowStack className={cn('pb-1 pl-2', className)} {...props} />
}
/**
@@ -44,13 +44,21 @@ export function SidebarRowNest({ className, ...props }: React.ComponentProps<'di
* the session list. One flat row — a small caption plus a hairline rule — so it
* groups sessions by recency without adding a level of indentation.
*/
-export function SidebarDateDivider({ className, label, ...props }: React.ComponentProps<'div'> & { label: string }) {
+export function SidebarDateDivider({
+ action,
+ className,
+ label,
+ ...props
+}: React.ComponentProps<'div'> & { action?: React.ReactNode; label: string }) {
return (
- <div className={cn('flex select-none items-center gap-2 px-2 pb-0.5 pt-2', className)} {...props}>
+ // group/workspace: a divider heads a group the same way a repo header does,
+ // so it borrows the header's hover-revealed "+" verbatim.
+ <div className={cn('group/workspace flex select-none items-center gap-2 px-2 pb-0.5 pt-2', className)} {...props}>
<span className="shrink-0 text-[0.64rem] font-semibold uppercase tracking-[0.12em] text-(--ui-text-quaternary)">
{label}
</span>
<span aria-hidden="true" className="h-px flex-1 bg-(--ui-stroke-tertiary)" />
+ {action}
</div>
)
}
diff --git a/apps/desktop/src/app/chat/sidebar/filter-menu.tsx b/apps/desktop/src/app/chat/sidebar/filter-menu.tsx
new file mode 100644
index 00000000000..2bb1e247c8b
--- /dev/null
+++ b/apps/desktop/src/app/chat/sidebar/filter-menu.tsx
@@ -0,0 +1,346 @@
+import { useStore } from '@nanostores/react'
+
+import { sessionDotClassName } from '@/app/chat/session-status-dot'
+import { Button } from '@/components/ui/button'
+import { Codicon } from '@/components/ui/codicon'
+import {
+ DropdownMenu,
+ DropdownMenuCheckboxItem,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+ DropdownMenuTrigger
+} from '@/components/ui/dropdown-menu'
+import { useI18n } from '@/i18n'
+import { desktopGit } from '@/lib/desktop-git'
+import { cn } from '@/lib/utils'
+import {
+ $sidebarFiltersActive,
+ $sidebarGrouping,
+ $sidebarOrdering,
+ $sidebarPrFilter,
+ $sidebarProjectFilter,
+ $sidebarRowMeta,
+ $sidebarShowArchived,
+ $sidebarStatusFilter,
+ $sidebarViewCustomized,
+ $sidebarWorkspaceNodeOpen,
+ resetSidebarView,
+ setSidebarGrouping,
+ setSidebarOrdering,
+ setSidebarShowArchived,
+ setWorkspaceNodesOpen,
+ type SidebarGrouping,
+ type SidebarOrdering,
+ type SidebarRowMeta,
+ toggleSidebarPrFilter,
+ toggleSidebarProjectFilter,
+ toggleSidebarRowMeta,
+ toggleSidebarStatusFilter
+} from '@/store/layout'
+import { $projectTree } from '@/store/projects'
+import type { PullRequestBucket } from '@/store/pull-requests'
+import { $unreadFinishedSessionIds, markAllSessionsRead } from '@/store/session'
+import type { SessionStatusBucket } from '@/store/session-dot-state'
+import { $sessionsHaveCost } from '@/store/sidebar-archive'
+
+interface Option<T extends string = string> {
+ /** A status dot's full className, from the row's own vocabulary. */
+ dot?: string
+ icon?: string
+ id: T
+ label: string
+}
+
+const GROUPINGS: Option<SidebarGrouping>[] = [
+ { icon: 'clock', id: 'date', label: 'Updated' },
+ { icon: 'root-folder', id: 'project', label: 'Project' },
+ { icon: 'pulse', id: 'status', label: 'Status' }
+]
+
+const ORDERINGS: Option<SidebarOrdering>[] = [
+ { icon: 'clock', id: 'updated', label: 'Updated' },
+ { icon: 'add', id: 'created', label: 'Created' },
+ { icon: 'pulse', id: 'status', label: 'Status' },
+ { icon: 'symbol-numeric', id: 'tokens', label: 'Tokens' },
+ { icon: 'credit-card', id: 'cost', label: 'Cost' },
+ { icon: 'list-ordered', id: 'manual', label: 'Manual' }
+]
+
+const ROW_META: Option<SidebarRowMeta>[] = [
+ { icon: 'clock', id: 'updated', label: 'Updated' },
+ { icon: 'symbol-numeric', id: 'tokens', label: 'Tokens' },
+ { icon: 'credit-card', id: 'cost', label: 'Cost' },
+ { icon: 'git-pull-request', id: 'pr', label: 'PR' },
+ { icon: 'account', id: 'profile', label: 'Profile' }
+]
+
+const PR_FILTERS: Option<PullRequestBucket>[] = [
+ { icon: 'git-pull-request', id: 'open', label: 'Open' },
+ { icon: 'git-pull-request-draft', id: 'draft', label: 'Draft' },
+ { icon: 'git-merge', id: 'merged', label: 'Merged' },
+ { icon: 'git-pull-request-closed', id: 'closed', label: 'Closed' },
+ { icon: 'circle-slash', id: 'none', label: 'No PR' }
+]
+
+const STATUS_FILTERS: Option<SessionStatusBucket>[] = [
+ { dot: sessionDotClassName('needs-input'), id: 'needs-input', label: 'Needs input' },
+ { dot: sessionDotClassName('working'), id: 'working', label: 'Working' },
+ { dot: sessionDotClassName('unread'), id: 'unread', label: 'Unread' },
+ { dot: sessionDotClassName('draft'), id: 'draft', label: 'Draft' },
+ { dot: cn(sessionDotClassName('idle'), 'bg-(--ui-text-quaternary)'), id: 'idle', label: 'Idle' }
+]
+
+function OptionGlyph({ option }: { option: Option }) {
+ if (option.dot) {
+ return <span aria-hidden="true" className={cn('shrink-0', option.dot)} />
+ }
+
+ return option.icon ? <Codicon className="text-(--ui-text-tertiary)" name={option.icon} size="0.8125rem" /> : null
+}
+
+/** Every option row — single or multi select — leaves the menu open, so a whole
+ * view can be set up in one pass. Only the actions at the bottom dismiss it. */
+const keepOpen = (event: Event) => event.preventDefault()
+
+function OptionCheckbox({ checked, onCheck, option }: { checked: boolean; onCheck: () => void; option: Option }) {
+ return (
+ <DropdownMenuCheckboxItem
+ checked={checked}
+ onSelect={event => {
+ keepOpen(event)
+ onCheck()
+ }}
+ >
+ <OptionGlyph option={option} />
+ {option.label}
+ </DropdownMenuCheckboxItem>
+ )
+}
+
+function OptionRadio({ option }: { option: Option }) {
+ return (
+ <DropdownMenuRadioItem onSelect={keepOpen} value={option.id}>
+ <OptionGlyph option={option} />
+ {option.label}
+ </DropdownMenuRadioItem>
+ )
+}
+
+export function SidebarFilterMenu({ className }: { className?: string }) {
+ const { t } = useI18n()
+ const grouping = useStore($sidebarGrouping)
+ const ordering = useStore($sidebarOrdering)
+ const rowMeta = useStore($sidebarRowMeta)
+ const statusFilter = useStore($sidebarStatusFilter)
+ const projectFilter = useStore($sidebarProjectFilter)
+ const prFilter = useStore($sidebarPrFilter)
+ const showArchived = useStore($sidebarShowArchived)
+ const filtersActive = useStore($sidebarFiltersActive)
+ const viewCustomized = useStore($sidebarViewCustomized)
+ const nodeOpen = useStore($sidebarWorkspaceNodeOpen)
+ const projects = useStore($projectTree)
+ const hasCost = useStore($sessionsHaveCost)
+ const unreadIds = useStore($unreadFinishedSessionIds)
+ // PR state comes from `gh` on whichever machine holds the checkout — Electron
+ // locally, the gateway's REST mirror remotely. Resolved per render, not once
+ // at module load: switching to a remote profile swaps the bridge underneath.
+ const prAvailable = Boolean(desktopGit()?.review?.prList)
+ // Project rows default open, so "all collapsed" means every one of them has
+ // been explicitly shut.
+ const projectsCollapsed = projects.length > 0 && projects.every(project => nodeOpen[project.id] === false)
+
+ const groupingLabel = GROUPINGS.find(option => option.id === grouping)?.label
+
+ // Two options are conditional: dragging a row is what picks manual, so it
+ // only appears as a way back out once there's a hand-picked order to leave;
+ // and cost is hidden until some session actually reports spend.
+ const orderings = ORDERINGS.filter(option => {
+ if (option.id === 'manual') {
+ return ordering === 'manual'
+ }
+
+ return option.id !== 'cost' || hasCost || ordering === 'cost'
+ })
+
+ const rowMetaOptions = ROW_META.filter(option => {
+ if (option.id === 'cost') {
+ return hasCost || rowMeta.includes('cost')
+ }
+
+ return option.id !== 'pr' || prAvailable
+ })
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ aria-label="Filters"
+ className={cn(
+ className,
+ 'data-[state=open]:bg-(--ui-control-active-background) data-[state=open]:text-foreground data-[state=open]:opacity-100',
+ // Active filters read as "this control is engaged", the same way the
+ // open menu does — never as an accent, which the sidebar reserves
+ // for a session that is actually doing something.
+ filtersActive && 'bg-(--ui-control-active-background) text-foreground opacity-100'
+ )}
+ size="icon-xs"
+ type="button"
+ variant="ghost"
+ >
+ <Codicon name="list-filter" size="0.75rem" />
+ </Button>
+ </DropdownMenuTrigger>
+
+ <DropdownMenuContent align="start" className="min-w-52">
+ <DropdownMenuGroup>
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger hideChevron>
+ Grouping
+ <span className="ml-auto flex items-center gap-1 pl-4 text-(--ui-text-tertiary)">
+ {groupingLabel}
+ <Codicon name="chevron-right" size="1rem" />
+ </span>
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent>
+ <DropdownMenuRadioGroup
+ onValueChange={value => setSidebarGrouping(value as SidebarGrouping)}
+ value={grouping}
+ >
+ {GROUPINGS.map(option => (
+ <OptionRadio key={option.id} option={option} />
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>Ordering</DropdownMenuSubTrigger>
+ <DropdownMenuSubContent>
+ <DropdownMenuRadioGroup
+ onValueChange={value => setSidebarOrdering(value as SidebarOrdering)}
+ value={ordering}
+ >
+ {orderings.map(option => (
+ <OptionRadio key={option.id} option={option} />
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>Show</DropdownMenuSubTrigger>
+ <DropdownMenuSubContent>
+ {rowMetaOptions.map(option => (
+ <OptionCheckbox
+ checked={rowMeta.includes(option.id)}
+ key={option.id}
+ onCheck={() => toggleSidebarRowMeta(option.id)}
+ option={option}
+ />
+ ))}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ </DropdownMenuGroup>
+
+ <DropdownMenuSeparator />
+
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>Filters</DropdownMenuLabel>
+
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>Status</DropdownMenuSubTrigger>
+ <DropdownMenuSubContent>
+ {STATUS_FILTERS.map(option => (
+ <OptionCheckbox
+ checked={statusFilter.includes(option.id)}
+ key={option.id}
+ onCheck={() => toggleSidebarStatusFilter(option.id)}
+ option={option}
+ />
+ ))}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+
+ {/* `gh` only exists where the checkout does, so on a remote backend
+ this submenu never appears rather than filtering everything out. */}
+ {prAvailable && (
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>Pull request</DropdownMenuSubTrigger>
+ <DropdownMenuSubContent>
+ {PR_FILTERS.map(option => (
+ <OptionCheckbox
+ checked={prFilter.includes(option.id)}
+ key={option.id}
+ onCheck={() => toggleSidebarPrFilter(option.id)}
+ option={option}
+ />
+ ))}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ )}
+
+ {projects.length > 1 && (
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>Project</DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="max-h-80 overflow-y-auto">
+ {projects.map(project => (
+ <OptionCheckbox
+ checked={projectFilter.includes(project.id)}
+ key={project.id}
+ onCheck={() => toggleSidebarProjectFilter(project.id)}
+ option={{
+ icon: project.isNoProject ? 'home' : 'root-folder',
+ id: project.id,
+ // Home is synthetic, so its label is ours to translate.
+ label: project.isNoProject ? t.sidebar.projects.home : project.label
+ }}
+ />
+ ))}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ )}
+
+ <OptionCheckbox
+ checked={showArchived}
+ onCheck={() => setSidebarShowArchived(!showArchived)}
+ option={{ id: 'archived', label: 'Archived' }}
+ />
+
+ {/* One way back rather than two near-identical ones: this drops the
+ grouping and sort too, which "clear filters" left behind. */}
+ {viewCustomized && <DropdownMenuItem onSelect={resetSidebarView}>Reset to defaults</DropdownMenuItem>}
+ </DropdownMenuGroup>
+
+ <DropdownMenuSeparator />
+
+ {/* Only the project rows fold, and only when they're what you're
+ looking at — sweeping Pinned and Cron shut alongside them is not
+ what "collapse all" means here. Their lanes underneath keep their
+ own state, so re-opening a project shows it as you left it. */}
+ {grouping === 'project' && projects.length > 0 && (
+ <DropdownMenuItem
+ onSelect={() =>
+ setWorkspaceNodesOpen(
+ projects.map(project => project.id),
+ projectsCollapsed
+ )
+ }
+ >
+ {projectsCollapsed ? 'Expand all' : 'Collapse all'}
+ </DropdownMenuItem>
+ )}
+ <DropdownMenuItem disabled={unreadIds.length === 0} onSelect={markAllSessionsRead}>
+ Mark all as read
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
+}
diff --git a/apps/desktop/src/app/chat/sidebar/index.tsx b/apps/desktop/src/app/chat/sidebar/index.tsx
index 33090ed4886..d22f84e0bc2 100644
--- a/apps/desktop/src/app/chat/sidebar/index.tsx
+++ b/apps/desktop/src/app/chat/sidebar/index.tsx
@@ -36,21 +36,27 @@ import {
$dismissedAutoProjectIds,
$panesFlipped,
$pinnedSessionIds,
- $sidebarAgentsGrouped,
$sidebarCronOpen,
+ $sidebarFiltersActive,
+ $sidebarGrouping,
$sidebarMessagingOpenIds,
+ $sidebarOrdering,
$sidebarPinsOpen,
+ $sidebarPrDataWanted,
+ $sidebarPrFilter,
+ $sidebarProjectFilter,
$sidebarProjectOrderIds,
$sidebarRecentsOpen,
$sidebarSessionOrderIds,
$sidebarSessionOrderManual,
+ $sidebarShowArchived,
+ $sidebarStatusFilter,
$sidebarWorkspaceOrderIds,
$sidebarWorkspaceParentOrderIds,
filterVisibleProjects,
pinSession,
SESSION_SEARCH_FOCUS_EVENT,
setPinnedSessionOrder,
- setSidebarAgentsGrouped,
setSidebarCronOpen,
setSidebarPinsOpen,
setSidebarProjectOrderIds,
@@ -82,6 +88,14 @@ import {
refreshWorktrees,
scanAndRecordRepos
} from '@/store/projects'
+import {
+ $prBranchBySession,
+ $pullRequestsByBranch,
+ pullRequestBucket,
+ recoverSessionPullRequests,
+ refreshPullRequests,
+ sessionPrKey
+} from '@/store/pull-requests'
import { openRouteTile } from '@/store/route-tiles'
import {
$cronSessions,
@@ -96,7 +110,9 @@ import {
sessionPinId,
setCurrentCwd
} from '@/store/session'
+import { $sessionDotStateById, sessionStatusBucket, sessionStatusRank } from '@/store/session-dot-state'
import { $focusedStoredSessionId, $workingSessionIds, type SplitDir } from '@/store/session-states'
+import { $archivedSessions, loadArchivedSessions, sessionCostUsd } from '@/store/sidebar-archive'
import {
type AppView,
@@ -109,12 +125,14 @@ import {
import type { SidebarNavItem } from '../../types'
import { SidebarCronJobsSection } from './cron-jobs-section'
+import { SidebarFilterMenu } from './filter-menu'
import { SidebarLoadMoreRow } from './load-more-row'
import { orderByIds, reconcileOrderIds, resolveManualSessionOrderIds, sameIds } from './order'
import { ProfileRail } from './profile-switcher'
import { ProjectDialog } from './project-dialog'
import {
excludeProjectSessions,
+ liveSessionProjectId,
orderProjectsByIds,
overlayLiveLanes,
overlayLivePreviews,
@@ -142,6 +160,11 @@ import { CONTEXT_SPLIT_KIT, SplitSubmenu } from './split-submenu'
const NON_SESSION_INITIAL_ROWS = 3
const NON_SESSION_LOAD_STEP = 10
+// How long after connecting to warm the project tree for someone who isn't in
+// the grouped view. Long enough that the flat list — the thing actually on
+// screen — has the connection to itself first.
+const PROJECT_TREE_WARM_MS = 2_000
+
const SIDEBAR_NAV: SidebarNavItem[] = [
{
id: 'new-session',
@@ -183,6 +206,11 @@ const COMPACT_FLAT = 'compact:max-h-none compact:overflow-visible'
// Vertical scroll only — never a horizontal bar from glow bleed, long titles, etc.
const SCROLL_Y = 'overflow-y-auto overflow-x-hidden overscroll-contain'
+// The outer list reserves its bar's width whether or not one is showing, so
+// filtering or collapsing a section doesn't reflow every row sideways. Only the
+// outer one: nested scrollers would each reserve their own and stack the inset.
+const SCROLL_GUTTER = '[scrollbar-gutter:stable]'
+
// A non-session group's scroll body: own scroller when tall, flattened when compact.
const GROUP_BODY = cn(SCROLL_Y, COMPACT_FLAT)
@@ -287,7 +315,19 @@ export function ChatSidebar({
)
const panesFlipped = useStore($panesFlipped)
- const agentsGrouped = useStore($sidebarAgentsGrouped)
+ const grouping = useStore($sidebarGrouping)
+ const ordering = useStore($sidebarOrdering)
+ const statusFilter = useStore($sidebarStatusFilter)
+ const projectFilter = useStore($sidebarProjectFilter)
+ const prFilter = useStore($sidebarPrFilter)
+ const prDataWanted = useStore($sidebarPrDataWanted)
+ const prBranchOverrides = useStore($prBranchBySession)
+ const pullRequests = useStore($pullRequestsByBranch)
+ const filtersActive = useStore($sidebarFiltersActive)
+ const showArchived = useStore($sidebarShowArchived)
+ const archivedSessions = useStore($archivedSessions)
+ const dotStates = useStore($sessionDotStateById)
+ const agentsGrouped = grouping === 'project'
const pinnedSessionIds = useStore($pinnedSessionIds)
const pinsOpen = useStore($sidebarPinsOpen)
const agentsOpen = useStore($sidebarRecentsOpen)
@@ -381,13 +421,51 @@ export function ChatSidebar({
// that profile's sessions (clean rows, no per-row tags); ALL fans every
// profile in, grouped by profile below. Single-profile users land here with
// scope === their only profile, so nothing is filtered out.
+ // Archived rows are excluded from the sessions query, so Archived is a view of
+ // its own set rather than a filter over this one — a flat list of archived
+ // rows, no project tree, no date or status dividers.
+ const scopedSessions = useMemo(() => {
+ const pool = showArchived ? archivedSessions : sessions
+
+ return showAllProfiles ? pool : pool.filter(s => normalizeProfileKey(s.profile) === profileScope)
+ }, [sessions, archivedSessions, showArchived, showAllProfiles, profileScope])
+
+ // One predicate for the status/project filters, so the flat list and the
+ // project lanes narrow by the same rule. A project lane holds rows the loaded
+ // page may not, so it has to be answerable per session rather than by
+ // membership in the filtered set.
+ const sessionMatchesFilters = useCallback(
+ (session: SessionInfo) => {
+ if (statusFilter.length && !statusFilter.includes(sessionStatusBucket(dotStates[session.id]))) {
+ return false
+ }
+
+ if (prFilter.length) {
+ const key = sessionPrKey(session)
+
+ if (!prFilter.includes(pullRequestBucket(key ? pullRequests[key] : undefined))) {
+ return false
+ }
+ }
+
+ // Same membership the sidebar groups and colors by, so a filtered row
+ // lands in the lane the user picked it from.
+ return !projectFilter.length || projectFilter.includes(liveSessionProjectId(session, projects) ?? '')
+ },
+ [statusFilter, projectFilter, prFilter, pullRequests, projects, dotStates]
+ )
+
+ const filtersNarrow = statusFilter.length > 0 || projectFilter.length > 0 || prFilter.length > 0
+
const visibleSessions = useMemo(
- () => (showAllProfiles ? sessions : sessions.filter(s => normalizeProfileKey(s.profile) === profileScope)),
- [sessions, showAllProfiles, profileScope]
+ () => (filtersNarrow ? scopedSessions.filter(sessionMatchesFilters) : scopedSessions),
+ [scopedSessions, filtersNarrow, sessionMatchesFilters]
)
// Recents by activity (last_active || started_at). User send stamps
- // last_active immediately; manual drag order still wins below.
+ // last_active immediately. Ordering by status doesn't sort here — it re-slots
+ // rows *inside* whatever dividers are on, via sortOrderIds below — so the
+ // date buckets stay chronological either way.
const sortedSessions = useMemo(
() => [...visibleSessions].sort((a, b) => sessionTime(b) - sessionTime(a)),
[visibleSessions]
@@ -447,6 +525,14 @@ export function ChatSidebar({
[pinnedIdentitySet]
)
+ // What the project tree drops: pins (they live in their own section) plus
+ // anything the active filters exclude, so filtering works the same whether
+ // you're looking at the flat list or the lanes.
+ const isHiddenFromProjects = useCallback(
+ (session: SessionInfo) => isPinnedSession(session) || (filtersNarrow && !sessionMatchesFilters(session)),
+ [isPinnedSession, filtersNarrow, sessionMatchesFilters]
+ )
+
// Full-text search across *all* sessions (not just the loaded page) so 699
// sessions stay findable. Debounced; loaded sessions are matched instantly
// client-side and merged ahead of the server hits.
@@ -548,7 +634,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
+ const worktreeGroupingActive = agentsGrouped && !showAllProfiles && !showArchived
const gatewayReady = gatewayState === 'open'
// The backend project tree is a structural snapshot, NOT a per-message feed.
@@ -559,16 +645,107 @@ export function ChatSidebar({
// completing does NOT re-run the heavy list_sessions_rich scan. Project
// mutations refresh the tree from their own store actions.
useEffect(() => {
- if (worktreeGroupingActive && gatewayReady) {
+ if (!gatewayReady) {
+ return
+ }
+
+ if (worktreeGroupingActive) {
void refreshProjects()
// 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
// of the crawl blocking the first render.
void refreshProjectTree().finally(() => void scanAndRecordRepos())
+
+ return
}
+
+ // Flat view: warm the tree in the background anyway. Fetching it only on
+ // the switch meant the first switch of every run paid for the whole round
+ // trip behind a skeleton, and the menu's Project filter had nothing to
+ // list until you'd visited the grouped view at least once.
+ const warm = window.setTimeout(() => void refreshProjectTree(), PROJECT_TREE_WARM_MS)
+
+ return () => window.clearTimeout(warm)
}, [worktreeGroupingActive, 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
+ // whatever is loaded, whether or not the badge is on: gating it on the badge
+ // meant switching PR on showed a half-empty list until a second pass caught
+ // up. One request per batch of never-scanned rows, and the scanned set makes
+ // that batch empty from the second pass on, so this settles to nothing.
+ useEffect(() => {
+ if (!gatewayReady) {
+ return
+ }
+
+ const warm = window.setTimeout(() => void recoverSessionPullRequests(scopedSessions), PROJECT_TREE_WARM_MS)
+
+ return () => window.clearTimeout(warm)
+ }, [gatewayReady, scopedSessions])
+
+ // PR state is only fetched for someone who asked to see it — the badge or the
+ // filter — and it asks about the branches on screen, so the answer can't be
+ // crowded out by a busy repo's newer PRs.
+ const prLookupsByRepo = useMemo(() => {
+ if (!prDataWanted) {
+ return {}
+ }
+
+ const byRepo: Record<string, string[]> = {}
+
+ for (const session of scopedSessions) {
+ // The row's own key, so a session bound to a branch (or a PR number) it
+ // was stamped with asks about THAT, not the branch it started on.
+ const [root, lookup] = sessionPrKey(session)?.split('\n') ?? []
+
+ if (root && lookup && !byRepo[root]?.includes(lookup)) {
+ byRepo[root] = [...(byRepo[root] ?? []), lookup]
+ }
+ }
+
+ return byRepo
+ // prBranchOverrides is what `sessionPrKey` reads through — a recovered PR
+ // has to re-ask with the key it just learned.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [prDataWanted, scopedSessions, prBranchOverrides])
+
+ // A stable identity for "the same question as last time", so a re-render that
+ // rebuilds the map doesn't re-ask GitHub.
+ const prQueryKey = JSON.stringify(
+ Object.entries(prLookupsByRepo)
+ .map(([root, lookups]) => [root, [...lookups].sort()] as const)
+ .sort(([a], [b]) => a.localeCompare(b))
+ )
+
+ useEffect(() => {
+ if (prQueryKey === '[]') {
+ return
+ }
+
+ const byRepo = Object.fromEntries(JSON.parse(prQueryKey) as [string, string[]][])
+
+ void refreshPullRequests(byRepo)
+
+ // A PR opens, merges or gets closed on github.com, not in here — so like
+ // the project tree, re-pull when the window comes back. The store's own
+ // staleness window keeps a flurry of focus events to one call per repo.
+ const onActive = () => {
+ if (document.visibilityState !== 'hidden') {
+ void refreshPullRequests(byRepo)
+ }
+ }
+
+ window.addEventListener('focus', onActive)
+ document.addEventListener('visibilitychange', onActive)
+
+ return () => {
+ window.removeEventListener('focus', onActive)
+ document.removeEventListener('visibilitychange', onActive)
+ }
+ }, [prQueryKey])
+
// Out-of-band repo changes (a `git init` / `rm -rf` in another terminal) emit
// no git events, so — like every git GUI — re-pull on window focus / tab
// visibility instead of stranding the tree until a hard reload. The tree
@@ -629,18 +806,22 @@ export function ChatSidebar({
}
const sorted = sortProjectsForOverview(
- filterVisibleProjects(projectTree, dismissedAutoProjects).map(project =>
- excludeProjectSessions(
- {
- ...project,
- // Home is synthetic, so its name is ours to translate — every other
- // label is a repo basename or a name the user typed.
- label: project.isNoProject ? s.projects.home : project.label,
- repos: orderRepos(project.repos)
- },
- isPinnedSession
- )
- ),
+ filterVisibleProjects(projectTree, dismissedAutoProjects)
+ // A filtered-out project drops its whole lane, header included — hiding
+ // only its rows would leave a row of empty folders behind.
+ .filter(project => !projectFilter.length || projectFilter.includes(project.id))
+ .map(project =>
+ excludeProjectSessions(
+ {
+ ...project,
+ // Home is synthetic, so its name is ours to translate — every
+ // other label is a repo basename or a name the user typed.
+ label: project.isNoProject ? s.projects.home : project.label,
+ repos: orderRepos(project.repos)
+ },
+ isHiddenFromProjects
+ )
+ ),
activeProjectId
)
@@ -654,8 +835,9 @@ export function ChatSidebar({
dismissedAutoProjects,
orderRepos,
activeProjectId,
+ projectFilter,
projectOrderIds,
- isPinnedSession,
+ isHiddenFromProjects,
s
])
@@ -725,9 +907,9 @@ export function ChatSidebar({
// presentation copy (Home is translated there), not the raw payload's.
return excludeProjectSessions(
{ ...hydrated, label: overviewEnteredProject.label, repos: orderRepos(hydrated.repos) },
- isPinnedSession
+ isHiddenFromProjects
)
- }, [overviewEnteredProject, enteredProjectTree, orderRepos, isPinnedSession])
+ }, [overviewEnteredProject, enteredProjectTree, orderRepos, isHiddenFromProjects])
// Overlay live `$sessions` onto the entered project so a just-created session
// (which the backend snapshot hasn't folded in yet) counts as content and
@@ -1019,11 +1201,15 @@ export function ChatSidebar({
// 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 loadedSessionCount = showAllProfiles ? sessions.length : scopedSessions.length
- const hasMoreSessions = showAllProfiles
- ? Object.values(sessionProfilesTruncated).some(Boolean)
- : Boolean(sessionProfilesTruncated[profileScope])
+ // The archived view is its own (single, capped) query — paging the live
+ // sessions list from under it would just fold un-archived rows back in.
+ const hasMoreSessions =
+ !showArchived &&
+ (showAllProfiles
+ ? Object.values(sessionProfilesTruncated).some(Boolean)
+ : Boolean(sessionProfilesTruncated[profileScope]))
const displayRecentsCountRef = useRef(0)
const loadedRecentsCountRef = useRef(0)
@@ -1068,6 +1254,44 @@ export function ChatSidebar({
}
}, [onLoadMoreSessions, recentsLoadMorePending])
+ // Archived rows are excluded from the sessions query, so the view has to
+ // fetch its own set.
+ useEffect(() => {
+ if (showArchived) {
+ void loadArchivedSessions()
+ }
+ }, [showArchived])
+
+ // Ranking by size is a question about the whole list ("what did I burn money
+ // on"), so it drops the calendar dividers and ranks globally — "Today" above
+ // the priciest session you have ever had would be a lie. Time- and
+ // 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
// The recents list owns its own (virtualized) scroll container only when it's a
@@ -1113,9 +1337,15 @@ export function ChatSidebar({
}
}, [activeRepoTrees, workspaceParentOrderIds, workspaceOrderIds])
- const showSessionSkeletons = sessionsLoading && sortedSessions.length === 0
+ // Skeletons mean "still loading", so they key off the UNFILTERED set. Keyed
+ // off the filtered one, a filter that matches nothing showed skeletons on
+ // every background refresh instead of the empty state.
+ const showSessionSkeletons = sessionsLoading && scopedSessions.length === 0
- const showSessionSections = showSessionSkeletons || sortedSessions.length > 0 || projectModel.length > 0
+ // Filtered down to nothing still renders the section: the empty state is what
+ // tells you the filter — not an empty account — is why the list is bare.
+ const showSessionSections =
+ showSessionSkeletons || filtersActive || sortedSessions.length > 0 || projectModel.length > 0
// Each reorderable list reports its OWN new id order; persisting is a direct,
// typed write — no id-prefix sniffing to figure out which level moved.
@@ -1262,7 +1492,7 @@ export function ChatSidebar({
)}
{showSessionSections && (
- <div className={cn('flex min-h-0 flex-1 flex-col pb-1.75', SCROLL_Y)}>
+ <div className={cn('flex min-h-0 flex-1 flex-col pb-1.75', SCROLL_Y, SCROLL_GUTTER)}>
{trimmedQuery && (
<SidebarSessionsSection
activeSessionId={activeSidebarSessionId}
@@ -1329,14 +1559,19 @@ export function ChatSidebar({
// virtualized long list, which must keep its own scroller.
!recentsVirtualizes && COMPACT_FLAT
)}
- dateGrouped
dndSensors={dndSensors}
emptyState={
showSessionSkeletons ? (
<SidebarSessionSkeletons />
) : (
<div className="grid min-h-16 place-items-center rounded-lg px-2 text-center text-xs text-(--ui-text-tertiary)">
- {inProject ? s.projectEmpty : pinnedSessions.length > 0 ? s.allPinned : s.noSessions}
+ {inProject
+ ? s.projectEmpty
+ : filtersActive
+ ? s.noFilterMatches
+ : pinnedSessions.length > 0
+ ? s.allPinned
+ : s.noSessions}
</div>
)
}
@@ -1356,6 +1591,11 @@ export function ChatSidebar({
) : null
}
forceEmptyState={showSessionSkeletons}
+ // Archived is a plain list, and so is a magnitude-ranked one.
+ // Otherwise project lanes stay chronological whatever the flat
+ // list does — only the flat list can swap its dividers for
+ // WORKING / DONE.
+ grouping={showArchived || rankedGlobally ? 'none' : grouping === 'status' ? 'status' : 'date'}
groups={displayAgentGroups}
headerAction={
inProject && enteredProject ? (
@@ -1411,26 +1651,7 @@ export function ChatSidebar({
</Tip>
) : null}
<div className="grid size-6 place-items-center">
- {!showAllProfiles && agentSessions.length > 0 ? (
- <Tip label={agentsGrouped ? s.showSessions : s.showProjects}>
- <Button
- aria-label={agentsGrouped ? s.showSessions : s.showProjects}
- className={cn(
- HEADER_NAV_BTN,
- agentsGrouped && 'bg-(--ui-control-active-background) text-foreground opacity-100'
- )}
- onClick={event => {
- event.stopPropagation()
- setSidebarRecentsOpen(true)
- setSidebarAgentsGrouped(!agentsGrouped)
- }}
- size="icon-xs"
- variant="ghost"
- >
- <Codicon name={agentsGrouped ? 'list-unordered' : 'root-folder'} size="0.75rem" />
- </Button>
- </Tip>
- ) : null}
+ {!showAllProfiles ? <SidebarFilterMenu className={HEADER_NAV_BTN} /> : null}
</div>
</div>
)
@@ -1444,7 +1665,7 @@ export function ChatSidebar({
) : undefined
}
liveSessions={inProject ? agentSessions : undefined}
- manualOrderIds={agentOrderManual ? agentOrderIds : undefined}
+ manualOrderIds={agentOrderManual ? agentOrderIds : sortOrderIds}
onArchiveSession={onArchiveSession}
onBranchSession={onBranchSession}
onDeleteSession={onDeleteSession}
diff --git a/apps/desktop/src/app/chat/sidebar/projects/index.ts b/apps/desktop/src/app/chat/sidebar/projects/index.ts
index 53366611c34..fb242fe7344 100644
--- a/apps/desktop/src/app/chat/sidebar/projects/index.ts
+++ b/apps/desktop/src/app/chat/sidebar/projects/index.ts
@@ -12,6 +12,7 @@ export { ProjectMenu } from './project-menu'
export { SidebarWorkspaceGroup } from './workspace-group'
export {
excludeProjectSessions,
+ liveSessionProjectId,
overlayLiveLanes,
overlayLivePreviews,
sessionRecency,
diff --git a/apps/desktop/src/app/chat/sidebar/session-row.tsx b/apps/desktop/src/app/chat/sidebar/session-row.tsx
index 85ac56d06a8..9f355b9d5f0 100644
--- a/apps/desktop/src/app/chat/sidebar/session-row.tsx
+++ b/apps/desktop/src/app/chat/sidebar/session-row.tsx
@@ -1,6 +1,8 @@
+import { useStore } from '@nanostores/react'
import { memo } from 'react'
import type * as React from 'react'
+import { PrTag } from '@/app/chat/pr-tag'
import { ProfileTag } from '@/app/chat/profile-tag'
import { startSessionDrag } from '@/app/chat/session-drag'
import { PlatformAvatar } from '@/app/messaging/platform-icon'
@@ -11,17 +13,29 @@ import { Tip } from '@/components/ui/tooltip'
import type { SessionInfo } from '@/hermes'
import { type Translations, useI18n } from '@/i18n'
import { sessionTitle } from '@/lib/chat-runtime'
+import { compactNumber } from '@/lib/format'
import { triggerHaptic } from '@/lib/haptics'
import { middleClickHandlers } from '@/lib/middle-click'
import { handoffOriginSource, sessionSourceLabel } from '@/lib/session-source'
import { coarseElapsed } from '@/lib/time'
import { useStoreSelector } from '@/lib/use-session-slice'
import { cn } from '@/lib/utils'
+import { $sidebarRowMeta } from '@/store/layout'
+import { normalizeProfileKey } from '@/store/profile'
+import { $pullRequestsByBranch, sessionPrKey } from '@/store/pull-requests'
import { $sessionDotStateById, hasLiveTurn, showsRunningArc } from '@/store/session-dot-state'
+import { sessionCostUsd } from '@/store/sidebar-archive'
import { SessionStatusDot } from '../session-status-dot'
-import { SidebarRowBody, SidebarRowGrab, SidebarRowLabel, SidebarRowLead, SidebarRowShell } from './chrome'
+import {
+ SidebarRowBody,
+ SidebarRowGrab,
+ SidebarRowLabel,
+ SidebarRowLead,
+ SidebarRowLeadGlyph,
+ SidebarRowShell
+} from './chrome'
import { SessionActionsMenu, SessionContextMenu } from './session-actions-menu'
import { useProfilePrewarm } from './use-profile-prewarm'
@@ -79,6 +93,48 @@ function SidebarSessionRowImpl({
const title = sessionTitle(session)
const age = formatAge(session.last_active || session.started_at, r)
const handleLabel = `Reorder ${title}`
+ // Opt-in row metadata from the sidebar's filter menu. Read from the store
+ // rather than threaded as props: the subscription re-renders past the memo
+ // below, and a toggle should repaint every row at once anyway.
+ const rowMeta = useStore($sidebarRowMeta)
+ // Pinned metadata occupies the actions slot and swaps out for the kebab on
+ // hover, so the row reserves the same width either way and never reflows.
+ const pinnedAge = rowMeta.includes('updated')
+ // The default profile has no mark worth spending a row slot on — a chip on
+ // every row that says "the normal one" is noise. Named profiles only.
+ const hasProfileTag = normalizeProfileKey(session.profile) !== 'default'
+ const pinnedProfile = hasProfileTag && rowMeta.includes('profile')
+ // The branch's PR, if the row was asked to show one. A selector, not a plain
+ // useStore: a repo's PRs land as a single map write, and only the rows on
+ // those branches should repaint.
+ const prKey = sessionPrKey(session)
+ const pr = useStoreSelector($pullRequestsByBranch, prs => (rowMeta.includes('pr') && prKey ? prs[prKey] : undefined))
+ const totalTokens = session.input_tokens + session.output_tokens
+ const cost = sessionCostUsd(session)
+
+ // Tokens, cost and age share the one trailing slot rather than each claiming
+ // their own column: several switched on read as one figure, not as a
+ // widening gutter.
+ const pinnedFacts = [
+ rowMeta.includes('tokens') && totalTokens > 0 ? compactNumber(totalTokens) : null,
+ // Sub-cent spend rounds to "$0.00", which reads as a bug rather than as a
+ // cheap session — below a cent the row says nothing at all.
+ rowMeta.includes('cost') && cost >= 0.01 ? `$${cost.toFixed(2)}` : null,
+ pinnedAge ? age : null
+ ].filter(Boolean) as string[]
+
+ // The kebab covers the END of the slot, so only the last fact steps aside for
+ // it. With tokens and age both on, hovering costs you the age and keeps the
+ // number you switched on to read.
+ const pinnedTail = pinnedFacts.at(-1) ?? ''
+ const pinnedHead = pinnedFacts.slice(0, -1).join(' · ')
+ const pinnedLabel = pinnedFacts.join(' · ')
+ // Chips that ride in the BODY, beside the title. The kebab lifts out of the
+ // actions slot, so it only ever covers what's in there — a body chip has no
+ // reason to step aside, and the hover-age (which does overlay the body) is
+ // dropped rather than made to fight them.
+ const bodyChip = Boolean(pr) || pinnedProfile || (showProfile && hasProfileTag)
+ const pinnedMeta = Boolean(pinnedLabel) || bodyChip
// A handed-off session's live source is local, but it originated on a
// messaging platform — surface that origin as a small badge so e.g. a
// Telegram thread continued here still reads as Telegram.
@@ -90,6 +146,14 @@ function SidebarSessionRowImpl({
const dotState = useStoreSelector($sessionDotStateById, states => states[session.id] ?? 'idle')
const liveTurn = hasLiveTurn(dotState)
+ // An archived session has no live status to paint, so the archive glyph takes
+ // the lead slot the dot would occupy instead of adding a column of its own.
+ const lead = session.archived ? (
+ <SidebarRowLeadGlyph className="text-(--ui-text-quaternary)">
+ <Codicon name="archive" size="0.75rem" />
+ </SidebarRowLeadGlyph>
+ ) : null
+
return (
<SessionContextMenu
onArchive={onArchive}
@@ -103,10 +167,36 @@ function SidebarSessionRowImpl({
>
<SidebarRowShell
actions={
- <div className="relative z-2 grid w-[1.375rem] place-items-center" data-row-actions>
- {!liveTurn && (
- <span className="pointer-events-none absolute right-6 top-1/2 min-w-6 -translate-y-1/2 text-right text-[0.625rem] leading-none text-(--ui-text-tertiary) opacity-0 transition-opacity group-hover:opacity-100">
- {age}
+ // Pinned metadata sits in normal flow and the kebab lifts out of it,
+ // so this slot's intrinsic width IS the metadata's — the row's
+ // `auto` actions column measures it and the title truncates against
+ // whatever is switched on, with no width to hand-maintain.
+ <div className="relative z-2 flex items-center justify-end" data-row-actions>
+ {/* Pinned metadata stays put through a turn — it was switched on to
+ be read. Only the tail hands its slot to the kebab; anything
+ ahead of it stays legible while you hover. The hover-only age is
+ an overlay instead, so it needs the row to open up 48px of right
+ padding — which beside a body chip reads as a hole. A row that
+ already shows a chip skips it. */}
+ {(pinnedLabel || (!liveTurn && !bodyChip)) && (
+ <span
+ className={cn(
+ 'pointer-events-none whitespace-nowrap text-right text-[0.625rem] leading-none text-(--ui-text-tertiary)',
+ !pinnedLabel && 'absolute right-6 opacity-0 transition-opacity group-hover:opacity-100'
+ )}
+ >
+ {pinnedLabel ? (
+ <>
+ {pinnedHead}
+ {/* Never narrower than the kebab that has to cover it. */}
+ <span className="inline-block min-w-5 transition-opacity group-hover:opacity-0">
+ {pinnedHead && ' · '}
+ {pinnedTail}
+ </span>
+ </>
+ ) : (
+ age
+ )}
</span>
)}
<SessionActionsMenu
@@ -121,7 +211,10 @@ function SidebarSessionRowImpl({
>
<Button
aria-label={r.sessionActions}
- className="size-5 rounded-[4px] bg-transparent text-transparent transition-colors duration-100 hover:bg-(--ui-control-active-background) hover:text-foreground focus-visible:bg-(--ui-control-active-background) focus-visible:text-foreground focus-visible:ring-0 data-[state=open]:bg-(--ui-control-active-background) data-[state=open]:text-foreground group-hover:text-(--ui-text-tertiary) [&_svg]:size-3.5!"
+ className={cn(
+ 'size-5 rounded-[4px] bg-transparent text-transparent transition-colors duration-100 hover:bg-(--ui-control-active-background) hover:text-foreground focus-visible:bg-(--ui-control-active-background) focus-visible:text-foreground focus-visible:ring-0 data-[state=open]:bg-(--ui-control-active-background) data-[state=open]:text-foreground group-hover:text-(--ui-text-tertiary) [&_svg]:size-3.5!',
+ pinnedLabel && 'absolute right-0'
+ )}
size="icon"
variant="ghost"
>
@@ -173,7 +266,10 @@ function SidebarSessionRowImpl({
>
{showsRunningArc(dotState) && <span aria-hidden="true" className="arc-border arc-row" />}
<SidebarRowBody
- className={cn('z-0 group-hover:pr-12', branchStem && 'pl-3.5')}
+ // Pinned metadata already sits in the actions slot, so the title only
+ // needs a gap from it — and the same gap on hover, or the row would
+ // jump every time the kebab took over.
+ className={cn('z-0', pinnedMeta ? 'pr-2' : 'group-hover:pr-12', branchStem && 'pl-3.5')}
// Middle-click = open in a new tab (browser muscle memory).
{...middleClickHandlers(() => {
triggerHaptic('selection')
@@ -217,16 +313,18 @@ function SidebarSessionRowImpl({
>
{reorderable ? (
<SidebarRowGrab ariaLabel={handleLabel} dragging={dragging} dragHandleProps={dragHandleProps}>
- <SessionStatusDot
- branchStem={branchStem}
- className="transition-opacity group-hover/handle:opacity-0 group-focus-within/handle:opacity-0"
- session={session}
- storedSessionId={session.id}
- />
+ {lead ?? (
+ <SessionStatusDot
+ branchStem={branchStem}
+ className="transition-opacity group-hover/handle:opacity-0 group-focus-within/handle:opacity-0"
+ session={session}
+ storedSessionId={session.id}
+ />
+ )}
</SidebarRowGrab>
) : (
<SidebarRowLead className="overflow-hidden">
- <SessionStatusDot branchStem={branchStem} session={session} storedSessionId={session.id} />
+ {lead ?? <SessionStatusDot branchStem={branchStem} session={session} storedSessionId={session.id} />}
</SidebarRowLead>
)}
{handoffSource && handoffLabel ? (
@@ -241,7 +339,10 @@ function SidebarSessionRowImpl({
<SidebarRowLabel className="flex-1 font-normal group-hover:text-foreground group-data-[working=true]:text-foreground/90">
{title}
</SidebarRowLabel>
- {showProfile && <ProfileTag profile={session.profile} />}
+ {/* Stays put on hover, unlike the other chips: it's a link, and the
+ kebab lives in its own column rather than over this one. */}
+ {pr && <PrTag pr={pr} />}
+ {(showProfile || pinnedProfile) && hasProfileTag && <ProfileTag profile={session.profile} />}
</SidebarRowBody>
</SidebarRowShell>
</SessionContextMenu>
diff --git a/apps/desktop/src/app/chat/sidebar/sessions-section.test.tsx b/apps/desktop/src/app/chat/sidebar/sessions-section.test.tsx
index b9097e429a9..19b20a1addd 100644
--- a/apps/desktop/src/app/chat/sidebar/sessions-section.test.tsx
+++ b/apps/desktop/src/app/chat/sidebar/sessions-section.test.tsx
@@ -109,7 +109,7 @@ describe('SidebarSessionsSection memoization & virtualizer stability', () => {
expect(nextRowsRef).toBe(initialRowsRef)
})
- it('re-computes flatRows reference when dateGrouped or sessions change', () => {
+ it('re-computes flatRows reference when grouping or sessions change', () => {
mockVirtualListPropsHistory.length = 0
const initialSessions = generateSessions(VIRTUALIZE_THRESHOLD + 2)
@@ -117,8 +117,8 @@ describe('SidebarSessionsSection memoization & virtualizer stability', () => {
const { rerender } = render(
<SidebarSessionsSection
activeSessionId={null}
- dateGrouped={false}
emptyState={<div>Empty</div>}
+ grouping="none"
label="Sessions"
onArchiveSession={noop}
onDeleteSession={noop}
@@ -133,12 +133,12 @@ describe('SidebarSessionsSection memoization & virtualizer stability', () => {
const firstRowsRef = mockVirtualListPropsHistory[0].rows
- // Change dateGrouped to true
+ // Switch on date dividers
rerender(
<SidebarSessionsSection
activeSessionId={null}
- dateGrouped={true}
emptyState={<div>Empty</div>}
+ grouping="date"
label="Sessions"
onArchiveSession={noop}
onDeleteSession={noop}
@@ -159,8 +159,8 @@ describe('SidebarSessionsSection memoization & virtualizer stability', () => {
rerender(
<SidebarSessionsSection
activeSessionId={null}
- dateGrouped={true}
emptyState={<div>Empty</div>}
+ grouping="date"
label="Sessions"
onArchiveSession={noop}
onDeleteSession={noop}
diff --git a/apps/desktop/src/app/chat/sidebar/sessions-section.tsx b/apps/desktop/src/app/chat/sidebar/sessions-section.tsx
index 4ab211f0373..461a40fd96e 100644
--- a/apps/desktop/src/app/chat/sidebar/sessions-section.tsx
+++ b/apps/desktop/src/app/chat/sidebar/sessions-section.tsx
@@ -1,4 +1,5 @@
import type { useSensors } from '@dnd-kit/core'
+import { useStore } from '@nanostores/react'
import type * as React from 'react'
import { useCallback, useMemo } from 'react'
@@ -9,10 +10,16 @@ import type { HermesGitWorktree } from '@/global'
import type { SessionInfo } from '@/hermes'
import { useI18n } from '@/i18n'
import { flattenSessionsWithBranches } from '@/lib/session-branch-tree'
-import { groupEntriesByRecency, type SidebarListRow, toSessionRows } from '@/lib/session-date-groups'
+import {
+ groupEntriesByRecency,
+ groupEntriesByStatus,
+ type SidebarListRow,
+ toSessionRows
+} from '@/lib/session-date-groups'
import { sessionBucketLabel } from '@/lib/time'
import { cn } from '@/lib/utils'
import { sessionPinId } from '@/store/session'
+import { $sessionDotStateById, hasLiveTurn } from '@/store/session-dot-state'
import { SidebarDateDivider, SidebarSectionMeta } from './chrome'
import { orderRowsWithinGroups, reorderableRowIds } from './order'
@@ -24,6 +31,7 @@ import {
SidebarWorkspaceGroup,
type SidebarWorkspaceTree
} from './projects'
+import { WorkspaceAddButton } from './projects/workspace-header'
import { ReorderableList, useSortableBindings } from './reorderable-list'
import { SidebarSessionSkeletons } from './section-states'
import { SidebarSessionRow } from './session-row'
@@ -149,11 +157,12 @@ interface SidebarSessionsSectionProps {
// lists (Pinned / search results) in the All-profiles view, where no group
// header communicates ownership (#66003).
showProfileTags?: boolean
- // Insert "Yesterday" / "Last week" date dividers into the chronological
- // session list (flat recents + entered-project lanes). Off for hand-ordered
- // lists, pinned, messaging groups, and the project overview, where the order
- // isn't strictly by recency so a date bucket would be misleading.
- dateGrouped?: boolean
+ // Which dividers to fold into the flat list: `date` gives the chronological
+ // "Yesterday" / "Last week" separators (flat recents + entered-project lanes),
+ // `status` splits into WORKING / DONE under the same separators. `none` for
+ // pinned, messaging groups, and the project overview, where the order isn't
+ // strictly by recency so a bucket would be misleading.
+ grouping?: 'date' | 'none' | 'status'
}
export function SidebarSessionsSection({
@@ -195,10 +204,12 @@ export function SidebarSessionsSection({
projectBackRow,
dndSensors,
showProfileTags = false,
- dateGrouped = false
+ grouping = 'none'
}: SidebarSessionsSectionProps) {
const { t } = useI18n()
const dividerLabels = t.sidebar.dateDivider
+ const statusDividerLabels = t.sidebar.statusDivider
+ const dotStates = useStore($sessionDotStateById)
const sectionOpen = collapsible ? open : true
const hasGroupedSessions = Boolean(groups?.some(group => group.sessions.length > 0))
// A defined project list is itself content (even an empty project should
@@ -262,14 +273,29 @@ export function SidebarSessionsSection({
]
)
- // A single flat/virtual/lane list row — either a date divider or a session.
+ // Date dividers head a group the same way a repo header does, so they carry
+ // the same hover-revealed "+". Only for dates: "new session in WORKING" is
+ // not a thing.
+ const dividerAction =
+ grouping === 'date' && onNewSessionInWorkspace ? (
+ <WorkspaceAddButton label={t.sidebar.nav['new-session']} onClick={() => onNewSessionInWorkspace(null)} />
+ ) : null
+
+ // A single flat/virtual/lane list row — either a divider or a session.
const renderListRow = useCallback(
- (row: SidebarListRow, draggable: boolean) =>
- row.kind === 'divider' ? (
- <SidebarDateDivider key={row.key} label={sessionBucketLabel(row.bucket, dividerLabels)} />
- ) : (
- renderRow(row.entry.session, draggable, row.entry.branchStem)
- ),
+ (row: SidebarListRow, draggable: boolean, action?: React.ReactNode) => {
+ if (row.kind === 'session') {
+ return renderRow(row.entry.session, draggable, row.entry.branchStem)
+ }
+
+ return (
+ <SidebarDateDivider
+ action={action}
+ key={row.key}
+ label={'label' in row ? row.label : sessionBucketLabel(row.bucket, dividerLabels)}
+ />
+ )
+ },
[dividerLabels, renderRow]
)
@@ -287,11 +313,11 @@ export function SidebarSessionsSection({
(items: SessionInfo[]) => {
const entries = flattenSessionsWithBranches(items)
- return (dateGrouped ? groupEntriesByRecency(entries) : toSessionRows(entries)).map(row =>
+ return (grouping === 'date' ? groupEntriesByRecency(entries) : toSessionRows(entries)).map(row =>
renderListRow(row, false)
)
},
- [dateGrouped, renderListRow]
+ [grouping, renderListRow]
)
// Flat recents as list rows: grouped by recency when enabled, plain otherwise.
@@ -299,10 +325,19 @@ export function SidebarSessionsSection({
// row ranks it among its own day's chats instead of freezing the whole list
// into an undated manual mode.
const flatRows: SidebarListRow[] = useMemo(() => {
- const rows = dateGrouped ? groupEntriesByRecency(displayEntries) : toSessionRows(displayEntries)
+ const rows =
+ grouping === 'date'
+ ? groupEntriesByRecency(displayEntries)
+ : grouping === 'status'
+ ? groupEntriesByStatus(
+ displayEntries,
+ entry => hasLiveTurn(dotStates[entry.session.id] ?? 'idle'),
+ statusDividerLabels
+ )
+ : toSessionRows(displayEntries)
return manualOrderIds?.length ? orderRowsWithinGroups(rows, manualOrderIds) : rows
- }, [dateGrouped, displayEntries, manualOrderIds])
+ }, [grouping, displayEntries, dotStates, manualOrderIds, statusDividerLabels])
// dnd-kit must see exactly the ids it renders, in render order: the sortable
// set is derived from the rows, not from `sessions`. Feeding it the unrendered
@@ -410,6 +445,7 @@ export function SidebarSessionsSection({
<VirtualSessionList
activeSessionId={activeSessionId}
className={contentClassName}
+ dividerAction={dividerAction}
onArchiveSession={onArchiveSession}
onBranchSession={onBranchSession}
onDeleteSession={onDeleteSession}
@@ -433,11 +469,11 @@ export function SidebarSessionsSection({
} else if (sessionsDraggable && onReorderSessions) {
inner = (
<ReorderableList ids={sortableRowIds} onReorder={onReorderSessions} sensors={dndSensors}>
- {flatRows.map(row => renderListRow(row, true))}
+ {flatRows.map(row => renderListRow(row, true, dividerAction))}
</ReorderableList>
)
} else {
- inner = flatRows.map(row => renderListRow(row, false))
+ inner = flatRows.map(row => renderListRow(row, false, dividerAction))
}
// The virtualizer owns its own scroller, so suppress the wrapper's overflow
diff --git a/apps/desktop/src/app/chat/sidebar/virtual-session-list.tsx b/apps/desktop/src/app/chat/sidebar/virtual-session-list.tsx
index 68f0d74867d..e9b38c21549 100644
--- a/apps/desktop/src/app/chat/sidebar/virtual-session-list.tsx
+++ b/apps/desktop/src/app/chat/sidebar/virtual-session-list.tsx
@@ -1,6 +1,7 @@
import { useSortable } from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities'
import { useVirtualizer } from '@tanstack/react-virtual'
+import type * as React from 'react'
import { type FC, useCallback, useRef } from 'react'
import type { SessionInfo } from '@/hermes'
@@ -29,6 +30,8 @@ interface SessionRowCommonProps {
export interface VirtualSessionListProps {
activeSessionId: null | string
className?: string
+ /** Hover-revealed control for date dividers (the group-level "+"). */
+ dividerAction?: React.ReactNode
rows: SidebarListRow[]
onArchiveSession: (sessionId: string) => void
onBranchSession?: (sessionId: string, profile?: string) => void
@@ -46,6 +49,7 @@ const OVERSCAN_ROWS = 12
export const VirtualSessionList: FC<VirtualSessionListProps> = ({
activeSessionId,
className,
+ dividerAction,
rows: listRows,
onArchiveSession,
onBranchSession,
@@ -90,9 +94,10 @@ export const VirtualSessionList: FC<VirtualSessionListProps> = ({
if (row.kind === 'divider') {
return (
<SidebarDateDivider
+ action={dividerAction}
data-index={virtualItem.index}
key={row.key}
- label={sessionBucketLabel(row.bucket, dividerLabels)}
+ label={'label' in row ? row.label : sessionBucketLabel(row.bucket, dividerLabels)}
ref={virtualizer.measureElement}
/>
)
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 596a336f4e3..ba2e560b475 100644
--- a/apps/desktop/src/app/session/hooks/use-session-list-actions.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-list-actions.ts
@@ -1,4 +1,4 @@
-import { useCallback, useRef } from 'react'
+import { useCallback, useEffect, useRef } from 'react'
import { getCronJobs, listAllProfileSessions, listSidebarSessions, type SessionInfo } from '@/hermes'
import { sameCronSignature } from '@/lib/session-signatures'
@@ -9,7 +9,15 @@ import {
normalizeSessionSource
} from '@/lib/session-source'
import { setCronJobs } from '@/store/cron'
-import { $pinnedSessionIds, $sessionsLimit, bumpSessionsLimit, SIDEBAR_SESSIONS_PAGE_SIZE } from '@/store/layout'
+import {
+ $pinnedSessionIds,
+ $sessionsLimit,
+ $sidebarFiltersActive,
+ bumpSessionsLimit,
+ raiseSessionsLimit,
+ SIDEBAR_FILTERED_PAGE_SIZE,
+ SIDEBAR_SESSIONS_PAGE_SIZE
+} from '@/store/layout'
import { ALL_PROFILES, normalizeProfileKey } from '@/store/profile'
import { $removedSessionIds } from '@/store/projects'
import {
@@ -244,6 +252,36 @@ export function useSessionListActions({ profileScope }: UseSessionListActionsArg
await refreshSessions()
}, [refreshSessions])
+ // A filter searches the loaded page, so switching one on has to deepen the
+ // page — otherwise "merged PRs" answers for the last 50 rows and reads as
+ // "you only have 6 merged PRs". Clearing the filters hands the window back:
+ // the list refreshes on every settled turn, and paying for 300 rows a turn
+ // once the view is unfiltered again buys nothing. Whatever the user had
+ // paged to by hand is what it returns to.
+ const unfilteredLimit = useRef<null | number>(null)
+
+ useEffect(
+ () =>
+ $sidebarFiltersActive.subscribe(active => {
+ if (active) {
+ unfilteredLimit.current ??= $sessionsLimit.get()
+
+ if (raiseSessionsLimit(SIDEBAR_FILTERED_PAGE_SIZE)) {
+ void refreshSessions()
+ }
+ } else if (unfilteredLimit.current !== null) {
+ const restored = unfilteredLimit.current
+ unfilteredLimit.current = null
+
+ if ($sessionsLimit.get() > restored) {
+ $sessionsLimit.set(restored)
+ void refreshSessions()
+ }
+ }
+ }),
+ [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) => {
diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.ts
index e2663ecef88..61452064cf1 100644
--- a/apps/desktop/src/i18n/ar.ts
+++ b/apps/desktop/src/i18n/ar.ts
@@ -1560,6 +1560,7 @@ export const ar = defineLocale({
noWorkspace: 'بدون مساحة عمل',
projectEmpty: 'لا توجد جلسات بعد',
noSessions: 'لا توجد جلسات بعد',
+ noFilterMatches: 'لا توجد جلسات تطابق عوامل التصفية هذه',
projects: {
sectionLabel: 'المشاريع',
home: 'الرئيسية',
diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts
index cb3ac391fed..807bfadd771 100644
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@ -1869,6 +1869,7 @@ export const en: Translations = {
noWorkspace: 'No workspace',
projectEmpty: 'No sessions yet',
noSessions: 'No sessions yet',
+ noFilterMatches: 'No sessions match these filters',
projects: {
sectionLabel: 'Projects',
home: 'Home',
@@ -1986,6 +1987,10 @@ export const en: Translations = {
thisWeek: 'Earlier this week',
lastWeek: 'Last week',
thisMonth: 'Earlier this month'
+ },
+ statusDivider: {
+ working: 'Working',
+ done: 'Done'
}
},
diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.ts
index 8742c3f0dce..740fbb2bb47 100644
--- a/apps/desktop/src/i18n/ja.ts
+++ b/apps/desktop/src/i18n/ja.ts
@@ -1696,6 +1696,7 @@ export const ja = defineLocale({
noWorkspace: 'ワークスペースなし',
projectEmpty: 'セッションはまだありません',
noSessions: 'セッションはまだありません',
+ noFilterMatches: 'このフィルターに一致するセッションはありません',
projects: {
sectionLabel: 'プロジェクト',
home: 'ホーム',
@@ -1804,6 +1805,10 @@ export const ja = defineLocale({
thisWeek: '今週',
lastWeek: '先週',
thisMonth: '今月'
+ },
+ statusDivider: {
+ working: '実行中',
+ done: '完了'
}
},
diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts
index 6a33c3631a5..4132d501576 100644
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@ -1564,6 +1564,7 @@ export interface Translations {
noWorkspace: string
projectEmpty: string
noSessions: string
+ noFilterMatches: string
projects: {
sectionLabel: string
home: string
@@ -1679,6 +1680,10 @@ export interface Translations {
lastWeek: string
thisMonth: string
}
+ statusDivider: {
+ working: string
+ done: string
+ }
}
composer: {
diff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.ts
index 977eacb4e40..fb84840259e 100644
--- a/apps/desktop/src/i18n/zh-hant.ts
+++ b/apps/desktop/src/i18n/zh-hant.ts
@@ -1641,6 +1641,7 @@ export const zhHant = defineLocale({
noWorkspace: '無工作區',
projectEmpty: '尚無工作階段',
noSessions: '尚無工作階段',
+ noFilterMatches: '沒有工作階段符合這些篩選條件',
projects: {
sectionLabel: '專案',
home: '主頁',
@@ -1746,6 +1747,10 @@ export const zhHant = defineLocale({
thisWeek: '本週',
lastWeek: '上週',
thisMonth: '本月'
+ },
+ statusDivider: {
+ working: '進行中',
+ done: '已完成'
}
},
diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts
index 45c1b7bb7aa..c1a98c251df 100644
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@ -2062,6 +2062,7 @@ export const zh: Translations = {
noWorkspace: '无工作区',
projectEmpty: '暂无会话',
noSessions: '暂无会话',
+ noFilterMatches: '没有会话符合这些筛选条件',
projects: {
sectionLabel: '项目',
home: '主页',
@@ -2178,6 +2179,10 @@ export const zh: Translations = {
thisWeek: '本周',
lastWeek: '上周',
thisMonth: '本月'
+ },
+ statusDivider: {
+ working: '进行中',
+ done: '已完成'
}
},
diff --git a/apps/desktop/src/lib/session-date-groups.ts b/apps/desktop/src/lib/session-date-groups.ts
index 776186cff85..803fbae1d7f 100644
--- a/apps/desktop/src/lib/session-date-groups.ts
+++ b/apps/desktop/src/lib/session-date-groups.ts
@@ -1,11 +1,14 @@
import { type SidebarSessionEntry } from '@/lib/session-branch-tree'
import { calendarBucket, HOUR, localeWeekStartDay, MINUTE, SECOND, type SessionBucket } from '@/lib/time'
-// A flat list row is either a chronological date-bucket divider or a session
-// entry. Interleaving these lets the flat list (and the virtualizer) render
-// date separators inline without a second layer of nesting.
+// A flat list row is either a divider or a session entry. Interleaving these
+// lets the flat list (and the virtualizer) render separators inline without a
+// second layer of nesting. A divider either names a calendar bucket (resolved
+// against the locale's labels at render time) or carries its own label.
export type SidebarListRow =
- { bucket: SessionBucket; key: string; kind: 'divider' } | { entry: SidebarSessionEntry; kind: 'session' }
+ | { bucket: SessionBucket; key: string; kind: 'divider' }
+ | { entry: SidebarSessionEntry; kind: 'session' }
+ | { key: string; kind: 'divider'; label: string }
// The row's own age label reads from `last_active || started_at`; bucket off the
// same value so a divider lines up with what the row actually shows.
@@ -143,6 +146,34 @@ export function groupEntriesByRecency(
return rows
}
+// Split into two runs — still busy, and everything else — under the same
+// dividers the date grouping uses. Branch children ride with their parent, as
+// they do there. Entries arrive already ordered, so each run is contiguous.
+export function groupEntriesByStatus(
+ entries: readonly SidebarSessionEntry[],
+ isWorking: (entry: SidebarSessionEntry) => boolean,
+ labels: { done: string; working: string }
+): SidebarListRow[] {
+ const working: SidebarSessionEntry[] = []
+ const done: SidebarSessionEntry[] = []
+ let cluster = done
+
+ for (const entry of entries) {
+ if (!entry.branchStem) {
+ cluster = isWorking(entry) ? working : done
+ }
+
+ cluster.push(entry)
+ }
+
+ return [
+ ...(working.length ? [{ key: 'status:working', kind: 'divider' as const, label: labels.working }] : []),
+ ...toSessionRows(working),
+ ...(done.length ? [{ key: 'status:done', kind: 'divider' as const, label: labels.done }] : []),
+ ...toSessionRows(done)
+ ]
+}
+
// Wrap entries as plain session rows (no dividers) so the ungrouped path shares
// the same `SidebarListRow[]` shape as the grouped one.
export function toSessionRows(entries: readonly SidebarSessionEntry[]): SidebarListRow[] {
diff --git a/apps/desktop/src/store/layout.ts b/apps/desktop/src/store/layout.ts
index ca2070792d9..52d04795fd2 100644
--- a/apps/desktop/src/store/layout.ts
+++ b/apps/desktop/src/store/layout.ts
@@ -4,10 +4,12 @@ import { SIDEBAR_COLLAPSE_MEDIA_QUERY } from '@/app/layout-constants'
import { PANE_TOGGLE_REVEAL_EVENT } from '@/components/pane-shell'
import { isPaneVisible, revealTreePane } from '@/components/pane-shell/tree/store'
import { matchesQuery } from '@/hooks/use-media-query'
-import { Codecs, persistentAtom } from '@/lib/persisted'
+import { type Codec, Codecs, persistentAtom } from '@/lib/persisted'
import { arraysEqual, insertUniqueId, readKey } from '@/lib/storage'
import { $paneStates, ensurePaneRegistered, setPaneOpen, setPaneWidthOverride, togglePane } from './panes'
+import type { PullRequestBucket } from './pull-requests'
+import type { SessionStatusBucket } from './session-dot-state'
export const SIDEBAR_DEFAULT_WIDTH = 237
export const SIDEBAR_MAX_WIDTH = 360
@@ -19,6 +21,10 @@ export const FILE_BROWSER_MIN_WIDTH = '10rem'
export const FILE_BROWSER_MAX_WIDTH = '20rem'
export const SIDEBAR_SESSIONS_PAGE_SIZE = 50
+// How deep the list reaches once a filter is on. A filter that only searches
+// the loaded page answers the wrong question — "6 merged PRs" really meant "6
+// among the last 50 rows" — so narrowing the view widens the window it reads.
+export const SIDEBAR_FILTERED_PAGE_SIZE = 300
const SIDEBAR_PINNED_STORAGE_KEY = 'hermes.desktop.pinnedSessions'
const SIDEBAR_AGENTS_GROUPED_STORAGE_KEY = 'hermes.desktop.agentsGroupedByWorkspace'
@@ -26,6 +32,13 @@ const SIDEBAR_CRON_OPEN_STORAGE_KEY = 'hermes.desktop.sidebarCronOpen'
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_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_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'
const SIDEBAR_PROJECT_ORDER_STORAGE_KEY = 'hermes.desktop.projectOrder'
@@ -186,6 +199,107 @@ export const $sidebarMessagingOpenIds = persistentAtom(
Codecs.stringArray
)
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'
+/** 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. */
+export type SidebarSortKey = Exclude<SidebarOrdering, 'manual'>
+/** Optional per-row metadata the user can switch on. */
+export type SidebarRowMeta = 'cost' | 'pr' | 'profile' | 'tokens' | 'updated'
+
+function oneOf<T extends string>(values: readonly T[], fallback: T): Codec<T> {
+ return {
+ decode: raw => (values.includes(raw as T) ? (raw as T) : fallback),
+ encode: value => value
+ }
+}
+
+function listOf<T extends string>(values: readonly T[]): Codec<T[]> {
+ return {
+ decode: raw => Codecs.stringArray.decode(raw).filter((item): item is T => values.includes(item as T)),
+ encode: value => Codecs.stringArray.encode(value)
+ }
+}
+
+const ROW_META: readonly SidebarRowMeta[] = ['cost', 'pr', 'profile', 'tokens', 'updated']
+const STATUS_FILTERS: readonly SessionStatusBucket[] = ['needs-input', 'working', 'unread', 'draft', 'idle']
+const PR_FILTERS: readonly PullRequestBucket[] = ['open', 'draft', 'merged', 'closed', 'none']
+export const SIDEBAR_SORT_KEYS: readonly SidebarSortKey[] = ['updated', 'created', 'status', 'tokens', 'cost']
+
+// `project` deliberately does NOT live here. Entering a project from ⌘K, the
+// projects store, or a repo scan flips $sidebarAgentsGrouped directly, so that
+// atom stays the single authority for the project view and this one only holds
+// the grouping to fall back to when the user leaves it.
+const $sidebarFlatGrouping = persistentAtom<SidebarGrouping>(
+ SIDEBAR_GROUPING_STORAGE_KEY,
+ 'date',
+ oneOf(['date', 'status'], 'date')
+)
+
+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))
+
+// Archived sessions are a separate backend query (`archived: 'only'`), so this
+// flag both filters the list and drives the fetch.
+export const $sidebarShowArchived = persistentAtom(SIDEBAR_SHOW_ARCHIVED_STORAGE_KEY, false, Codecs.bool)
+
+export const $sidebarStatusFilter = persistentAtom<SessionStatusBucket[]>(
+ SIDEBAR_STATUS_FILTER_STORAGE_KEY,
+ [],
+ listOf(STATUS_FILTERS)
+)
+
+// Project ids as `liveSessionProjectId` reports them: an explicit project's id,
+// or a repo root path for an auto-promoted one.
+export const $sidebarProjectFilter = persistentAtom(
+ SIDEBAR_PROJECT_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.
+export const $sidebarPrFilter = persistentAtom<PullRequestBucket[]>(
+ SIDEBAR_PR_FILTER_STORAGE_KEY,
+ [],
+ listOf(PR_FILTERS)
+)
+
+export const $sidebarGrouping: ReadableAtom<SidebarGrouping> = computed(
+ [$sidebarAgentsGrouped, $sidebarFlatGrouping],
+ (grouped, grouping) => (grouped ? 'project' : grouping)
+)
+
+// A hand-dragged order outranks any sort key — dragging IS how you pick manual,
+// so the menu reflects that rather than offering a fourth way to say it.
+export const $sidebarOrdering: ReadableAtom<SidebarOrdering> = computed(
+ [$sidebarSessionOrderManual, $sidebarSortKey],
+ (manual, key) => (manual ? 'manual' : key)
+)
+
+export const $sidebarFiltersActive: ReadableAtom<boolean> = computed(
+ [$sidebarStatusFilter, $sidebarProjectFilter, $sidebarPrFilter, $sidebarShowArchived],
+ (statuses, projects, prs, archived) => statuses.length > 0 || projects.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
+)
+
// When true, the sessions sidebar moves to the right and the file browser +
// preview rail move to the left — a mirror of the default layout.
export const $panesFlipped = persistentAtom(PANES_FLIPPED_STORAGE_KEY, false, Codecs.bool)
@@ -214,6 +328,16 @@ export function toggleWorkspaceNodeCollapsed(id: string, defaultOpen = true): vo
setWorkspaceNodeOpen(id, !workspaceNodeOpen(id, defaultOpen))
}
+// Fold a whole level shut (or open) in one write — the sidebar's "Collapse all"
+// over the project rows. Their lanes keep their own state underneath, so
+// re-opening a project shows it as the user left it.
+export function setWorkspaceNodesOpen(ids: readonly string[], open: boolean): void {
+ $sidebarWorkspaceNodeOpen.set({
+ ...$sidebarWorkspaceNodeOpen.get(),
+ ...Object.fromEntries(ids.map(id => [id, open]))
+ })
+}
+
// Dismiss ("delete") an auto-derived project from the overview.
export function dismissAutoProject(id: string): void {
const current = $dismissedAutoProjectIds.get()
@@ -367,6 +491,79 @@ export function setSidebarAgentsGrouped(grouped: boolean) {
$sidebarAgentsGrouped.set(grouped)
}
+export function setSidebarGrouping(grouping: SidebarGrouping) {
+ setSidebarAgentsGrouped(grouping === 'project')
+
+ if (grouping !== 'project') {
+ $sidebarFlatGrouping.set(grouping)
+ }
+}
+
+export function setSidebarOrdering(ordering: SidebarOrdering) {
+ if (ordering === 'manual') {
+ setSidebarSessionOrderManual(true)
+
+ return
+ }
+
+ // Picking a sort key is the only way back out of a hand-dragged order, so it
+ // has to drop the saved sequence as well as the flag.
+ setSidebarSessionOrderManual(false)
+ setSidebarSessionOrderIds([])
+ $sidebarSortKey.set(ordering)
+}
+
+export function setSidebarShowArchived(show: boolean) {
+ $sidebarShowArchived.set(show)
+}
+
+function toggleIn<T extends string>($atom: WritableAtom<T[]>, value: T) {
+ const current = $atom.get()
+
+ $atom.set(current.includes(value) ? current.filter(item => item !== value) : [...current, value])
+}
+
+export function toggleSidebarRowMeta(meta: SidebarRowMeta) {
+ toggleIn($sidebarRowMeta, meta)
+}
+
+export function toggleSidebarStatusFilter(status: SessionStatusBucket) {
+ toggleIn($sidebarStatusFilter, status)
+}
+
+export function toggleSidebarProjectFilter(projectId: string) {
+ toggleIn($sidebarProjectFilter, projectId)
+}
+
+export function toggleSidebarPrFilter(bucket: PullRequestBucket) {
+ toggleIn($sidebarPrFilter, bucket)
+}
+
+function clearSidebarFilters() {
+ $sidebarStatusFilter.set([])
+ $sidebarProjectFilter.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. */
+export function resetSidebarView() {
+ setSidebarGrouping('date')
+ setSidebarOrdering('updated')
+ $sidebarRowMeta.set([])
+ clearSidebarFilters()
+}
+
+/** Whether anything on screen needs PR data — the gate on shelling out to
+ * `gh`. Nobody pays for a network call per repo to render a view that would
+ * not show a PR anywhere. */
+export const $sidebarPrDataWanted: ReadableAtom<boolean> = computed(
+ [$sidebarRowMeta, $sidebarPrFilter],
+ (rowMeta, prFilter) => rowMeta.includes('pr') || prFilter.length > 0
+)
+
// Write an order list only when it actually changed, so an identical drag
// result keeps the same array reference and subscribers don't churn.
function setOrderIds($atom: WritableAtom<string[]>, ids: string[]) {
@@ -447,6 +644,18 @@ export function bumpSessionsLimit(step: number = SIDEBAR_SESSIONS_PAGE_SIZE) {
$sessionsLimit.set($sessionsLimit.get() + safeStep)
}
+/** Raise the window to at least `floor`, never shrinking it. Returns true when
+ * it moved, so the caller knows a refetch is worth it. */
+export function raiseSessionsLimit(floor: number): boolean {
+ if ($sessionsLimit.get() >= floor) {
+ return false
+ }
+
+ $sessionsLimit.set(floor)
+
+ return true
+}
+
export function resetSessionsLimit() {
if ($sessionsLimit.get() !== SIDEBAR_SESSIONS_PAGE_SIZE) {
$sessionsLimit.set(SIDEBAR_SESSIONS_PAGE_SIZE)
diff --git a/apps/desktop/src/store/session-dot-state.ts b/apps/desktop/src/store/session-dot-state.ts
index 2d8a56a0f75..bf94a1658ed 100644
--- a/apps/desktop/src/store/session-dot-state.ts
+++ b/apps/desktop/src/store/session-dot-state.ts
@@ -37,6 +37,24 @@ export const showsRunningArc = (state: SessionDotState): boolean => state === 's
* answer has not ended. */
export const hasLiveTurn = (state: SessionDotState): boolean => showsRunningArc(state) || state === 'needs-input'
+/** The buckets the sidebar's status filter and ordering work in. `stalled` and
+ * `background` fold into the state a user would name them. */
+export type SessionStatusBucket = 'draft' | 'idle' | 'needs-input' | 'unread' | 'working'
+
+export const sessionStatusBucket = (state: SessionDotState = 'idle'): SessionStatusBucket =>
+ state === 'stalled' || state === 'background' ? 'working' : state
+
+const STATUS_RANK: Record<SessionStatusBucket, number> = {
+ 'needs-input': 0,
+ working: 1,
+ unread: 2,
+ draft: 3,
+ idle: 4
+}
+
+/** Loudest first — what ordering by status sorts on. */
+export const sessionStatusRank = (state?: SessionDotState): number => STATUS_RANK[sessionStatusBucket(state)]
+
let dotStates: Readonly<Record<string, SessionDotState>> = {}
export const $sessionDotStateById = computed(
diff --git a/apps/desktop/src/store/session.ts b/apps/desktop/src/store/session.ts
index cd1e6003e4c..a8024c0739f 100644
--- a/apps/desktop/src/store/session.ts
+++ b/apps/desktop/src/store/session.ts
@@ -603,6 +603,12 @@ export const setActiveSessionStoredIdRotation = (next: Updater<ActiveSessionStor
// Written by session-states.ts (handleTransition), cleared here on session open.
export const $unreadFinishedSessionIds = atom<string[]>([])
+export const markAllSessionsRead = () => {
+ if ($unreadFinishedSessionIds.get().length) {
+ $unreadFinishedSessionIds.set([])
+ }
+}
+
export const setSelectedStoredSessionId = (next: Updater<string | null>) => {
updateAtom($selectedStoredSessionId, next)
// Opening a session clears its unread state — the user is now looking at it.
diff --git a/apps/desktop/src/store/sidebar-archive.ts b/apps/desktop/src/store/sidebar-archive.ts
new file mode 100644
index 00000000000..52652b9c46b
--- /dev/null
+++ b/apps/desktop/src/store/sidebar-archive.ts
@@ -0,0 +1,40 @@
+import { atom, computed } from 'nanostores'
+
+import { listAllProfileSessions, type SessionInfo } from '@/hermes'
+
+import { $sessions } from './session'
+
+// Archived rows are excluded from the sessions query, so the Archived view has
+// to fetch its own set. Capped: it's a lookup surface, not a feed.
+const ARCHIVED_FETCH_LIMIT = 200
+
+export const $archivedSessions = atom<SessionInfo[]>([])
+export const $archivedSessionsLoading = atom(false)
+
+export async function loadArchivedSessions(): Promise<void> {
+ if ($archivedSessionsLoading.get()) {
+ return
+ }
+
+ $archivedSessionsLoading.set(true)
+
+ try {
+ const result = await listAllProfileSessions(ARCHIVED_FETCH_LIMIT, 0, 'only')
+
+ $archivedSessions.set(result.sessions)
+ } catch {
+ $archivedSessions.set([])
+ } finally {
+ $archivedSessionsLoading.set(false)
+ }
+}
+
+/** Spend on a session — provider-reported price when we have one, our own
+ * estimate otherwise. */
+export const sessionCostUsd = (session: SessionInfo): number =>
+ session.actual_cost_usd || session.estimated_cost_usd || 0
+
+/** Whether ANY loaded session reports spend. Subscription auth never quotes a
+ * price, so for those users a cost sort would rank a list of zeroes — the
+ * menu hides the option instead of offering a dead one. */
+export const $sessionsHaveCost = computed($sessions, sessions => sessions.some(session => sessionCostUsd(session) > 0))
diff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.ts
index ad0ba7d180d..7b298a5fccf 100644
--- a/apps/desktop/src/types/hermes.ts
+++ b/apps/desktop/src/types/hermes.ts
@@ -481,6 +481,12 @@ export interface SessionInfo {
* pins so a pinned conversation survives auto-compression. */
_lineage_root_id?: null | string
input_tokens: number
+ /** Spend for the session, straight off the `sessions` row. `actual` is set
+ * when the provider reported a price; `estimated` is our own pricing-table
+ * math. Both are 0 on subscription auth that never quotes a price, which is
+ * why the sidebar only offers a cost sort when some session has spend. */
+ actual_cost_usd?: null | number
+ estimated_cost_usd?: null | number
is_active: boolean
last_active: number
message_count: number