feat(sidebar): add repo-grouped session navigation with live status (#361)

* feat(sidebar): add repo-grouped session navigation with live status

- Add a searchable, collapsible session tree to the desktop sidebar, grouped by repository with pinned and time-bucketed ordering.
- Track per-session busy, retry, and compact status in a shared store fed by the SSE event stream and scoped by directory.
- Extract shared navigation components reused by the desktop tree and the mobile repo quick-switch sheet.
- Show a Git tab and hide Schedules inside a repo on the mobile tab bar; add Repos and Assistant entries to the session More drawer.
- Replace the CommitsTab local relative-time formatter with a shared formatShortRelativeTime util.

* refactor(sidebar): unify session status tracking and navigation helpers

* feat(sidebar): add collapsible sessions and menu sections

* fix(sessions): keep specific live status over snapshot busy
This commit is contained in:
Chris Scott authored and GitHub committed 2026-09-26 21:50:23 -04:00
1 parent 1389e8e59c
commit 015a44a5f3
45 files changed
+3347 -763

No files matched your search

@@ -0,0 +1,363 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { MemoryRouter, useLocation } from 'react-router-dom'
import type { ReactNode } from 'react'
import { TooltipProvider } from '@/components/ui/tooltip'
import { DesktopSessionTree } from './DesktopSessionTree'
import type { Repo } from '@/api/types'
type SessionFixture = {
id: string
projectID: string
title: string
time: { created: number; updated: number; archived?: number }
location: { directory: string }
parentID?: string
cost: number
tokens: { input: number; output: number; reasoning: number; cache: { read: number; write: number } }
}
type SessionsHookCall = { directories: string[]; options?: { search?: string; limit?: number } }
type SessionPinFixture = { sessionId: string; directory: string; pinnedAt: number }
const {
listReposMock,
sessionsData,
sessionsHookCalls,
createSessionCalls,
permissionSessions,
formSessions,
emptyOnSearch,
getSessionMock,
sessionPinsData,
sessionsHasNextPage,
} = vi.hoisted(() => ({
listReposMock: vi.fn(),
sessionsData: [] as SessionFixture[],
sessionsHookCalls: [] as SessionsHookCall[],
createSessionCalls: [] as Array<{ directory?: string; vars?: unknown }>,
permissionSessions: { current: new Set<string>() },
formSessions: { current: new Set<string>() },
emptyOnSearch: { current: false },
getSessionMock: vi.fn(),
sessionPinsData: { current: [] as SessionPinFixture[] },
sessionsHasNextPage: { current: false },
}))
vi.mock('@/api/repos', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/api/repos')>()
return { ...actual, listRepos: listReposMock }
})
vi.mock('@/api/opencode', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/api/opencode')>()
return { ...actual, getSession: getSessionMock }
})
vi.mock('@/hooks/useOpenCode', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/hooks/useOpenCode')>()
return {
...actual,
useSessionsAcrossDirectories: (directories: string[], options?: { search?: string; limit?: number }) => {
sessionsHookCalls.push({ directories, options })
const data =
options?.search && emptyOnSearch.current
? []
: sessionsData.filter((session) => directories.includes(session.location.directory))
return { data, isLoading: false, isError: false, hasNextPage: sessionsHasNextPage.current }
},
useCreateSession: (directory?: string) => ({
mutate: (vars?: unknown) => {
createSessionCalls.push({ directory, vars })
},
}),
}
})
vi.mock('@/hooks/useSessionPins', () => ({
useSessionPins: () => ({ data: sessionPinsData.current }),
}))
vi.mock('@/contexts/EventContext', () => ({
usePermissions: () => ({
hasForSession: (sessionID: string) => permissionSessions.current.has(sessionID),
}),
useForms: () => ({
hasForSession: (sessionID: string) => formSessions.current.has(sessionID),
}),
}))
function createRepo(overrides: Partial<Repo> & { id: number; fullPath: string }): Repo {
return {
localPath: `repos/${overrides.id}`,
defaultBranch: 'main',
cloneStatus: 'ready',
clonedAt: 0,
...overrides,
}
}
function createSession(id: string, directory: string, updated = Date.now()): SessionFixture {
return {
id,
projectID: 'proj-1',
title: `Session ${id}`,
time: { created: updated - 10000, updated },
location: { directory },
cost: 0,
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
}
}
const repoA = createRepo({ id: 1, fullPath: '/repos/a', name: 'Alpha', lastAccessedAt: 20 })
const repoB = createRepo({ id: 2, fullPath: '/repos/b', name: 'Beta', lastAccessedAt: 10 })
const repoC = createRepo({ id: 3, fullPath: '/repos/c', name: 'Gamma', lastAccessedAt: 30 })
function LocationDisplay() {
const location = useLocation()
return <div data-testid="location">{location.pathname}</div>
}
function createWrapper(initialEntries: string[]) {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
})
return ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>
<TooltipProvider>
<MemoryRouter initialEntries={initialEntries}>
{children}
<LocationDisplay />
</MemoryRouter>
</TooltipProvider>
</QueryClientProvider>
)
}
const toggleFor = (name: string) => screen.getByRole('button', { name: `Show sessions in ${name}` })
const fetchedDirectories = () => new Set(sessionsHookCalls.flatMap((call) => call.directories))
describe('DesktopSessionTree', () => {
beforeEach(() => {
listReposMock.mockReset()
listReposMock.mockResolvedValue([repoA, repoB, repoC])
sessionsData.splice(
0,
sessionsData.length,
createSession('a1', '/repos/a'),
createSession('b1', '/repos/b'),
createSession('c1', '/repos/c'),
)
sessionsHookCalls.splice(0, sessionsHookCalls.length)
createSessionCalls.splice(0, createSessionCalls.length)
permissionSessions.current = new Set()
formSessions.current = new Set()
emptyOnSearch.current = false
getSessionMock.mockReset()
getSessionMock.mockResolvedValue(undefined)
sessionPinsData.current = []
sessionsHasNextPage.current = false
})
it('lists every repo by last access, even inside a repo, with no Recent section', async () => {
render(<DesktopSessionTree />, { wrapper: createWrapper(['/repos/1']) })
await screen.findByText('Alpha')
const names = screen
.getAllByRole('button', { name: /^Show sessions in / })
.map((button) => button.getAttribute('aria-label'))
expect(names).toEqual(['Show sessions in Gamma', 'Show sessions in Alpha', 'Show sessions in Beta'])
expect(screen.queryByText('Recent')).toBeNull()
})
it('opens the active repo by default and lazily fetches only its sessions', async () => {
render(<DesktopSessionTree />, { wrapper: createWrapper(['/repos/1']) })
expect(await screen.findByRole('button', { name: /^Session a1/ })).toBeTruthy()
expect(toggleFor('Alpha')).toHaveAttribute('aria-expanded', 'true')
expect(toggleFor('Beta')).toHaveAttribute('aria-expanded', 'false')
expect(screen.queryByRole('button', { name: /^Session b1/ })).toBeNull()
expect(fetchedDirectories()).toEqual(new Set(['/repos/a']))
})
it('opens nothing outside a repo', async () => {
render(<DesktopSessionTree />, { wrapper: createWrapper(['/']) })
await screen.findByText('Alpha')
expect(screen.queryByRole('button', { name: /^Session / })).toBeNull()
expect(sessionsHookCalls).toHaveLength(0)
})
it('keeps only one repo open at a time', async () => {
const user = userEvent.setup()
render(<DesktopSessionTree />, { wrapper: createWrapper(['/repos/1']) })
await screen.findByRole('button', { name: /^Session a1/ })
await user.click(toggleFor('Beta'))
expect(toggleFor('Alpha')).toHaveAttribute('aria-expanded', 'false')
expect(toggleFor('Beta')).toHaveAttribute('aria-expanded', 'true')
expect(screen.getByRole('button', { name: /^Session b1/ })).toBeTruthy()
expect(screen.queryByRole('button', { name: /^Session a1/ })).toBeNull()
await user.click(toggleFor('Beta'))
expect(toggleFor('Beta')).toHaveAttribute('aria-expanded', 'false')
expect(screen.queryByRole('button', { name: /^Session / })).toBeNull()
})
it('opens the repo page when the repo name is clicked', async () => {
const user = userEvent.setup()
render(<DesktopSessionTree />, { wrapper: createWrapper(['/']) })
await user.click(await screen.findByRole('button', { name: 'Beta' }))
expect(screen.getByTestId('location').textContent).toBe('/repos/2')
})
it('navigates to a session and marks it current', async () => {
const user = userEvent.setup()
sessionsData.push(createSession('a2', '/repos/a', Date.now() - 1000))
render(<DesktopSessionTree />, { wrapper: createWrapper(['/repos/1/sessions/a1']) })
expect(await screen.findByRole('button', { name: /^Session a1/ })).toHaveAttribute('aria-current', 'page')
await user.click(screen.getByRole('button', { name: /^Session a2/ }))
expect(screen.getByTestId('location').textContent).toBe('/repos/1/sessions/a2')
expect(screen.getByRole('button', { name: /^Session a2/ })).toHaveAttribute('aria-current', 'page')
expect(screen.getByRole('button', { name: /^Session a1/ })).not.toHaveAttribute('aria-current')
})
it('offers All sessions when there is a next page', async () => {
const user = userEvent.setup()
sessionsHasNextPage.current = true
render(<DesktopSessionTree />, { wrapper: createWrapper(['/repos/1/sessions/a1']) })
await user.click(await screen.findByText('All sessions'))
expect(screen.getByTestId('location').textContent).toBe('/repos/1')
})
it('hides All sessions when there is no next page', async () => {
render(<DesktopSessionTree />, { wrapper: createWrapper(['/repos/1']) })
await screen.findByRole('button', { name: /^Session a1/ })
expect(screen.queryByText('All sessions')).toBeNull()
})
it('shows a pinned session that is outside the first page', async () => {
sessionsData.splice(
0,
sessionsData.length,
createSession('a1', '/repos/a', Date.now()),
createSession('a2', '/repos/a', Date.now() - 1000),
)
sessionPinsData.current = [{ sessionId: 'old', directory: '/repos/a', pinnedAt: 1 }]
getSessionMock.mockImplementation((id: string) =>
Promise.resolve(createSession(id, '/repos/a', Date.now() - 100000)),
)
render(<DesktopSessionTree />, { wrapper: createWrapper(['/repos/1']) })
await screen.findByRole('button', { name: /Session old/ })
const rows = screen.getAllByRole('button', { name: /Session / })
expect(rows[0]).toHaveTextContent('Session old')
expect(rows[0].querySelector('[aria-label="Pinned"]')).not.toBeNull()
expect(getSessionMock).toHaveBeenCalledWith('old')
})
it('keeps a non-ready repo navigable without actions or session requests', async () => {
const user = userEvent.setup()
const notReady = createRepo({ id: 4, fullPath: '/repos/d', name: 'Delta', cloneStatus: 'cloning' })
listReposMock.mockResolvedValue([repoA, notReady])
render(<DesktopSessionTree />, { wrapper: createWrapper(['/repos/4']) })
await screen.findByText('Delta')
expect(toggleFor('Delta')).toHaveAttribute('aria-expanded', 'true')
expect(screen.queryByRole('button', { name: 'New session in Delta' })).toBeNull()
expect(await screen.findByText('Repository not ready')).toBeTruthy()
expect(fetchedDirectories()).not.toContain('/repos/d')
await user.click(screen.getByRole('button', { name: 'Delta' }))
expect(screen.getByTestId('location').textContent).toBe('/repos/4')
})
it('commits the search on Enter across ready repos and clears with Escape', async () => {
const user = userEvent.setup()
listReposMock.mockResolvedValue([repoA, repoB, createRepo({ id: 4, fullPath: '/repos/d', name: 'Delta', cloneStatus: 'cloning' })])
render(<DesktopSessionTree />, { wrapper: createWrapper(['/']) })
const input = await screen.findByLabelText('Search sessions')
await screen.findByText('Alpha')
await user.type(input, 'Session{Enter}')
const searchCall = sessionsHookCalls.find((call) => call.options?.search === 'Session')
expect(searchCall?.directories).toEqual(['/repos/a', '/repos/b'])
expect(await screen.findByRole('button', { name: /^Session a1/ })).toBeTruthy()
expect(screen.getByRole('button', { name: /^Session b1/ })).toBeTruthy()
expect(screen.queryByRole('button', { name: /^Show sessions in / })).toBeNull()
await user.type(input, '{Escape}')
expect(input).toHaveValue('')
await waitFor(() => expect(screen.queryByRole('button', { name: /^Session / })).toBeNull())
expect(toggleFor('Alpha')).toBeTruthy()
})
it('clears a committed search with the clear button', async () => {
const user = userEvent.setup()
render(<DesktopSessionTree />, { wrapper: createWrapper(['/']) })
const input = await screen.findByLabelText('Search sessions')
await user.type(input, 'Session{Enter}')
await screen.findByRole('button', { name: /^Session a1/ })
await user.click(screen.getByLabelText('Clear search'))
expect(input).toHaveValue('')
expect(screen.queryByLabelText('Clear search')).toBeNull()
expect(toggleFor('Alpha')).toBeTruthy()
})
it('shows the empty search state when a committed search returns nothing', async () => {
const user = userEvent.setup()
emptyOnSearch.current = true
render(<DesktopSessionTree />, { wrapper: createWrapper(['/']) })
const input = await screen.findByLabelText('Search sessions')
await user.type(input, 'nothing{Enter}')
expect(await screen.findByText('No sessions found')).toBeTruthy()
})
it('creates a session in the repo full path', async () => {
const user = userEvent.setup()
render(<DesktopSessionTree />, { wrapper: createWrapper(['/']) })
await user.click(await screen.findByRole('button', { name: 'New session in Beta' }))
expect(createSessionCalls).toContainEqual({ directory: '/repos/b', vars: { agent: undefined } })
})
it('renders permission and form badges for sessions with pending requests', async () => {
sessionsData.push(createSession('a2', '/repos/a', Date.now() - 1000))
permissionSessions.current = new Set(['a1'])
formSessions.current = new Set(['a2'])
render(<DesktopSessionTree />, { wrapper: createWrapper(['/repos/1']) })
await screen.findByRole('button', { name: /^Session a1/ })
expect(screen.getByLabelText('Pending permission')).toBeTruthy()
expect(screen.getByLabelText('Pending form')).toBeTruthy()
})
})
@@ -0,0 +1,132 @@
import { useMemo, useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import { Search } from 'lucide-react'
import type { Repo } from '@/api/types'
import { Input } from '@/components/ui/input'
import { useNavigableRepos, useSidebarRepoGroups } from '@/hooks/useSidebarRepoGroups'
import {
NewSessionButton,
RepoNavGroup,
RepoSessionNavList,
SearchClearButton,
SessionNavRow,
SessionNavStatus,
} from '@/components/navigation/RepoSessionNav'
import { getActiveRepoId, isCurrentSessionItem, isRepoReady } from '@/components/navigation/sidebar-session-tree'
function SessionSearchInput({
hasActiveSearch,
onSubmit,
onClear,
}: {
hasActiveSearch: boolean
onSubmit: (query: string) => void
onClear: () => void
}) {
const [draft, setDraft] = useState('')
const clear = () => {
setDraft('')
onClear()
}
const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
if (event.key === 'Enter') {
event.preventDefault()
onSubmit(draft.trim())
} else if (event.key === 'Escape') {
clear()
}
}
return (
<div className="relative">
<Search className="absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
value={draft}
onChange={(event) => setDraft(event.target.value)}
onKeyDown={handleKeyDown}
aria-label="Search sessions"
placeholder="Search sessions..."
autoComplete="off"
name="sidebar-session-search"
className="h-8 pl-8 pr-9"
/>
{(draft.length > 0 || hasActiveSearch) && <SearchClearButton onClear={clear} />}
</div>
)
}
function SessionSearchResults({ repos, search }: { repos: Repo[]; search: string }) {
const navigate = useNavigate()
const location = useLocation()
const searchableRepos = useMemo(() => repos.filter(isRepoReady), [repos])
const { groups, isLoading, isError } = useSidebarRepoGroups({ repos: searchableRepos, search })
const matchingGroups = groups.filter((group) => group.items.length > 0)
if (isLoading) return <SessionNavStatus>Loading sessions...</SessionNavStatus>
if (isError) return <SessionNavStatus>Failed to load sessions</SessionNavStatus>
if (matchingGroups.length === 0) return <SessionNavStatus>No sessions found</SessionNavStatus>
return (
<>
{matchingGroups.map((group) => (
<RepoNavGroup
key={group.repo.id}
name={group.label}
branch={group.branchLabel}
isWorktree={group.repo.isWorktree}
isOpen
isCurrent={group.repo.id === getActiveRepoId(location.pathname)}
onOpenRepo={() => navigate(`/repos/${group.repo.id}`)}
actions={<NewSessionButton repo={group.repo} onOpenSession={navigate} />}
>
{group.items.map((item) => (
<SessionNavRow
key={item.key}
item={item}
isCurrent={isCurrentSessionItem(item, location.pathname)}
onSelect={navigate}
/>
))}
</RepoNavGroup>
))}
</>
)
}
export function DesktopSessionTree() {
const navigate = useNavigate()
const location = useLocation()
const [search, setSearch] = useState('')
const { repos, isLoading } = useNavigableRepos()
return (
<div className="flex min-h-0 flex-1 flex-col">
<div className="px-2 pb-2">
<SessionSearchInput
hasActiveSearch={search.length > 0}
onSubmit={setSearch}
onClear={() => setSearch('')}
/>
</div>
<div role="region" aria-label="Session navigator" className="min-h-0 flex-1 overflow-y-auto pb-2">
{isLoading ? (
<SessionNavStatus>Loading repos...</SessionNavStatus>
) : search ? (
<SessionSearchResults repos={repos} search={search} />
) : (
<RepoSessionNavList
repos={repos}
activeRepoId={getActiveRepoId(location.pathname)}
isVisible
onOpenRepo={(repoId) => navigate(`/repos/${repoId}`)}
onSelectSession={navigate}
renderActions={(repo) => <NewSessionButton repo={repo} onOpenSession={navigate} />}
/>
)}
</div>
</div>
)
}
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { MemoryRouter, useLocation, useNavigate } from 'react-router-dom'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { TooltipProvider } from '@/components/ui/tooltip'
import { DesktopSidebar } from './DesktopSidebar'
import * as useDesktopModule from '@/hooks/useDesktop'
import * as useSidebarCollapsedModule from '@/hooks/useSidebarCollapsed'
@@ -10,6 +11,9 @@ import * as useAuthModule from '@/hooks/useAuth'
vi.mock('@/hooks/useDesktop')
vi.mock('@/hooks/useSidebarCollapsed')
vi.mock('@/hooks/useAuth')
vi.mock('@/components/navigation/DesktopSessionTree', () => ({
DesktopSessionTree: () => <div data-testid="session-tree" />,
}))
function LocationDisplay() {
const location = useLocation()
@@ -34,7 +38,7 @@ function createWrapper(initialEntries?: string[]) {
return ({ children }: { children: React.ReactNode }) => (
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={initialEntries}>
{children}
<TooltipProvider>{children}</TooltipProvider>
</MemoryRouter>
</QueryClientProvider>
)
@@ -43,6 +47,7 @@ function createWrapper(initialEntries?: string[]) {
describe('DesktopSidebar', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.mocked(useSidebarCollapsedModule.useSidebarSectionCollapsed).mockReturnValue([false, vi.fn()])
})
it('returns null when user is not authenticated', () => {
@@ -125,7 +130,7 @@ describe('DesktopSidebar', () => {
render(<DesktopSidebar />, { wrapper: createWrapper(['/repos/5']) })
expect(screen.getByText('New Session')).toBeInTheDocument()
expect(screen.queryByText('New Session')).toBeNull()
expect(screen.getByText('Assistant')).toBeInTheDocument()
})
@@ -140,7 +145,7 @@ describe('DesktopSidebar', () => {
render(<DesktopSidebar />, { wrapper: createWrapper(['/repos/5/sessions/abc']) })
expect(screen.getByText('New Session')).toBeInTheDocument()
expect(screen.queryByText('New Session')).toBeNull()
expect(screen.getByText('Assistant')).toBeInTheDocument()
})
@@ -169,14 +174,14 @@ describe('DesktopSidebar', () => {
logout: vi.fn(),
} as any)
render(<DesktopSidebar />, { wrapper: createWrapper(['/repos/5']) })
render(<DesktopSidebar />, { wrapper: createWrapper(['/']) })
fireEvent.click(screen.getByText('New Session'))
fireEvent.click(screen.getByText('New Repo'))
expect(dispatchEventSpy).toHaveBeenCalledWith(
expect.objectContaining({
type: 'oc:sidebar:action',
detail: { action: 'new-session' },
detail: { action: 'new-repo' },
})
)
})
@@ -250,4 +255,93 @@ describe('DesktopSidebar', () => {
expect(screen.getByTestId('location').textContent).toBe('/repos/5/schedules?returnTo=%2Frepos%2F5%2Fsessions%2Fabc%3Fassistant%3D1')
})
it('renders the session tree, tool toolbar and account footer when expanded', () => {
vi.spyOn(useDesktopModule, 'useDesktop').mockReturnValue(true)
vi.spyOn(useSidebarCollapsedModule, 'useSidebarCollapsed').mockReturnValue([false, vi.fn()])
vi.spyOn(useAuthModule, 'useAuth').mockReturnValue({
isAuthenticated: true,
isLoading: false,
logout: vi.fn(),
} as any)
render(<DesktopSidebar />, { wrapper: createWrapper(['/repos/5']) })
expect(screen.getByTestId('session-tree')).toBeInTheDocument()
expect(screen.getByText('Files')).toBeInTheDocument()
expect(screen.getByText('Settings')).toBeInTheDocument()
expect(screen.getByText('Logout')).toBeInTheDocument()
})
it('renders the vertical nav list and no session tree when collapsed', () => {
vi.spyOn(useDesktopModule, 'useDesktop').mockReturnValue(true)
vi.spyOn(useSidebarCollapsedModule, 'useSidebarCollapsed').mockReturnValue([true, vi.fn()])
vi.spyOn(useAuthModule, 'useAuth').mockReturnValue({
isAuthenticated: true,
isLoading: false,
logout: vi.fn(),
} as any)
render(<DesktopSidebar />, { wrapper: createWrapper(['/repos/5']) })
expect(screen.queryByTestId('session-tree')).toBeNull()
expect(screen.getByText('Files')).toBeInTheDocument()
expect(screen.getByText('Settings')).toBeInTheDocument()
})
it('hides the session tree when the sessions section is collapsed', () => {
vi.spyOn(useDesktopModule, 'useDesktop').mockReturnValue(true)
vi.spyOn(useSidebarCollapsedModule, 'useSidebarCollapsed').mockReturnValue([false, vi.fn()])
vi.mocked(useSidebarCollapsedModule.useSidebarSectionCollapsed).mockImplementation((section: string) =>
section === 'sessions' ? [true, vi.fn()] : [false, vi.fn()],
)
vi.spyOn(useAuthModule, 'useAuth').mockReturnValue({
isAuthenticated: true,
isLoading: false,
logout: vi.fn(),
} as any)
render(<DesktopSidebar />, { wrapper: createWrapper(['/repos/5']) })
expect(screen.queryByTestId('session-tree')).toBeNull()
expect(screen.getByText('Files')).toBeInTheDocument()
})
it('hides the menu items when the menu section is collapsed', () => {
vi.spyOn(useDesktopModule, 'useDesktop').mockReturnValue(true)
vi.spyOn(useSidebarCollapsedModule, 'useSidebarCollapsed').mockReturnValue([false, vi.fn()])
vi.mocked(useSidebarCollapsedModule.useSidebarSectionCollapsed).mockImplementation((section: string) =>
section === 'menu' ? [true, vi.fn()] : [false, vi.fn()],
)
vi.spyOn(useAuthModule, 'useAuth').mockReturnValue({
isAuthenticated: true,
isLoading: false,
logout: vi.fn(),
} as any)
render(<DesktopSidebar />, { wrapper: createWrapper(['/repos/5']) })
expect(screen.getByTestId('session-tree')).toBeInTheDocument()
expect(screen.queryByText('Files')).toBeNull()
expect(screen.getByText('Settings')).toBeInTheDocument()
})
it('toggles the sessions section from its header', () => {
const toggle = vi.fn()
vi.spyOn(useDesktopModule, 'useDesktop').mockReturnValue(true)
vi.spyOn(useSidebarCollapsedModule, 'useSidebarCollapsed').mockReturnValue([false, vi.fn()])
vi.mocked(useSidebarCollapsedModule.useSidebarSectionCollapsed).mockImplementation((section: string) =>
[false, section === 'sessions' ? toggle : vi.fn()],
)
vi.spyOn(useAuthModule, 'useAuth').mockReturnValue({
isAuthenticated: true,
isLoading: false,
logout: vi.fn(),
} as any)
render(<DesktopSidebar />, { wrapper: createWrapper(['/repos/5']) })
fireEvent.click(screen.getByRole('button', { name: 'Sessions' }))
expect(toggle).toHaveBeenCalledTimes(1)
})
})
@@ -1,25 +1,31 @@
import { useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import { useDesktop } from '@/hooks/useDesktop'
import { useSidebarCollapsed } from '@/hooks/useSidebarCollapsed'
import { useSidebarCollapsed, useSidebarSectionCollapsed } from '@/hooks/useSidebarCollapsed'
import { emitSidebarAction } from '@/hooks/useSidebarAction'
import { useAuth } from '@/hooks/useAuth'
import { useUrlParams } from '@/hooks/useUrlParams'
import { buildNavModel, type MoreDrawerItem, type NavPrimaryCta } from '@/components/navigation/moreDrawerItems'
import { getPathWithReturnTo } from '@/lib/navigation'
import { RepoQuickSwitchSheet } from '@/components/navigation/RepoQuickSwitchSheet'
import { DesktopSessionTree } from '@/components/navigation/DesktopSessionTree'
import {
Sidebar,
SidebarCollapsibleSection,
SidebarSection,
SidebarItem,
} from '@/components/ui/sidebar'
import { FolderGit2 } from 'lucide-react'
const ACCOUNT_ITEM_KEYS = new Set(['settings', 'logout'])
export function DesktopSidebar() {
const location = useLocation()
const navigate = useNavigate()
const { updateParams } = useUrlParams()
const [collapsed, toggle] = useSidebarCollapsed()
const [sessionsCollapsed, toggleSessionsCollapsed] = useSidebarSectionCollapsed('sessions')
const [menuCollapsed, toggleMenuCollapsed] = useSidebarSectionCollapsed('menu')
const [repoSwitcherOpen, setRepoSwitcherOpen] = useState(false)
const { isAuthenticated, isLoading, logout } = useAuth()
@@ -73,10 +79,12 @@ export function DesktopSidebar() {
{ key: 'repos', label: 'Repos', icon: FolderGit2 },
...routeItems,
]
const toolItems = navItems.filter((item) => !ACCOUNT_ITEM_KEYS.has(item.key))
const accountItems = navItems.filter((item) => ACCOUNT_ITEM_KEYS.has(item.key))
return (
<>
<Sidebar collapsed={collapsed} onToggle={toggle} className='mt-2'>
<Sidebar collapsed={collapsed} onToggle={toggle} widthClass='w-72' className='mt-2'>
{primary.length > 0 && (
<SidebarSection collapsed={collapsed}>
{primary.map((item: NavPrimaryCta) => (
@@ -93,18 +101,65 @@ export function DesktopSidebar() {
</SidebarSection>
)}
<div className="flex flex-col gap-1 p-2 pt-0">
{navItems.map((item: MoreDrawerItem) => (
<SidebarItem
key={item.key}
icon={item.icon}
label={item.label}
collapsed={collapsed}
onClick={() => handleItemClick(item)}
danger={item.danger}
/>
))}
</div>
{collapsed ? (
<div className="flex flex-col gap-1 p-2 pt-0">
{navItems.map((item: MoreDrawerItem) => (
<SidebarItem
key={item.key}
icon={item.icon}
label={item.label}
collapsed={collapsed}
onClick={() => handleItemClick(item)}
danger={item.danger}
/>
))}
</div>
) : (
<>
<SidebarCollapsibleSection
label="Sessions"
collapsed={sessionsCollapsed}
onToggle={toggleSessionsCollapsed}
className="border-t border-border"
>
<DesktopSessionTree />
</SidebarCollapsibleSection>
<SidebarCollapsibleSection
label="Menu"
collapsed={menuCollapsed}
onToggle={toggleMenuCollapsed}
className="flex-1 min-h-fit border-t border-border"
contentClassName="overflow-y-auto"
>
<div className="flex flex-col gap-1 p-2 pt-0">
{toolItems.map((item: MoreDrawerItem) => (
<SidebarItem
key={item.key}
icon={item.icon}
label={item.label}
collapsed={false}
onClick={() => handleItemClick(item)}
danger={item.danger}
/>
))}
</div>
</SidebarCollapsibleSection>
<div className="flex gap-1 border-t border-border p-2">
{accountItems.map((item: MoreDrawerItem) => (
<SidebarItem
key={item.key}
icon={item.icon}
label={item.label}
collapsed
onClick={() => handleItemClick(item)}
danger={item.danger}
/>
))}
</div>
</>
)}
</Sidebar>
<RepoQuickSwitchSheet
@@ -59,7 +59,32 @@ describe('MobileTabBar', () => {
</QueryClientProvider>,
)
expect(screen.getByText('Repos')).toBeInTheDocument()
expect(screen.getByText('Schedules')).toBeInTheDocument()
expect(screen.getByText('Git')).toBeInTheDocument()
expect(screen.queryByText('Schedules')).not.toBeInTheDocument()
const labels = screen.getAllByRole('button').map((button) => button.textContent)
expect(labels).toEqual(['Repos', 'Files', 'Git', 'Assistant', 'More'])
})
it('opens the source control dialog when Git is clicked on repo detail path', async () => {
vi.mocked(useMobile).mockReturnValue(true)
const queryClient = new QueryClient()
const user = userEvent.setup()
render(
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={['/repos/123']}>
<Routes>
<Route path="*" element={<>
<MobileTabBar />
<LocationSpy />
</>} />
</Routes>
</MemoryRouter>
</QueryClientProvider>,
)
await user.click(screen.getByRole('button', { name: 'Git' }))
expect(screen.getByTestId('location')).toHaveTextContent('dialog=sourceControl')
})
it('renders global tabs on assistant session list path', () => {
@@ -152,6 +177,7 @@ describe('MobileTabBar', () => {
expect(screen.getByText('Assistant')).toBeInTheDocument()
expect(screen.getByText('Schedules')).toBeInTheDocument()
expect(screen.getByText('More')).toBeInTheDocument()
expect(screen.queryByText('Git')).not.toBeInTheDocument()
})
it('renders tab bar on /schedules path', () => {
@@ -1,12 +1,13 @@
import { memo, useMemo } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import { FolderGit2, FolderOpen, CalendarClock, Menu, Info, History, Bot } from 'lucide-react'
import { FolderGit2, FolderOpen, CalendarClock, Menu, Info, History, Bot, GitCommitHorizontal } from 'lucide-react'
import { cn } from '@/lib/utils'
import { useMobile } from '@/hooks/useMobile'
import { useMobileTabBar } from '@/hooks/useMobileTabBar'
import { useUrlParams } from '@/hooks/useUrlParams'
import { useScheduleUrlState, type ScheduleTab } from '@/hooks/useScheduleUrlState'
import { getAssistantPath, isAssistantPath } from '@/lib/navigation'
import { getAssistantPath, isAssistantPath, parseRepoRoute } from '@/lib/navigation'
import { openDialogParam } from '@/hooks/useDialogParam'
interface TabDef {
key: string
@@ -24,7 +25,7 @@ interface GlobalTabsArgs {
close: ReturnType<typeof useMobileTabBar>['close']
navigate: ReturnType<typeof useNavigate>
isInsideRepo: boolean
repoId: string | null
repoId: number | null
updateParams: ReturnType<typeof useUrlParams>['updateParams']
}
@@ -33,7 +34,7 @@ type TabBarMode = 'hidden' | 'global' | 'schedule'
interface MobileTabRouteState {
mode: TabBarMode
isInsideRepo: boolean
repoId: string | null
repoId: number | null
}
function getMobileTabRouteState(pathname: string): MobileTabRouteState {
@@ -41,20 +42,18 @@ function getMobileTabRouteState(pathname: string): MobileTabRouteState {
return { mode: 'global', isInsideRepo: false, repoId: null }
}
const repoMatch = pathname.match(/^\/repos\/(\d+)(?:\/([^/]+))?/)
const repoId = repoMatch?.[1] ?? null
const repoSection = repoMatch?.[2]
const { repoId, section: repoSection } = parseRepoRoute(pathname)
if (pathname === '/' || pathname === '/schedules') {
return { mode: 'global', isInsideRepo: false, repoId: null }
}
if (!repoId) {
if (repoId === null) {
return { mode: 'hidden', isInsideRepo: false, repoId: null }
}
switch (repoSection) {
case undefined:
case null:
return { mode: 'global', isInsideRepo: true, repoId }
case 'schedules':
return { mode: 'schedule', isInsideRepo: true, repoId }
@@ -64,9 +63,15 @@ function getMobileTabRouteState(pathname: string): MobileTabRouteState {
}
function buildGlobalTabs({ pathname, openSheet, open, close, navigate, isInsideRepo, repoId, updateParams }: GlobalTabsArgs): TabDef[] {
const openRepoDialog = (dialog: string) => {
openDialogParam(updateParams, dialog)
}
const inRepo = isInsideRepo && repoId !== null
const handleFilesClick = () => {
if (isInsideRepo && repoId) {
updateParams((p) => { p.set('dialog', 'files'); p.delete('mobileTab') }, 'push')
if (inRepo) {
openRepoDialog('files')
} else {
open('files')
}
@@ -92,6 +97,15 @@ function buildGlobalTabs({ pathname, openSheet, open, close, navigate, isInsideR
onClick: handleFilesClick,
active: openSheet === 'files',
},
...(inRepo
? [{
key: 'source-control',
label: 'Git',
icon: GitCommitHorizontal,
onClick: () => openRepoDialog('sourceControl'),
active: false,
}]
: []),
{
key: 'assistant',
label: 'Assistant',
@@ -99,13 +113,15 @@ function buildGlobalTabs({ pathname, openSheet, open, close, navigate, isInsideR
onClick: handleAssistantClick,
active: isAssistantPath(pathname) && !openSheet,
},
{
key: 'schedules',
label: 'Schedules',
icon: CalendarClock,
onClick: () => navigate('/schedules'),
active: pathname === '/schedules' && !openSheet,
},
...(!inRepo
? [{
key: 'schedules',
label: 'Schedules',
icon: CalendarClock,
onClick: () => navigate('/schedules'),
active: pathname === '/schedules' && !openSheet,
}]
: []),
{
key: 'more',
label: 'More',
@@ -262,4 +262,44 @@ describe('MoreDrawer', () => {
expect(navigateMock).toHaveBeenCalledWith('/repos/1/schedules?returnTo=%2Frepos%2F1%2Fsessions%2Fsession-1%3Fassistant%3D1')
})
it('swaps the menu for the Repos sheet from a session', () => {
const navigateMock = vi.fn()
vi.mocked(useNavigate).mockReturnValue(navigateMock)
mockAuth()
mockServerHealth()
renderMoreDrawer({ initialEntry: '/repos/1/sessions/session-1?mobileTab=more', routePath: '/repos/:id/sessions/:sessionId' })
fireEvent.click(screen.getByText('Repos'))
expect(navigateMock).toHaveBeenCalledWith({ search: 'mobileTab=repos' }, { replace: false })
})
it('keeps Home and hides the Repos row outside a session', () => {
mockAuth()
mockServerHealth()
renderMoreDrawer({ initialEntry: '/repos/1', routePath: '/repos/:id' })
expect(screen.getByText('Home')).toBeInTheDocument()
expect(screen.queryByText('Repos')).not.toBeInTheDocument()
})
it('offers the Assistant from a repo session', () => {
const navigateMock = vi.fn()
vi.mocked(useNavigate).mockReturnValue(navigateMock)
mockAuth()
mockServerHealth()
renderMoreDrawer({ initialEntry: '/repos/1/sessions/session-1', routePath: '/repos/:id/sessions/:sessionId' })
fireEvent.click(screen.getByRole('button', { name: 'Assistant' }))
expect(navigateMock).toHaveBeenCalledWith('/assistant')
})
it('does not offer the Assistant from an assistant session', () => {
mockAuth()
mockServerHealth()
renderMoreDrawer({ initialEntry: '/repos/1/sessions/session-1?assistant=1', routePath: '/repos/:id/sessions/:sessionId' })
expect(screen.queryByRole('button', { name: 'Assistant' })).not.toBeInTheDocument()
})
})
@@ -1,6 +1,6 @@
import { useNavigate, useLocation, useParams } from 'react-router-dom'
import { useState, useRef, useEffect } from 'react'
import { ChevronDown, ChevronRight, Command as CommandIcon, FileText, X, GitBranch } from 'lucide-react'
import { ChevronDown, ChevronRight, Command as CommandIcon, FileText, FolderGit2, X, GitBranch } from 'lucide-react'
import { useAuth } from '@/hooks/useAuth'
import { useServerHealth } from '@/hooks/useServerHealth'
import { useCommands } from '@/hooks/useCommands'
@@ -11,11 +11,12 @@ import { getRepo } from '@/api/repos'
import { useRefreshOnOpen } from '@/hooks/useRefreshOnOpen'
import { SideDrawer, SideDrawerContent } from '@/components/ui/side-drawer'
import { FileBrowserSheet } from '@/components/file-browser/FileBrowserSheet'
import { buildMoreItems } from './moreDrawerItems'
import { buildMoreItems, buildNavModel } from './moreDrawerItems'
import { useSwipeBack } from '@/hooks/useMobile'
import { getRepoDisplayName } from '@/lib/utils'
import { getPathWithReturnTo, isAssistantPath } from '@/lib/navigation'
import type { CommandInfo } from '@opencode-manager/shared/opencode'
import { useMobileTabBar } from '@/hooks/useMobileTabBar'
interface MoreDrawerProps {
isOpen: boolean
@@ -41,6 +42,7 @@ export function MoreDrawer({ isOpen, onClose }: MoreDrawerProps) {
const activePromptFileBasePath = useUIState((state) => state.activePromptFileBasePath)
const selectPromptCommand = useUIState((state) => state.selectPromptCommand)
const selectPromptFile = useUIState((state) => state.selectPromptFile)
const { open: openMobileSheet } = useMobileTabBar()
useEffect(() => {
if (isOpen && swipeRef.current) {
@@ -116,6 +118,9 @@ export function MoreDrawer({ isOpen, onClose }: MoreDrawerProps) {
}
const items = buildMoreItems(location.pathname)
const assistantCta = isSessionDetail && !isAssistantSession
? buildNavModel(location.pathname).primary.find((cta) => cta.key === 'assistant')
: undefined
const commands = filterCommands('')
const opencodeVersion = health?.opencodeVersion
@@ -160,6 +165,25 @@ export function MoreDrawer({ isOpen, onClose }: MoreDrawerProps) {
<SideDrawerContent className="flex flex-col gap-1">
{isSessionDetail && (
<div className="flex flex-col gap-1">
<button
type="button"
onClick={() => openMobileSheet('repos')}
className="flex items-center gap-3 p-3 rounded-lg hover:bg-accent transition-colors text-left w-full"
>
<FolderGit2 className="w-5 h-5 text-muted-foreground" />
<span className="font-medium text-foreground flex-1">Repos</span>
<ChevronRight className="w-4 h-4 text-muted-foreground" />
</button>
{assistantCta?.to && (
<button
type="button"
onClick={() => navigate(assistantCta.to!)}
className="flex items-center gap-3 p-3 rounded-lg hover:bg-accent transition-colors text-left w-full"
>
<assistantCta.icon className="w-5 h-5 text-muted-foreground" />
<span className="font-medium text-foreground flex-1">{assistantCta.label}</span>
</button>
)}
<button
type="button"
onClick={() => setCommandsOpen((open) => !open)}
@@ -1,5 +1,5 @@
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { describe, it, expect, vi } from 'vitest'
import { beforeEach, describe, it, expect, vi } from 'vitest'
import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { RepoQuickSwitchSheet } from './RepoQuickSwitchSheet'
@@ -7,8 +7,91 @@ import { listRepos } from '@/api/repos'
import { useMobileTabBar } from '@/hooks/useMobileTabBar'
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
type SessionFixture = {
id: string
projectID: string
title: string
time: { created: number; updated: number }
location: { directory: string }
cost: number
tokens: { input: number; output: number; reasoning: number; cache: { read: number; write: number } }
}
const { sessionsData, sessionsHookCalls, permissionSessions, createSessionDirectories } = vi.hoisted(() => ({
sessionsData: [] as Array<{
id: string
projectID: string
title: string
time: { created: number; updated: number }
location: { directory: string }
cost: number
tokens: { input: number; output: number; reasoning: number; cache: { read: number; write: number } }
}>,
sessionsHookCalls: [] as string[][],
permissionSessions: { current: new Set<string>() },
createSessionDirectories: [] as string[],
}))
vi.mock('@/api/repos')
vi.mock('@/contexts/EventContext', () => ({
usePermissions: () => ({
hasForSession: (id: string) => permissionSessions.current.has(id),
}),
useForms: () => ({ hasForSession: () => false }),
}))
vi.mock('@/hooks/useOpenCode', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/hooks/useOpenCode')>()
return {
...actual,
useSessionsAcrossDirectories: (directories: string[]) => {
sessionsHookCalls.push(directories)
return { data: sessionsData, isLoading: false, isError: false }
},
useCreateSession: (directory: string, onSuccess?: (session: { id: string }) => void) => ({
mutate: () => {
createSessionDirectories.push(directory)
onSuccess?.({ id: 'new-session' })
},
}),
}
})
vi.mock('@/hooks/useSessionPins', () => ({
useSessionPins: () => ({ data: [] }),
}))
function createSession(id: string, updated: number, directory: string): SessionFixture {
return {
id,
projectID: 'proj-1',
title: `Session ${id}`,
time: { created: updated - 10000, updated },
location: { directory },
cost: 0,
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
}
}
function createRepo(id: number, name: string, fullPath: string) {
return {
id,
name,
repoUrl: `https://github.com/test/${name}.git`,
localPath: fullPath,
fullPath,
sourcePath: null,
currentBranch: 'main',
defaultBranch: 'main',
cloneStatus: 'ready' as const,
clonedAt: 0,
isLocal: false,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
}
}
function createWrapper() {
const queryClient = new QueryClient({
defaultOptions: {
@@ -44,6 +127,9 @@ function MobileSheetHarness() {
describe('RepoQuickSwitchSheet', () => {
beforeEach(() => {
vi.clearAllMocks()
sessionsData.splice(0, sessionsData.length)
sessionsHookCalls.splice(0, sessionsHookCalls.length)
permissionSessions.current.clear()
})
it('renders with loading state', async () => {
@@ -486,4 +572,242 @@ describe('RepoQuickSwitchSheet', () => {
expect(screen.getByTestId('location')).toHaveTextContent('/repos/2')
})
it('does not render sessions for collapsed repos and does not fetch them', async () => {
const now = Date.now()
vi.mocked(listRepos).mockResolvedValue([
createRepo(1, 'repo1', '/path/to/repo1'),
createRepo(2, 'repo2', '/path/to/repo2'),
])
sessionsData.push(createSession('s1', now, '/path/to/repo1'))
render(
<RepoQuickSwitchSheet isOpen onClose={vi.fn()} />,
{ wrapper: createWrapper() },
)
await waitFor(() => {
expect(screen.getByText('repo1')).toBeInTheDocument()
expect(screen.getByText('repo2')).toBeInTheDocument()
})
expect(screen.queryByText('Session s1')).not.toBeInTheDocument()
expect(sessionsHookCalls.some((directories) => directories.includes('/path/to/repo1'))).toBe(false)
})
it('expands a repo to show its sessions', async () => {
const now = Date.now()
vi.mocked(listRepos).mockResolvedValue([createRepo(1, 'repo1', '/path/to/repo1')])
sessionsData.push(createSession('s1', now, '/path/to/repo1'))
render(
<RepoQuickSwitchSheet isOpen onClose={vi.fn()} />,
{ wrapper: createWrapper() },
)
const toggle = await screen.findByRole('button', { name: 'Show sessions in repo1' })
expect(toggle).toHaveAttribute('aria-expanded', 'false')
fireEvent.click(toggle)
expect(await screen.findByText('Session s1')).toBeInTheDocument()
expect(toggle).toHaveAttribute('aria-expanded', 'true')
expect(sessionsHookCalls.some((directories) => directories.includes('/path/to/repo1'))).toBe(true)
})
it('navigates to a session when it is tapped', async () => {
const now = Date.now()
vi.mocked(listRepos).mockResolvedValue([createRepo(1, 'repo1', '/path/to/repo1')])
sessionsData.push(createSession('s1', now, '/path/to/repo1'))
render(
<QueryClientProvider client={new QueryClient()}>
<MemoryRouter initialEntries={['/?mobileTab=repos']}>
<Routes>
<Route path="*" element={<MobileSheetHarness />} />
</Routes>
</MemoryRouter>
</QueryClientProvider>,
)
fireEvent.click(await screen.findByRole('button', { name: 'Show sessions in repo1' }))
fireEvent.click(await screen.findByText('Session s1'))
expect(screen.getByTestId('location')).toHaveTextContent('/repos/1/sessions/s1')
})
it('expands the active repo by default and shows its sessions', async () => {
const now = Date.now()
vi.mocked(listRepos).mockResolvedValue([createRepo(1, 'repo1', '/path/to/repo1')])
sessionsData.push(createSession('s1', now, '/path/to/repo1'))
render(
<QueryClientProvider client={new QueryClient()}>
<MemoryRouter initialEntries={['/repos/1']}>
<Routes>
<Route path="*" element={<MobileSheetHarness />} />
</Routes>
</MemoryRouter>
</QueryClientProvider>,
)
expect(await screen.findByText('Session s1')).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Show sessions in repo1' })).toHaveAttribute(
'aria-expanded',
'true',
)
})
it('clears the search with the clear button', async () => {
vi.mocked(listRepos).mockResolvedValue([
createRepo(1, 'repo1', '/path/to/repo1'),
createRepo(2, 'repo2', '/path/to/repo2'),
])
render(<RepoQuickSwitchSheet isOpen onClose={vi.fn()} />, { wrapper: createWrapper() })
const input = await screen.findByPlaceholderText('Search projects...')
await waitFor(() => expect(screen.getByText('repo2')).toBeInTheDocument())
expect(screen.queryByLabelText('Clear search')).toBeNull()
fireEvent.change(input, { target: { value: 'repo1' } })
expect(screen.queryByText('repo2')).toBeNull()
fireEvent.click(screen.getByLabelText('Clear search'))
expect(input).toHaveValue('')
expect(screen.getByText('repo2')).toBeInTheDocument()
expect(screen.queryByLabelText('Clear search')).toBeNull()
})
it('keeps only one repo expanded at a time', async () => {
vi.mocked(listRepos).mockResolvedValue([
createRepo(1, 'repo1', '/path/to/repo1'),
createRepo(2, 'repo2', '/path/to/repo2'),
])
render(
<QueryClientProvider client={new QueryClient()}>
<MemoryRouter initialEntries={['/repos/1?mobileTab=repos']}>
<Routes>
<Route path="*" element={<RepoQuickSwitchSheet isOpen onClose={vi.fn()} />} />
</Routes>
</MemoryRouter>
</QueryClientProvider>,
)
const repo1Toggle = await screen.findByRole('button', { name: 'Show sessions in repo1' })
const repo2Toggle = screen.getByRole('button', { name: 'Show sessions in repo2' })
expect(repo1Toggle).toHaveAttribute('aria-expanded', 'true')
expect(repo2Toggle).toHaveAttribute('aria-expanded', 'false')
expect(screen.queryByText('HERE')).toBeNull()
expect(screen.getByText('repo1').closest('button')).toHaveAttribute('aria-current', 'page')
fireEvent.click(repo2Toggle)
expect(repo1Toggle).toHaveAttribute('aria-expanded', 'false')
expect(repo2Toggle).toHaveAttribute('aria-expanded', 'true')
fireEvent.click(repo2Toggle)
expect(repo1Toggle).toHaveAttribute('aria-expanded', 'false')
expect(repo2Toggle).toHaveAttribute('aria-expanded', 'false')
})
it('makes the expanded repo header sticky and leaves collapsed headers static', async () => {
vi.mocked(listRepos).mockResolvedValue([
createRepo(1, 'repo1', '/path/to/repo1'),
createRepo(2, 'repo2', '/path/to/repo2'),
])
render(
<QueryClientProvider client={new QueryClient()}>
<MemoryRouter initialEntries={['/repos/1?mobileTab=repos']}>
<Routes>
<Route path="*" element={<RepoQuickSwitchSheet isOpen onClose={vi.fn()} />} />
</Routes>
</MemoryRouter>
</QueryClientProvider>,
)
const expandedToggle = await screen.findByRole('button', { name: 'Show sessions in repo1' })
const collapsedToggle = screen.getByRole('button', { name: 'Show sessions in repo2' })
expect(expandedToggle.parentElement).toHaveClass('sticky')
expect(collapsedToggle.parentElement).not.toHaveClass('sticky')
})
it('renders a pending permission indicator on a session row', async () => {
vi.mocked(listRepos).mockResolvedValue([createRepo(1, 'repo1', '/path/to/repo1')])
sessionsData.push(createSession('s1', Date.now(), '/path/to/repo1'))
permissionSessions.current.add('s1')
render(
<RepoQuickSwitchSheet isOpen onClose={vi.fn()} />,
{ wrapper: createWrapper() },
)
fireEvent.click(await screen.findByRole('button', { name: 'Show sessions in repo1' }))
expect(await screen.findByLabelText('Pending permission')).toBeInTheDocument()
})
it('renders the relative time on a session row', async () => {
vi.mocked(listRepos).mockResolvedValue([createRepo(1, 'repo1', '/path/to/repo1')])
sessionsData.push(createSession('s1', Date.now() - 5 * 60_000, '/path/to/repo1'))
render(
<RepoQuickSwitchSheet isOpen onClose={vi.fn()} />,
{ wrapper: createWrapper() },
)
fireEvent.click(await screen.findByRole('button', { name: 'Show sessions in repo1' }))
expect(await screen.findByText('5m ago')).toBeInTheDocument()
})
it('renders a closing spacer at the end of the scroll area', async () => {
vi.mocked(listRepos).mockResolvedValue([createRepo(1, 'repo1', '/path/to/repo1')])
render(
<RepoQuickSwitchSheet isOpen onClose={vi.fn()} />,
{ wrapper: createWrapper() },
)
await waitFor(() => {
expect(screen.getByText('repo1')).toBeInTheDocument()
})
expect(document.body.querySelector('[aria-hidden="true"].h-16')).not.toBeNull()
})
it('starts a new session in a repo, opens it and closes the sheet', async () => {
createSessionDirectories.splice(0, createSessionDirectories.length)
vi.mocked(listRepos).mockResolvedValue([
createRepo(1, 'repo1', '/path/to/repo1'),
createRepo(2, 'repo2', '/path/to/repo2'),
])
const handleClose = vi.fn()
let pathname = ''
function LocationProbe() {
pathname = useLocation().pathname
return null
}
render(
<QueryClientProvider client={new QueryClient()}>
<MemoryRouter initialEntries={['/repos/1']}>
<RepoQuickSwitchSheet isOpen onClose={handleClose} />
<LocationProbe />
</MemoryRouter>
</QueryClientProvider>,
)
fireEvent.click(await screen.findByRole('button', { name: 'New session in repo2' }))
expect(createSessionDirectories).toEqual(['/path/to/repo2'])
expect(pathname).toBe('/repos/2/sessions/new-session')
expect(handleClose).toHaveBeenCalled()
})
})
@@ -1,17 +1,17 @@
import { useState, useMemo } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import { useQuery } from '@tanstack/react-query'
import { useRefreshOnOpen } from '@/hooks/useRefreshOnOpen'
import { Input } from '@/components/ui/input'
import { BottomSheet, BottomSheetHeader, BottomSheetContent } from '@/components/ui/bottom-sheet'
import { Button } from '@/components/ui/button'
import { cn, getRepoDisplayName } from '@/lib/utils'
import { listRepos } from '@/api/repos'
import { getRepoDisplayName } from '@/lib/utils'
import { AddRepoDialog } from '@/components/repo/AddRepoDialog'
import { FolderGit2, Check, Plus, GitBranch } from 'lucide-react'
import { FolderGit2, Plus } from 'lucide-react'
import { useUrlParams } from '@/hooks/useUrlParams'
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
import { getAssistantPath, isAssistantPath } from '@/lib/navigation'
import { getAssistantPath } from '@/lib/navigation'
import { NewSessionButton, RepoSessionNavList, SearchClearButton } from '@/components/navigation/RepoSessionNav'
import { getActiveRepoId } from '@/components/navigation/sidebar-session-tree'
import { useNavigableRepos } from '@/hooks/useSidebarRepoGroups'
interface RepoQuickSwitchSheetProps {
isOpen: boolean
@@ -24,35 +24,19 @@ export function RepoQuickSwitchSheet({ isOpen, onClose }: RepoQuickSwitchSheetPr
const { searchParams } = useUrlParams()
const [searchQuery, setSearchQuery] = useState('')
const [addRepoOpen, setAddRepoOpen] = useState(false)
const activeRepoId = getActiveRepoId(location.pathname)
const activeRepoId = useMemo(() => {
if (isAssistantPath(location.pathname)) return null
const match = location.pathname.match(/^\/repos\/(\d+)/)
return match ? Number(match[1]) : null
}, [location.pathname])
const { repos, isLoading, refetch } = useNavigableRepos(isOpen)
const { data: repos, isLoading, refetch } = useQuery({
queryKey: ['repos'],
queryFn: listRepos,
enabled: isOpen,
})
useRefreshOnOpen(isOpen, () => { void refetch() })
const regularRepos = useMemo(
() => repos?.filter((r) => r.id !== ASSISTANT_REPO_ID) ?? null,
[repos],
)
useRefreshOnOpen(isOpen, refetch)
const filteredRepos = useMemo(() => {
if (!regularRepos) return []
const sorted = [...regularRepos].sort((a, b) => (b.lastAccessedAt ?? 0) - (a.lastAccessedAt ?? 0))
if (!searchQuery.trim()) return sorted
if (!searchQuery.trim()) return repos
const query = searchQuery.toLowerCase()
return sorted.filter((repo) =>
return repos.filter((repo) =>
getRepoDisplayName(repo).toLowerCase().includes(query)
)
}, [regularRepos, searchQuery])
}, [repos, searchQuery])
const isUrlControlledSheet = searchParams.get('mobileTab') === 'repos'
@@ -80,18 +64,21 @@ export function RepoQuickSwitchSheet({ isOpen, onClose }: RepoQuickSwitchSheetPr
return (
<>
<BottomSheet isOpen={isOpen} onClose={onClose} heightClass="h-[70dvh]" ariaLabel="Switch repo">
<BottomSheetHeader>
<BottomSheetHeader className="border-b-0">
<div className="flex items-center gap-2">
<Input
type="text"
placeholder="Search projects..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
autoFocus
className="flex-1"
autoComplete="off"
name="repo-quick-switch"
/>
<div className="relative flex-1">
<Input
type="text"
placeholder="Search projects..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
autoFocus
className="pr-9"
autoComplete="off"
name="repo-quick-switch"
/>
{searchQuery.length > 0 && <SearchClearButton onClear={() => setSearchQuery('')} />}
</div>
<Button
type="button"
size="lg"
@@ -107,68 +94,29 @@ export function RepoQuickSwitchSheet({ isOpen, onClose }: RepoQuickSwitchSheetPr
</Button>
</div>
</BottomSheetHeader>
<BottomSheetContent className="flex flex-col gap-2 overflow-y-auto pt-2">
<BottomSheetContent className="flex flex-col px-0 pt-0 gap-0">
{isLoading ? (
<div className="flex flex-col gap-2">
<div className="flex flex-col gap-2 px-4 pt-3">
{Array.from({ length: 5 }).map((_, i) => (
<div key={i} className="h-14 rounded-lg bg-muted animate-pulse" />
))}
</div>
) : filteredRepos.length === 0 ? (
<div className="flex flex-col items-center justify-center py-12 text-muted-foreground">
<div className="flex flex-col items-center justify-center px-4 pt-3 pb-12 text-muted-foreground">
<FolderGit2 className="h-12 w-12 mb-3 opacity-50" />
<p className="text-sm">No repos found</p>
</div>
) : (
<div className="flex flex-col gap-2">
{filteredRepos.map((repo) => {
const isActive = repo.id === activeRepoId
const branchToDisplay = repo.currentBranch || repo.branch
return (
<button
key={repo.id}
type="button"
onClick={() => handleClick(repo.id)}
aria-current={isActive ? 'page' : undefined}
className={cn(
'group flex items-center gap-3 p-3 rounded-lg border transition-all text-left w-full',
isActive
? 'border-primary bg-primary/5'
: 'border-border hover:border-accent hover:bg-accent/50',
)}
>
<div className="flex-shrink-0">
<div
className={cn(
'flex items-center justify-center w-8 h-8 rounded-md',
isActive ? 'bg-primary text-primary-foreground' : 'bg-primary/10 text-primary',
)}
>
<FolderGit2 className="h-4 w-4" />
</div>
</div>
<div className="flex-1 min-w-0">
<div className="font-medium text-sm text-foreground truncate">
{getRepoDisplayName(repo)}
</div>
{branchToDisplay && (
<div
className={cn(
'flex items-center gap-1 text-xs',
repo.isWorktree ? 'text-purple-400' : 'text-muted-foreground',
)}
>
<GitBranch className="h-3 w-3 shrink-0" />
<span className="truncate">{branchToDisplay}</span>
</div>
)}
</div>
{isActive && <Check className="h-4 w-4 text-primary flex-shrink-0" />}
</button>
)
})}
</div>
<RepoSessionNavList
repos={filteredRepos}
activeRepoId={activeRepoId}
isVisible={isOpen}
onOpenRepo={handleClick}
onSelectSession={(path) => navigateAndClose(path)}
renderActions={(repo) => <NewSessionButton repo={repo} onOpenSession={(path) => navigateAndClose(path)} />}
/>
)}
<div aria-hidden="true" className="h-16 shrink-0" />
</BottomSheetContent>
</BottomSheet>
<AddRepoDialog open={addRepoOpen} onOpenChange={setAddRepoOpen} />
@@ -0,0 +1,279 @@
import { useEffect, useMemo, useState, type CSSProperties, type ReactNode } from 'react'
import { useLocation } from 'react-router-dom'
import { Bell, ChevronDown, ChevronRight, HelpCircle, Pin, Plus, X } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { SessionStatusIndicator } from '@/components/ui/session-status-indicator'
import { useForms, usePermissions } from '@/contexts/EventContext'
import { useCreateSession } from '@/hooks/useOpenCode'
import { useSidebarRepoGroups } from '@/hooks/useSidebarRepoGroups'
import { cn, formatShortRelativeTime, getRepoBranchLabel, getRepoDisplayName } from '@/lib/utils'
import { getSessionPath } from '@/lib/navigation'
import {
isCurrentSessionItem,
isRepoReady,
type SidebarSessionItem,
} from '@/components/navigation/sidebar-session-tree'
import type { Repo } from '@/api/types'
const OPEN_REPO_HEADER_STYLE: CSSProperties = {
background: 'color-mix(in srgb, var(--color-primary) 15%, var(--color-card))',
}
function OpenRepoRail() {
return <span aria-hidden="true" className="absolute inset-y-0 left-0 w-[3px] bg-primary" />
}
interface RepoNavGroupProps {
name: string
branch?: string | null
isWorktree?: boolean
isOpen: boolean
isCurrent: boolean
onOpenRepo: () => void
onToggle?: () => void
actions?: ReactNode
children?: ReactNode
}
export function RepoNavGroup({
name,
branch,
isWorktree,
isOpen,
isCurrent,
onOpenRepo,
onToggle,
actions,
children,
}: RepoNavGroupProps) {
return (
<div className="relative">
<div
className={cn(
'relative flex h-[52px] items-stretch border-b border-border bg-card',
isOpen && 'sticky top-0 z-10',
)}
style={isOpen ? OPEN_REPO_HEADER_STYLE : undefined}
>
{isOpen && <OpenRepoRail />}
<button
type="button"
onClick={onOpenRepo}
aria-current={isCurrent ? 'page' : undefined}
className="flex min-w-0 flex-1 flex-col justify-center gap-0.5 pl-4 pr-2 text-left hover:bg-white/[0.03]"
>
<span className="truncate text-[15px] font-bold tracking-tight text-orange-600 dark:text-orange-400">
{name}
</span>
{branch && (
<span
className={cn(
'truncate font-mono text-[11.5px]',
isWorktree ? 'text-purple-400' : 'text-muted-foreground',
)}
>
{branch}
</span>
)}
</button>
{actions && <div className="flex shrink-0 items-center pr-2">{actions}</div>}
{onToggle && (
<button
type="button"
aria-expanded={isOpen}
aria-label={`Show sessions in ${name}`}
onClick={onToggle}
className="flex w-11 shrink-0 items-center justify-center border-l border-border/60 text-muted-foreground"
>
{isOpen ? <ChevronDown className="h-4 w-4 text-primary" /> : <ChevronRight className="h-4 w-4" />}
</button>
)}
</div>
{isOpen && children && (
<div className="relative">
<OpenRepoRail />
{children}
</div>
)}
</div>
)
}
interface SessionNavRowProps {
item: SidebarSessionItem
isCurrent: boolean
onSelect: (path: string) => void
repoLabel?: string
}
export function SessionNavRow({ item, isCurrent, onSelect, repoLabel }: SessionNavRowProps) {
const { hasForSession: hasPermission } = usePermissions()
const { hasForSession: hasForm } = useForms()
return (
<button
type="button"
onClick={() => onSelect(item.path)}
aria-current={isCurrent ? 'page' : undefined}
title={item.branchLabel ? `${item.repoLabel} · ${item.branchLabel}` : item.repoLabel}
className={cn(
'flex h-9 w-full items-center gap-2 pl-4 pr-3.5 text-left text-[13.5px] text-foreground hover:bg-accent/50',
isCurrent && 'bg-primary/25 font-semibold',
)}
>
<span className="w-3 shrink-0">
{item.isPinned && <Pin className="h-3 w-3" aria-label="Pinned" />}
</span>
<span className="min-w-0 flex-1 truncate">{item.session.title || 'Untitled Session'}</span>
{repoLabel && (
<span className="max-w-24 shrink-0 truncate text-xs text-orange-600 dark:text-orange-400">{repoLabel}</span>
)}
<SessionStatusIndicator sessionID={item.session.id} size="sm" />
{hasPermission(item.session.id) && (
<Bell className="h-3 w-3 shrink-0 text-orange-500" aria-label="Pending permission" />
)}
{hasForm(item.session.id) && (
<HelpCircle className="h-3 w-3 shrink-0 text-blue-500" aria-label="Pending form" />
)}
<span className="ml-auto min-w-[30px] shrink-0 text-right text-xs tabular-nums text-muted-foreground">
{formatShortRelativeTime(new Date(item.session.time.updated))}
</span>
</button>
)
}
export function SessionNavStatus({ children }: { children: ReactNode }) {
return <div className="flex h-10 items-center pl-4 text-xs text-muted-foreground">{children}</div>
}
function SessionNavLink({ children, onClick }: { children: ReactNode; onClick: () => void }) {
return (
<button
type="button"
onClick={onClick}
className="flex h-9 w-full items-center pl-4 text-left text-xs text-muted-foreground hover:bg-accent/50"
>
{children}
</button>
)
}
export function SearchClearButton({ onClear }: { onClear: () => void }) {
return (
<button
type="button"
aria-label="Clear search"
onClick={onClear}
className="absolute right-1 top-1/2 flex h-8 w-8 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground hover:text-foreground"
>
<X className="h-4 w-4" />
</button>
)
}
interface RepoSessionListProps {
repo: Repo
onSelectSession: (path: string) => void
}
function RepoSessionList({ repo, onSelectSession }: RepoSessionListProps) {
const location = useLocation()
const repos = useMemo(() => [repo], [repo])
const { groups, isLoading, isError, hasMore } = useSidebarRepoGroups({ repos })
const items = groups[0]?.items ?? []
if (isLoading) return <SessionNavStatus>Loading sessions...</SessionNavStatus>
if (isError) return <SessionNavStatus>Failed to load sessions</SessionNavStatus>
if (items.length === 0) return <SessionNavStatus>No sessions</SessionNavStatus>
return (
<>
{items.map((item) => (
<SessionNavRow
key={item.key}
item={item}
isCurrent={isCurrentSessionItem(item, location.pathname)}
onSelect={onSelectSession}
/>
))}
{hasMore && (
<SessionNavLink onClick={() => onSelectSession(`/repos/${repo.id}`)}>All sessions</SessionNavLink>
)}
</>
)
}
interface RepoSessionNavListProps {
repos: Repo[]
activeRepoId: number | null
isVisible: boolean
onOpenRepo: (repoId: number) => void
onSelectSession: (path: string) => void
renderActions?: (repo: Repo) => ReactNode
}
export function RepoSessionNavList({
repos,
activeRepoId,
isVisible,
onOpenRepo,
onSelectSession,
renderActions,
}: RepoSessionNavListProps) {
const [expandedRepoId, setExpandedRepoId] = useState<number | null>(null)
useEffect(() => {
if (isVisible && activeRepoId !== null) setExpandedRepoId(activeRepoId)
}, [isVisible, activeRepoId])
return (
<div className="flex flex-col">
{repos.map((repo) => {
const isExpanded = expandedRepoId === repo.id
const ready = isRepoReady(repo)
return (
<RepoNavGroup
key={repo.id}
name={getRepoDisplayName(repo)}
branch={getRepoBranchLabel(repo)}
isWorktree={repo.isWorktree}
isOpen={isExpanded}
isCurrent={repo.id === activeRepoId}
onOpenRepo={() => onOpenRepo(repo.id)}
onToggle={() => setExpandedRepoId((current) => (current === repo.id ? null : repo.id))}
actions={ready ? renderActions?.(repo) : undefined}
>
{ready ? (
<RepoSessionList repo={repo} onSelectSession={onSelectSession} />
) : (
<SessionNavStatus>Repository not ready</SessionNavStatus>
)}
</RepoNavGroup>
)
})}
</div>
)
}
export function NewSessionButton({
repo,
onOpenSession,
}: {
repo: Repo
onOpenSession: (path: string) => void
}) {
const createSession = useCreateSession(repo.fullPath, (session) => {
onOpenSession(getSessionPath(repo.id, session.id))
})
return (
<Button
type="button"
size="icon-sm"
aria-label={`New session in ${getRepoDisplayName(repo)}`}
onClick={() => createSession.mutate({ agent: undefined })}
>
<Plus className="h-3.5 w-3.5" />
</Button>
)
}
@@ -118,24 +118,19 @@ describe('buildNavModel', () => {
expect(model.primary[1].to).toBe('/assistant')
})
it('returns new-session and assistant primary CTAs for repo detail', () => {
it('returns only the assistant primary CTA for repo detail', () => {
const model = buildNavModel('/repos/5')
expect(model.primary).toHaveLength(2)
expect(model.primary[0].key).toBe('new-session')
expect(model.primary[0].onSelect).toBe('new-session')
expect(model.primary[1].key).toBe('assistant')
expect(model.primary[1].to).toBe('/assistant')
expect(model.primary).toHaveLength(1)
expect(model.primary[0].key).toBe('assistant')
expect(model.primary[0].to).toBe('/assistant')
})
it('returns new-session and assistant primary CTAs for session detail', () => {
it('returns only the assistant primary CTA for session detail', () => {
const model = buildNavModel('/repos/5/sessions/abc')
expect(model.primary).toHaveLength(2)
expect(model.primary[0].key).toBe('new-session')
expect(model.primary[0].onSelect).toBe('new-session')
expect(model.primary[0].variant).toBe('primary')
expect(model.primary[1].key).toBe('assistant')
expect(model.primary[1].to).toBe('/assistant')
expect(model.primary[1].variant).toBe('secondary')
expect(model.primary).toHaveLength(1)
expect(model.primary[0].key).toBe('assistant')
expect(model.primary[0].to).toBe('/assistant')
expect(model.primary[0].variant).toBe('secondary')
})
it('returns new-session and assistant primary CTAs for assistant workspace', () => {
@@ -64,10 +64,7 @@ function buildRouteNavModel(pathname: string): NavModel {
]
return {
primary: [
{ key: 'new-session', label: 'New Session', icon: SquarePlus, onSelect: 'new-session', variant: 'primary' },
getAssistantNavItem(pathname),
],
primary: [getAssistantNavItem(pathname)],
items,
}
}
@@ -85,10 +82,7 @@ function buildRouteNavModel(pathname: string): NavModel {
]
return {
primary: [
{ key: 'new-session', label: 'New Session', icon: SquarePlus, onSelect: 'new-session', variant: 'primary' },
getAssistantNavItem(pathname),
],
primary: [getAssistantNavItem(pathname)],
items,
}
}
@@ -0,0 +1,185 @@
import { describe, it, expect } from 'vitest'
import type { Repo, Session } from '@/api/types'
import {
buildSidebarRepoGroups,
getActiveRepoId,
isCurrentSessionItem,
isRepoReady,
selectNavigableRepos,
} from './sidebar-session-tree'
const NOW = 1_000_000_000_000
function atStartOfDay(offsetMs: number): number {
const start = new Date(NOW)
start.setHours(0, 0, 0, 0)
return start.getTime() + offsetMs
}
function createSession(id: string, updated: number, directory: string): Session {
return {
id,
projectID: 'proj-1',
title: `Session ${id}`,
time: { created: updated - 10000, updated },
location: { directory },
cost: 0,
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
}
}
function createRepo(overrides: Partial<Repo> & { id: number; fullPath: string }): Repo {
return {
localPath: `repos/${overrides.id}`,
defaultBranch: 'main',
cloneStatus: 'ready',
clonedAt: 0,
...overrides,
}
}
describe('getActiveRepoId', () => {
it('returns the repo id for repo and session routes', () => {
expect(getActiveRepoId('/repos/3')).toBe(3)
expect(getActiveRepoId('/repos/3/sessions/abc')).toBe(3)
})
it('returns null outside a repo and on assistant routes', () => {
expect(getActiveRepoId('/')).toBeNull()
expect(getActiveRepoId('/assistant')).toBeNull()
expect(getActiveRepoId('/repos/1/assistant')).toBeNull()
})
})
describe('isCurrentSessionItem', () => {
const repo = createRepo({ id: 1, fullPath: '/repos/a' })
const [item] = buildSidebarRepoGroups({
repos: [repo],
sessions: [createSession('a1', NOW, '/repos/a')],
pinnedKeys: new Set(),
now: NOW,
})[0].items
it('matches only the exact repo and session route', () => {
expect(isCurrentSessionItem(item, '/repos/1/sessions/a1')).toBe(true)
expect(isCurrentSessionItem(item, '/repos/1')).toBe(false)
expect(isCurrentSessionItem(item, '/repos/2/sessions/a1')).toBe(false)
})
})
describe('isRepoReady', () => {
it('is true only for ready repos', () => {
expect(isRepoReady(createRepo({ id: 1, fullPath: '/repos/a' }))).toBe(true)
expect(isRepoReady(createRepo({ id: 2, fullPath: '/repos/b', cloneStatus: 'cloning' }))).toBe(false)
expect(isRepoReady(createRepo({ id: 3, fullPath: '/repos/c', cloneStatus: 'error' }))).toBe(false)
})
})
describe('selectNavigableRepos', () => {
it('excludes the assistant repo but keeps repos that are not ready', () => {
const repos = [
createRepo({ id: 0, fullPath: '/assistant' }),
createRepo({ id: 1, fullPath: '/repos/a' }),
createRepo({ id: 2, fullPath: '/repos/b', cloneStatus: 'cloning' }),
]
expect(selectNavigableRepos(repos).map((repo) => repo.id)).toEqual([1, 2])
})
it('sorts by last access, newest first, with never-accessed repos last', () => {
const repos = [
createRepo({ id: 1, fullPath: '/repos/a', lastAccessedAt: 10 }),
createRepo({ id: 2, fullPath: '/repos/b' }),
createRepo({ id: 3, fullPath: '/repos/c', lastAccessedAt: 30 }),
]
expect(selectNavigableRepos(repos).map((repo) => repo.id)).toEqual([3, 1, 2])
})
it('does not mutate the input', () => {
const repos = [
createRepo({ id: 1, fullPath: '/repos/a', lastAccessedAt: 1 }),
createRepo({ id: 2, fullPath: '/repos/b', lastAccessedAt: 2 }),
]
selectNavigableRepos(repos)
expect(repos.map((repo) => repo.id)).toEqual([1, 2])
})
})
describe('buildSidebarRepoGroups', () => {
const repoA = createRepo({ id: 1, fullPath: '/repos/a', name: 'Alpha' })
const repoB = createRepo({ id: 2, fullPath: '/repos/b', name: 'Beta' })
it('returns one group per repo in input order with pinned first then recency', () => {
const sessions = [
createSession('a1', atStartOfDay(3000), '/repos/a'),
createSession('a2', atStartOfDay(5000), '/repos/a'),
createSession('a3', atStartOfDay(1000), '/repos/a'),
createSession('b1', atStartOfDay(4000), '/repos/b'),
]
const pinnedKeys = new Set(['/repos/a:a2'])
const groups = buildSidebarRepoGroups({ repos: [repoB, repoA], sessions, pinnedKeys, now: NOW })
expect(groups.map((group) => group.repo.id)).toEqual([2, 1])
expect(groups[0].items.map((item) => item.session.id)).toEqual(['b1'])
expect(groups[1].items.map((item) => item.session.id)).toEqual(['a2', 'a1', 'a3'])
expect(groups[1].items[0].isPinned).toBe(true)
expect(groups[1].items[1].isPinned).toBe(false)
})
it('excludes subtasks, archived sessions and sessions from unknown directories', () => {
const archived = createSession('archived', atStartOfDay(6000), '/repos/a')
archived.time.archived = atStartOfDay(6000)
const sessions = [
createSession('root', atStartOfDay(3000), '/repos/a'),
{ ...createSession('child', atStartOfDay(4000), '/repos/a'), parentID: 'root' },
archived,
createSession('unknown', atStartOfDay(7000), '/repos/c'),
]
const groups = buildSidebarRepoGroups({ repos: [repoA], sessions, pinnedKeys: new Set(), now: NOW })
expect(groups).toHaveLength(1)
expect(groups[0].items.map((item) => item.session.id)).toEqual(['root'])
})
it('builds item fields from the owning repo', () => {
const worktree = createRepo({
id: 3,
fullPath: '/repos/wt',
name: 'Worktree',
currentBranch: 'feature/x',
isWorktree: true,
})
const sessions = [createSession('w1', atStartOfDay(1000), '/repos/wt')]
const groups = buildSidebarRepoGroups({
repos: [worktree],
sessions,
pinnedKeys: new Set(['/repos/wt:w1']),
now: NOW,
})
const item = groups[0].items[0]
expect(item.key).toBe('/repos/wt:w1')
expect(item.repoId).toBe(3)
expect(item.repoLabel).toBe('Worktree')
expect(item.branchLabel).toBe('feature/x')
expect(item.isWorktree).toBe(true)
expect(item.isPinned).toBe(true)
expect(item.path).toBe('/repos/3/sessions/w1')
})
it('falls back to repo.branch when currentBranch is absent', () => {
const repo = createRepo({ id: 4, fullPath: '/repos/d', branch: 'main' })
const sessions = [createSession('d1', atStartOfDay(1000), '/repos/d')]
const groups = buildSidebarRepoGroups({ repos: [repo], sessions, pinnedKeys: new Set(), now: NOW })
expect(groups[0].branchLabel).toBe('main')
expect(groups[0].items[0].branchLabel).toBe('main')
})
})
@@ -0,0 +1,102 @@
import type { Repo, Session } from '@/api/types'
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
import { getRepoBranchLabel, getRepoDisplayName } from '@/lib/utils'
import { buildSessionKey } from '@/lib/sessionKey'
import { getSessionPath, isAssistantPath, parseRepoRoute } from '@/lib/navigation'
import { partitionSessions, selectRootSessions } from '@/components/session/session-partition'
export const SIDEBAR_SESSIONS_PER_REPO = 10
export interface SidebarSessionItem {
key: string
session: Session
repoId: number
repoLabel: string
branchLabel: string | null
isWorktree: boolean
isPinned: boolean
path: string
}
export interface SidebarRepoGroup {
repo: Repo
label: string
branchLabel: string | null
items: SidebarSessionItem[]
}
export function isCurrentSessionItem(item: SidebarSessionItem, pathname: string): boolean {
const selection = parseRepoRoute(pathname)
return item.repoId === selection.repoId && item.session.id === selection.sessionId
}
export function getActiveRepoId(pathname: string): number | null {
if (isAssistantPath(pathname)) return null
return parseRepoRoute(pathname).repoId
}
export function isRepoReady(repo: Repo): boolean {
return repo.cloneStatus === 'ready'
}
export function selectNavigableRepos(repos: Repo[]): Repo[] {
return repos
.filter((repo) => repo.id !== ASSISTANT_REPO_ID)
.sort((a, b) => (b.lastAccessedAt ?? 0) - (a.lastAccessedAt ?? 0))
}
export function buildSidebarRepoGroups(input: {
repos: Repo[]
sessions: Session[]
pinnedKeys: ReadonlySet<string>
now: number
}): SidebarRepoGroup[] {
const { repos, sessions, pinnedKeys, now } = input
const keyFn = (session: Session) => buildSessionKey(session.location.directory, session.id)
const repoByDirectory = new Map(repos.map((repo) => [repo.fullPath, repo]))
const roots = selectRootSessions(sessions, {
directories: new Set(repos.map((repo) => repo.fullPath)),
keyFn,
}).flatMap((session) => {
if (session.time.archived) return []
const repo = repoByDirectory.get(session.location.directory)
if (!repo) return []
return [{ session, repo }]
})
const sessionsByDirectory = new Map<string, Session[]>()
for (const { session, repo } of roots) {
const list = sessionsByDirectory.get(repo.fullPath)
if (list) {
list.push(session)
} else {
sessionsByDirectory.set(repo.fullPath, [session])
}
}
const createItem = (session: Session, repo: Repo): SidebarSessionItem => {
const key = keyFn(session)
return {
key,
session,
repoId: repo.id,
repoLabel: getRepoDisplayName(repo),
branchLabel: getRepoBranchLabel(repo),
isWorktree: Boolean(repo.isWorktree),
isPinned: pinnedKeys.has(key),
path: getSessionPath(repo.id, session.id),
}
}
return repos.map((repo) => {
const repoRoots = sessionsByDirectory.get(repo.fullPath) ?? []
const { pinned, today, older } = partitionSessions(repoRoots, pinnedKeys, keyFn, now)
return {
repo,
label: getRepoDisplayName(repo),
branchLabel: getRepoBranchLabel(repo),
items: [...pinned, ...today, ...older].map((session) => createItem(session, repo)),
}
})
}
+3 -22
View File
@@ -25,28 +25,9 @@ import {
} from "./repo-list-state"
import { RepoListControls } from "./RepoListControls"
import { invalidateRepoListCaches } from "@/lib/queryInvalidation"
import { formatShortRelativeTime } from "@/lib/utils"
import { ASSISTANT_REPO_ID } from "@opencode-manager/shared/utils"
function formatActivityLabel(timestamp: number): string {
const now = Date.now()
const diff = now - timestamp
const seconds = Math.floor(diff / 1000)
const minutes = Math.floor(seconds / 60)
const hours = Math.floor(minutes / 60)
const days = Math.floor(hours / 24)
if (days > 0) {
return days === 1 ? '1d ago' : `${days}d ago`
}
if (hours > 0) {
return hours === 1 ? '1h ago' : `${hours}h ago`
}
if (minutes > 0) {
return minutes === 1 ? '1m ago' : `${minutes}m ago`
}
return 'just now'
}
interface RepoCardWrapperProps {
repo: Repo
onDelete: (id: number) => void
@@ -458,7 +439,7 @@ export function RepoList() {
manageMode={isSelectionActive}
isMobile={isMobile}
isManualSort={isManualSort}
activityLabel={formatActivityLabel(repo.activityTimestamp)}
activityLabel={formatShortRelativeTime(new Date(repo.activityTimestamp))}
hasSelectedRepos={selectedRepos.size > 0}
selectionMode={selectionMode}
/>
@@ -487,7 +468,7 @@ export function RepoList() {
gitStatus={gitStatuses?.get(repo.id)}
manageMode={isSelectionActive}
isMobile={isMobile}
activityLabel={formatActivityLabel(repo.activityTimestamp)}
activityLabel={formatShortRelativeTime(new Date(repo.activityTimestamp))}
hasSelectedRepos={selectedRepos.size > 0}
selectionMode={selectionMode}
/>
@@ -3,8 +3,8 @@ import { useSessionsAcrossDirectories, useDeleteSession, useCreateSession } from
import type { DeleteSessionTarget } from "@/hooks/useOpenCode";
import type { Session } from "@/api/types";
import { useSessionPins, useToggleSessionPin } from '@/hooks/useSessionPins';
import { buildSessionKey } from '@/lib/sessionKey';
import { partitionSessions } from './session-partition';
import { buildSessionKey, buildPinnedSessionKeys } from '@/lib/sessionKey';
import { partitionSessions, selectRootSessions } from './session-partition';
import { DeleteSessionDialog } from "./DeleteSessionDialog";
import { SessionCard } from "./SessionCard";
import { Card } from "@/components/ui/card";
@@ -48,7 +48,7 @@ export const SessionList = ({
const { data: sessionPins } = useSessionPins();
const togglePin = useToggleSessionPin();
const pinnedKeys = useMemo(
() => new Set((sessionPins ?? []).map((p) => buildSessionKey(p.directory, p.sessionId))),
() => buildPinnedSessionKeys(sessionPins ?? []),
[sessionPins],
);
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
@@ -57,25 +57,10 @@ export const SessionList = ({
const [manageMode, setManageMode] = useState(false);
const sessionListRef = useRef<HTMLDivElement>(null);
const filteredSessions = useMemo(() => {
if (!sessions) return [];
const filtered = sessions.filter((session) => {
if (session.parentID) return false;
if (directorySet.size > 0 && !directorySet.has(session.location.directory)) return false;
return true;
});
const uniqueSessions = new Map<string, (typeof filtered)[number]>();
filtered.forEach((session) => {
const key = getSessionSelectionKey(session);
if (!uniqueSessions.has(key)) {
uniqueSessions.set(key, session);
}
});
return Array.from(uniqueSessions.values()).sort((a, b) => b.time.updated - a.time.updated);
}, [sessions, directorySet, getSessionSelectionKey]);
const filteredSessions = useMemo(
() => selectRootSessions(sessions ?? [], { directories: directorySet, keyFn: getSessionSelectionKey }),
[sessions, directorySet, getSessionSelectionKey],
);
const { pinned: pinnedSessions, today: todaySessions, older: olderSessions } = useMemo(
() => partitionSessions(filteredSessions, pinnedKeys, getSessionSelectionKey),
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
import { partitionSessions } from './session-partition'
import { partitionSessions, selectRootSessions } from './session-partition'
import type { Session } from '@/api/types'
function createSession(id: string, updated: number, directory = '/test'): Session {
@@ -17,6 +17,53 @@ function createSession(id: string, updated: number, directory = '/test'): Sessio
const keyFn = (s: Session) =>
`${s.location.directory}:${s.id}`
describe('selectRootSessions', () => {
it('drops sessions that have a parentID', () => {
const sessions = [
createSession('root', 2000),
{ ...createSession('child', 1000), parentID: 'root' },
]
const result = selectRootSessions(sessions, { keyFn })
expect(result.map((s) => s.id)).toEqual(['root'])
})
it('drops sessions outside the directory set but keeps sessions with no directory', () => {
const sessions = [
createSession('inside', 3000, '/a'),
createSession('outside', 2000, '/b'),
{ ...createSession('no-directory', 1000), location: {} as Session['location'] },
]
const result = selectRootSessions(sessions, { directories: new Set(['/a']), keyFn })
expect(result.map((s) => s.id)).toEqual(['inside', 'no-directory'])
})
it('keeps the first occurrence when deduping by key', () => {
const first = createSession('dup', 2000, '/a')
const second = createSession('dup', 5000, '/a')
const result = selectRootSessions([first, second], { keyFn })
expect(result).toHaveLength(1)
expect(result[0].time.updated).toBe(2000)
})
it('returns the result sorted by updated descending', () => {
const sessions = [
createSession('old', 1000),
createSession('new', 3000),
createSession('mid', 2000),
]
const result = selectRootSessions(sessions, { keyFn })
expect(result.map((s) => s.id)).toEqual(['new', 'mid', 'old'])
})
})
describe('partitionSessions', () => {
it('places pinned sessions in pinned array sorted by updated desc', () => {
const now = 1_000_000_000_000
@@ -6,9 +6,37 @@ export interface PartitionedSessions {
older: Session[]
}
export interface SelectRootSessionsOptions {
directories?: ReadonlySet<string>
keyFn: (session: Session) => string
}
export function selectRootSessions(
sessions: Session[],
options: SelectRootSessionsOptions,
): Session[] {
const { directories, keyFn } = options
const roots = sessions.filter((session) => {
if (session.parentID) return false
const directory = session.location.directory
if (directories && directories.size > 0 && directory && !directories.has(directory)) return false
return true
})
const uniqueSessions = new Map<string, Session>()
for (const session of roots) {
const key = keyFn(session)
if (!uniqueSessions.has(key)) {
uniqueSessions.set(key, session)
}
}
return Array.from(uniqueSessions.values()).sort((a, b) => b.time.updated - a.time.updated)
}
export function partitionSessions(
sessions: Session[],
pinnedKeys: Set<string>,
pinnedKeys: ReadonlySet<string>,
keyFn: (session: Session) => string,
now: number = Date.now(),
): PartitionedSessions {
@@ -1,6 +1,6 @@
import { useGitLog } from '@/api/git'
import { Loader2, GitCommit, AlertCircle, ArrowUp } from 'lucide-react'
import { cn } from '@/lib/utils'
import { cn, formatShortRelativeTime } from '@/lib/utils'
import { GIT_UI_COLORS } from '@/lib/git-status-styles'
interface CommitsTabProps {
@@ -9,26 +9,6 @@ interface CommitsTabProps {
onSelectCommit?: (hash: string) => void
}
function formatRelativeTime(timestamp: string): string {
const date = new Date(parseInt(timestamp, 10) * 1000)
const now = new Date()
const diffMs = now.getTime() - date.getTime()
const diffSeconds = Math.floor(diffMs / 1000)
const diffMinutes = Math.floor(diffSeconds / 60)
const diffHours = Math.floor(diffMinutes / 60)
const diffDays = Math.floor(diffHours / 24)
const diffWeeks = Math.floor(diffDays / 7)
const diffMonths = Math.floor(diffDays / 30)
if (diffSeconds < 60) return 'just now'
if (diffMinutes < 60) return `${diffMinutes}m ago`
if (diffHours < 24) return `${diffHours}h ago`
if (diffDays < 7) return `${diffDays}d ago`
if (diffWeeks < 4) return `${diffWeeks}w ago`
return `${diffMonths}mo ago`
}
export function CommitsTab({ repoId, branch, onSelectCommit }: CommitsTabProps) {
const { data, isLoading, error } = useGitLog(repoId, 50, branch)
@@ -78,7 +58,7 @@ export function CommitsTab({ repoId, branch, onSelectCommit }: CommitsTabProps)
<span>·</span>
<span className="truncate">{commit.authorName}</span>
<span>·</span>
<span className="flex-shrink-0">{formatRelativeTime(commit.date)}</span>
<span className="flex-shrink-0">{formatShortRelativeTime(new Date(parseInt(commit.date, 10) * 1000))}</span>
{commit.unpushed && (
<span className={cn('flex items-center gap-0.5 px-1 rounded', GIT_UI_COLORS.unpushed)}>
<ArrowUp className="w-3 h-3" />
+3 -2
View File
@@ -104,11 +104,12 @@ export function BottomSheet({
export interface BottomSheetHeaderProps {
title?: string
children?: React.ReactNode
className?: string
}
export function BottomSheetHeader({ title, children }: BottomSheetHeaderProps) {
export function BottomSheetHeader({ title, children, className }: BottomSheetHeaderProps) {
return (
<div className="flex-shrink-0 border-b border-border bg-background px-4 py-3">
<div className={cn('flex-shrink-0 border-b border-border bg-background px-4 py-3', className)}>
{title && (
<h2 className="text-lg font-semibold text-foreground">{title}</h2>
)}
+53 -1
View File
@@ -1,6 +1,6 @@
import { describe, it, expect, vi } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { Sidebar, SidebarSection, SidebarItem, SidebarCollapseToggle } from './sidebar'
import { Sidebar, SidebarCollapsibleSection, SidebarSection, SidebarItem, SidebarCollapseToggle } from './sidebar'
import { TooltipProvider } from './tooltip'
import { Folder } from 'lucide-react'
@@ -58,6 +58,58 @@ describe('SidebarSection', () => {
})
})
describe('SidebarCollapsibleSection', () => {
it('renders label and children when expanded', () => {
render(
<SidebarCollapsibleSection label="Sessions" collapsed={false} onToggle={vi.fn()}>
<div>Content</div>
</SidebarCollapsibleSection>
)
expect(screen.getByRole('button', { name: 'Sessions' })).toHaveAttribute('aria-expanded', 'true')
expect(screen.getByText('Content')).toBeInTheDocument()
})
it('hides children when collapsed', () => {
render(
<SidebarCollapsibleSection label="Sessions" collapsed={true} onToggle={vi.fn()}>
<div>Content</div>
</SidebarCollapsibleSection>
)
expect(screen.getByRole('button', { name: 'Sessions' })).toHaveAttribute('aria-expanded', 'false')
expect(screen.queryByText('Content')).not.toBeInTheDocument()
})
it('calls onToggle when the header is clicked', () => {
const handleToggle = vi.fn()
render(
<SidebarCollapsibleSection label="Menu" collapsed={false} onToggle={handleToggle}>
<div>Content</div>
</SidebarCollapsibleSection>
)
fireEvent.click(screen.getByRole('button', { name: 'Menu' }))
expect(handleToggle).toHaveBeenCalledTimes(1)
})
it('applies contentClassName to the content wrapper', () => {
render(
<SidebarCollapsibleSection
label="Menu"
collapsed={false}
onToggle={vi.fn()}
contentClassName="overflow-y-auto"
>
<div>Content</div>
</SidebarCollapsibleSection>
)
expect(screen.getByText('Content').parentElement).toHaveClass('overflow-y-auto')
})
})
describe('SidebarItem', () => {
it('fires onClick when clicked', () => {
const handleClick = vi.fn()
+42 -1
View File
@@ -1,5 +1,6 @@
import { useId } from 'react'
import type { LucideIcon } from 'lucide-react'
import { ChevronLeft, ChevronRight } from 'lucide-react'
import { ChevronDown, ChevronLeft, ChevronRight } from 'lucide-react'
import { cn } from '@/lib/utils'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
@@ -56,6 +57,46 @@ export function SidebarSection({ label, collapsed, children }: SidebarSectionPro
)
}
export interface SidebarCollapsibleSectionProps {
label: string
collapsed: boolean
onToggle: () => void
className?: string
contentClassName?: string
children: React.ReactNode
}
export function SidebarCollapsibleSection({
label,
collapsed,
onToggle,
className,
contentClassName,
children,
}: SidebarCollapsibleSectionProps) {
const contentId = useId()
return (
<div className={cn('flex min-h-0 flex-col', className)}>
<button
type="button"
onClick={onToggle}
aria-expanded={!collapsed}
aria-controls={contentId}
className="flex w-full items-center justify-between gap-2 px-3 py-1.5 text-xs font-medium uppercase tracking-wider text-muted-foreground transition-colors hover:text-foreground"
>
<span className="truncate">{label}</span>
<ChevronDown className={cn('h-3.5 w-3.5 shrink-0 transition-transform', collapsed && '-rotate-90')} />
</button>
{!collapsed && (
<div id={contentId} className={cn('flex min-h-0 flex-1 flex-col', contentClassName)}>
{children}
</div>
)}
</div>
)
}
export interface SidebarItemProps {
icon: LucideIcon
label: string