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

+6 -2
View File
@@ -140,8 +140,12 @@ Supported diagram types:
Access your sessions from the sidebar:
- Sessions are organized by repository
- Most recent sessions appear first
- Sessions are organized by repository; the current repository is expanded and one repository is open at a time
- Pinned sessions appear first, followed by the most recent sessions
- A live indicator marks sessions that are working, retrying, or compacting
- **All sessions** opens the repository's full session list when it has more sessions than the sidebar shows
- Repositories that are still cloning, or whose clone failed, show **Repository not ready** until they are ready
- On desktop, type in the sidebar search box and press **Enter** to search sessions across all repositories; press **Escape** to clear
- Click a session to resume
![Session List](../images/chat-session-list.png)
@@ -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
+390
View File
@@ -5,12 +5,14 @@ import type { ReactNode } from 'react'
import { MemoryRouter, useLocation } from 'react-router-dom'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { FormInfo, PermissionRequest } from '@opencode-manager/shared/opencode'
import { useSessionStatus } from '@/stores/sessionStatusStore'
import { EventProvider, useEventContext, useForms, usePermissions, useSSEHealth } from './EventContext'
const mocks = vi.hoisted(() => ({
listRepos: vi.fn(),
listPendingPermissions: vi.fn(),
listPendingForms: vi.fn(),
listActiveSessions: vi.fn(),
replyPermission: vi.fn(),
replyForm: vi.fn(),
cancelForm: vi.fn(),
@@ -23,6 +25,7 @@ vi.mock('@/api/repos', () => ({
}))
vi.mock('@/api/opencode', () => ({
listActiveSessions: mocks.listActiveSessions,
listPendingPermissions: mocks.listPendingPermissions,
listPendingForms: mocks.listPendingForms,
replyPermission: mocks.replyPermission,
@@ -126,6 +129,14 @@ function createTestQueryClient() {
})
}
function createDeferred<T>() {
let resolve!: (value: T) => void
const promise = new Promise<T>((res) => {
resolve = res
})
return { promise, resolve }
}
function createWrapper(queryClient = createTestQueryClient()) {
return ({ children }: { children: ReactNode }) => (
<MemoryRouter>
@@ -153,10 +164,12 @@ describe('EventProvider permissions and forms', () => {
mocks.listRepos.mockResolvedValue([])
mocks.listPendingPermissions.mockResolvedValue([])
mocks.listPendingForms.mockResolvedValue([])
mocks.listActiveSessions.mockResolvedValue({})
mocks.replyPermission.mockResolvedValue(undefined)
mocks.replyForm.mockResolvedValue(undefined)
mocks.cancelForm.mockResolvedValue(undefined)
mocks.getHealth.mockReturnValue({ isConnected: false, isHealthy: false, lastEventAt: null, isStalled: false })
useSessionStatus.setState({ statuses: new Map(), statusCache: new Map(), statusRevisions: new Map(), revision: 0 })
mocks.subscribeGlobalMonitor.mockReturnValue({
dispose: vi.fn(),
updateDirectories: vi.fn(),
@@ -956,4 +969,381 @@ describe('EventProvider permissions and forms', () => {
expect(afterBooleanChange).toBe(initialRenderCount + 1)
expect(renderCount).toBe(afterBooleanChange)
})
it('applies a session.status event from the global monitor to the status store', async () => {
render(<Harness />, { wrapper: createWrapper() })
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({
type: 'session.status',
data: { sessionID: 'session-9', status: { type: 'busy' } },
directory: '/repo',
})
})
expect(useSessionStatus.getState().getStatus('session-9')).toEqual({ type: 'busy' })
})
it('applies execution lifecycle and idle events from the global monitor to the status store', async () => {
render(<Harness />, { wrapper: createWrapper() })
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type: 'session.execution.started', data: { sessionID: 'session-9' }, directory: '/repo' })
})
expect(useSessionStatus.getState().getStatus('session-9')).toEqual({ type: 'busy' })
act(() => {
onEvent({ type: 'session.execution.succeeded', data: { sessionID: 'session-9' }, directory: '/repo' })
})
expect(useSessionStatus.getState().getStatus('session-9')).toEqual({ type: 'idle' })
act(() => {
onEvent({ type: 'session.execution.started', data: { sessionID: 'session-9' }, directory: '/repo' })
onEvent({ type: 'session.idle', data: { sessionID: 'session-9' }, directory: '/repo' })
})
expect(useSessionStatus.getState().getStatus('session-9')).toEqual({ type: 'idle' })
})
it('reconciles the global active snapshot on reconnect and clears omitted sessions', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
mocks.listActiveSessions.mockResolvedValue({ 'session-other': { type: 'running' } })
render(<Harness />, { wrapper: createWrapper() })
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
act(() => {
useSessionStatus.getState().setStatus('session-other', { type: 'busy' })
useSessionStatus.getState().setStatus('session-stale', { type: 'busy' })
})
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const handleStatusChange = lastSubscribeCall[0].onStatusChange as (connected: boolean) => void
act(() => {
handleStatusChange(true)
})
await waitFor(() => {
expect(useSessionStatus.getState().getStatus('session-other')).toEqual({ type: 'busy' })
expect(useSessionStatus.getState().getStatus('session-stale')).toEqual({ type: 'idle' })
})
})
it('ignores a superseded connect snapshot that resolves after a newer reconnect snapshot', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
const first = createDeferred<Record<string, unknown>>()
const second = createDeferred<Record<string, unknown>>()
mocks.listActiveSessions
.mockReturnValueOnce(first.promise)
.mockReturnValueOnce(second.promise)
render(<Harness />, { wrapper: createWrapper() })
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const handleStatusChange = lastSubscribeCall[0].onStatusChange as (connected: boolean) => void
act(() => {
handleStatusChange(true)
})
expect(mocks.listActiveSessions).toHaveBeenCalledTimes(1)
act(() => {
handleStatusChange(false)
handleStatusChange(true)
})
expect(mocks.listActiveSessions).toHaveBeenCalledTimes(2)
await act(async () => {
second.resolve({ 'session-new': { type: 'running' } })
await second.promise
})
await waitFor(() => {
expect(useSessionStatus.getState().getStatus('session-new')).toEqual({ type: 'busy' })
})
await act(async () => {
first.resolve({ 'session-old': { type: 'running' } })
await first.promise
})
expect(useSessionStatus.getState().getStatus('session-new')).toEqual({ type: 'busy' })
expect(useSessionStatus.getState().getStatus('session-old')).toEqual({ type: 'idle' })
})
it('does not apply a global snapshot that resolves after unmount', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
const deferred = createDeferred<Record<string, unknown>>()
mocks.listActiveSessions.mockReturnValueOnce(deferred.promise)
const { unmount } = render(<Harness />, { wrapper: createWrapper() })
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const handleStatusChange = lastSubscribeCall[0].onStatusChange as (connected: boolean) => void
act(() => {
handleStatusChange(true)
})
expect(mocks.listActiveSessions).toHaveBeenCalledTimes(1)
unmount()
await act(async () => {
deferred.resolve({ 'session-late': { type: 'running' } })
await deferred.promise
})
expect(useSessionStatus.getState().getStatus('session-late')).toEqual({ type: 'idle' })
})
it('does not let a deferred connect snapshot revert an idle event received while it was in flight', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
const deferred = createDeferred<Record<string, unknown>>()
mocks.listActiveSessions.mockReturnValueOnce(deferred.promise)
render(<Harness />, { wrapper: createWrapper() })
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
const handleStatusChange = lastSubscribeCall[0].onStatusChange as (connected: boolean) => void
act(() => {
handleStatusChange(true)
})
expect(mocks.listActiveSessions).toHaveBeenCalledTimes(1)
act(() => {
onEvent({ type: 'session.status', data: { sessionID: 'session-a', status: { type: 'busy' } }, directory: '/repo' })
onEvent({ type: 'session.idle', data: { sessionID: 'session-a' }, directory: '/repo' })
})
await act(async () => {
deferred.resolve({ 'session-a': { type: 'running' } })
await deferred.promise
})
expect(useSessionStatus.getState().getStatus('session-a')).toEqual({ type: 'idle' })
})
it('does not let a deferred empty connect snapshot erase a session that started while it was in flight', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
const deferred = createDeferred<Record<string, unknown>>()
mocks.listActiveSessions.mockReturnValueOnce(deferred.promise)
render(<Harness />, { wrapper: createWrapper() })
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
const handleStatusChange = lastSubscribeCall[0].onStatusChange as (connected: boolean) => void
act(() => {
handleStatusChange(true)
})
expect(mocks.listActiveSessions).toHaveBeenCalledTimes(1)
act(() => {
onEvent({ type: 'session.execution.started', data: { sessionID: 'session-a' }, directory: '/repo' })
})
await act(async () => {
deferred.resolve({})
await deferred.promise
})
expect(useSessionStatus.getState().getStatus('session-a')).toEqual({ type: 'busy' })
})
it('does not let a deferred connect snapshot resurrect an unknown session that went idle', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
const deferred = createDeferred<Record<string, unknown>>()
mocks.listActiveSessions.mockReturnValueOnce(deferred.promise)
render(<Harness />, { wrapper: createWrapper() })
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
const handleStatusChange = lastSubscribeCall[0].onStatusChange as (connected: boolean) => void
act(() => {
handleStatusChange(true)
})
expect(mocks.listActiveSessions).toHaveBeenCalledTimes(1)
act(() => {
onEvent({ type: 'session.idle', data: { sessionID: 'session-unseen' }, directory: '/repo' })
})
await act(async () => {
deferred.resolve({ 'session-unseen': { type: 'running' } })
await deferred.promise
})
expect(useSessionStatus.getState().getStatus('session-unseen')).toEqual({ type: 'idle' })
})
it('debounces a session list invalidation on session lifecycle events', async () => {
const queryClient = createTestQueryClient()
const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
queryClient.setQueryData(['opencode', 'sessions', '/repo'], { pages: [], pageParams: [] })
render(<Harness />, { wrapper: createWrapper(queryClient) })
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type: 'session.created', data: { sessionID: 'session-9' }, directory: '/repo' })
onEvent({ type: 'session.renamed', data: { sessionID: 'session-9', title: 'Renamed' }, directory: '/repo' })
onEvent({ type: 'session.deleted', data: { sessionID: 'session-9' }, directory: '/repo' })
})
await waitFor(() => {
expect(queryClient.getQueryState(['opencode', 'sessions', '/repo'])?.isInvalidated).toBe(true)
})
expect(invalidateQueries).toHaveBeenCalledTimes(1)
})
it('invalidates only the session list for the event directory', async () => {
const queryClient = createTestQueryClient()
queryClient.setQueryData(['opencode', 'sessions', '/repo-a'], { pages: [], pageParams: [] })
queryClient.setQueryData(['opencode', 'sessions', '/repo-b'], { pages: [], pageParams: [] })
render(<Harness />, { wrapper: createWrapper(queryClient) })
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type: 'session.created', data: { sessionID: 'session-9' }, directory: '/repo-a' })
})
await waitFor(() => {
expect(queryClient.getQueryState(['opencode', 'sessions', '/repo-a'])?.isInvalidated).toBe(true)
})
expect(queryClient.getQueryState(['opencode', 'sessions', '/repo-b'])?.isInvalidated).toBe(false)
})
it('does not invalidate session lists on session.usage.updated', async () => {
const queryClient = createTestQueryClient()
const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
queryClient.setQueryData(['opencode', 'sessions', '/repo'], { pages: [], pageParams: [] })
render(<Harness />, { wrapper: createWrapper(queryClient) })
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
invalidateQueries.mockClear()
act(() => {
onEvent({ type: 'session.usage.updated', data: { sessionID: 'session-9', cost: 0, tokens: {} }, directory: '/repo' })
})
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 300))
})
expect(invalidateQueries).not.toHaveBeenCalled()
expect(queryClient.getQueryState(['opencode', 'sessions', '/repo'])?.isInvalidated).toBe(false)
})
it('fetches the active session snapshot on connect and polls every 5 seconds while connected', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
mocks.listActiveSessions.mockResolvedValue({})
render(<Harness />, { wrapper: createWrapper() })
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const handleStatusChange = lastSubscribeCall[0].onStatusChange as (connected: boolean) => void
vi.useFakeTimers()
try {
act(() => {
handleStatusChange(true)
})
expect(mocks.listActiveSessions).toHaveBeenCalledTimes(1)
await act(async () => {
await vi.advanceTimersByTimeAsync(5000)
})
expect(mocks.listActiveSessions).toHaveBeenCalledTimes(2)
await act(async () => {
await vi.advanceTimersByTimeAsync(5000)
})
expect(mocks.listActiveSessions).toHaveBeenCalledTimes(3)
act(() => {
handleStatusChange(false)
})
await act(async () => {
await vi.advanceTimersByTimeAsync(15000)
})
expect(mocks.listActiveSessions).toHaveBeenCalledTimes(3)
} finally {
vi.useRealTimers()
}
})
it('stops polling the active session snapshot after unmount', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
mocks.listActiveSessions.mockResolvedValue({})
const { unmount } = render(<Harness />, { wrapper: createWrapper() })
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const handleStatusChange = lastSubscribeCall[0].onStatusChange as (connected: boolean) => void
vi.useFakeTimers()
try {
act(() => {
handleStatusChange(true)
})
expect(mocks.listActiveSessions).toHaveBeenCalledTimes(1)
unmount()
await act(async () => {
await vi.advanceTimersByTimeAsync(15000)
})
expect(mocks.listActiveSessions).toHaveBeenCalledTimes(1)
} finally {
vi.useRealTimers()
}
})
})
+82 -2
View File
@@ -4,6 +4,7 @@ import { useNavigate } from 'react-router-dom'
import { useQueryClient, useQuery } from '@tanstack/react-query'
import {
cancelForm,
listActiveSessions,
listPendingForms,
listPendingPermissions,
replyForm,
@@ -15,7 +16,15 @@ import type { PermissionResponse, SSHHostKeyRequest, Repo } from '@/api/types'
import { showToast } from '@/lib/toast'
import { openCodeEventStream, type EventStreamHealthState } from '@/lib/opencode-event-stream'
import { addToSessionKeyedState, removeFromSessionKeyedState } from '@/lib/sessionKeyedState'
import { invalidateProviderCachesDebounced, invalidateQueryKeysDebounced, invalidateRepoGitCachesDebounced } from '@/lib/queryInvalidation'
import { busyStatusesFromActiveSessions, useSessionStatus } from '@/stores/sessionStatusStore'
import {
invalidateProviderCachesDebounced,
invalidateQueryKeysDebounced,
invalidateRepoGitCachesDebounced,
invalidateSessionListCachesDebounced,
} from '@/lib/queryInvalidation'
const STATUS_POLL_INTERVAL_MS = 5000
type PermissionsBySession = Record<string, PermissionRequest[]>
type FormsBySession = Record<string, FormInfo[]>
@@ -150,6 +159,8 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
const sessionDirectoriesRef = useRef<Map<string, string>>(new Map())
const prevPermissionCountRef = useRef(0)
const initialFetchDoneRef = useRef(false)
const statusSyncVersionRef = useRef(0)
const statusPollIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null)
const subscriptionRef = useRef<ReturnType<typeof openCodeEventStream.subscribeGlobalMonitor> | null>(null)
const reposRef = useRef<typeof repos>(null)
@@ -371,6 +382,41 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
await reconcilePendingActionsForDirectories([...new Set(reposToUse.map(r => r.fullPath))])
}, [reconcilePendingActionsForDirectories])
const fetchInitialSessionStatuses = useCallback(async () => {
const syncVersion = ++statusSyncVersionRef.current
const snapshotToken = useSessionStatus.getState().beginStatusSnapshot()
try {
const active = await listActiveSessions()
if (statusSyncVersionRef.current !== syncVersion) {
useSessionStatus.getState().endStatusSnapshot(snapshotToken)
return
}
useSessionStatus.getState().replaceStatuses(
busyStatusesFromActiveSessions(active),
snapshotToken,
)
} catch (error) {
useSessionStatus.getState().endStatusSnapshot(snapshotToken)
if (import.meta.env.DEV) {
console.warn('Failed to fetch active sessions:', error)
}
}
}, [])
const stopStatusPoll = useCallback(() => {
if (statusPollIntervalRef.current === null) return
clearInterval(statusPollIntervalRef.current)
statusPollIntervalRef.current = null
}, [])
const startStatusPoll = useCallback(() => {
stopStatusPoll()
statusPollIntervalRef.current = setInterval(() => {
void fetchInitialSessionStatuses()
}, STATUS_POLL_INTERVAL_MS)
}, [fetchInitialSessionStatuses, stopStatusPoll])
const syncPermissionsForSession = useCallback(async (directory: string, sessionID: string) => {
const pendingPermissions = await listPendingPermissions(directory)
rememberSessionDirectory(sessionID, directory)
@@ -413,6 +459,33 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
removeForm(id, sessionID)
break
}
case 'session.status': {
const { sessionID, status } = event.data
useSessionStatus.getState().setStatus(sessionID, status)
break
}
case 'session.idle': {
useSessionStatus.getState().setStatus(event.data.sessionID, { type: 'idle' })
break
}
case 'session.execution.started': {
useSessionStatus.getState().setStatus(event.data.sessionID, { type: 'busy' })
break
}
case 'session.execution.succeeded':
case 'session.execution.failed':
case 'session.execution.interrupted': {
useSessionStatus.getState().setStatus(event.data.sessionID, { type: 'idle' })
invalidateSessionListCachesDebounced(queryClient, event.directory)
break
}
case 'session.created':
case 'session.renamed':
case 'session.deleted':
case 'session.moved':
case 'session.metadata.updated':
invalidateSessionListCachesDebounced(queryClient, event.directory)
break
case 'credential.updated':
case 'credential.switched':
case 'integration.updated':
@@ -455,6 +528,11 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
if (connected) {
initialFetchDoneRef.current = false
fetchInitialPendingData()
fetchInitialSessionStatuses()
startStatusPoll()
} else {
statusSyncVersionRef.current += 1
stopStatusPoll()
}
}
@@ -473,10 +551,12 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
subscriptionRef.current = subscription
return () => {
statusSyncVersionRef.current += 1
stopStatusPoll()
subscription.dispose()
subscriptionRef.current = null
}
}, [addPermission, removePermission, addForm, removeForm, rememberSessionDirectory, fetchInitialPendingData, queryClient, handleHealthChange, reconcilePendingActionsForDirectories, collectTrackedDirectories])
}, [addPermission, removePermission, addForm, removeForm, rememberSessionDirectory, fetchInitialPendingData, fetchInitialSessionStatuses, startStatusPoll, stopStatusPoll, queryClient, handleHealthChange, reconcilePendingActionsForDirectories, collectTrackedDirectories])
useEffect(() => {
reposRef.current = repos
+16 -5
View File
@@ -1,6 +1,16 @@
import { useCallback } from 'react'
import { useUrlParams } from './useUrlParams'
export function openDialogParam(
updateParams: ReturnType<typeof useUrlParams>['updateParams'],
name: string,
): void {
updateParams((p) => {
p.set('dialog', name)
p.delete('mobileTab')
}, 'push')
}
export function useDialogParam(name: string): [boolean, (open: boolean) => void] {
const { searchParams, updateParams } = useUrlParams()
@@ -8,14 +18,15 @@ export function useDialogParam(name: string): [boolean, (open: boolean) => void]
const setOpen = useCallback(
(open: boolean) => {
if (open) {
openDialogParam(updateParams, name)
return
}
updateParams((p) => {
if (open) {
p.set('dialog', name)
p.delete('mobileTab')
} else if (p.get('dialog') === name) {
if (p.get('dialog') === name) {
p.delete('dialog')
}
}, open ? 'push' : 'replace')
}, 'replace')
},
[updateParams, name],
)
+27 -17
View File
@@ -25,7 +25,7 @@ import { showToast } from "../lib/toast";
import { useSendErrorStore } from "../stores/sendErrorStore";
import { useSessionStatus } from "../stores/sessionStatusStore";
import { invalidateSessionListCaches, sessionTranscriptQueryKey } from "../lib/queryInvalidation";
import { buildSessionKey } from "../lib/sessionKey";
import { buildPinnedSessionKeys, buildSessionKey } from "../lib/sessionKey";
import { toggleSessionPin } from "../api/sessionPins";
import { SESSION_PINS_QUERY_KEY } from "./useSessionPins";
import { admitInboxItem, type TranscriptCache } from "../lib/session-projection";
@@ -39,6 +39,8 @@ const isSameModelRef = (left: ModelRef, right: ModelRef | undefined) =>
const SESSION_LIST_PAGE_SIZE = 25
const EMPTY_SESSIONS: SessionInfo[] = []
interface UseSessionsAcrossDirectoriesOptions {
search?: string
limit?: number
@@ -110,8 +112,13 @@ export const useSessionsAcrossDirectories = (
refetchOnReconnect: true,
});
const data = useMemo(
() => query.data?.pages.flatMap((page) => page.items) ?? EMPTY_SESSIONS,
[query.data],
);
return {
data: query.data?.pages.flatMap((page) => page.items) ?? [],
data,
isLoading: query.isLoading,
isError: query.isError,
fetchNextPage: query.fetchNextPage,
@@ -122,16 +129,22 @@ export const useSessionsAcrossDirectories = (
};
};
const sessionQueryKey = (sessionID: string | undefined, directory?: string) =>
["opencode", "session", sessionID, directory] as const;
export const sessionQueryOptions = (sessionID: string | undefined, directory?: string) => ({
queryKey: sessionQueryKey(sessionID, directory),
queryFn: () => getSession(sessionID!),
enabled: !!sessionID,
refetchOnWindowFocus: true,
refetchOnReconnect: true,
staleTime: 15000,
retry: (failureCount: number, error: unknown) =>
!(error instanceof FetchError && error.statusCode === 404) && failureCount < 3,
});
export const useSession = (sessionID: string | undefined, directory?: string) => {
return useQuery({
queryKey: ["opencode", "session", sessionID, directory],
queryFn: () => getSession(sessionID!),
enabled: !!sessionID,
refetchOnWindowFocus: true,
refetchOnReconnect: true,
staleTime: 15000,
retry: (failureCount, error) => !(error instanceof FetchError && error.statusCode === 404) && failureCount < 3,
});
return useQuery(sessionQueryOptions(sessionID, directory));
};
export const useCreateSession = (
@@ -232,7 +245,7 @@ const cleanupSessionPins = (
) => {
const pins = queryClient.getQueryData<SessionPin[]>(SESSION_PINS_QUERY_KEY) ?? [];
if (pins.length === 0) return;
const pinnedKeys = new Set(pins.map((p) => buildSessionKey(p.directory, p.sessionId)));
const pinnedKeys = buildPinnedSessionKeys(pins);
const targets = (Array.isArray(variables) ? variables : [variables])
.map((target) => ({
sessionId: getDeleteSessionTargetId(target),
@@ -256,15 +269,12 @@ export const useUpdateSession = (directory?: string) => {
},
onSuccess: (_, variables) => {
const { sessionID } = variables;
queryClient.invalidateQueries({ queryKey: ["opencode", "session", sessionID, directory] });
queryClient.invalidateQueries({ queryKey: sessionQueryKey(sessionID, directory) });
invalidateSessionListCaches(queryClient);
},
});
};
const sessionQueryKey = (sessionID: string, directory?: string) =>
["opencode", "session", sessionID, directory] as const;
const patchCachedSessionSelection = (
queryClient: ReturnType<typeof useQueryClient>,
sessionID: string,
@@ -459,7 +469,7 @@ export const useSendShell = (directory?: string) => {
const { sessionID } = variables;
queryClient.invalidateQueries({
queryKey: ["opencode", "session", sessionID, directory],
queryKey: sessionQueryKey(sessionID, directory),
});
},
});
+27 -246
View File
@@ -4,16 +4,9 @@ import type { ReactNode } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { useSSE } from './useSSE'
import { useSessionStatus } from '../stores/sessionStatusStore'
import { useSendErrorStore } from '../stores/sendErrorStore'
import { showToast } from '@/lib/toast'
const mocks = vi.hoisted(() => ({
active: vi.fn(),
}))
vi.mock('@/api/opencode', () => ({
listActiveSessions: mocks.active,
}))
vi.mock('@/lib/toast', () => ({
showToast: {
dismiss: vi.fn(),
@@ -60,14 +53,15 @@ describe('useSSE', () => {
beforeEach(() => {
vi.clearAllMocks()
MockEventSource.instances = []
mocks.active.mockResolvedValue({})
useSessionStatus.getState().replaceStatuses({})
useSessionStatus.setState({ statuses: new Map(), statusCache: new Map(), statusRevisions: new Map(), revision: 0 })
useSendErrorStore.setState({ errors: {} })
globalThis.EventSource = MockEventSource as unknown as typeof EventSource
globalThis.fetch = vi.fn(() => Promise.resolve({ ok: true } as Response))
})
afterEach(() => {
useSessionStatus.getState().replaceStatuses({})
useSessionStatus.setState({ statuses: new Map(), statusCache: new Map(), statusRevisions: new Map(), revision: 0 })
useSendErrorStore.setState({ errors: {} })
globalThis.EventSource = originalEventSource
globalThis.fetch = originalFetch
})
@@ -130,92 +124,7 @@ describe('useSSE', () => {
unmount()
})
it('clears stale active statuses from the initial status snapshot', async () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
},
})
useSessionStatus.getState().setStatus('session-1', { type: 'busy' })
const { unmount } = renderHook(
() => useSSE('/repo', 'session-1'),
{ wrapper: createWrapper(queryClient) }
)
await waitFor(() => expect(MockEventSource.instances).toHaveLength(1))
await connect(0, 'client-1')
await waitFor(() => {
expect(useSessionStatus.getState().getStatus('session-1')).toEqual({ type: 'idle' })
})
unmount()
})
it('preserves optimistic active status when a poll snapshot omits the session', () => {
useSessionStatus.getState().setOptimisticActive('session-1', 10_000)
useSessionStatus.getState().replaceStatuses({})
expect(useSessionStatus.getState().getStatus('session-1')).toEqual({ type: 'busy' })
useSessionStatus.getState().replaceStatuses({
'session-1': { type: 'idle' },
})
expect(useSessionStatus.getState().getStatus('session-1')).toEqual({ type: 'idle' })
})
it('ignores stale status snapshots after the directory changes', async () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
},
})
let resolveRepoA: (value: Record<string, { type: 'running' }>) => void = () => {}
let resolveRepoB: (value: Record<string, { type: 'running' }>) => void = () => {}
mocks.active
.mockImplementationOnce(() => new Promise((resolve) => { resolveRepoA = resolve }))
.mockImplementationOnce(() => new Promise((resolve) => { resolveRepoB = resolve }))
const { rerender, unmount } = renderHook(
({ directory }) => useSSE(directory, 'session-1'),
{ wrapper: createWrapper(queryClient), initialProps: { directory: '/repo-a' } }
)
await waitFor(() => expect(MockEventSource.instances).toHaveLength(1))
await connect(0, 'client-1')
rerender({ directory: '/repo-b' })
await waitFor(() => expect(MockEventSource.instances).toHaveLength(2))
await connect(1, 'client-2')
await act(async () => {
resolveRepoB({ 'session-b': { type: 'running' } })
})
await waitFor(() => {
expect(useSessionStatus.getState().getStatus('session-b')).toEqual({ type: 'busy' })
})
await act(async () => {
resolveRepoA({ 'session-a': { type: 'running' } })
})
expect(useSessionStatus.getState().getStatus('session-b')).toEqual({ type: 'busy' })
expect(useSessionStatus.getState().getStatus('session-a')).toEqual({ type: 'idle' })
unmount()
})
it('invalidates the session list and cached session query on session.created', async () => {
it('invalidates the cached session query on session.created', async () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
@@ -244,15 +153,12 @@ describe('useSSE', () => {
await waitFor(() => {
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'session', 'session-2'] })
expect(invalidateQueries).toHaveBeenCalledWith(
expect.objectContaining({ predicate: expect.any(Function) }),
)
})
unmount()
})
it('invalidates the session list and cached session query on session.renamed', async () => {
it('invalidates the cached session query on session.renamed', async () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
@@ -281,15 +187,12 @@ describe('useSSE', () => {
await waitFor(() => {
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'session', 'session-2'] })
expect(invalidateQueries).toHaveBeenCalledWith(
expect.objectContaining({ predicate: expect.any(Function) }),
)
})
unmount()
})
it('invalidates the session list and removes the session query on session.deleted', async () => {
it('removes the session query on session.deleted', async () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
@@ -319,44 +222,6 @@ describe('useSSE', () => {
await waitFor(() => {
expect(removeQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'session', 'session-2'] })
expect(invalidateQueries).toHaveBeenCalledWith(
expect.objectContaining({ predicate: expect.any(Function) }),
)
})
unmount()
})
it('invalidates the session list on session.moved', async () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
},
})
const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
const { result, unmount } = renderHook(
() => useSSE('/repo', 'session-1'),
{ wrapper: createWrapper(queryClient) }
)
await waitFor(() => expect(MockEventSource.instances).toHaveLength(1))
await connect(0, 'client-1')
await waitFor(() => expect(result.current.isConnected).toBe(true))
invalidateQueries.mockClear()
act(() => {
MockEventSource.instances[0].emit('message', {
type: 'session.moved',
directory: '/repo',
data: { sessionID: 'session-2', projectID: 'proj-1', location: { directory: '/repo-2' } },
})
})
await waitFor(() => {
expect(invalidateQueries).toHaveBeenCalledWith(
expect.objectContaining({ predicate: expect.any(Function) }),
)
})
unmount()
@@ -552,7 +417,7 @@ describe('useSSE', () => {
unmount()
})
it('handles envelopes whose directory is null', async () => {
it('does not write session status from stream events', async () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
@@ -569,24 +434,35 @@ describe('useSSE', () => {
await waitFor(() => expect(result.current.isConnected).toBe(true))
act(() => {
MockEventSource.instances[0].emit('message', {
directory: null,
payload: { type: 'session.execution.started', data: { sessionID: 'session-9' } },
})
const events = [
{ type: 'session.status', directory: '/repo', data: { sessionID: 'session-1', status: { type: 'busy' } } },
{ type: 'session.execution.started', directory: '/repo', data: { sessionID: 'session-1' } },
{ type: 'session.idle', directory: '/repo', data: { sessionID: 'session-1' } },
]
for (const event of events) {
MockEventSource.instances[0].emit('message', event)
}
})
expect(useSessionStatus.getState().getStatus('session-9')).toEqual({ type: 'busy' })
expect(useSessionStatus.getState().getStatus('session-1')).toEqual({ type: 'idle' })
unmount()
})
it('applies session.status and session.idle to the status store', async () => {
it('clears the network send error on session.idle', async () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
},
})
useSendErrorStore.getState().setError({
sessionID: 'session-1',
title: 'Failed to send',
message: 'Network error',
kind: 'network',
})
const { result, unmount } = renderHook(
() => useSSE('/repo', 'session-1'),
{ wrapper: createWrapper(queryClient) }
@@ -596,16 +472,6 @@ describe('useSSE', () => {
await connect(0, 'client-1')
await waitFor(() => expect(result.current.isConnected).toBe(true))
act(() => {
MockEventSource.instances[0].emit('message', {
type: 'session.status',
directory: '/repo',
data: { sessionID: 'session-1', status: { type: 'busy' } },
})
})
expect(useSessionStatus.getState().getStatus('session-1')).toEqual({ type: 'busy' })
act(() => {
MockEventSource.instances[0].emit('message', {
type: 'session.idle',
@@ -614,46 +480,7 @@ describe('useSSE', () => {
})
})
expect(useSessionStatus.getState().getStatus('session-1')).toEqual({ type: 'idle' })
unmount()
})
it('applies session execution lifecycle events to the status store', async () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
},
})
const { result, unmount } = renderHook(
() => useSSE('/repo', 'session-1'),
{ wrapper: createWrapper(queryClient) }
)
await waitFor(() => expect(MockEventSource.instances).toHaveLength(1))
await connect(0, 'client-1')
await waitFor(() => expect(result.current.isConnected).toBe(true))
const emit = (type: string, data: Record<string, unknown>) => {
act(() => {
MockEventSource.instances[0].emit('message', { type, directory: '/repo', data })
})
}
emit('session.execution.started', { sessionID: 'session-1' })
expect(useSessionStatus.getState().getStatus('session-1')).toEqual({ type: 'busy' })
emit('session.execution.succeeded', { sessionID: 'session-1' })
expect(useSessionStatus.getState().getStatus('session-1')).toEqual({ type: 'idle' })
emit('session.execution.started', { sessionID: 'session-1' })
emit('session.execution.failed', { sessionID: 'session-1', error: { message: 'failed' } })
expect(useSessionStatus.getState().getStatus('session-1')).toEqual({ type: 'idle' })
emit('session.execution.started', { sessionID: 'session-1' })
emit('session.execution.interrupted', { sessionID: 'session-1', reason: 'user' })
expect(useSessionStatus.getState().getStatus('session-1')).toEqual({ type: 'idle' })
expect(useSendErrorStore.getState().getError('session-1')).toBeNull()
unmount()
})
@@ -697,52 +524,6 @@ describe('useSSE', () => {
unmount()
})
it('invalidates the session list on terminal execution, metadata, and usage events', async () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
},
})
const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
const { result, unmount } = renderHook(
() => useSSE('/repo', 'session-1'),
{ wrapper: createWrapper(queryClient) }
)
await waitFor(() => expect(MockEventSource.instances).toHaveLength(1))
await connect(0, 'client-1')
await waitFor(() => expect(result.current.isConnected).toBe(true))
const emit = (type: string, data: Record<string, unknown>) => {
act(() => {
MockEventSource.instances[0].emit('message', { type, directory: '/repo', data })
})
}
for (const type of ['session.execution.succeeded', 'session.execution.failed', 'session.execution.interrupted']) {
invalidateQueries.mockClear()
emit(type, { sessionID: 'session-2' })
await waitFor(() => {
expect(invalidateQueries).toHaveBeenCalledWith(
expect.objectContaining({ predicate: expect.any(Function) }),
)
})
}
for (const type of ['session.metadata.updated', 'session.usage.updated']) {
invalidateQueries.mockClear()
emit(type, { sessionID: 'session-2', metadata: {}, cost: 0, tokens: {} })
await waitFor(() => {
expect(invalidateQueries).toHaveBeenCalledWith(
expect.objectContaining({ predicate: expect.any(Function) }),
)
})
}
unmount()
})
it('does not invalidate the session list on per-token delta events', async () => {
const queryClient = new QueryClient({
defaultOptions: {
+4 -70
View File
@@ -1,15 +1,12 @@
import { useEffect, useRef, useState, useCallback, useMemo } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import type { SessionInfo, V2Event } from '@opencode-manager/shared/opencode'
import { invalidateSessionListCaches, invalidateSessionListCachesDebounced, shellsQueryKey } from '@/lib/queryInvalidation'
import { invalidateSessionListCaches, shellsQueryKey } from '@/lib/queryInvalidation'
import { showToast } from '@/lib/toast'
import { useSessionStatus } from '@/stores/sessionStatusStore'
import { useSendErrorStore } from '@/stores/sendErrorStore'
import { openCodeEventStream } from '@/lib/opencode-event-stream'
import type { EventStreamSubscription } from '@/lib/opencode-event-stream'
import { listActiveSessions, type ShellInfo } from '@/api/opencode'
const STATUS_POLL_INTERVAL_MS = 5000
import type { ShellInfo } from '@/api/opencode'
type V2StreamEvent = V2Event & { directory?: string }
@@ -51,14 +48,11 @@ export const useSSE = (directory?: string | string[], currentSessionId?: string)
const queryClient = useQueryClient()
const mountedRef = useRef(true)
const sessionIdRef = useRef(currentSessionId)
const statusSyncVersionRef = useRef(0)
const eventStreamSubscriptionRef = useRef<EventStreamSubscription | null>(null)
sessionIdRef.current = currentSessionId
const [isConnected, setIsConnected] = useState(false)
const [error, setError] = useState<string | null>(null)
const [isReconnecting, setIsReconnecting] = useState(false)
const setSessionStatus = useSessionStatus((state) => state.setStatus)
const replaceSessionStatuses = useSessionStatus((state) => state.replaceStatuses)
const resolveCacheDirectory = useCallback(
(eventDirectory: string | undefined): string | undefined => {
@@ -75,12 +69,10 @@ export const useSSE = (directory?: string | string[], currentSessionId?: string)
switch (event.type) {
case 'session.created':
invalidateSessionListCachesDebounced(queryClient)
invalidateSessionQueryIfCached(queryClient, event.data.sessionID)
break
case 'session.renamed':
invalidateSessionListCachesDebounced(queryClient)
invalidateSessionQueryIfCached(queryClient, event.data.sessionID)
break
@@ -108,39 +100,13 @@ export const useSSE = (directory?: string | string[], currentSessionId?: string)
break
case 'session.deleted':
invalidateSessionListCaches(queryClient)
queryClient.removeQueries({ queryKey: ['opencode', 'session', event.data.sessionID] })
break
case 'session.moved':
invalidateSessionListCachesDebounced(queryClient)
break
case 'session.status':
setSessionStatus(event.data.sessionID, event.data.status)
break
case 'session.idle':
setSessionStatus(event.data.sessionID, { type: 'idle' })
useSendErrorStore.getState().clearNetworkError(event.data.sessionID)
break
case 'session.execution.started':
setSessionStatus(event.data.sessionID, { type: 'busy' })
break
case 'session.execution.succeeded':
case 'session.execution.failed':
case 'session.execution.interrupted':
setSessionStatus(event.data.sessionID, { type: 'idle' })
invalidateSessionListCachesDebounced(queryClient)
break
case 'session.metadata.updated':
case 'session.usage.updated':
invalidateSessionListCachesDebounced(queryClient)
break
case 'shell.created': {
const info = event.data.info
queryClient.setQueryData<ShellInfo[]>(shellsQueryKey(cacheDirectory), (current) =>
@@ -168,36 +134,7 @@ export const useSSE = (directory?: string | string[], currentSessionId?: string)
default:
break
}
}, [queryClient, directorySet, resolveCacheDirectory, setSessionStatus])
const fetchInitialData = useCallback(async () => {
if (!primaryDirectory || !mountedRef.current) return
const syncVersion = ++statusSyncVersionRef.current
try {
const active = await listActiveSessions()
if (mountedRef.current && statusSyncVersionRef.current === syncVersion && active) {
const statuses = Object.fromEntries(
Object.keys(active).map((sessionID) => [sessionID, { type: 'busy' as const }]),
)
replaceSessionStatuses(statuses)
}
} catch (err) {
if (err instanceof Error && !err.message.includes('aborted')) {
throw err
}
}
}, [primaryDirectory, replaceSessionStatuses])
useEffect(() => {
if (!primaryDirectory) return
const interval = setInterval(() => {
void fetchInitialData().catch(() => undefined)
}, STATUS_POLL_INTERVAL_MS)
return () => clearInterval(interval)
}, [primaryDirectory, fetchInitialData])
}, [queryClient, directorySet, resolveCacheDirectory])
const refreshCurrentSession = useCallback(() => {
const sessionId = sessionIdRef.current
@@ -222,7 +159,6 @@ export const useSSE = (directory?: string | string[], currentSessionId?: string)
mountedRef.current = true
if (directoriesList.length === 0) {
statusSyncVersionRef.current += 1
setIsConnected(false)
setIsReconnecting(false)
return
@@ -241,7 +177,6 @@ export const useSSE = (directory?: string | string[], currentSessionId?: string)
if (connected) {
setError(null)
void fetchInitialData().catch(() => undefined)
syncCurrentSession()
eventStreamSubscriptionRef.current?.reportVisibility(document.visibilityState === 'visible', sessionIdRef.current)
} else {
@@ -278,7 +213,6 @@ export const useSSE = (directory?: string | string[], currentSessionId?: string)
return () => {
mountedRef.current = false
statusSyncVersionRef.current += 1
document.removeEventListener('visibilitychange', handleVisibilityChange)
window.removeEventListener('focus', handleReconnect)
window.removeEventListener('online', handleReconnect)
@@ -288,7 +222,7 @@ export const useSSE = (directory?: string | string[], currentSessionId?: string)
eventStreamSubscriptionRef.current = null
}
}
}, [directoryKey, directoriesList, handleSSEEvent, fetchInitialData, syncCurrentSession, refreshCurrentSession, queryClient])
}, [directoryKey, directoriesList, handleSSEEvent, syncCurrentSession, refreshCurrentSession, queryClient])
useEffect(() => {
if (isConnected && document.visibilityState === 'visible') {
+78 -42
View File
@@ -1,15 +1,15 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { renderHook, act } from '@testing-library/react'
import { useSidebarCollapsed } from './useSidebarCollapsed'
import { useSidebarCollapsed, useSidebarSectionCollapsed } from './useSidebarCollapsed'
describe('useSidebarCollapsed', () => {
const localStorageMock = {
getItem: vi.fn(),
setItem: vi.fn(),
removeItem: vi.fn(),
clear: vi.fn(),
}
const localStorageMock = {
getItem: vi.fn(),
setItem: vi.fn(),
removeItem: vi.fn(),
clear: vi.fn(),
}
describe('sidebar collapse hooks', () => {
beforeEach(() => {
vi.clearAllMocks()
Object.defineProperty(global, 'localStorage', {
@@ -26,50 +26,86 @@ describe('useSidebarCollapsed', () => {
vi.restoreAllMocks()
})
it('returns false by default when no stored value', () => {
localStorageMock.getItem.mockReturnValue(null)
describe('useSidebarCollapsed', () => {
it('returns false by default when no stored value', () => {
localStorageMock.getItem.mockReturnValue(null)
const { result } = renderHook(() => useSidebarCollapsed())
const { result } = renderHook(() => useSidebarCollapsed())
expect(result.current[0]).toBe(false)
})
it('returns stored value from localStorage', () => {
localStorageMock.getItem.mockReturnValue('true')
const { result } = renderHook(() => useSidebarCollapsed())
expect(result.current[0]).toBe(true)
})
it('toggles collapsed state and persists to localStorage', () => {
localStorageMock.getItem.mockReturnValue(null)
const { result } = renderHook(() => useSidebarCollapsed())
expect(result.current[0]).toBe(false)
act(() => {
result.current[1]()
expect(result.current[0]).toBe(false)
})
expect(result.current[0]).toBe(true)
expect(localStorageMock.setItem).toHaveBeenCalledWith('oc:sidebar:collapsed', 'true')
it('returns stored value from localStorage', () => {
localStorageMock.getItem.mockReturnValue('true')
const { result } = renderHook(() => useSidebarCollapsed())
expect(result.current[0]).toBe(true)
})
it('toggles collapsed state and persists to localStorage', () => {
localStorageMock.getItem.mockReturnValue(null)
const { result } = renderHook(() => useSidebarCollapsed())
expect(result.current[0]).toBe(false)
act(() => {
result.current[1]()
})
expect(result.current[0]).toBe(true)
expect(localStorageMock.setItem).toHaveBeenCalledWith('oc:sidebar:collapsed', 'true')
})
it('returns false when stored value is malformed JSON', () => {
localStorageMock.getItem.mockReturnValue('not-json{{')
const { result } = renderHook(() => useSidebarCollapsed())
expect(result.current[0]).toBe(false)
})
it('returns false when stored value is JSON but not a boolean', () => {
localStorageMock.getItem.mockReturnValue('"some string"')
const { result } = renderHook(() => useSidebarCollapsed())
expect(result.current[0]).toBe(false)
})
})
it('returns false when stored value is malformed JSON', () => {
localStorageMock.getItem.mockReturnValue('not-json{{')
describe('useSidebarSectionCollapsed', () => {
it('returns false by default when no stored value', () => {
localStorageMock.getItem.mockReturnValue(null)
const { result } = renderHook(() => useSidebarCollapsed())
const { result } = renderHook(() => useSidebarSectionCollapsed('sessions'))
expect(result.current[0]).toBe(false)
})
expect(result.current[0]).toBe(false)
})
it('returns false when stored value is JSON but not a boolean', () => {
localStorageMock.getItem.mockReturnValue('"some string"')
it('returns stored value from the section key', () => {
localStorageMock.getItem.mockReturnValue('true')
const { result } = renderHook(() => useSidebarCollapsed())
const { result } = renderHook(() => useSidebarSectionCollapsed('menu'))
expect(result.current[0]).toBe(false)
expect(localStorageMock.getItem).toHaveBeenCalledWith('oc:sidebar:collapsed:menu')
expect(result.current[0]).toBe(true)
})
it('toggles collapsed state and persists under the section key', () => {
localStorageMock.getItem.mockReturnValue(null)
const { result } = renderHook(() => useSidebarSectionCollapsed('sessions'))
expect(result.current[0]).toBe(false)
act(() => {
result.current[1]()
})
expect(result.current[0]).toBe(true)
expect(localStorageMock.setItem).toHaveBeenCalledWith('oc:sidebar:collapsed:sessions', 'true')
})
})
})
+30 -20
View File
@@ -2,32 +2,42 @@ import { useState, useCallback } from 'react'
const STORAGE_KEY = 'oc:sidebar:collapsed'
export function useSidebarCollapsed(): [boolean, () => void] {
const [collapsed, setCollapsed] = useState(() => {
if (typeof window === 'undefined') {
return false
}
const stored = localStorage.getItem(STORAGE_KEY)
if (stored === null) {
return false
}
try {
const parsed = JSON.parse(stored)
return typeof parsed === 'boolean' ? parsed : false
} catch {
return false
}
})
function readStoredBoolean(key: string, fallback: boolean): boolean {
if (typeof window === 'undefined') {
return fallback
}
const stored = localStorage.getItem(key)
if (stored === null) {
return fallback
}
try {
const parsed = JSON.parse(stored)
return typeof parsed === 'boolean' ? parsed : fallback
} catch {
return fallback
}
}
function usePersistentBoolean(key: string, fallback: boolean): [boolean, () => void] {
const [value, setValue] = useState(() => readStoredBoolean(key, fallback))
const toggle = useCallback(() => {
setCollapsed((prev: boolean) => {
setValue((prev: boolean) => {
const newValue = !prev
if (typeof window !== 'undefined') {
localStorage.setItem(STORAGE_KEY, JSON.stringify(newValue))
localStorage.setItem(key, JSON.stringify(newValue))
}
return newValue
})
}, [])
}, [key])
return [collapsed, toggle]
return [value, toggle]
}
export function useSidebarCollapsed(): [boolean, () => void] {
return usePersistentBoolean(STORAGE_KEY, false)
}
export function useSidebarSectionCollapsed(section: string): [boolean, () => void] {
return usePersistentBoolean(`${STORAGE_KEY}:${section}`, false)
}
@@ -0,0 +1,81 @@
import { useMemo } from 'react'
import { useQueries, useQuery } from '@tanstack/react-query'
import { listRepos } from '@/api/repos'
import { sessionQueryOptions, useSessionsAcrossDirectories } from '@/hooks/useOpenCode'
import { useSessionPins } from '@/hooks/useSessionPins'
import { buildPinnedSessionKeys, buildSessionKey } from '@/lib/sessionKey'
import type { Repo, Session } from '@/api/types'
import {
SIDEBAR_SESSIONS_PER_REPO,
buildSidebarRepoGroups,
selectNavigableRepos,
type SidebarRepoGroup,
} from '@/components/navigation/sidebar-session-tree'
const combinePinnedSessions = (results: Array<{ data?: Session }>): Session[] =>
results.flatMap((result) => (result.data ? [result.data] : []))
const mergeSessions = (sessions: Session[], pinnedSessions: Session[]): Session[] => {
if (pinnedSessions.length === 0) return sessions
const seen = new Set(sessions.map((session) => session.id))
const extras: Session[] = []
for (const session of pinnedSessions) {
if (seen.has(session.id)) continue
seen.add(session.id)
extras.push(session)
}
return extras.length === 0 ? sessions : [...sessions, ...extras]
}
export function useSidebarRepoGroups(input: {
repos: Repo[]
search?: string
}): { groups: SidebarRepoGroup[]; isLoading: boolean; isError: boolean; hasMore: boolean } {
const { repos, search } = input
const directories = useMemo(() => repos.map((repo) => repo.fullPath), [repos])
const { data: sessions, isLoading, isError, hasNextPage } = useSessionsAcrossDirectories(directories, {
search,
limit: SIDEBAR_SESSIONS_PER_REPO,
})
const { data: sessionPins } = useSessionPins()
const pinnedKeys = useMemo(() => buildPinnedSessionKeys(sessionPins ?? []), [sessionPins])
const missingPins = useMemo(() => {
if (search) return []
const repoDirectories = new Set(directories)
const fetchedKeys = new Set(
sessions.map((session) => buildSessionKey(session.location.directory, session.id)),
)
return (sessionPins ?? []).filter(
(pin) =>
repoDirectories.has(pin.directory) &&
!fetchedKeys.has(buildSessionKey(pin.directory, pin.sessionId)),
)
}, [directories, search, sessionPins, sessions])
const pinnedSessions = useQueries({
queries: missingPins.map((pin) => sessionQueryOptions(pin.sessionId, pin.directory)),
combine: combinePinnedSessions,
})
const mergedSessions = useMemo(
() => mergeSessions(sessions, pinnedSessions),
[sessions, pinnedSessions],
)
const groups = useMemo(
() => buildSidebarRepoGroups({ repos, sessions: mergedSessions, pinnedKeys, now: Date.now() }),
[repos, mergedSessions, pinnedKeys],
)
return { groups, isLoading, isError, hasMore: Boolean(hasNextPage) }
}
export function useNavigableRepos(enabled = true): { repos: Repo[]; isLoading: boolean; refetch: () => void } {
const { data, isLoading, refetch } = useQuery({ queryKey: ['repos'], queryFn: listRepos, enabled })
const repos = useMemo(() => selectNavigableRepos(data ?? []), [data])
return { repos, isLoading, refetch: () => { void refetch() } }
}
+39 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
import { getSessionListPath, getSwipeBackTarget, getAssistantPath, getAssistantSessionListPath, isAssistantPath, getPathWithReturnTo, getReturnToPath } from './navigation';
import { getSessionListPath, getSwipeBackTarget, getAssistantPath, getAssistantSessionListPath, isAssistantPath, getPathWithReturnTo, getReturnToPath, getSessionPath, parseRepoRoute } from './navigation';
describe('getAssistantPath', () => {
it('returns /assistant', () => {
@@ -60,6 +60,44 @@ describe('getSessionListPath', () => {
});
});
describe('getSessionPath', () => {
it('builds a session detail path from a numeric or string repo id', () => {
expect(getSessionPath(5, 'ses_1')).toBe('/repos/5/sessions/ses_1');
expect(getSessionPath('5', 'ses_1')).toBe('/repos/5/sessions/ses_1');
});
});
describe('parseRepoRoute', () => {
it('parses a repo and session route', () => {
expect(parseRepoRoute('/repos/5/sessions/ses_1')).toEqual({
repoId: 5,
section: 'sessions',
sessionId: 'ses_1',
});
});
it('parses a repo route without a section', () => {
expect(parseRepoRoute('/repos/5')).toEqual({ repoId: 5, section: null, sessionId: null });
});
it('parses a repo section route without a session id', () => {
expect(parseRepoRoute('/repos/5/schedules')).toEqual({
repoId: 5,
section: 'schedules',
sessionId: null,
});
expect(parseRepoRoute('/repos/5/sessions')).toEqual({
repoId: 5,
section: 'sessions',
sessionId: null,
});
});
it('returns nulls for an unrelated route', () => {
expect(parseRepoRoute('/')).toEqual({ repoId: null, section: null, sessionId: null });
});
});
describe('return target helpers', () => {
it('adds encoded returnTo params for internal paths', () => {
expect(getPathWithReturnTo('/repos/5/schedules', '/repos/5/sessions/abc?assistant=1')).toBe(
+18
View File
@@ -10,6 +10,24 @@ export function isAssistantPath(pathname: string): boolean {
return pathname === '/assistant' || /^\/repos\/[^/]+\/assistant$/.test(pathname);
}
export function getSessionPath(repoId: number | string, sessionId: string): string {
return `/repos/${repoId}/sessions/${sessionId}`;
}
export function parseRepoRoute(pathname: string): { repoId: number | null; section: string | null; sessionId: string | null } {
const match = /^\/repos\/(\d+)(?:\/([^/]+)(?:\/([^/]+))?)?/.exec(pathname);
if (!match) {
return { repoId: null, section: null, sessionId: null };
}
const section = match[2] ?? null;
return {
repoId: Number(match[1]),
section,
sessionId: section === 'sessions' ? (match[3] ?? null) : null,
};
}
export function getSessionListPath(repoId: string | number, isAssistantSession: boolean, tab?: string): string {
if (isAssistantSession) {
return getAssistantSessionListPath();
@@ -5,6 +5,7 @@ import {
invalidateProviderCaches,
invalidateProviderCachesDebounced,
invalidateQueryKeysDebounced,
invalidateSessionListCachesDebounced,
refreshOpenCodeServerCaches,
} from './queryInvalidation'
@@ -95,6 +96,54 @@ describe('invalidateProviderCachesDebounced', () => {
})
})
describe('invalidateSessionListCachesDebounced', () => {
afterEach(() => {
vi.useRealTimers()
})
const sessionListKey = (directoryKey: string) => ['opencode', 'sessions', directoryKey]
it('invalidates only the session lists that include the event directory', () => {
vi.useFakeTimers()
const queryClient = new QueryClient()
queryClient.setQueryData(sessionListKey('/a'), { pages: [], pageParams: [] })
queryClient.setQueryData(sessionListKey('/b'), { pages: [], pageParams: [] })
invalidateSessionListCachesDebounced(queryClient, '/a')
vi.advanceTimersByTime(200)
expect(queryClient.getQueryState(sessionListKey('/a'))?.isInvalidated).toBe(true)
expect(queryClient.getQueryState(sessionListKey('/b'))?.isInvalidated).toBe(false)
})
it('merges directories reported within the debounce window into one flush', () => {
vi.useFakeTimers()
const queryClient = new QueryClient()
queryClient.setQueryData(sessionListKey('/a|/b'), { pages: [], pageParams: [] })
queryClient.setQueryData(sessionListKey('/c'), { pages: [], pageParams: [] })
invalidateSessionListCachesDebounced(queryClient, '/a')
invalidateSessionListCachesDebounced(queryClient, '/b')
vi.advanceTimersByTime(200)
expect(queryClient.getQueryState(sessionListKey('/a|/b'))?.isInvalidated).toBe(true)
expect(queryClient.getQueryState(sessionListKey('/c'))?.isInvalidated).toBe(false)
})
it('invalidates every session list when called without a directory', () => {
vi.useFakeTimers()
const queryClient = new QueryClient()
queryClient.setQueryData(sessionListKey('/a'), { pages: [], pageParams: [] })
queryClient.setQueryData(sessionListKey('/b'), { pages: [], pageParams: [] })
invalidateSessionListCachesDebounced(queryClient)
vi.advanceTimersByTime(200)
expect(queryClient.getQueryState(sessionListKey('/a'))?.isInvalidated).toBe(true)
expect(queryClient.getQueryState(sessionListKey('/b'))?.isInvalidated).toBe(true)
})
})
describe('invalidateQueryKeysDebounced', () => {
afterEach(() => {
vi.useRealTimers()
+48 -11
View File
@@ -155,18 +155,55 @@ export function invalidateSessionListCaches(queryClient: QueryClient) {
})
}
const sessionListInvalidationTimers = new WeakMap<QueryClient, ReturnType<typeof setTimeout>>()
interface SessionListInvalidationState {
timer: ReturnType<typeof setTimeout> | null
directories: Set<string>
invalidateAll: boolean
}
export function invalidateSessionListCachesDebounced(queryClient: QueryClient, delayMs = 200) {
const existing = sessionListInvalidationTimers.get(queryClient)
if (existing) clearTimeout(existing)
sessionListInvalidationTimers.set(
queryClient,
setTimeout(() => {
sessionListInvalidationTimers.delete(queryClient)
invalidateSessionListCaches(queryClient)
}, delayMs),
)
const sessionListInvalidationStates = new WeakMap<QueryClient, SessionListInvalidationState>()
function sessionListQueryMatchesDirectories(queryKey: readonly unknown[], directories: Set<string>) {
if (queryKey[0] !== 'opencode' || queryKey[1] !== 'sessions') return false
const directoryKey = queryKey[2]
if (typeof directoryKey !== 'string') return false
return directoryKey.split('|').some((directory) => directories.has(directory))
}
function flushSessionListInvalidation(
queryClient: QueryClient,
state: SessionListInvalidationState,
) {
if (state.invalidateAll) {
invalidateSessionListCaches(queryClient)
return
}
queryClient.invalidateQueries({
predicate: (query) => sessionListQueryMatchesDirectories(query.queryKey, state.directories),
})
}
export function invalidateSessionListCachesDebounced(
queryClient: QueryClient,
directory?: string,
delayMs = 200,
) {
const state = sessionListInvalidationStates.get(queryClient) ?? {
timer: null,
directories: new Set<string>(),
invalidateAll: false,
}
if (state.timer) clearTimeout(state.timer)
if (directory) {
state.directories.add(directory)
} else {
state.invalidateAll = true
}
sessionListInvalidationStates.set(queryClient, state)
state.timer = setTimeout(() => {
sessionListInvalidationStates.delete(queryClient)
flushSessionListInvalidation(queryClient, state)
}, delayMs)
}
const queryKeysInvalidationTimers = new WeakMap<QueryClient, Map<string, ReturnType<typeof setTimeout>>>()
+11
View File
@@ -0,0 +1,11 @@
import { describe, it, expect } from 'vitest'
import { buildPinnedSessionKeys } from './sessionKey'
describe('buildPinnedSessionKeys', () => {
it('builds a session key for each pin', () => {
const keys = buildPinnedSessionKeys([{ directory: '/a', sessionId: 's1' }])
expect(keys.has('/a:s1')).toBe(true)
expect(keys.size).toBe(1)
})
})
+6
View File
@@ -1,3 +1,9 @@
export function buildSessionKey(directory: string | undefined, id: string): string {
return `${directory ?? ''}:${id}`
}
export function buildPinnedSessionKeys(
pins: ReadonlyArray<{ directory: string; sessionId: string }>,
): Set<string> {
return new Set(pins.map((pin) => buildSessionKey(pin.directory, pin.sessionId)))
}
+35 -1
View File
@@ -1,5 +1,11 @@
import { describe, it, expect, afterEach } from 'vitest'
import { getRepoDisplayName, sanitizeForTTS, randomId } from './utils'
import {
getRepoDisplayName,
getRepoBranchLabel,
sanitizeForTTS,
randomId,
formatShortRelativeTime,
} from './utils'
describe('sanitizeForTTS', () => {
it('should handle headers', () => {
@@ -147,3 +153,31 @@ describe('getRepoDisplayName', () => {
expect(getRepoDisplayName({ repoUrl: null, localPath: null, sourcePath: null })).toBe('Repository')
})
})
describe('getRepoBranchLabel', () => {
it('prefers currentBranch', () => {
expect(getRepoBranchLabel({ currentBranch: 'feature/x', branch: 'main' })).toBe('feature/x')
})
it('falls back to branch', () => {
expect(getRepoBranchLabel({ branch: 'main' })).toBe('main')
})
it('returns null when neither is present', () => {
expect(getRepoBranchLabel({})).toBeNull()
})
})
describe('formatShortRelativeTime', () => {
const now = new Date('2026-01-01T12:00:00.000Z')
const at = (offsetMs: number) => new Date(now.getTime() - offsetMs)
it('formats each threshold boundary', () => {
expect(formatShortRelativeTime(at(30_000), now)).toBe('just now')
expect(formatShortRelativeTime(at(5 * 60_000), now)).toBe('5m ago')
expect(formatShortRelativeTime(at(3 * 60 * 60_000), now)).toBe('3h ago')
expect(formatShortRelativeTime(at(2 * 24 * 60 * 60_000), now)).toBe('2d ago')
expect(formatShortRelativeTime(at(14 * 24 * 60 * 60_000), now)).toBe('2w ago')
expect(formatShortRelativeTime(at(60 * 24 * 60 * 60_000), now)).toBe('2mo ago')
})
})
+22
View File
@@ -1,9 +1,14 @@
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
import type { CSSProperties } from "react"
import type { Repo } from "@/api/types"
export { getRepoDisplayName } from '@opencode-manager/shared/utils'
export function getRepoBranchLabel(repo: Pick<Repo, 'currentBranch' | 'branch'>): string | null {
return repo.currentBranch || repo.branch || null
}
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
@@ -15,6 +20,23 @@ export function randomId(): string {
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 11)}`
}
export function formatShortRelativeTime(date: Date, now: Date = new Date()): string {
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 const GPU_ACCELERATED_STYLE: CSSProperties = {
transform: 'translateZ(0)',
backfaceVisibility: 'hidden',
-5
View File
@@ -23,7 +23,6 @@ import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, D
import { ResetPermissionsDialog } from "@/components/repo/ResetPermissionsDialog";
import { PendingActionsGroup } from "@/components/notifications/PendingActionsGroup";
import { getRepoDisplayName } from "@/lib/utils";
import { useSidebarAction } from "@/hooks/useSidebarAction";
import { isWorktreeSibling } from "@opencode-manager/shared/utils";
export function RepoDetail() {
@@ -147,10 +146,6 @@ export function RepoDetail() {
navigate(sessionUrl(sessionId));
};
useSidebarAction('new-session', () => {
handleCreateSession();
});
if (repoLoading) {
return (
<div className="flex items-center justify-center min-h-screen bg-background">
-5
View File
@@ -49,7 +49,6 @@ import { SourceControlPanel } from "@/components/source-control";
import { SessionSendErrorBanner } from "@/components/session/SessionSendErrorBanner";
import { BackgroundWorkBar } from "@/components/session/BackgroundWorkBar";
import { useDialogParam } from "@/hooks/useDialogParam";
import { useSidebarAction } from "@/hooks/useSidebarAction";
import { SessionMoreButton } from "@/components/navigation/SessionMoreButton";
const OLDER_HISTORY_SCROLL_THRESHOLD_PX = 200
@@ -300,10 +299,6 @@ export function SessionDetail() {
}
}, [createSession, navigate, repoId, sessionRouteSuffix]);
useSidebarAction('new-session', () => {
handleNewSession();
});
const undoMessage = useUndoMessage({
sessionId: sessionId ?? '',
directory: sessionDirectory,
@@ -0,0 +1,251 @@
import { beforeEach, describe, expect, it } from 'vitest'
import { busyStatusesFromActiveSessions, useSessionStatus } from './sessionStatusStore'
const resetStore = () => {
useSessionStatus.setState({
statuses: new Map(),
statusCache: new Map(),
statusRevisions: new Map(),
revision: 0,
})
}
describe('sessionStatusStore', () => {
beforeEach(() => {
resetStore()
})
it('fully replaces the map for a global snapshot', () => {
const store = useSessionStatus.getState()
store.setStatus('session-a', { type: 'busy' })
store.setStatus('session-b', { type: 'busy' })
const token = store.beginStatusSnapshot()
useSessionStatus.getState().replaceStatuses({ 'session-a': { type: 'busy' } }, token)
expect(useSessionStatus.getState().getStatus('session-a')).toEqual({ type: 'busy' })
expect(useSessionStatus.getState().getStatus('session-b')).toEqual({ type: 'idle' })
})
it('preserves an optimistic active session across a global snapshot', () => {
useSessionStatus.getState().setOptimisticActive('session-a', 10_000)
const token = useSessionStatus.getState().beginStatusSnapshot()
useSessionStatus.getState().replaceStatuses({}, token)
expect(useSessionStatus.getState().getStatus('session-a')).toEqual({ type: 'busy' })
useSessionStatus.getState().clearStatus('session-a')
})
it('keeps a more specific live status when a snapshot reports the session as busy', () => {
const store = useSessionStatus.getState()
const retry = { type: 'retry' as const, attempt: 2, message: 'rate limited', next: 1234 }
store.setStatus('session-retry', retry)
store.setStatus('session-compact', { type: 'compact' })
const token = useSessionStatus.getState().beginStatusSnapshot()
useSessionStatus.getState().replaceStatuses(
{ 'session-retry': { type: 'busy' }, 'session-compact': { type: 'busy' } },
token,
)
expect(useSessionStatus.getState().getStatus('session-retry')).toEqual(retry)
expect(useSessionStatus.getState().getStatus('session-compact')).toEqual({ type: 'compact' })
})
it('maps active session ids to busy statuses', () => {
expect(busyStatusesFromActiveSessions({ 'session-a': { type: 'running' } })).toEqual({
'session-a': { type: 'busy' },
})
})
it('leaves the store state untouched for an idle event on an untracked session with no snapshot in flight', () => {
const before = useSessionStatus.getState()
before.setStatus('untracked', { type: 'idle' })
expect(useSessionStatus.getState()).toBe(before)
})
it('leaves the statuses map identity unchanged for a repeated identical busy status outside a snapshot', () => {
const store = useSessionStatus.getState()
store.setStatus('session-a', { type: 'busy' })
const statuses = useSessionStatus.getState().statuses
store.setStatus('session-a', { type: 'busy' })
expect(useSessionStatus.getState().statuses).toBe(statuses)
})
it('clears recorded revisions when the last snapshot ends via replaceStatuses', () => {
const store = useSessionStatus.getState()
store.setStatus('session-a', { type: 'busy' })
const token = store.beginStatusSnapshot()
store.setStatus('session-b', { type: 'busy' })
useSessionStatus.getState().replaceStatuses({}, token)
expect(useSessionStatus.getState().statusRevisions.size).toBe(0)
})
it('clears recorded revisions when the last snapshot ends via endStatusSnapshot', () => {
const store = useSessionStatus.getState()
store.setStatus('session-a', { type: 'busy' })
const token = store.beginStatusSnapshot()
store.setStatus('session-b', { type: 'busy' })
useSessionStatus.getState().endStatusSnapshot(token)
expect(useSessionStatus.getState().statusRevisions.size).toBe(0)
})
it('does not replace the statuses map for an unchanged snapshot', () => {
const store = useSessionStatus.getState()
store.setStatus('session-a', { type: 'busy' })
const statuses = useSessionStatus.getState().statuses
const token = store.beginStatusSnapshot()
useSessionStatus.getState().replaceStatuses({ 'session-a': { type: 'busy' } }, token)
expect(useSessionStatus.getState().statuses).toBe(statuses)
})
it('keeps an event received during an in-flight snapshot over the snapshot', () => {
const store = useSessionStatus.getState()
const token = store.beginStatusSnapshot()
store.setStatus('session-a', { type: 'busy' })
useSessionStatus.getState().replaceStatuses({}, token)
expect(useSessionStatus.getState().getStatus('session-a')).toEqual({ type: 'busy' })
})
it('does not let a snapshot captured before an idle event resurrect the session', () => {
const store = useSessionStatus.getState()
store.setStatus('session-a', { type: 'busy' })
const snapshotRevision = store.beginStatusSnapshot()
store.setStatus('session-a', { type: 'idle' })
useSessionStatus.getState().replaceStatuses(
{ 'session-a': { type: 'busy' } },
snapshotRevision,
)
expect(useSessionStatus.getState().getStatus('session-a')).toEqual({ type: 'idle' })
})
it('does not let an older empty snapshot erase a session that started after it was captured', () => {
const store = useSessionStatus.getState()
const snapshotRevision = store.beginStatusSnapshot()
store.setStatus('session-a', { type: 'busy' })
useSessionStatus.getState().replaceStatuses({}, snapshotRevision)
expect(useSessionStatus.getState().getStatus('session-a')).toEqual({ type: 'busy' })
})
it('applies unrelated snapshot entries while preserving a newer live entry', () => {
const store = useSessionStatus.getState()
const snapshotRevision = store.beginStatusSnapshot()
store.setStatus('session-live', { type: 'busy' })
useSessionStatus.getState().replaceStatuses(
{ 'session-snapshot': { type: 'busy' } },
snapshotRevision,
)
expect(useSessionStatus.getState().getStatus('session-live')).toEqual({ type: 'busy' })
expect(useSessionStatus.getState().getStatus('session-snapshot')).toEqual({ type: 'busy' })
})
it('clears an inactive session from a snapshot captured after its last event', () => {
const store = useSessionStatus.getState()
store.setStatus('session-a', { type: 'busy' })
const snapshotRevision = store.beginStatusSnapshot()
useSessionStatus.getState().replaceStatuses({}, snapshotRevision)
expect(useSessionStatus.getState().getStatus('session-a')).toEqual({ type: 'idle' })
})
it('applies a snapshot captured after a live idle event', () => {
const store = useSessionStatus.getState()
store.setStatus('session-a', { type: 'idle' })
const snapshotRevision = store.beginStatusSnapshot()
useSessionStatus.getState().replaceStatuses(
{ 'session-a': { type: 'busy' } },
snapshotRevision,
)
expect(useSessionStatus.getState().getStatus('session-a')).toEqual({ type: 'busy' })
})
it('does not let an initial snapshot resurrect an unknown session that received an idle event', () => {
const store = useSessionStatus.getState()
const snapshotRevision = store.beginStatusSnapshot()
store.setStatus('unseen', { type: 'idle' })
useSessionStatus.getState().replaceStatuses(
{ unseen: { type: 'busy' } },
snapshotRevision,
)
expect(useSessionStatus.getState().getStatus('unseen')).toEqual({ type: 'idle' })
})
it('does not let a deferred empty snapshot erase a repeated busy event', () => {
const store = useSessionStatus.getState()
store.setStatus('repeat', { type: 'busy' })
const snapshotRevision = store.beginStatusSnapshot()
store.setStatus('repeat', { type: 'busy' })
useSessionStatus.getState().replaceStatuses({}, snapshotRevision)
expect(useSessionStatus.getState().getStatus('repeat')).toEqual({ type: 'busy' })
})
it('rejects an older global snapshot once a newer global snapshot has been applied', () => {
const store = useSessionStatus.getState()
const older = store.beginStatusSnapshot()
const newer = store.beginStatusSnapshot()
useSessionStatus.getState().replaceStatuses(
{ active: { type: 'busy' } },
newer,
)
useSessionStatus.getState().replaceStatuses({}, older)
expect(useSessionStatus.getState().getStatus('active')).toEqual({ type: 'busy' })
})
it('rejects an older global snapshot that would clear sessions added by a newer snapshot', () => {
const store = useSessionStatus.getState()
const older = store.beginStatusSnapshot()
const newer = store.beginStatusSnapshot()
useSessionStatus.getState().replaceStatuses({}, newer)
useSessionStatus.getState().replaceStatuses(
{ active: { type: 'busy' } },
older,
)
expect(useSessionStatus.getState().getStatus('active')).toEqual({ type: 'idle' })
})
it('applies a newer snapshot after an older snapshot in completion order', () => {
const store = useSessionStatus.getState()
const older = store.beginStatusSnapshot()
const newer = store.beginStatusSnapshot()
useSessionStatus.getState().replaceStatuses({}, older)
useSessionStatus.getState().replaceStatuses(
{ active: { type: 'busy' } },
newer,
)
expect(useSessionStatus.getState().getStatus('active')).toEqual({ type: 'busy' })
})
})
+209 -110
View File
@@ -6,12 +6,21 @@ export type SessionStatusType =
| { type: 'compact' }
| { type: 'retry'; attempt: number; message: string; next: number }
interface StatusSnapshotToken {
revision: number
order: number
}
interface SessionStatusStore {
statuses: Map<string, SessionStatusType>
statusCache: Map<string, string>
statusRevisions: Map<string, number>
revision: number
setStatus: (sessionID: string, status: SessionStatusType) => void
setOptimisticActive: (sessionID: string, timeoutMs?: number) => void
replaceStatuses: (statuses: Record<string, SessionStatusType>) => void
replaceStatuses: (statuses: Record<string, SessionStatusType>, token: StatusSnapshotToken) => void
beginStatusSnapshot: () => StatusSnapshotToken
endStatusSnapshot: (token: StatusSnapshotToken) => void
getStatus: (sessionID: string) => SessionStatusType
clearStatus: (sessionID: string) => void
}
@@ -19,6 +28,9 @@ interface SessionStatusStore {
const DEFAULT_STATUS: SessionStatusType = { type: 'idle' }
const OPTIMISTIC_ACTIVE_TIMEOUT_MS = 120_000
const optimisticActiveTimers = new Map<string, ReturnType<typeof setTimeout>>()
const inFlightSnapshots = new Map<number, number>()
let snapshotOrderCounter = 0
let lastAppliedSnapshotOrder = 0
const clearOptimisticActiveTimer = (sessionID: string): void => {
const timer = optimisticActiveTimers.get(sessionID)
@@ -34,119 +46,206 @@ const getStatusHash = (status: SessionStatusType): string => {
return status.type
}
export const useSessionStatus = create<SessionStatusStore>((set, get) => ({
statuses: new Map(),
statusCache: new Map(),
setStatus: (sessionID: string, status: SessionStatusType) => {
clearOptimisticActiveTimer(sessionID)
const hash = getStatusHash(status)
const previousHash = get().statusCache.get(sessionID)
if (previousHash === hash) return
const sameEntries = <V>(left: Map<string, V>, right: Map<string, V>): boolean => {
if (left.size !== right.size) return false
for (const [sessionID, value] of right.entries()) {
if (left.get(sessionID) !== value) return false
}
return true
}
if (status.type === 'idle') {
if (!previousHash) return
const registerSnapshot = (token: StatusSnapshotToken): void => {
inFlightSnapshots.set(token.order, token.revision)
}
const releaseSnapshot = (token: StatusSnapshotToken): void => {
inFlightSnapshots.delete(token.order)
}
const oldestInFlightSnapshotRevision = (): number | null => {
let oldest: number | null = null
for (const revision of inFlightSnapshots.values()) {
if (oldest === null || revision < oldest) oldest = revision
}
return oldest
}
const prunedRevisions = (currentRevisions: Map<string, number>): Map<string, number> => {
const oldestSnapshotRevision = oldestInFlightSnapshotRevision()
const nextRevisions = new Map<string, number>()
if (oldestSnapshotRevision === null) return nextRevisions
for (const [sessionID, revision] of currentRevisions.entries()) {
if (revision > oldestSnapshotRevision) nextRevisions.set(sessionID, revision)
}
return nextRevisions
}
export function busyStatusesFromActiveSessions(active: Record<string, unknown>): Record<string, SessionStatusType> {
return Object.fromEntries(
Object.keys(active).map((sessionID) => [sessionID, { type: 'busy' as const }]),
)
}
export const useSessionStatus = create<SessionStatusStore>((set, get) => {
const recordRevisionPatch = (
state: SessionStatusStore,
sessionID: string,
): Pick<SessionStatusStore, 'statusRevisions' | 'revision'> | null => {
if (inFlightSnapshots.size === 0) return null
const revision = state.revision + 1
const statusRevisions = new Map(state.statusRevisions)
statusRevisions.set(sessionID, revision)
return { statusRevisions, revision }
}
const applyStatusPatch = (
state: SessionStatusStore,
sessionID: string,
status: SessionStatusType,
): Partial<SessionStatusStore> => {
const statuses = new Map(state.statuses)
const statusCache = new Map(state.statusCache)
statuses.set(sessionID, status)
statusCache.set(sessionID, getStatusHash(status))
return { statuses, statusCache, ...(recordRevisionPatch(state, sessionID) ?? {}) }
}
return {
statuses: new Map(),
statusCache: new Map(),
statusRevisions: new Map(),
revision: 0,
setStatus: (sessionID: string, status: SessionStatusType) => {
if (status.type === 'idle') {
get().clearStatus(sessionID)
return
}
clearOptimisticActiveTimer(sessionID)
if (get().statusCache.get(sessionID) === getStatusHash(status)) {
const patch = recordRevisionPatch(get(), sessionID)
if (patch) set(patch)
return
}
set((state) => applyStatusPatch(state, sessionID, status))
},
setOptimisticActive: (sessionID: string, timeoutMs = OPTIMISTIC_ACTIVE_TIMEOUT_MS) => {
clearOptimisticActiveTimer(sessionID)
const timer = setTimeout(() => {
optimisticActiveTimers.delete(sessionID)
const currentStatus = get().getStatus(sessionID)
if (currentStatus.type === 'busy') {
get().clearStatus(sessionID)
}
}, timeoutMs)
optimisticActiveTimers.set(sessionID, timer)
if (get().statusCache.get(sessionID) === getStatusHash({ type: 'busy' })) {
const patch = recordRevisionPatch(get(), sessionID)
if (patch) set(patch)
return
}
set((state) => applyStatusPatch(state, sessionID, { type: 'busy' }))
},
replaceStatuses: (statuses: Record<string, SessionStatusType>, token: StatusSnapshotToken) => {
releaseSnapshot(token)
if (token.order < lastAppliedSnapshotOrder) {
const currentRevisions = get().statusRevisions
const nextRevisions = prunedRevisions(currentRevisions)
if (!sameEntries(currentRevisions, nextRevisions)) {
set({ statusRevisions: nextRevisions })
}
return
}
lastAppliedSnapshotOrder = token.order
for (const sessionID of Object.keys(statuses)) {
clearOptimisticActiveTimer(sessionID)
}
const currentStatuses = get().statuses
const currentRevisions = get().statusRevisions
const captureRevision = token.revision
const isLiveAfterCapture = (sessionID: string): boolean => {
if (optimisticActiveTimers.has(sessionID)) return true
const touched = currentRevisions.get(sessionID)
return touched !== undefined && touched > captureRevision
}
const newMap = new Map<string, SessionStatusType>()
const newCache = new Map<string, string>()
for (const [sessionID, status] of currentStatuses.entries()) {
if (!isLiveAfterCapture(sessionID)) continue
newMap.set(sessionID, status)
newCache.set(sessionID, getStatusHash(status))
}
for (const [sessionID, status] of Object.entries(statuses)) {
if (isLiveAfterCapture(sessionID)) continue
if (status.type === 'idle') continue
const current = currentStatuses.get(sessionID)
const effective = status.type === 'busy' && current !== undefined && current.type !== 'idle' ? current : status
newMap.set(sessionID, effective)
newCache.set(sessionID, getStatusHash(effective))
}
const nextRevisions = prunedRevisions(currentRevisions)
if (sameEntries(get().statusCache, newCache) && sameEntries(currentRevisions, nextRevisions)) return
set({
statuses: newMap,
statusCache: newCache,
statusRevisions: nextRevisions,
})
},
beginStatusSnapshot: () => {
const token: StatusSnapshotToken = {
revision: get().revision,
order: ++snapshotOrderCounter,
}
registerSnapshot(token)
return token
},
endStatusSnapshot: (token: StatusSnapshotToken) => {
releaseSnapshot(token)
if (inFlightSnapshots.size > 0) return
if (get().statusRevisions.size === 0) return
set({ statusRevisions: new Map() })
},
getStatus: (sessionID: string) => {
return get().statuses.get(sessionID) || DEFAULT_STATUS
},
clearStatus: (sessionID: string) => {
clearOptimisticActiveTimer(sessionID)
if (!get().statuses.has(sessionID) && inFlightSnapshots.size === 0) return
set((state) => {
const newMap = new Map(state.statuses)
const newCache = new Map(state.statusCache)
newMap.delete(sessionID)
newCache.delete(sessionID)
return { statuses: newMap, statusCache: newCache }
const revisionPatch = recordRevisionPatch(state, sessionID)
if (!state.statuses.has(sessionID)) return revisionPatch ?? state
const statuses = new Map(state.statuses)
const statusCache = new Map(state.statusCache)
statuses.delete(sessionID)
statusCache.delete(sessionID)
return { statuses, statusCache, ...(revisionPatch ?? {}) }
})
return
}
set((state) => {
const newMap = new Map(state.statuses)
const newCache = new Map(state.statusCache)
newMap.set(sessionID, status)
newCache.set(sessionID, hash)
return { statuses: newMap, statusCache: newCache }
})
},
setOptimisticActive: (sessionID: string, timeoutMs = OPTIMISTIC_ACTIVE_TIMEOUT_MS) => {
clearOptimisticActiveTimer(sessionID)
const timer = setTimeout(() => {
optimisticActiveTimers.delete(sessionID)
const currentStatus = get().getStatus(sessionID)
if (currentStatus.type === 'busy') {
get().clearStatus(sessionID)
}
}, timeoutMs)
optimisticActiveTimers.set(sessionID, timer)
const hash = getStatusHash({ type: 'busy' })
const previousHash = get().statusCache.get(sessionID)
if (previousHash === hash) return
set((state) => {
const newMap = new Map(state.statuses)
const newCache = new Map(state.statusCache)
newMap.set(sessionID, { type: 'busy' })
newCache.set(sessionID, hash)
return { statuses: newMap, statusCache: newCache }
})
},
replaceStatuses: (statuses: Record<string, SessionStatusType>) => {
for (const sessionID of Object.keys(statuses)) {
clearOptimisticActiveTimer(sessionID)
}
const newMap = new Map<string, SessionStatusType>()
const newCache = new Map<string, string>()
const currentStatuses = get().statuses
for (const [sessionID, status] of Object.entries(statuses)) {
if (status.type === 'idle') continue
newMap.set(sessionID, status)
newCache.set(sessionID, getStatusHash(status))
}
for (const [sessionID, status] of currentStatuses.entries()) {
if (!optimisticActiveTimers.has(sessionID) || sessionID in statuses) continue
newMap.set(sessionID, status)
newCache.set(sessionID, getStatusHash(status))
}
const currentCache = get().statusCache
if (currentCache.size === newCache.size) {
let unchanged = true
for (const [sessionID, hash] of newCache.entries()) {
if (currentCache.get(sessionID) !== hash) {
unchanged = false
break
}
}
if (unchanged) return
}
set({ statuses: newMap, statusCache: newCache })
},
getStatus: (sessionID: string) => {
return get().statuses.get(sessionID) || DEFAULT_STATUS
},
clearStatus: (sessionID: string) => {
clearOptimisticActiveTimer(sessionID)
const previousHash = get().statusCache.get(sessionID)
if (!previousHash) return
set((state) => {
const newMap = new Map(state.statuses)
const newCache = new Map(state.statusCache)
newMap.delete(sessionID)
newCache.delete(sessionID)
return { statuses: newMap, statusCache: newCache }
})
},
}))
},
}
})
export const useSessionStatusForSession = (sessionID: string | undefined): SessionStatusType => {
return useSessionStatus((state) =>