feat(servers): switch the sidebar listing between local and linked servers

The Servers section becomes a Local/server switcher shared by the desktop sidebar, collapsed rail and mobile repo sheet. Selecting a linked server lists its projects and sessions with the same navigation as local repos, and a remote project page mirrors the local repo page.
This commit is contained in:
Chris Scott committed 2026-10-19 10:16:32 -04:00
1 parent cb9b7645e6
commit 36b8c1b200
29 files changed
+2080 -201

No files matched your search

@@ -5,7 +5,9 @@ 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 { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
import { DesktopSessionTree } from './DesktopSessionTree'
import { useSidebarServerStore } from '@/stores/sidebarServerStore'
import type { Repo } from '@/api/types'
type SessionFixture = {
@@ -90,6 +92,11 @@ vi.mock('@/hooks/useSessionPins', () => ({
useSessionPins: () => ({ data: sessionPinsData.current }),
}))
vi.mock('@/hooks/useOpenCodeServers', () => ({
useOpenCodeServers: () => ({ servers: [], isLoading: false }),
useOpenCodeServerStatuses: () => ({ statuses: [], statusById: {}, isLoading: false }),
}))
vi.mock('@/contexts/EventContext', () => ({
usePermissions: () => ({
hasForSession: (sessionID: string) => permissionSessions.current.has(sessionID),
@@ -156,6 +163,8 @@ const fetchedDirectories = () => new Set(sessionsHookCalls.flatMap((call) => cal
describe('DesktopSessionTree', () => {
beforeEach(() => {
localStorage.clear()
useSidebarServerStore.setState({ serverId: LOCAL_OPENCODE_SERVER_ID })
listReposMock.mockReset()
listReposMock.mockResolvedValue([repoA, repoB, repoC])
getRepoSiblingsMock.mockReset()
@@ -1,11 +1,15 @@
import { useMemo, useState } from 'react'
import { useMemo, useState, type ReactNode } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import { Search } from 'lucide-react'
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
import type { Repo, Session } from '@/api/types'
import { Input } from '@/components/ui/input'
import { RepoActivityIndicator } from '@/components/activity/RepoActivityIndicator'
import { useNavigableRepos, useSidebarRepoGroups } from '@/hooks/useSidebarRepoGroups'
import { useSessionSearch } from '@/hooks/useSessionSearch'
import { useSessionPins } from '@/hooks/useSessionPins'
import { useSidebarServerSelection } from '@/hooks/useSidebarServerSelection'
import { RemoteProjectNavList } from '@/components/navigation/RemoteProjectNav'
import {
NewSessionButton,
RepoNavGroup,
@@ -21,7 +25,7 @@ import {
isCurrentSessionItem,
isRepoReady,
} from '@/components/navigation/sidebar-session-tree'
import { getRepoPath } from '@/lib/navigation'
import { getRepoPath, getSessionPath } from '@/lib/navigation'
import { getRepoDisplayName } from '@/lib/utils'
import { buildPinnedSessionKeys } from '@/lib/sessionKey'
@@ -52,6 +56,28 @@ function SessionSearchInput({ value, onChange }: { value: string; onChange: (val
)
}
function SessionTreeLayout({
draft,
onDraftChange,
children,
}: {
draft: string
onDraftChange: (value: string) => void
children: ReactNode
}) {
return (
<div className="flex min-h-0 flex-1 flex-col">
<div className="px-2 pb-2">
<SessionSearchInput value={draft} onChange={onDraftChange} />
</div>
<div role="region" aria-label="Session navigator" className="min-h-0 flex-1 overflow-y-auto pb-2">
{children}
</div>
</div>
)
}
interface SessionSearchResultsProps {
nameMatchedRepos: Repo[]
otherRepos: Repo[]
@@ -90,14 +116,21 @@ function SessionSearchResults({
{matchingGroups.map((group) => (
<RepoNavGroup
key={group.repo.id}
repo={group.repo}
name={group.label}
branch={group.branchLabel}
isWorktree={group.repo.isWorktree}
isOpen
isCurrent={group.repo.id === getActiveRepoId(location.pathname)}
onOpenRepo={() => navigate(getRepoPath(group.repo.id))}
actions={<NewSessionButton repo={group.repo} onOpenSession={navigate} />}
indicator={<RepoActivityIndicator repo={group.repo} />}
actions={
<NewSessionButton
directory={group.repo.fullPath}
label={group.label}
sessionPath={(sessionId) => getSessionPath(group.repo.id, sessionId)}
onOpenSession={navigate}
/>
}
>
{group.items.map((item) => (
<SessionNavRow
@@ -113,7 +146,7 @@ function SessionSearchResults({
)
}
export function DesktopSessionTree() {
function LocalSessionTree() {
const navigate = useNavigate()
const location = useLocation()
const { repos, isLoading } = useNavigableRepos()
@@ -147,33 +180,65 @@ export function DesktopSessionTree() {
}
return (
<div className="flex min-h-0 flex-1 flex-col">
<div className="px-2 pb-2">
<SessionSearchInput value={draft} onChange={handleSearchChange} />
</div>
<div role="region" aria-label="Session navigator" className="min-h-0 flex-1 overflow-y-auto pb-2">
{isLoading ? (
<SessionNavStatus>Loading repos...</SessionNavStatus>
) : trimmedDraft ? (
<SessionSearchResults
nameMatchedRepos={nameMatchedRepos}
otherRepos={otherRepos}
sessions={filteredSessions}
isSearchLoading={isSearchLoading}
isSearchError={isSearchError}
/>
) : (
<RepoSessionNavList
repos={repos}
activeRepoId={getActiveRepoId(location.pathname)}
isVisible
onOpenRepo={(repoId) => navigate(getRepoPath(repoId))}
onSelectSession={navigate}
renderActions={(repo) => <NewSessionButton repo={repo} onOpenSession={navigate} />}
/>
)}
</div>
</div>
<SessionTreeLayout draft={draft} onDraftChange={handleSearchChange}>
{isLoading ? (
<SessionNavStatus>Loading repos...</SessionNavStatus>
) : trimmedDraft ? (
<SessionSearchResults
nameMatchedRepos={nameMatchedRepos}
otherRepos={otherRepos}
sessions={filteredSessions}
isSearchLoading={isSearchLoading}
isSearchError={isSearchError}
/>
) : (
<RepoSessionNavList
repos={repos}
activeRepoId={getActiveRepoId(location.pathname)}
isVisible
onOpenRepo={(repoId) => navigate(getRepoPath(repoId))}
onSelectSession={navigate}
renderActions={(repo) => (
<NewSessionButton
directory={repo.fullPath}
label={getRepoDisplayName(repo)}
sessionPath={(sessionId) => getSessionPath(repo.id, sessionId)}
onOpenSession={navigate}
/>
)}
/>
)}
</SessionTreeLayout>
)
}
function RemoteSessionTree({ serverId }: { serverId: string }) {
const navigate = useNavigate()
const [draft, setDraft] = useState('')
return (
<SessionTreeLayout draft={draft} onDraftChange={setDraft}>
<RemoteProjectNavList
serverId={serverId}
isVisible
search={draft}
onOpenProject={navigate}
onSelectSession={navigate}
/>
</SessionTreeLayout>
)
}
/**
* The sidebar session navigator. Follows the selected server: local repos for this machine, or the
* selected linked server's projects with the same rows and search behaviour.
*/
export function DesktopSessionTree() {
const [selectedServerId] = useSidebarServerSelection()
if (selectedServerId !== LOCAL_OPENCODE_SERVER_ID) {
return <RemoteSessionTree serverId={selectedServerId} />
}
return <LocalSessionTree />
}
@@ -6,6 +6,9 @@ import { useSidebarWidth } from '@/hooks/useSidebarWidth'
import { useAuth } from '@/hooks/useAuth'
import { useUrlParams } from '@/hooks/useUrlParams'
import { useOpenNavItem } from '@/hooks/useOpenNavItem'
import { useOpenCodeServers } from '@/hooks/useOpenCodeServers'
import { useSidebarServerSelection } from '@/hooks/useSidebarServerSelection'
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
import { buildNavModel, type MoreDrawerItem, type NavPrimaryCta } from '@/components/navigation/moreDrawerItems'
import { RepoQuickSwitchSheet } from '@/components/navigation/RepoQuickSwitchSheet'
import { DesktopSessionTree } from '@/components/navigation/DesktopSessionTree'
@@ -28,6 +31,12 @@ export function DesktopSidebar() {
const [sidebarWidth, setSidebarWidth] = useSidebarWidth()
const [repoSwitcherOpen, setRepoSwitcherOpen] = useState(false)
const { isAuthenticated, isLoading, logout } = useAuth()
const [selectedServerId] = useSidebarServerSelection()
const { servers } = useOpenCodeServers()
const selectedServerName =
selectedServerId === LOCAL_OPENCODE_SERVER_ID
? null
: servers.find((server) => server.id === selectedServerId)?.name ?? null
const isDesktop = useDesktop()
@@ -109,7 +118,9 @@ export function DesktopSidebar() {
<LinkedServersNav />
<section aria-label="Sessions" className="flex min-h-0 flex-1 flex-col border-t border-border">
<h2 className="px-3 py-1.5 text-xs font-medium uppercase tracking-wider text-muted-foreground">Sessions</h2>
<h2 className="px-3 py-1.5 text-xs font-medium uppercase tracking-wider text-muted-foreground">
Sessions{selectedServerName ? ` · ${selectedServerName}` : ''}
</h2>
<DesktopSessionTree />
</section>
@@ -1,12 +1,15 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { MemoryRouter } from 'react-router-dom'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { MemoryRouter, useLocation } from 'react-router-dom'
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
import { LinkedServersNav } from './LinkedServersNav'
import { useSidebarServerStore } from '@/stores/sidebarServerStore'
const mocks = vi.hoisted(() => ({
useOpenCodeServers: vi.fn(),
useOpenCodeServerStatuses: vi.fn(),
useServerActivityState: vi.fn(),
useLocalActivityState: vi.fn(),
}))
vi.mock('@/hooks/useOpenCodeServers', () => ({
@@ -16,6 +19,7 @@ vi.mock('@/hooks/useOpenCodeServers', () => ({
vi.mock('@/hooks/useActiveWork', () => ({
useServerActivityState: mocks.useServerActivityState,
useLocalActivityState: mocks.useLocalActivityState,
}))
const kitchen = {
@@ -31,10 +35,16 @@ const kitchen = {
const office = { ...kitchen, id: 'srv_office', name: 'Office' }
function LocationDisplay() {
const location = useLocation()
return <div data-testid="location">{location.pathname}</div>
}
function renderNav(pathname = '/') {
return render(
<MemoryRouter initialEntries={[pathname]}>
<LinkedServersNav />
<LocationDisplay />
</MemoryRouter>,
)
}
@@ -43,6 +53,7 @@ function renderRail(pathname = '/') {
return render(
<MemoryRouter initialEntries={[pathname]}>
<LinkedServersNav variant="rail" />
<LocationDisplay />
</MemoryRouter>,
)
}
@@ -50,8 +61,11 @@ function renderRail(pathname = '/') {
describe('LinkedServersNav', () => {
beforeEach(() => {
vi.clearAllMocks()
localStorage.clear()
useSidebarServerStore.setState({ serverId: LOCAL_OPENCODE_SERVER_ID })
mocks.useOpenCodeServers.mockReturnValue({ servers: [], isLoading: false })
mocks.useServerActivityState.mockReturnValue(null)
mocks.useLocalActivityState.mockReturnValue(null)
mocks.useOpenCodeServerStatuses.mockReturnValue({
statuses: [],
statusById: { srv_kitchen: { serverId: 'srv_kitchen', connected: true, version: null, error: null } },
@@ -60,20 +74,21 @@ describe('LinkedServersNav', () => {
})
it('renders nothing when no linked servers exist', () => {
const { container } = renderNav()
renderNav()
expect(container).toBeEmptyDOMElement()
expect(screen.queryByText('Servers')).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: /Local/ })).not.toBeInTheDocument()
})
it('lists enabled servers with a link and connection dot', () => {
it('lists the local machine and enabled servers as toggle buttons with connection dots', () => {
mocks.useOpenCodeServers.mockReturnValue({ servers: [kitchen, office], isLoading: false })
renderNav()
expect(screen.getByText('Servers')).toBeInTheDocument()
expect(screen.getByRole('link', { name: /Kitchen/ })).toHaveAttribute('href', '/servers/srv_kitchen')
expect(screen.getByRole('link', { name: /Office/ })).toHaveAttribute('href', '/servers/srv_office')
expect(screen.getByRole('button', { name: /Local/ })).toHaveAttribute('aria-pressed', 'true')
expect(screen.getByRole('button', { name: /Kitchen/ })).toHaveAttribute('aria-pressed', 'false')
expect(screen.getByRole('button', { name: /Office/ })).toHaveAttribute('aria-pressed', 'false')
expect(screen.getByRole('img', { name: 'Connected' })).toBeInTheDocument()
expect(screen.getByRole('img', { name: 'Disconnected' })).toBeInTheDocument()
})
@@ -86,42 +101,93 @@ describe('LinkedServersNav', () => {
renderNav()
expect(screen.getByRole('link', { name: /Kitchen/ })).toBeInTheDocument()
expect(screen.queryByRole('link', { name: /Office/ })).not.toBeInTheDocument()
expect(screen.getByRole('button', { name: /Kitchen/ })).toBeInTheDocument()
expect(screen.queryByRole('button', { name: /Office/ })).not.toBeInTheDocument()
})
it('renders enabled servers as icon links in the collapsed rail', () => {
it('selects a server without navigating', () => {
mocks.useOpenCodeServers.mockReturnValue({ servers: [kitchen, office], isLoading: false })
renderNav()
fireEvent.click(screen.getByRole('button', { name: /Office/ }))
expect(screen.getByRole('button', { name: /Office/ })).toHaveAttribute('aria-pressed', 'true')
expect(screen.getByRole('button', { name: /Office/ })).toHaveAttribute('aria-current', 'true')
expect(screen.getByRole('button', { name: /Kitchen/ })).toHaveAttribute('aria-pressed', 'false')
expect(screen.getByRole('button', { name: /Local/ })).toHaveAttribute('aria-pressed', 'false')
expect(screen.getByTestId('location')).toHaveTextContent('/')
})
it('selects the local machine without navigating', () => {
useSidebarServerStore.setState({ serverId: 'srv_kitchen' })
mocks.useOpenCodeServers.mockReturnValue({ servers: [kitchen], isLoading: false })
renderNav()
fireEvent.click(screen.getByRole('button', { name: /Local/ }))
expect(screen.getByRole('button', { name: /Local/ })).toHaveAttribute('aria-pressed', 'true')
expect(screen.getByTestId('location')).toHaveTextContent('/')
})
it('follows a linked server route', async () => {
mocks.useOpenCodeServers.mockReturnValue({ servers: [kitchen], isLoading: false })
renderNav('/servers/srv_kitchen/sessions/abc')
await waitFor(() =>
expect(screen.getByRole('button', { name: /Kitchen/ })).toHaveAttribute('aria-pressed', 'true'),
)
expect(screen.getByRole('button', { name: /Local/ })).toHaveAttribute('aria-pressed', 'false')
})
it('falls back to local when the persisted server is disabled', async () => {
useSidebarServerStore.setState({ serverId: 'srv_office' })
mocks.useOpenCodeServers.mockReturnValue({
servers: [kitchen, { ...office, enabled: false }],
isLoading: false,
})
renderNav()
await waitFor(() =>
expect(screen.getByRole('button', { name: /Local/ })).toHaveAttribute('aria-pressed', 'true'),
)
})
it('renders the local machine and enabled servers as icon toggles in the collapsed rail', () => {
mocks.useOpenCodeServers.mockReturnValue({ servers: [kitchen], isLoading: false })
renderRail('/servers/srv_kitchen/sessions/abc')
expect(screen.getByRole('link', { name: 'Kitchen' })).toHaveAttribute(
'aria-current',
'page',
)
expect(screen.getByRole('button', { name: 'Local' })).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Kitchen' })).toHaveAttribute('aria-pressed', 'true')
expect(screen.queryByText('Servers')).not.toBeInTheDocument()
})
it('renders nothing in the collapsed rail when no linked servers exist', () => {
const { container } = renderRail()
renderRail()
expect(container).toBeEmptyDOMElement()
expect(screen.queryByRole('button', { name: 'Local' })).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Kitchen' })).not.toBeInTheDocument()
})
it('hands navigation to the caller in the sheet variant', () => {
it('switches the selected server in the sheet variant without navigating', () => {
mocks.useOpenCodeServers.mockReturnValue({ servers: [kitchen], isLoading: false })
const onNavigate = vi.fn()
render(
<MemoryRouter>
<LinkedServersNav variant="sheet" onNavigate={onNavigate} />
<MemoryRouter initialEntries={['/']}>
<LinkedServersNav variant="sheet" />
<LocationDisplay />
</MemoryRouter>,
)
expect(screen.getByRole('heading', { name: 'Servers' })).toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: /Kitchen/ }))
expect(onNavigate).toHaveBeenCalledWith('/servers/srv_kitchen')
expect(screen.getByRole('button', { name: /Kitchen/ })).toHaveAttribute('aria-pressed', 'true')
expect(screen.getByTestId('location')).toHaveTextContent('/')
})
it('shows the activity indicator only for the server with an active session', () => {
@@ -139,6 +205,15 @@ describe('LinkedServersNav', () => {
expect(screen.getByRole('img', { name: 'Connected' })).toBeInTheDocument()
})
it('shows local activity on the local row', () => {
mocks.useOpenCodeServers.mockReturnValue({ servers: [kitchen], isLoading: false })
mocks.useLocalActivityState.mockReturnValue('running')
renderNav()
expect(screen.getByRole('img', { name: 'Sessions running' })).toBeInTheDocument()
})
it('shows the running indicator in the sheet variant', () => {
mocks.useOpenCodeServers.mockReturnValue({ servers: [kitchen], isLoading: false })
mocks.useServerActivityState.mockReturnValue('running')
@@ -1,11 +1,10 @@
import { Link, useLocation } from 'react-router-dom'
import { Server } from 'lucide-react'
import type { OpenCodeServer } from '@opencode-manager/shared/schemas'
import { Laptop, Server } from 'lucide-react'
import { LOCAL_OPENCODE_SERVER_ID, type OpenCodeServer } from '@opencode-manager/shared/schemas'
import { useOpenCodeServers, useOpenCodeServerStatuses } from '@/hooks/useOpenCodeServers'
import { useServerActivityState } from '@/hooks/useActiveWork'
import { useLocalActivityState, useServerActivityState } from '@/hooks/useActiveWork'
import { useSidebarServerSelection } from '@/hooks/useSidebarServerSelection'
import { ActivityStateIndicator } from '@/components/activity/ActivityStateIndicator'
import { SidebarSection } from '@/components/ui/sidebar'
import { getServerPath } from '@/lib/navigation'
import { cn } from '@/lib/utils'
export type LinkedServersVariant = 'sidebar' | 'rail' | 'sheet'
@@ -13,12 +12,6 @@ export type LinkedServersVariant = 'sidebar' | 'rail' | 'sheet'
interface LinkedServersNavProps {
/** `sidebar` renders the labelled section, `rail` the collapsed icon column, `sheet` the mobile sheet group. */
variant?: LinkedServersVariant
/** When provided, each row is a button that hands navigation to the caller instead of rendering a link. */
onNavigate?: (path: string) => void
}
function isActiveServerPath(pathname: string, path: string) {
return pathname === path || pathname.startsWith(`${path}/`)
}
function ServerConnectionDot({ connected }: { connected: boolean }) {
@@ -34,57 +27,84 @@ function ServerConnectionDot({ connected }: { connected: boolean }) {
)
}
interface LinkedServerRowProps {
server: OpenCodeServer
variant: 'sidebar' | 'sheet'
path: string
active: boolean
connected: boolean
onNavigate?: (path: string) => void
}
function LinkedServerRow({ server, variant, path, active, connected, onNavigate }: LinkedServerRowProps) {
const activity = useServerActivityState(server.id)
const className = cn(
function rowClassName(active: boolean, variant: 'sidebar' | 'sheet') {
return cn(
'flex items-center gap-3 rounded-md p-2.5 text-sm transition-colors duration-150',
'focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background',
active ? 'bg-accent text-accent-foreground' : 'text-foreground hover:bg-accent/50',
variant === 'sheet' && 'mx-2 p-2 text-left',
)
const content = (
<>
}
function railClassName(active: boolean) {
return cn(
'flex items-center justify-center rounded-md p-2.5 transition-colors duration-150',
'focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background',
active ? 'bg-accent text-accent-foreground' : 'text-foreground hover:bg-accent/50',
)
}
interface LocalServerRowProps {
variant: 'sidebar' | 'sheet'
active: boolean
onSelect: () => void
}
function LocalServerRow({ variant, active, onSelect }: LocalServerRowProps) {
const activity = useLocalActivityState()
return (
<button
type="button"
onClick={onSelect}
aria-pressed={active}
aria-current={active ? 'true' : undefined}
className={rowClassName(active, variant)}
>
<Laptop className="h-5 w-5 shrink-0" />
<span className="min-w-0 flex-1 truncate">Local</span>
<ActivityStateIndicator state={activity} />
</button>
)
}
interface LinkedServerRowProps {
server: OpenCodeServer
variant: 'sidebar' | 'sheet'
active: boolean
connected: boolean
onSelect: () => void
}
function LinkedServerRow({ server, variant, active, connected, onSelect }: LinkedServerRowProps) {
const activity = useServerActivityState(server.id)
return (
<button
type="button"
onClick={onSelect}
aria-pressed={active}
aria-current={active ? 'true' : undefined}
className={rowClassName(active, variant)}
>
<Server className="h-5 w-5 shrink-0" />
<span className="min-w-0 flex-1 truncate">{server.name}</span>
<ActivityStateIndicator state={activity} />
<ServerConnectionDot connected={connected} />
</>
)
if (onNavigate) {
return (
<button
type="button"
onClick={() => onNavigate(path)}
aria-current={active ? 'page' : undefined}
className={className}
>
{content}
</button>
)
}
return (
<Link to={path} className={className}>
{content}
</Link>
</button>
)
}
export function LinkedServersNav({ variant = 'sidebar', onNavigate }: LinkedServersNavProps) {
const location = useLocation()
/**
* The server switcher. Selecting a row changes which server's projects and sessions the sidebar
* lists; it never navigates. Hidden when no linked server is enabled.
*/
export function LinkedServersNav({ variant = 'sidebar' }: LinkedServersNavProps) {
const { servers, isLoading } = useOpenCodeServers()
const { statusById } = useOpenCodeServerStatuses()
const [selectedServerId, selectServer] = useSidebarServerSelection()
const enabledServers = servers.filter((server) => server.enabled)
const localActive = selectedServerId === LOCAL_OPENCODE_SERVER_ID
if (isLoading || enabledServers.length === 0) {
return null
@@ -93,46 +113,57 @@ export function LinkedServersNav({ variant = 'sidebar', onNavigate }: LinkedServ
if (variant === 'rail') {
return (
<div className="flex flex-col gap-1 px-2">
<button
type="button"
onClick={() => selectServer(LOCAL_OPENCODE_SERVER_ID)}
title="Local"
aria-pressed={localActive}
aria-current={localActive ? 'true' : undefined}
className={railClassName(localActive)}
>
<Laptop className="h-5 w-5 shrink-0" />
<span className="sr-only">Local</span>
</button>
{enabledServers.map((server) => {
const path = getServerPath(server.id)
const active = isActiveServerPath(location.pathname, path)
const active = selectedServerId === server.id
return (
<Link
<button
key={server.id}
to={path}
type="button"
onClick={() => selectServer(server.id)}
title={server.name}
aria-current={active ? 'page' : undefined}
className={cn(
'flex items-center justify-center rounded-md p-2.5 transition-colors duration-150',
'focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background',
active ? 'bg-accent text-accent-foreground' : 'text-foreground hover:bg-accent/50',
)}
aria-pressed={active}
aria-current={active ? 'true' : undefined}
className={railClassName(active)}
>
<Server className="h-5 w-5 shrink-0" />
<span className="sr-only">{server.name}</span>
</Link>
</button>
)
})}
</div>
)
}
const rows = enabledServers.map((server) => {
const path = getServerPath(server.id)
return (
const rows = [
<LocalServerRow
key={LOCAL_OPENCODE_SERVER_ID}
variant={variant}
active={localActive}
onSelect={() => selectServer(LOCAL_OPENCODE_SERVER_ID)}
/>,
...enabledServers.map((server) => (
<LinkedServerRow
key={server.id}
server={server}
variant={variant}
path={path}
active={isActiveServerPath(location.pathname, path)}
active={selectedServerId === server.id}
connected={statusById[server.id]?.connected ?? false}
onNavigate={onNavigate}
onSelect={() => selectServer(server.id)}
/>
)
})
)),
]
if (variant === 'sheet') {
return (
@@ -0,0 +1,310 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import { MemoryRouter, Route, Routes, useLocation, useNavigate } from 'react-router-dom'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import type { OpenCodeProject } from '@/api/opencode'
import { RemoteProjectNavList } from './RemoteProjectNav'
type SessionFixture = {
id: string
projectID: string
title: string
time: { created: number; updated: number; archived?: number }
location: { directory: string }
cost: number
tokens: { input: number; output: number; reasoning: number; cache: { read: number; write: number } }
}
const mocks = vi.hoisted(() => ({
listProjects: vi.fn(),
useOpenCodeServers: vi.fn(),
useOpenCodeServerStatuses: vi.fn(),
useSessionsAcrossDirectories: vi.fn(),
useCreateSession: vi.fn(),
sessionsCalls: [] as Array<{ directories: string[]; options?: { serverId?: string } }>,
createCalls: [] as Array<{ directory?: string; serverId?: string }>,
sessions: [] as SessionFixture[],
hasNextPage: { current: false },
}))
vi.mock('@/api/opencode', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/api/opencode')>()
return { ...actual, listProjects: mocks.listProjects }
})
vi.mock('@/hooks/useOpenCodeServers', () => ({
useOpenCodeServers: mocks.useOpenCodeServers,
useOpenCodeServerStatuses: mocks.useOpenCodeServerStatuses,
}))
vi.mock('@/hooks/useOpenCode', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/hooks/useOpenCode')>()
return {
...actual,
useSessionsAcrossDirectories: (
directories: string[],
options?: { serverId?: string },
) => {
mocks.sessionsCalls.push({ directories, options })
return {
data: mocks.sessions.filter((session) => directories.includes(session.location.directory)),
isLoading: false,
isError: false,
hasNextPage: mocks.hasNextPage.current,
}
},
useCreateSession: (
directory: string,
onSuccess?: (session: { id: string }) => void,
serverId?: string,
) => ({
mutate: () => {
mocks.createCalls.push({ directory, serverId })
onSuccess?.({ id: 'new-session' })
},
isPending: false,
}),
}
})
vi.mock('@/hooks/useActiveWork', () => ({
useProjectActivityState: () => null,
}))
vi.mock('@/contexts/EventContext', () => ({
usePermissions: () => ({ hasForSession: () => false }),
useForms: () => ({ hasForSession: () => false }),
}))
const kitchen = {
id: 'srv_kitchen',
name: 'Kitchen',
baseUrl: 'https://kitchen.example.com',
username: 'opencode',
enabled: true,
hasPassword: true,
createdAt: 1,
updatedAt: 2,
}
function createProject(id: string, name: string | undefined, canonical: string): OpenCodeProject {
return {
id,
canonical,
name,
time: { created: 1, updated: 2 },
sandboxes: [],
} as OpenCodeProject
}
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 alpha = createProject('p1', 'Alpha', '/projects/alpha')
const beta = createProject('p2', undefined, '/projects/beta')
function LocationSpy() {
const { pathname, search } = useLocation()
return <div data-testid="location">{`${pathname}${search}`}</div>
}
function createWrapper(initialEntry: string) {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
})
return ({ children }: { children: React.ReactNode }) => (
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={[initialEntry]}>
<Routes>
<Route
path="*"
element={
<>
{children}
<LocationSpy />
</>
}
/>
</Routes>
</MemoryRouter>
</QueryClientProvider>
)
}
const toggleFor = (name: string) => screen.getByRole('button', { name: `Show sessions in ${name}` })
function RemoteListHarness({ serverId }: { serverId: string }) {
const navigate = useNavigate()
return (
<RemoteProjectNavList
serverId={serverId}
isVisible
onOpenProject={navigate}
onSelectSession={navigate}
/>
)
}
describe('RemoteProjectNavList', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.sessionsCalls.splice(0, mocks.sessionsCalls.length)
mocks.createCalls.splice(0, mocks.createCalls.length)
mocks.sessions = [createSession('a1', '/projects/alpha', Date.now())]
mocks.hasNextPage.current = false
mocks.listProjects.mockResolvedValue([alpha, beta])
mocks.useOpenCodeServers.mockReturnValue({ servers: [kitchen], isLoading: false })
mocks.useOpenCodeServerStatuses.mockReturnValue({
statuses: [],
statusById: { srv_kitchen: { serverId: 'srv_kitchen', connected: true, version: null, error: null } },
isLoading: false,
})
})
it('renders project names with their directory and activity indicator slot', async () => {
render(
<RemoteProjectNavList
serverId="srv_kitchen"
isVisible
onOpenProject={vi.fn()}
onSelectSession={vi.fn()}
/>,
{ wrapper: createWrapper('/') },
)
expect(await screen.findByText('Alpha')).toBeInTheDocument()
expect(screen.getByText('beta')).toBeInTheDocument()
expect(screen.getByText('/projects/alpha')).toBeInTheDocument()
expect(mocks.listProjects).toHaveBeenCalledWith('srv_kitchen')
})
it('expands the project of the current project route and loads its sessions', async () => {
render(<RemoteListHarness serverId="srv_kitchen" />, {
wrapper: createWrapper('/servers/srv_kitchen/projects?directory=%2Fprojects%2Falpha'),
})
await waitFor(() => expect(toggleFor('Alpha')).toHaveAttribute('aria-expanded', 'true'))
expect(await screen.findByRole('button', { name: /Session a1/ })).toBeInTheDocument()
expect(mocks.sessionsCalls.some((call) => call.directories.includes('/projects/alpha'))).toBe(true)
expect(mocks.sessionsCalls[0]?.options?.serverId).toBe('srv_kitchen')
fireEvent.click(screen.getByRole('button', { name: /Session a1/ }))
expect(screen.getByTestId('location')).toHaveTextContent('/servers/srv_kitchen/sessions/a1')
})
it('opens a project when its name is clicked', async () => {
render(<RemoteListHarness serverId="srv_kitchen" />, { wrapper: createWrapper('/') })
fireEvent.click(await screen.findByRole('button', { name: /^Alpha/ }))
expect(screen.getByTestId('location')).toHaveTextContent(
'/servers/srv_kitchen/projects?directory=%2Fprojects%2Falpha',
)
})
it('expands another project and shows its sessions', async () => {
mocks.sessions = [
createSession('a1', '/projects/alpha', Date.now()),
createSession('b1', '/projects/beta', Date.now() - 1000),
]
render(<RemoteListHarness serverId="srv_kitchen" />, { wrapper: createWrapper('/') })
await screen.findByText('beta')
fireEvent.click(toggleFor('beta'))
expect(await screen.findByRole('button', { name: /Session b1/ })).toBeInTheDocument()
expect(toggleFor('beta')).toHaveAttribute('aria-expanded', 'true')
})
it('creates a session on the selected server and opens it', async () => {
render(<RemoteListHarness serverId="srv_kitchen" />, { wrapper: createWrapper('/') })
fireEvent.click(await screen.findByRole('button', { name: 'New session in beta' }))
expect(mocks.createCalls).toContainEqual({ directory: '/projects/beta', serverId: 'srv_kitchen' })
expect(screen.getByTestId('location')).toHaveTextContent(
'/servers/srv_kitchen/sessions/new-session',
)
})
it('offers All sessions when the project has another page', async () => {
mocks.hasNextPage.current = true
render(<RemoteListHarness serverId="srv_kitchen" />, {
wrapper: createWrapper('/servers/srv_kitchen/projects?directory=%2Fprojects%2Falpha'),
})
fireEvent.click(await screen.findByText('All sessions'))
expect(screen.getByTestId('location')).toHaveTextContent(
'/servers/srv_kitchen/projects?directory=%2Fprojects%2Falpha',
)
})
it('shows a disabled state for a disabled server', () => {
mocks.useOpenCodeServers.mockReturnValue({
servers: [{ ...kitchen, enabled: false }],
isLoading: false,
})
render(
<RemoteProjectNavList
serverId="srv_kitchen"
isVisible
onOpenProject={vi.fn()}
onSelectSession={vi.fn()}
/>,
{ wrapper: createWrapper('/') },
)
expect(screen.getByText('Server is disabled')).toBeInTheDocument()
expect(mocks.listProjects).not.toHaveBeenCalled()
})
it('reports a failed project load', async () => {
mocks.listProjects.mockRejectedValue(new Error('offline'))
render(
<RemoteProjectNavList
serverId="srv_kitchen"
isVisible
onOpenProject={vi.fn()}
onSelectSession={vi.fn()}
/>,
{ wrapper: createWrapper('/') },
)
expect(await screen.findByText('Could not load projects')).toBeInTheDocument()
})
it('reports an unreachable server on a failed project load', async () => {
mocks.listProjects.mockRejectedValue(new Error('offline'))
mocks.useOpenCodeServerStatuses.mockReturnValue({
statuses: [],
statusById: { srv_kitchen: { serverId: 'srv_kitchen', connected: false, version: null, error: 'boom' } },
isLoading: false,
})
render(
<RemoteProjectNavList
serverId="srv_kitchen"
isVisible
onOpenProject={vi.fn()}
onSelectSession={vi.fn()}
/>,
{ wrapper: createWrapper('/') },
)
expect(await screen.findByText('Server unreachable')).toBeInTheDocument()
})
})
@@ -0,0 +1,435 @@
import { useEffect, useMemo, useState } from 'react'
import { useLocation } from 'react-router-dom'
import { useQuery } from '@tanstack/react-query'
import { listProjects, type OpenCodeProject } from '@/api/opencode'
import type { Session } from '@/api/types'
import { ActivityStateIndicator } from '@/components/activity/ActivityStateIndicator'
import { useSessionsAcrossDirectories, sessionQueryOptions } from '@/hooks/useOpenCode'
import { useOpenCodeServers, useOpenCodeServerStatuses } from '@/hooks/useOpenCodeServers'
import { useProjectActivityState } from '@/hooks/useActiveWork'
import { useSessionSearch } from '@/hooks/useSessionSearch'
import { serverScopedKey } from '@/lib/serverScope'
import {
getServerProjectPath,
getServerSessionPath,
parseServerProjectRoute,
parseServerSessionRoute,
} from '@/lib/navigation'
import { getDirectoryName } from '@/lib/utils'
import { getSessionKey } from '@/lib/sessionKey'
import {
NewSessionButton,
RepoNavGroup,
SessionNavLink,
SessionNavRow,
SessionNavStatus,
} from '@/components/navigation/RepoSessionNav'
import {
SIDEBAR_SESSIONS_PER_REPO,
isCurrentSessionItem,
normalizeDirectory,
type SidebarSessionItem,
} from '@/components/navigation/sidebar-session-tree'
function projectName(project: OpenCodeProject): string {
return project.name?.trim() || getDirectoryName(project.canonical)
}
function buildRemoteItem(session: Session, serverId: string, projectLabel: string): SidebarSessionItem {
return {
key: getSessionKey(session),
session,
repoId: 0,
serverId,
repoLabel: projectLabel,
branchLabel: null,
isWorktree: false,
isPinned: false,
path: getServerSessionPath(serverId, session.id),
}
}
function RemoteProjectActivityIndicator({ serverId, directory }: { serverId: string; directory: string }) {
const state = useProjectActivityState(serverId, directory)
return <ActivityStateIndicator state={state} />
}
function useActiveRemoteDirectory(serverId: string): string | null {
const { pathname, search } = useLocation()
const projectRoute = parseServerProjectRoute(pathname, search)
const sessionRoute = parseServerSessionRoute(pathname)
const sessionID = sessionRoute?.serverId === serverId ? sessionRoute.sessionId : undefined
const { data: session } = useQuery({
...sessionQueryOptions(sessionID, undefined, serverId),
enabled: Boolean(sessionID),
})
if (projectRoute?.serverId === serverId) return projectRoute.directory
return session?.location.directory ?? null
}
interface RemoteSessionRowsProps {
serverId: string
projectLabel: string
sessions: Session[]
isLoading: boolean
isError: boolean
hasMore?: boolean
allSessionsPath?: string
onSelectSession: (path: string) => void
}
function RemoteSessionRows({
serverId,
projectLabel,
sessions,
isLoading,
isError,
hasMore,
allSessionsPath,
onSelectSession,
}: RemoteSessionRowsProps) {
const location = useLocation()
const visibleSessions = useMemo(
() => sessions.filter((session) => !session.time.archived),
[sessions],
)
if (isLoading) return <SessionNavStatus>Loading sessions...</SessionNavStatus>
if (isError) return <SessionNavStatus>Failed to load sessions</SessionNavStatus>
if (visibleSessions.length === 0) return <SessionNavStatus>No sessions</SessionNavStatus>
return (
<>
{visibleSessions.map((session) => {
const item = buildRemoteItem(session, serverId, projectLabel)
return (
<SessionNavRow
key={item.key}
item={item}
isCurrent={isCurrentSessionItem(item, location.pathname)}
onSelect={onSelectSession}
/>
)
})}
{hasMore && allSessionsPath && (
<SessionNavLink onClick={() => onSelectSession(allSessionsPath)}>All sessions</SessionNavLink>
)}
</>
)
}
interface RemoteProjectSessionsProps {
serverId: string
project: OpenCodeProject
onSelectSession: (path: string) => void
}
function RemoteProjectSessions({ serverId, project, onSelectSession }: RemoteProjectSessionsProps) {
const { data, isLoading, isError, hasNextPage } = useSessionsAcrossDirectories([project.canonical], {
serverId,
limit: SIDEBAR_SESSIONS_PER_REPO,
})
return (
<RemoteSessionRows
serverId={serverId}
projectLabel={projectName(project)}
sessions={data}
isLoading={isLoading}
isError={isError}
hasMore={Boolean(hasNextPage)}
allSessionsPath={getServerProjectPath(serverId, project.canonical)}
onSelectSession={onSelectSession}
/>
)
}
interface RemoteProjectGroupProps {
serverId: string
project: OpenCodeProject
isOpen: boolean
isCurrent: boolean
onToggle?: () => void
onOpenProject: (path: string) => void
onSelectSession: (path: string) => void
children: React.ReactNode
}
function RemoteProjectGroup({
serverId,
project,
isOpen,
isCurrent,
onToggle,
onOpenProject,
onSelectSession,
children,
}: RemoteProjectGroupProps) {
const name = projectName(project)
return (
<RepoNavGroup
name={name}
branch={project.canonical}
isOpen={isOpen}
isCurrent={isCurrent}
onOpenRepo={() => onOpenProject(getServerProjectPath(serverId, project.canonical))}
onToggle={onToggle}
indicator={<RemoteProjectActivityIndicator serverId={serverId} directory={project.canonical} />}
actions={
<NewSessionButton
directory={project.canonical}
label={name}
serverId={serverId}
sessionPath={(sessionId) => getServerSessionPath(serverId, sessionId)}
onOpenSession={onSelectSession}
/>
}
>
{children}
</RepoNavGroup>
)
}
interface RemoteProjectGroupsProps {
serverId: string
projects: OpenCodeProject[]
activeDirectory: string | null
isVisible: boolean
onOpenProject: (path: string) => void
onSelectSession: (path: string) => void
}
function RemoteProjectGroups({
serverId,
projects,
activeDirectory,
isVisible,
onOpenProject,
onSelectSession,
}: RemoteProjectGroupsProps) {
const [expandedProjectId, setExpandedProjectId] = useState<string | null>(null)
const normalizedActiveDirectory = normalizeDirectory(activeDirectory)
useEffect(() => {
if (!isVisible || !normalizedActiveDirectory) return
const match = projects.find(
(project) => normalizeDirectory(project.canonical) === normalizedActiveDirectory,
)
if (match) setExpandedProjectId(match.id)
}, [isVisible, normalizedActiveDirectory, projects])
return (
<>
{projects.map((project) => {
const isExpanded = expandedProjectId === project.id
return (
<RemoteProjectGroup
key={project.id}
serverId={serverId}
project={project}
isOpen={isExpanded}
isCurrent={normalizeDirectory(project.canonical) === normalizedActiveDirectory}
onToggle={() =>
setExpandedProjectId((current) => (current === project.id ? null : project.id))
}
onOpenProject={onOpenProject}
onSelectSession={onSelectSession}
>
<RemoteProjectSessions
serverId={serverId}
project={project}
onSelectSession={onSelectSession}
/>
</RemoteProjectGroup>
)
})}
</>
)
}
interface RemoteProjectSearchResultsProps {
serverId: string
projects: OpenCodeProject[]
activeDirectory: string | null
search: string
onOpenProject: (path: string) => void
onSelectSession: (path: string) => void
}
function RemoteProjectSearchResults({
serverId,
projects,
activeDirectory,
search,
onOpenProject,
onSelectSession,
}: RemoteProjectSearchResultsProps) {
const directories = useMemo(() => projects.map((project) => project.canonical), [projects])
const {
setQuery,
filteredSessions,
isLoading,
isError,
} = useSessionSearch(directories, {
limit: SIDEBAR_SESSIONS_PER_REPO,
serverId,
initialQuery: search,
})
useEffect(() => {
setQuery(search)
}, [search, setQuery])
const needle = search.trim().toLowerCase()
const normalizedActiveDirectory = normalizeDirectory(activeDirectory)
const nameMatchedProjects = useMemo(
() =>
projects.filter(
(project) =>
projectName(project).toLowerCase().includes(needle) ||
project.canonical.toLowerCase().includes(needle),
),
[projects, needle],
)
const sessionsByProjectId = useMemo(() => {
const byDirectory = new Map<string, Session[]>()
for (const session of filteredSessions) {
const directory = normalizeDirectory(session.location.directory)
if (!directory) continue
const list = byDirectory.get(directory)
if (list) list.push(session)
else byDirectory.set(directory, [session])
}
const byProjectId = new Map<string, Session[]>()
for (const project of projects) {
const sessions = byDirectory.get(normalizeDirectory(project.canonical) ?? '')
if (sessions) byProjectId.set(project.id, sessions)
}
return byProjectId
}, [projects, filteredSessions])
const visibleProjects = useMemo(() => {
const nameMatchedIds = new Set(nameMatchedProjects.map((project) => project.id))
return projects.filter(
(project) => nameMatchedIds.has(project.id) || sessionsByProjectId.has(project.id),
)
}, [projects, nameMatchedProjects, sessionsByProjectId])
if (isLoading) return <SessionNavStatus>Loading sessions...</SessionNavStatus>
if (isError) return <SessionNavStatus>Failed to load sessions</SessionNavStatus>
if (visibleProjects.length === 0) return <SessionNavStatus>No sessions found</SessionNavStatus>
return (
<>
{visibleProjects.map((project) => {
const matchedSessions = sessionsByProjectId.get(project.id)
return (
<RemoteProjectGroup
key={project.id}
serverId={serverId}
project={project}
isOpen
isCurrent={normalizeDirectory(project.canonical) === normalizedActiveDirectory}
onOpenProject={onOpenProject}
onSelectSession={onSelectSession}
>
{matchedSessions ? (
<RemoteSessionRows
serverId={serverId}
projectLabel={projectName(project)}
sessions={matchedSessions}
isLoading={false}
isError={false}
onSelectSession={onSelectSession}
/>
) : (
<RemoteProjectSessions
serverId={serverId}
project={project}
onSelectSession={onSelectSession}
/>
)}
</RemoteProjectGroup>
)
})}
</>
)
}
interface RemoteProjectNavListProps {
serverId: string
isVisible: boolean
search?: string
onOpenProject: (path: string) => void
onSelectSession: (path: string) => void
}
/**
* The linked server's projects in the sidebar, styled like the local repo groups and expanded to
* the current project or session. Searching filters project names and that server's sessions.
*/
export function RemoteProjectNavList({
serverId,
isVisible,
search = '',
onOpenProject,
onSelectSession,
}: RemoteProjectNavListProps) {
const { servers, isLoading: isServersLoading } = useOpenCodeServers()
const { statusById } = useOpenCodeServerStatuses()
const server = servers.find((candidate) => candidate.id === serverId)
const activeDirectory = useActiveRemoteDirectory(serverId)
const projectsQuery = useQuery({
queryKey: serverScopedKey(['opencode', 'projects'], serverId),
queryFn: () => listProjects(serverId),
enabled: server?.enabled === true,
retry: false,
})
const projects = useMemo(() => projectsQuery.data ?? [], [projectsQuery.data])
const trimmedSearch = search.trim()
if (isServersLoading) return <SessionNavStatus>Loading projects...</SessionNavStatus>
if (!server) return <SessionNavStatus>Server not found</SessionNavStatus>
if (!server.enabled) return <SessionNavStatus>Server is disabled</SessionNavStatus>
if (projectsQuery.isLoading) return <SessionNavStatus>Loading projects...</SessionNavStatus>
if (projectsQuery.isError) {
return (
<SessionNavStatus>
{statusById[serverId]?.connected === false ? 'Server unreachable' : 'Could not load projects'}
</SessionNavStatus>
)
}
if (projects.length === 0) return <SessionNavStatus>No projects</SessionNavStatus>
if (trimmedSearch) {
return (
<RemoteProjectSearchResults
serverId={serverId}
projects={projects}
activeDirectory={activeDirectory}
search={trimmedSearch}
onOpenProject={onOpenProject}
onSelectSession={onSelectSession}
/>
)
}
return (
<RemoteProjectGroups
serverId={serverId}
projects={projects}
activeDirectory={activeDirectory}
isVisible={isVisible}
onOpenProject={onOpenProject}
onSelectSession={onSelectSession}
/>
)
}
@@ -4,8 +4,11 @@ import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { RepoQuickSwitchSheet } from './RepoQuickSwitchSheet'
import { getRepoSiblings, listRepos } from '@/api/repos'
import { listProjects, type OpenCodeProject } from '@/api/opencode'
import { useMobileTabBar } from '@/hooks/useMobileTabBar'
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
import { useSidebarServerStore } from '@/stores/sidebarServerStore'
import type { ActiveWorkItem } from '@/lib/activeWork'
type SessionFixture = {
@@ -53,10 +56,17 @@ vi.mock('@/hooks/useActiveWork', () => ({
useActivityWindowMinutes: activityMocks.useActivityWindowMinutes,
useRepoActivityState: () => null,
useServerActivityState: () => null,
useLocalActivityState: () => null,
useProjectActivityState: () => null,
}))
vi.mock('@/api/repos')
vi.mock('@/api/opencode', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/api/opencode')>()
return { ...actual, listProjects: vi.fn() }
})
vi.mock('@/contexts/EventContext', () => ({
usePermissions: () => ({
hasForSession: (id: string) => permissionSessions.current.has(id),
@@ -156,6 +166,16 @@ function createLinkedServer(id: string, name: string, enabled = true) {
}
}
function createProject(id: string, name: string, canonical: string): OpenCodeProject {
return {
id,
canonical,
name,
time: { created: 1, updated: 2 },
sandboxes: [],
} as OpenCodeProject
}
function setLinkedServers(servers: Array<ReturnType<typeof createLinkedServer>>) {
serverMocks.useOpenCodeServers.mockReturnValue({ servers, isLoading: false })
serverMocks.useOpenCodeServerStatuses.mockReturnValue({
@@ -205,7 +225,10 @@ function MobileSheetHarness() {
describe('RepoQuickSwitchSheet', () => {
beforeEach(() => {
vi.clearAllMocks()
localStorage.clear()
useSidebarServerStore.setState({ serverId: LOCAL_OPENCODE_SERVER_ID })
vi.mocked(getRepoSiblings).mockResolvedValue([])
vi.mocked(listProjects).mockResolvedValue([])
sessionsData.splice(0, sessionsData.length)
sessionsHookCalls.splice(0, sessionsHookCalls.length)
permissionSessions.current.clear()
@@ -994,8 +1017,9 @@ describe('RepoQuickSwitchSheet', () => {
expect(screen.queryByRole('heading', { name: 'Servers' })).toBeNull()
})
it('navigates to a linked server and closes the sheet', async () => {
it('switches to a linked server without navigating or closing the sheet', async () => {
vi.mocked(listRepos).mockResolvedValue([createRepo(1, 'repo1', '/path/to/repo1')])
vi.mocked(listProjects).mockResolvedValue([createProject('p1', 'Alpha', '/projects/alpha')])
setLinkedServers([createLinkedServer('srv_kitchen', 'Kitchen')])
const handleClose = vi.fn()
@@ -1019,7 +1043,43 @@ describe('RepoQuickSwitchSheet', () => {
fireEvent.click(await screen.findByRole('button', { name: /Kitchen/ }))
expect(screen.getByTestId('location')).toHaveTextContent('/servers/srv_kitchen')
expect(await screen.findByText('Alpha')).toBeInTheDocument()
expect(screen.queryByText('repo1')).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: /Add repository/ })).not.toBeInTheDocument()
expect(screen.getByTestId('location')).toHaveTextContent('/repos/1')
expect(handleClose).not.toHaveBeenCalled()
})
it('opens a remote project from the sheet and closes it', async () => {
vi.mocked(listRepos).mockResolvedValue([createRepo(1, 'repo1', '/path/to/repo1')])
vi.mocked(listProjects).mockResolvedValue([createProject('p1', 'Alpha', '/projects/alpha')])
setLinkedServers([createLinkedServer('srv_kitchen', 'Kitchen')])
const handleClose = vi.fn()
render(
<QueryClientProvider client={new QueryClient()}>
<MemoryRouter initialEntries={['/repos/1']}>
<Routes>
<Route
path="*"
element={
<>
<RepoQuickSwitchSheet isOpen onClose={handleClose} />
<LocationSpy />
</>
}
/>
</Routes>
</MemoryRouter>
</QueryClientProvider>,
)
fireEvent.click(await screen.findByRole('button', { name: /Kitchen/ }))
fireEvent.click(await screen.findByRole('button', { name: /^Alpha/ }))
expect(screen.getByTestId('location')).toHaveTextContent(
'/servers/srv_kitchen/projects?directory=%2Fprojects%2Falpha',
)
expect(handleClose).toHaveBeenCalled()
})
})
@@ -1,5 +1,6 @@
import { useState, useMemo } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
import { useRefreshOnOpen } from '@/hooks/useRefreshOnOpen'
import { Input } from '@/components/ui/input'
import { BottomSheet, BottomSheetHeader, BottomSheetContent } from '@/components/ui/bottom-sheet'
@@ -9,11 +10,13 @@ import { getRepoDisplayName } from '@/lib/utils'
import { AddRepoDialog } from '@/components/repo/AddRepoDialog'
import { FolderGit2, Plus } from 'lucide-react'
import { useUrlParams } from '@/hooks/useUrlParams'
import { getAssistantPath, getRepoPath } from '@/lib/navigation'
import { getAssistantPath, getRepoPath, getSessionPath } from '@/lib/navigation'
import { NewSessionButton, RepoSessionNavList, SearchClearButton } from '@/components/navigation/RepoSessionNav'
import { LinkedServersNav } from '@/components/navigation/LinkedServersNav'
import { RemoteProjectNavList } from '@/components/navigation/RemoteProjectNav'
import { getActiveRepoId } from '@/components/navigation/sidebar-session-tree'
import { useNavigableRepos } from '@/hooks/useSidebarRepoGroups'
import { useSidebarServerSelection } from '@/hooks/useSidebarServerSelection'
interface RepoQuickSwitchSheetProps {
isOpen: boolean
@@ -26,6 +29,8 @@ export function RepoQuickSwitchSheet({ isOpen, onClose }: RepoQuickSwitchSheetPr
const { searchParams } = useUrlParams()
const [searchQuery, setSearchQuery] = useState('')
const [addRepoOpen, setAddRepoOpen] = useState(false)
const [selectedServerId] = useSidebarServerSelection()
const isRemote = selectedServerId !== LOCAL_OPENCODE_SERVER_ID
const activeRepoId = getActiveRepoId(location.pathname)
const { repos, isLoading, refetch } = useNavigableRepos(isOpen)
@@ -81,32 +86,37 @@ export function RepoQuickSwitchSheet({ isOpen, onClose }: RepoQuickSwitchSheetPr
/>
{searchQuery.length > 0 && <SearchClearButton onClear={() => setSearchQuery('')} />}
</div>
<Button
type="button"
size="lg"
onClick={() => {
onClose()
setAddRepoOpen(true)
}}
className="flex-shrink-0"
>
<Plus className="h-4 w-4" />
<span className="hidden sm:inline">Repo</span>
<span className="sr-only">Add repository</span>
</Button>
{!isRemote && (
<Button
type="button"
size="lg"
onClick={() => {
onClose()
setAddRepoOpen(true)
}}
className="flex-shrink-0"
>
<Plus className="h-4 w-4" />
<span className="hidden sm:inline">Repo</span>
<span className="sr-only">Add repository</span>
</Button>
)}
</div>
</BottomSheetHeader>
<BottomSheetContent className="flex flex-col px-0 pt-0 gap-0">
{isOpen && (
<LinkedServersNav
variant="sheet"
onNavigate={(path) => navigateAndClose(path, { replace: true })}
/>
)}
{isOpen && <LinkedServersNav variant="sheet" />}
{isOpen && !searchQuery.trim() && (
<CompactActivityList onNavigate={(path) => navigateAndClose(path)} />
)}
{isLoading ? (
{isRemote ? (
<RemoteProjectNavList
serverId={selectedServerId}
isVisible={isOpen}
search={searchQuery}
onOpenProject={(path) => navigateAndClose(path, { replace: true })}
onSelectSession={(path) => navigateAndClose(path)}
/>
) : isLoading ? (
<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" />
@@ -124,7 +134,14 @@ export function RepoQuickSwitchSheet({ isOpen, onClose }: RepoQuickSwitchSheetPr
isVisible={isOpen}
onOpenRepo={handleClick}
onSelectSession={(path) => navigateAndClose(path)}
renderActions={(repo) => <NewSessionButton repo={repo} onOpenSession={(path) => navigateAndClose(path)} />}
renderActions={(repo) => (
<NewSessionButton
directory={repo.fullPath}
label={getRepoDisplayName(repo)}
sessionPath={(sessionId) => getSessionPath(repo.id, sessionId)}
onOpenSession={(path) => navigateAndClose(path)}
/>
)}
/>
)}
<div aria-hidden="true" className="h-16 shrink-0" />
@@ -9,7 +9,7 @@ import { useRepoSiblings } from '@/hooks/useRepoSiblings'
import { useSidebarRepoGroups } from '@/hooks/useSidebarRepoGroups'
import { buildWorktreeActivity, type ActiveWorktree } from '@/lib/activeWork'
import { cn, formatShortRelativeTime, getRepoBranchLabel, getRepoDisplayName } from '@/lib/utils'
import { getRepoPath, getSessionPath } from '@/lib/navigation'
import { getRepoPath } from '@/lib/navigation'
import {
isCurrentSessionItem,
isRepoReady,
@@ -26,7 +26,6 @@ function OpenRepoRail() {
}
interface RepoNavGroupProps {
repo: Repo
name: string
branch?: string | null
isWorktree?: boolean
@@ -34,12 +33,12 @@ interface RepoNavGroupProps {
isCurrent: boolean
onOpenRepo: () => void
onToggle?: () => void
indicator?: ReactNode
actions?: ReactNode
children?: ReactNode
}
export function RepoNavGroup({
repo,
name,
branch,
isWorktree,
@@ -47,6 +46,7 @@ export function RepoNavGroup({
isCurrent,
onOpenRepo,
onToggle,
indicator,
actions,
children,
}: RepoNavGroupProps) {
@@ -85,7 +85,7 @@ export function RepoNavGroup({
<span className="truncate text-[15px] font-bold tracking-tight text-highlight">
{name}
</span>
<RepoActivityIndicator repo={repo} />
{indicator}
</span>
{branch && (
<span
@@ -163,7 +163,7 @@ 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 }) {
export function SessionNavLink({ children, onClick }: { children: ReactNode; onClick: () => void }) {
return (
<button
type="button"
@@ -276,7 +276,6 @@ export function RepoSessionNavList({
return (
<RepoNavGroup
key={repo.id}
repo={repo}
name={getRepoDisplayName(repo)}
branch={getRepoBranchLabel(repo)}
isWorktree={repo.isWorktree}
@@ -284,6 +283,7 @@ export function RepoSessionNavList({
isCurrent={repo.id === activeRepoId}
onOpenRepo={() => onOpenRepo(repo.id)}
onToggle={() => setExpandedRepoId((current) => (current === repo.id ? null : repo.id))}
indicator={<RepoActivityIndicator repo={repo} />}
actions={ready ? renderActions?.(repo) : undefined}
>
{ready ? (
@@ -298,16 +298,28 @@ export function RepoSessionNavList({
)
}
export function NewSessionButton({
repo,
onOpenSession,
}: {
repo: Repo
interface NewSessionButtonProps {
directory: string
label: string
onOpenSession: (path: string) => void
}) {
const createSession = useCreateSession(repo.fullPath, (session) => {
onOpenSession(getSessionPath(repo.id, session.id))
})
sessionPath: (sessionId: string) => string
serverId?: string
}
export function NewSessionButton({
directory,
label,
onOpenSession,
sessionPath,
serverId,
}: NewSessionButtonProps) {
const createSession = useCreateSession(
directory,
(session) => {
onOpenSession(sessionPath(session.id))
},
serverId,
)
const isCreating = createSession.isPending
@@ -315,7 +327,7 @@ export function NewSessionButton({
<button
type="button"
title="New session"
aria-label={`New session in ${getRepoDisplayName(repo)}`}
aria-label={`New session in ${label}`}
aria-busy={isCreating}
disabled={isCreating}
onClick={() => createSession.mutate({ agent: undefined })}
@@ -225,7 +225,7 @@ export function ToolSidePanel({
onDone={closePanel}
/>
) : (
<RepoSkillsContent open repoId={repoId} onDone={closePanel} />
<RepoSkillsContent open repoId={repoId} directory={repoDirectory} onDone={closePanel} />
)
}
if (tool === 'sourceControl') {
@@ -75,6 +75,20 @@ describe('buildMoreItems', () => {
])
})
it('returns only the server tools a linked server can serve for /servers/:id/projects', () => {
const items = buildMoreItems('/servers/srv_kitchen/projects')
expect(items.map((item) => item.key)).toEqual([
'home',
'mcp',
'skills',
'source-control',
'terminal',
'settings',
'logout',
])
expect(items.find((item) => item.key === 'source-control')?.dialog).toBe('sourceControl')
})
it('omits the Actions item for an Assistant session', () => {
const items = buildMoreItems('/repos/0/sessions/abc')
expect(items).toHaveLength(12)
@@ -187,6 +201,16 @@ describe('buildToolItems', () => {
])
})
it('returns the linked-server project tools for the tool rail', () => {
expect(buildToolItems('/servers/srv_kitchen/projects').map((item) => item.key)).toEqual([
'activity',
'mcp',
'skills',
'source-control',
'terminal',
])
})
it('returns the home route tools', () => {
expect(buildToolItems('/').map((item) => item.key)).toEqual(['activity', 'all-schedules', 'files'])
})
@@ -49,6 +49,7 @@ function getBaseItems(): MoreDrawerItem[] {
const SESSION_DETAIL_PATH = /^\/repos\/(\d+)\/sessions\/[^/]+$/
const SERVER_SESSION_DETAIL_PATH = /^\/servers\/[^/]+\/sessions\/[^/]+$/
const SERVER_PROJECT_PATH = /^\/servers\/[^/]+\/projects$/
export function isSessionDetailPath(pathname: string): boolean {
return SESSION_DETAIL_PATH.test(pathname)
@@ -85,7 +86,7 @@ export function toolKeyOf(item: MoreDrawerItem): string | null {
function buildRouteNavModel(pathname: string): NavModel {
const baseItems = getBaseItems()
if (SERVER_SESSION_DETAIL_PATH.test(pathname)) {
if (SERVER_SESSION_DETAIL_PATH.test(pathname) || SERVER_PROJECT_PATH.test(pathname)) {
return {
primary: [getAssistantNavItem()],
items: [
@@ -2,7 +2,7 @@ import type { Repo, Session } from '@/api/types'
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
import { getRepoBranchLabel, getRepoDisplayName } from '@/lib/utils'
import { getSessionKey } from '@/lib/sessionKey'
import { getSessionPath, isAssistantPath, parseRepoRoute } from '@/lib/navigation'
import { getSessionPath, isAssistantPath, parseRepoRoute, parseServerSessionRoute } from '@/lib/navigation'
import { partitionSessions, selectRootSessions } from '@/components/session/session-partition'
import type { ActiveWorktree } from '@/lib/activeWork'
@@ -29,6 +29,8 @@ export interface SidebarSessionItem {
key: string
session: Session
repoId: number
/** The linked server owning the session; absent for local repo sessions. */
serverId?: string
repoLabel: string
branchLabel: string | null
/** Branch of the worktree the session runs in, when it runs in a worktree of the group's repo. */
@@ -46,6 +48,10 @@ export interface SidebarRepoGroup {
}
export function isCurrentSessionItem(item: SidebarSessionItem, pathname: string): boolean {
if (item.serverId) {
const selection = parseServerSessionRoute(pathname)
return selection?.serverId === item.serverId && item.session.id === selection.sessionId
}
const selection = parseRepoRoute(pathname)
return item.repoId === selection.repoId && item.session.id === selection.sessionId
}