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

+10
View File
@@ -7,6 +7,7 @@ import { Toaster } from 'sonner'
import { Repos } from './pages/Repos'
import { RepoDetail } from './pages/RepoDetail'
import { RemoteServer } from './pages/RemoteServer'
import { RemoteProject } from './pages/RemoteProject'
import { SessionDetail } from './pages/SessionDetail'
import { Schedules } from './pages/Schedules'
import { GlobalSchedules } from './pages/GlobalSchedules'
@@ -321,6 +322,15 @@ const router = createBrowserRouter([
),
loader: protectedLoader,
},
{
path: '/servers/:serverId/projects',
element: (
<ServerScope>
<RemoteProject />
</ServerScope>
),
loader: protectedLoader,
},
{
path: '/servers/:serverId/sessions/:sessionId',
element: (
@@ -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
}
@@ -28,12 +28,12 @@ function toRemoteSkillFileInfo(skill: SkillInfo): SkillFileInfo {
type RepoSkillsSessionProps =
| { sessionId: string; directory?: string; onSkillLoaded?: (skill: SkillFileInfo) => void }
| { sessionId?: undefined; directory?: undefined; onSkillLoaded?: undefined }
| { sessionId?: undefined; directory?: string; onSkillLoaded?: undefined }
type RepoSkillsDialogProps = {
open: boolean
onOpenChange: (open: boolean) => void
repoId: number
repoId?: number
} & RepoSkillsSessionProps
type RepoSkillsContentProps = {
@@ -150,7 +150,7 @@ export function RepoSkillsContent({
}
export function RepoSkillsDialog({ onOpenChange, ...props }: RepoSkillsDialogProps) {
if (!props.repoId && !props.sessionId) {
if (!props.repoId && !props.sessionId && !props.directory) {
return null
}
@@ -0,0 +1,36 @@
import type { LucideIcon } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'
interface LinkedServerStateCardProps {
icon: LucideIcon
title: string
description: string
actionLabel: string
onAction: () => void
}
/**
* Centered notice for a linked-server page that cannot render its content, such as a missing or
* disabled server or a route without its project directory.
*/
export function LinkedServerStateCard({
icon: Icon,
title,
description,
actionLabel,
onAction,
}: LinkedServerStateCardProps) {
return (
<Card className="flex flex-col items-center gap-3 p-6 text-center">
<Icon className="h-8 w-8 text-muted-foreground" />
<div>
<p className="font-medium">{title}</p>
<p className="text-sm text-muted-foreground">{description}</p>
</div>
<Button variant="outline" size="sm" onClick={onAction}>
{actionLabel}
</Button>
</Card>
)
}
+52
View File
@@ -20,6 +20,7 @@ import {
buildServerActivityIndex,
collectActiveRoots,
needsWorktreeLookup,
projectActivityFromIndex,
repoActivityFromIndex,
rootSessionID,
serverActivityFromIndex,
@@ -108,6 +109,57 @@ export function useServerActivityState(serverId: string): 'needs-input' | 'runni
)
}
/**
* Whether any local session is active, returned as a primitive so the local switcher row only
* re-renders when it changes. Reads only the session-status store and the pending queues.
*/
export function useLocalActivityState(): 'needs-input' | 'running' | null {
const pendingInputSessionIDs = usePendingInputSessionIDs()
return useSessionStatus((state) => {
const index = buildRepoActivityIndex({
statuses: state.statuses,
parents: state.parents,
runningShells: state.runningShells,
directories: state.directories,
pendingInputSessionIDs,
})
let running = false
for (const activity of index.values()) {
if (activity === 'needs-input') return 'needs-input'
running = true
}
return running ? 'running' : null
})
}
/**
* Whether a project on a linked server has any active session, returned as a primitive so rows
* only re-render when it changes.
*/
export function useProjectActivityState(
serverId: string,
directory: string,
): 'needs-input' | 'running' | null {
const pendingInputSessionIDs = usePendingInputSessionIDs()
return useSessionStatus((state) =>
projectActivityFromIndex(
serverId,
directory,
buildServerActivityIndex({
statuses: state.statuses,
parents: state.parents,
runningShells: state.runningShells,
directories: state.directories,
sessionServers: state.sessionServers,
pendingInputSessionIDs,
}),
),
)
}
interface SessionScope {
serverId: string
directory: string | undefined
+7 -1
View File
@@ -10,6 +10,10 @@ export interface UseSessionSearchOptions {
limit?: number
allDirectories?: boolean
project?: { id: string; subpath: string }
/** Searches a linked server instead of the route's server. */
serverId?: string
/** Seeds the search box, for callers that mount the hook after a query is already entered. */
initialQuery?: string
}
/**
@@ -20,7 +24,8 @@ export function useSessionSearch(directories: string[], options: UseSessionSearc
const limit = options.limit ?? DEFAULT_LIMIT
const allDirectories = options.allDirectories ?? false
const project = options.project
const [query, setQuery] = useState('')
const serverId = options.serverId
const [query, setQuery] = useState(options.initialQuery ?? '')
const trimmedQuery = query.trim()
const debouncedQuery = useDebouncedValue(trimmedQuery, 150)
const search = trimmedQuery ? debouncedQuery : ''
@@ -39,6 +44,7 @@ export function useSessionSearch(directories: string[], options: UseSessionSearc
keepPreviousResults: true,
allDirectories,
project,
serverId,
})
const directorySet = useMemo(() => new Set(directories), [directories])
@@ -0,0 +1,147 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import { MemoryRouter, useNavigate } from 'react-router-dom'
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
import { useSidebarServerSelection } from './useSidebarServerSelection'
import { SIDEBAR_SERVER_STORAGE_KEY, useSidebarServerStore } from '@/stores/sidebarServerStore'
const mocks = vi.hoisted(() => ({
useOpenCodeServers: vi.fn(),
}))
vi.mock('@/hooks/useOpenCodeServers', () => ({
useOpenCodeServers: mocks.useOpenCodeServers,
useOpenCodeServerStatuses: () => ({ statuses: [], statusById: {}, isLoading: false }),
}))
const kitchen = {
id: 'srv_kitchen',
name: 'Kitchen',
baseUrl: 'https://kitchen.example.com',
username: 'opencode',
enabled: true,
hasPassword: true,
createdAt: 1,
updatedAt: 2,
}
const office = { ...kitchen, id: 'srv_office', name: 'Office' }
function SelectionHarness() {
const [serverId, selectServer] = useSidebarServerSelection()
const navigate = useNavigate()
return (
<>
<div data-testid="selected">{serverId}</div>
<button type="button" onClick={() => selectServer('srv_kitchen')}>
Select kitchen
</button>
<button type="button" onClick={() => navigate('/repos/2')}>
Go to repo
</button>
<button type="button" onClick={() => navigate('/servers/srv_office')}>
Go to office
</button>
</>
)
}
function renderHarness(initialEntry = '/') {
return render(
<MemoryRouter initialEntries={[initialEntry]}>
<SelectionHarness />
</MemoryRouter>,
)
}
describe('useSidebarServerSelection', () => {
beforeEach(() => {
localStorage.clear()
useSidebarServerStore.setState({ serverId: LOCAL_OPENCODE_SERVER_ID })
mocks.useOpenCodeServers.mockReturnValue({ servers: [kitchen, office], isLoading: false })
})
it('defaults to the local server', () => {
renderHarness()
expect(screen.getByTestId('selected')).toHaveTextContent(LOCAL_OPENCODE_SERVER_ID)
})
it('selects the server named by a linked server route', async () => {
renderHarness('/servers/srv_kitchen/projects?directory=%2Fprojects%2Falpha')
await waitFor(() => expect(screen.getByTestId('selected')).toHaveTextContent('srv_kitchen'))
})
it('selects local on a local repo route', async () => {
useSidebarServerStore.setState({ serverId: 'srv_kitchen' })
renderHarness('/repos/1')
await waitFor(() =>
expect(screen.getByTestId('selected')).toHaveTextContent(LOCAL_OPENCODE_SERVER_ID),
)
})
it('keeps a manual selection while the local route stays unchanged', async () => {
renderHarness('/repos/1')
fireEvent.click(screen.getByRole('button', { name: 'Select kitchen' }))
expect(screen.getByTestId('selected')).toHaveTextContent('srv_kitchen')
})
it('follows a navigation to another linked server', async () => {
renderHarness('/servers/srv_kitchen')
fireEvent.click(screen.getByRole('button', { name: 'Go to office' }))
await waitFor(() => expect(screen.getByTestId('selected')).toHaveTextContent('srv_office'))
})
it('follows a navigation back to a local route', async () => {
useSidebarServerStore.setState({ serverId: 'srv_kitchen' })
renderHarness('/servers/srv_kitchen')
fireEvent.click(screen.getByRole('button', { name: 'Go to repo' }))
await waitFor(() =>
expect(screen.getByTestId('selected')).toHaveTextContent(LOCAL_OPENCODE_SERVER_ID),
)
})
it('falls back to local when the selected server is disabled', async () => {
useSidebarServerStore.setState({ serverId: 'srv_office' })
mocks.useOpenCodeServers.mockReturnValue({
servers: [kitchen, { ...office, enabled: false }],
isLoading: false,
})
renderHarness()
await waitFor(() =>
expect(screen.getByTestId('selected')).toHaveTextContent(LOCAL_OPENCODE_SERVER_ID),
)
})
it('falls back to local when the selected server no longer exists', async () => {
useSidebarServerStore.setState({ serverId: 'srv_gone' })
renderHarness()
await waitFor(() =>
expect(screen.getByTestId('selected')).toHaveTextContent(LOCAL_OPENCODE_SERVER_ID),
)
})
it('persists the selection', () => {
renderHarness()
fireEvent.click(screen.getByRole('button', { name: 'Select kitchen' }))
expect(JSON.parse(localStorage.getItem(SIDEBAR_SERVER_STORAGE_KEY) ?? 'null')).toBe(
'srv_kitchen',
)
})
})
@@ -0,0 +1,44 @@
import { useEffect } from 'react'
import { useLocation, useMatch } from 'react-router-dom'
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
import { useOpenCodeServers } from '@/hooks/useOpenCodeServers'
import { isAssistantPath, parseRepoRoute } from '@/lib/navigation'
import { useSidebarServerStore } from '@/stores/sidebarServerStore'
function isLocalRoute(pathname: string): boolean {
return parseRepoRoute(pathname).repoId !== null || isAssistantPath(pathname)
}
/**
* The linked server selected in the sidebar, defaulting to the local server. The route selects a
* server when the location changes, selecting a row never navigates, and a selected server that is
* missing or disabled falls back to local.
*/
export function useSidebarServerSelection(): [string, (serverId: string) => void] {
const { pathname } = useLocation()
const routeServerId = useMatch('/servers/:serverId/*')?.params.serverId
const { servers, isLoading } = useOpenCodeServers()
const serverId = useSidebarServerStore((state) => state.serverId)
const selectServer = useSidebarServerStore((state) => state.selectServer)
useEffect(() => {
const current = useSidebarServerStore.getState().serverId
if (routeServerId) {
if (current !== routeServerId) selectServer(routeServerId)
return
}
if (isLocalRoute(pathname) && current !== LOCAL_OPENCODE_SERVER_ID) {
selectServer(LOCAL_OPENCODE_SERVER_ID)
}
}, [pathname, routeServerId, selectServer])
useEffect(() => {
if (isLoading || serverId === LOCAL_OPENCODE_SERVER_ID) return
const server = servers.find((candidate) => candidate.id === serverId)
if (!server || !server.enabled) {
selectServer(LOCAL_OPENCODE_SERVER_ID)
}
}, [isLoading, servers, serverId, selectServer])
return [serverId, selectServer]
}
+11
View File
@@ -290,6 +290,17 @@ export function serverActivityFromIndex(
return running ? 'running' : null
}
/**
* A linked server project's activity from a prebuilt server index, keyed by server and directory.
*/
export function projectActivityFromIndex(
serverId: string,
directory: string,
index: ReadonlyMap<string, 'needs-input' | 'running'>,
): 'needs-input' | 'running' | null {
return index.get(serverIndexKey(serverId, directory)) ?? null
}
/**
* The repo's activity from a prebuilt index, checking each of its own paths and the directories of
* the worktrees it owns. Needs-input outranks running.
+29 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
import { getSessionListPath, getSwipeBackTarget, getAssistantPath, getAssistantSessionListPath, isAssistantPath, getPathWithReturnTo, getReturnToPath, getRepoPath, getServerPath, getServerSessionPath, getSessionPath, parseRepoRoute, parseServerSessionRoute } from './navigation';
import { getSessionListPath, getSwipeBackTarget, getAssistantPath, getAssistantSessionListPath, isAssistantPath, getPathWithReturnTo, getReturnToPath, getRepoPath, getServerPath, getServerProjectPath, getServerSessionPath, getSessionPath, parseRepoRoute, parseServerProjectRoute, parseServerSessionRoute } from './navigation';
describe('getAssistantPath', () => {
it('returns /assistant', () => {
@@ -141,6 +141,28 @@ describe('parseRepoRoute', () => {
});
});
describe('linked server project paths', () => {
it('builds a project path with encoded server id and directory', () => {
expect(getServerProjectPath('srv_kitchen', '/home/me/app')).toBe(
'/servers/srv_kitchen/projects?directory=%2Fhome%2Fme%2Fapp'
);
expect(getServerProjectPath('srv a/b', '/srv/my app')).toBe(
'/servers/srv%20a%2Fb/projects?directory=%2Fsrv%2Fmy%20app'
);
});
it('parses the server id and decoded directory from a project route', () => {
expect(
parseServerProjectRoute('/servers/srv_kitchen/projects', '?directory=%2Fhome%2Fme%2Fapp')
).toEqual({ serverId: 'srv_kitchen', directory: '/home/me/app' });
});
it('returns null without a directory or for other routes', () => {
expect(parseServerProjectRoute('/servers/srv_kitchen/projects', '')).toBeNull();
expect(parseServerProjectRoute('/servers/srv_kitchen', '?directory=%2Fhome%2Fme')).toBeNull();
});
});
describe('parseServerSessionRoute', () => {
it('parses a linked-server session route', () => {
expect(parseServerSessionRoute('/servers/srv_kitchen/sessions/ses_1')).toEqual({
@@ -217,6 +239,12 @@ describe('getSwipeBackTarget', () => {
it('returns root for a server page', () => {
expect(getSwipeBackTarget('/servers/srv_kitchen', '')).toBe('/');
});
it('returns the server page for a remote project page', () => {
expect(
getSwipeBackTarget('/servers/srv_kitchen/projects', '?directory=%2Fhome%2Fme%2Fapp')
).toBe('/servers/srv_kitchen');
});
});
describe('repo route', () => {
+20
View File
@@ -36,6 +36,21 @@ export function getServerSessionPath(serverId: string, sessionId: string): strin
return buildServerSessionPath(serverId, sessionId);
}
export function getServerProjectPath(serverId: string, directory: string): string {
return `/servers/${encodeURIComponent(serverId)}/projects?directory=${encodeURIComponent(directory)}`;
}
export function parseServerProjectRoute(
pathname: string,
search: string,
): { serverId: string; directory: string } | null {
const match = /^\/servers\/([^/]+)\/projects$/.exec(pathname);
if (!match) return null;
const directory = new URLSearchParams(search).get('directory');
if (!directory) return null;
return { serverId: decodeURIComponent(match[1]), directory };
}
export function parseServerSessionRoute(pathname: string): { serverId: string; sessionId: string } | null {
const match = /^\/servers\/([^/]+)\/sessions\/([^/]+)$/.exec(pathname);
if (!match) return null;
@@ -90,6 +105,11 @@ export function getReturnToPath(search: string, fallback: string): string {
}
export function getSwipeBackTarget(pathname: string, search = ''): string | null {
const serverProject = parseServerProjectRoute(pathname, search);
if (serverProject) {
return getServerPath(serverProject.serverId);
}
const serverSession = parseServerSessionRoute(pathname);
if (serverSession) {
return getServerPath(serverSession.serverId);
+221
View File
@@ -0,0 +1,221 @@
import { useNavigate, useParams, useSearchParams } from 'react-router-dom'
import { useQuery } from '@tanstack/react-query'
import { FolderGit2, GitBranch, Loader2, Plus, Server } from 'lucide-react'
import { getVcsInfo, listProjects } from '@/api/opencode'
import { useCreateSession } from '@/hooks/useOpenCode'
import { useOpenCodeServers } from '@/hooks/useOpenCodeServers'
import { useSettingsDialog } from '@/hooks/useSettingsDialog'
import { useSSE } from '@/hooks/useSSE'
import { useMobile } from '@/hooks/useMobile'
import { useToolPanel } from '@/hooks/useToolPanel'
import { useDialogParam } from '@/hooks/useDialogParam'
import { useTerminalDialogParam, useTerminalDirectoryParam } from '@/hooks/useOpenTerminal'
import { serverScopedKey } from '@/lib/serverScope'
import { getServerPath, getServerSessionPath } from '@/lib/navigation'
import { getDirectoryName } from '@/lib/utils'
import { Header } from '@/components/ui/header'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { SessionList } from '@/components/session/SessionList'
import { LinkedServerStateCard } from '@/components/servers/LinkedServerStateCard'
import { RemoteSchedulesButton } from '@/components/schedules/RemoteSchedulesButton'
import { RemoteMultiRunButton } from '@/components/repo/RemoteMultiRunButton'
import { RepoMcpDialog } from '@/components/repo/RepoMcpDialog'
import { RepoSkillsDialog } from '@/components/repo/RepoSkillsDialog'
import { RemoteSourceControlPanel } from '@/components/source-control/RemoteSourceControlContent'
import { TerminalPanel } from '@/components/terminal/TerminalPanel'
import { ToolSidePanel } from '@/components/navigation/ToolSidePanel'
function RemoteProjectContent({ serverId, directory }: { serverId: string; directory?: string }) {
const navigate = useNavigate()
const { servers, isLoading: serversLoading } = useOpenCodeServers()
const { setActiveTab } = useSettingsDialog()
const [mcpDialogOpen, setMcpDialogOpen] = useDialogParam('mcp')
const [skillsDialogOpen, setSkillsDialogOpen] = useDialogParam('skills')
const [sourceControlOpen, setSourceControlOpen] = useDialogParam('sourceControl')
const [terminalOpen, setTerminalOpen] = useTerminalDialogParam()
const terminalDirectory = useTerminalDirectoryParam()
const docked = !useMobile()
const toolPanel = useToolPanel(docked)
const server = servers.find((candidate) => candidate.id === serverId)
const isDisabled = server !== undefined && !server.enabled
const isReady = server?.enabled === true && Boolean(directory)
const createSession = useCreateSession(directory)
const projectsQuery = useQuery({
queryKey: serverScopedKey(['opencode', 'projects'], serverId),
queryFn: () => listProjects(serverId),
enabled: server?.enabled === true,
retry: false,
})
const vcsQuery = useQuery({
queryKey: [...serverScopedKey(['opencode', 'vcs', directory ?? ''], serverId), 'info'],
queryFn: () => getVcsInfo(directory ?? '', serverId),
enabled: isReady,
retry: false,
})
useSSE(directory)
const project = (projectsQuery.data ?? []).find((entry) => entry.canonical === directory)
const branch = vcsQuery.data?.branch.current ?? vcsQuery.data?.branch.default
const title = project?.name?.trim() || (directory ? getDirectoryName(directory) : 'Project')
const openSettings = () => setActiveTab('servers')
const handleCreateSession = () => {
createSession.mutate({}, {
onSuccess: (session) => navigate(getServerSessionPath(serverId, session.id)),
})
}
return (
<div className="flex h-full max-h-full min-w-0">
<div className="flex h-full max-h-full min-w-0 flex-1 flex-col overflow-hidden bg-gradient-to-br from-background via-background to-background pb-[calc(env(safe-area-inset-bottom)+56px)] sm:pb-0">
<Header>
<div className="flex min-w-0 flex-1 items-center gap-2 sm:gap-3">
<Header.BackButton to={getServerPath(serverId)} />
<Header.Title>{title}</Header.Title>
<Badge variant="outline" className="hidden shrink-0 sm:inline-flex">
<Server className="mr-1 h-3 w-3" />
{server?.name ?? 'Linked server'}
</Badge>
{branch ? (
<Badge variant="secondary" className="hidden shrink-0 md:inline-flex">
<GitBranch className="mr-1 h-3 w-3" />
{branch}
</Badge>
) : null}
</div>
<Header.Actions className="shrink-0 gap-1 pl-2 sm:gap-2">
{directory ? (
<>
<RemoteSchedulesButton serverId={serverId} directory={directory} />
<RemoteMultiRunButton serverId={serverId} directory={directory} />
<Button
onClick={handleCreateSession}
disabled={createSession.isPending}
size="sm"
className="hidden bg-primary text-primary-foreground transition-all duration-200 hover:scale-105 hover:bg-primary-hover sm:inline-flex"
>
{createSession.isPending ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Plus className="mr-2 h-4 w-4" />
)}
<span>New Session</span>
</Button>
<Button
onClick={handleCreateSession}
disabled={createSession.isPending}
aria-label="New Session"
size="sm"
className="h-10 w-10 bg-primary p-0 text-primary-foreground transition-all duration-200 hover:scale-105 hover:bg-primary-hover sm:hidden"
>
{createSession.isPending ? (
<Loader2 className="h-5 w-5 animate-spin" />
) : (
<Plus className="h-5 w-5" />
)}
</Button>
</>
) : null}
</Header.Actions>
</Header>
<div className="flex min-h-0 flex-1 flex-col">
{!serversLoading && !server ? (
<div className="mx-auto flex w-full max-w-4xl flex-col gap-4 p-3 sm:p-4">
<LinkedServerStateCard
icon={Server}
title="Server not found"
description="This linked server is no longer configured."
actionLabel="Open server settings"
onAction={openSettings}
/>
</div>
) : isDisabled ? (
<div className="mx-auto flex w-full max-w-4xl flex-col gap-4 p-3 sm:p-4">
<LinkedServerStateCard
icon={Server}
title="This server is disabled"
description="Enable it in Settings → Servers to browse its projects and sessions."
actionLabel="Open server settings"
onAction={openSettings}
/>
</div>
) : !directory ? (
<div className="mx-auto flex w-full max-w-4xl flex-col gap-4 p-3 sm:p-4">
<LinkedServerStateCard
icon={FolderGit2}
title="No project selected"
description="This project link is missing its directory on the server."
actionLabel="Back to server"
onAction={() => navigate(getServerPath(serverId))}
/>
</div>
) : isReady ? (
<SessionList
key={directory}
directory={directory}
createDirectory={directory}
onSelectSession={(sessionId) => navigate(getServerSessionPath(serverId, sessionId))}
/>
) : null}
</div>
</div>
{docked && directory ? (
<ToolSidePanel
panel={toolPanel}
filesBasePath={directory}
directory={directory}
terminalDirectory={terminalDirectory ?? directory}
terminalTarget={{ kind: 'server', serverId }}
repoDirectory={directory}
/>
) : null}
{directory ? (
<>
<RepoMcpDialog
open={!docked && mcpDialogOpen}
onOpenChange={setMcpDialogOpen}
directory={directory}
/>
<RepoSkillsDialog
open={!docked && skillsDialogOpen}
onOpenChange={setSkillsDialogOpen}
directory={directory}
/>
<RemoteSourceControlPanel
serverId={serverId}
directory={directory}
isOpen={!docked && sourceControlOpen}
onClose={() => setSourceControlOpen(false)}
/>
<TerminalPanel
target={{ kind: 'server', serverId }}
directory={terminalDirectory ?? directory}
isOpen={!docked && terminalOpen}
onClose={() => setTerminalOpen(false)}
/>
</>
) : null}
</div>
)
}
export function RemoteProject() {
const { serverId } = useParams<{ serverId: string }>()
const [searchParams] = useSearchParams()
const directory = searchParams.get('directory') ?? undefined
if (!serverId) {
return null
}
return <RemoteProjectContent serverId={serverId} directory={directory} />
}
+27 -30
View File
@@ -18,7 +18,7 @@ import { useOpenCodeServers, useOpenCodeServerStatuses } from '@/hooks/useOpenCo
import { useSettingsDialog } from '@/hooks/useSettingsDialog'
import { useSSE } from '@/hooks/useSSE'
import { serverScopedKey } from '@/lib/serverScope'
import { getServerSessionPath } from '@/lib/navigation'
import { getServerProjectPath, getServerSessionPath } from '@/lib/navigation'
import { getDirectoryName } from '@/lib/utils'
import { Header } from '@/components/ui/header'
import { Badge } from '@/components/ui/badge'
@@ -26,6 +26,7 @@ import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { SessionStatusIndicator } from '@/components/ui/session-status-indicator'
import { LinkedServerStateCard } from '@/components/servers/LinkedServerStateCard'
import { RemoteSchedulesButton } from '@/components/schedules/RemoteSchedulesButton'
import { RemoteMultiRunButton } from '@/components/repo/RemoteMultiRunButton'
@@ -123,15 +124,21 @@ function ProjectRow({ project, serverId }: { project: OpenCodeProject; serverId:
type="button"
onClick={() => setExpanded((current) => !current)}
aria-expanded={expanded}
className="flex min-w-0 flex-1 items-center gap-2 rounded-md p-1 text-left transition-colors hover:bg-accent/50"
aria-label={`${expanded ? 'Collapse' : 'Expand'} ${name}`}
className="shrink-0 rounded-md p-1 text-muted-foreground transition-colors hover:bg-accent/50"
>
{expanded ? (
<ChevronDown className="h-4 w-4 shrink-0 text-muted-foreground" />
<ChevronDown className="h-4 w-4 shrink-0" />
) : (
<ChevronRight className="h-4 w-4 shrink-0 text-muted-foreground" />
<ChevronRight className="h-4 w-4 shrink-0" />
)}
</button>
<Link
to={getServerProjectPath(serverId, project.canonical)}
className="flex min-w-0 flex-1 items-center gap-2 rounded-md p-1 text-left transition-colors hover:bg-accent/50"
>
<FolderGit2 className="h-4 w-4 shrink-0 text-muted-foreground" />
<span className="min-w-0">
<span className="min-w-0 flex-1">
<span className="block truncate text-sm font-semibold">{name}</span>
<span className="block truncate font-mono text-xs text-muted-foreground">{project.canonical}</span>
</span>
@@ -140,7 +147,7 @@ function ProjectRow({ project, serverId }: { project: OpenCodeProject; serverId:
{project.vcs}
</Badge>
) : null}
</button>
</Link>
<Button
size="sm"
variant="outline"
@@ -214,33 +221,23 @@ function RemoteServerContent({ serverId }: { serverId: string }) {
<div className="mx-auto flex w-full max-w-4xl flex-1 flex-col gap-4 overflow-y-auto p-3 pb-[calc(env(safe-area-inset-bottom)+60px)] sm:pb-4">
{!serversLoading && !server ? (
<Card className="flex flex-col items-center gap-3 p-6 text-center">
<Server className="h-8 w-8 text-muted-foreground" />
<div>
<p className="font-medium">Server not found</p>
<p className="text-sm text-muted-foreground">
This linked server is no longer configured.
</p>
</div>
<Button variant="outline" size="sm" onClick={openSettings}>
Open server settings
</Button>
</Card>
<LinkedServerStateCard
icon={Server}
title="Server not found"
description="This linked server is no longer configured."
actionLabel="Open server settings"
onAction={openSettings}
/>
) : null}
{isDisabled ? (
<Card className="flex flex-col items-center gap-3 p-6 text-center">
<Server className="h-8 w-8 text-muted-foreground" />
<div>
<p className="font-medium">This server is disabled</p>
<p className="text-sm text-muted-foreground">
Enable it in Settings → Servers to browse its projects and sessions.
</p>
</div>
<Button variant="outline" size="sm" onClick={openSettings}>
Open server settings
</Button>
</Card>
<LinkedServerStateCard
icon={Server}
title="This server is disabled"
description="Enable it in Settings → Servers to browse its projects and sessions."
actionLabel="Open server settings"
onAction={openSettings}
/>
) : null}
{server && !isDisabled && projectsQuery.isError ? (
@@ -0,0 +1,208 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, waitFor, fireEvent, act } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import { RemoteProject } from '../RemoteProject'
interface SessionListCapture {
directory?: string
createDirectory?: string
onSelectSession?: (sessionId: string) => void
}
const mocks = vi.hoisted(() => ({
listProjects: vi.fn(),
getVcsInfo: vi.fn(),
useCreateSession: vi.fn(),
useOpenCodeServers: vi.fn(),
useSettingsDialog: vi.fn(),
useSSE: vi.fn(),
createSession: vi.fn(),
lastSessionListProps: { current: undefined as SessionListCapture | undefined },
setActiveTab: vi.fn(),
}))
vi.mock('@/api/opencode', () => ({
listProjects: mocks.listProjects,
getVcsInfo: mocks.getVcsInfo,
}))
vi.mock('@/hooks/useOpenCode', () => ({
useCreateSession: mocks.useCreateSession,
}))
vi.mock('@/hooks/useOpenCodeServers', () => ({
useOpenCodeServers: mocks.useOpenCodeServers,
}))
vi.mock('@/hooks/useSettingsDialog', () => ({
useSettingsDialog: mocks.useSettingsDialog,
}))
vi.mock('@/hooks/useSSE', () => ({
useSSE: mocks.useSSE,
}))
vi.mock('@/components/session/SessionList', () => ({
SessionList: (props: SessionListCapture) => {
mocks.lastSessionListProps.current = props
return <div data-testid="session-list">{props.directory}</div>
},
}))
vi.mock('@/components/navigation/ToolSidePanel', () => ({
ToolSidePanel: () => <div data-testid="tool-panel" />,
}))
const server = {
id: 'srv_kitchen',
name: 'Kitchen',
baseUrl: 'https://kitchen.example.com',
username: 'opencode',
enabled: true,
hasPassword: true,
createdAt: 1,
updatedAt: 2,
}
const project = {
id: 'prj_1',
canonical: '/home/me/app',
name: 'App',
time: { created: 1, updated: 2, active: 2 },
sandboxes: [],
}
function createQueryClient() {
return new QueryClient({ defaultOptions: { queries: { retry: false } } })
}
function renderProject(path = '/servers/srv_kitchen/projects?directory=%2Fhome%2Fme%2Fapp') {
return render(
<QueryClientProvider client={createQueryClient()}>
<MemoryRouter initialEntries={[path]}>
<Routes>
<Route path="/servers/:serverId/projects" element={<RemoteProject />} />
<Route path="/servers/:serverId" element={<div data-testid="server-route" />} />
<Route path="/servers/:serverId/sessions/:sessionId" element={<div data-testid="session-route" />} />
</Routes>
</MemoryRouter>
</QueryClientProvider>,
)
}
describe('RemoteProject', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.lastSessionListProps.current = undefined
mocks.listProjects.mockResolvedValue([project])
mocks.getVcsInfo.mockResolvedValue({ branch: { current: 'main', default: 'main' } })
mocks.useCreateSession.mockReturnValue({ mutate: mocks.createSession, isPending: false })
mocks.useOpenCodeServers.mockReturnValue({ servers: [server], isLoading: false })
mocks.useSettingsDialog.mockReturnValue({ setActiveTab: mocks.setActiveTab })
mocks.useSSE.mockReturnValue({ isConnected: true, isReconnecting: false })
})
it('renders the project name, server name and branch from the linked server', async () => {
renderProject()
expect(await screen.findByText('App')).toBeInTheDocument()
expect(screen.getByText('Kitchen')).toBeInTheDocument()
await waitFor(() => {
expect(screen.getByText('main')).toBeInTheDocument()
})
expect(mocks.listProjects).toHaveBeenCalledWith('srv_kitchen')
expect(mocks.getVcsInfo).toHaveBeenCalledWith('/home/me/app', 'srv_kitchen')
})
it('falls back to the directory name when the server does not list the project', async () => {
mocks.listProjects.mockResolvedValue([])
renderProject()
expect(await screen.findByText('app')).toBeInTheDocument()
})
it('renders the session list for the project directory and subscribes to its events', () => {
renderProject()
expect(screen.getByTestId('session-list')).toHaveTextContent('/home/me/app')
expect(mocks.lastSessionListProps.current?.createDirectory).toBe('/home/me/app')
expect(mocks.useSSE).toHaveBeenCalledWith('/home/me/app')
})
it('opens a session from the session list on the remote session route', () => {
renderProject()
act(() => {
mocks.lastSessionListProps.current?.onSelectSession?.('ses_42')
})
expect(screen.getByTestId('session-route')).toBeInTheDocument()
})
it('creates a session in the project directory and navigates to it', async () => {
mocks.useCreateSession.mockReturnValue({
mutate: (_input: unknown, options?: { onSuccess?: (session: { id: string }) => void }) => {
options?.onSuccess?.({ id: 'ses_new' })
},
isPending: false,
})
renderProject()
fireEvent.click(screen.getAllByRole('button', { name: 'New Session' })[0])
await waitFor(() => {
expect(screen.getByTestId('session-route')).toBeInTheDocument()
})
expect(mocks.useCreateSession).toHaveBeenCalledWith('/home/me/app')
})
it('shows a missing-directory state without rendering the session list', async () => {
renderProject('/servers/srv_kitchen/projects')
expect(await screen.findByText('No project selected')).toBeInTheDocument()
expect(screen.queryByTestId('session-list')).not.toBeInTheDocument()
})
it('shows the disabled state without loading projects', async () => {
mocks.useOpenCodeServers.mockReturnValue({
servers: [{ ...server, enabled: false }],
isLoading: false,
})
renderProject()
expect(await screen.findByText('This server is disabled')).toBeInTheDocument()
expect(mocks.listProjects).not.toHaveBeenCalled()
expect(screen.queryByTestId('session-list')).not.toBeInTheDocument()
})
it('shows the missing-server state', async () => {
mocks.useOpenCodeServers.mockReturnValue({ servers: [], isLoading: false })
renderProject()
expect(await screen.findByText('Server not found')).toBeInTheDocument()
})
it('opens server settings from the disabled state', async () => {
mocks.useOpenCodeServers.mockReturnValue({
servers: [{ ...server, enabled: false }],
isLoading: false,
})
renderProject()
fireEvent.click(await screen.findByRole('button', { name: 'Open server settings' }))
expect(mocks.setActiveTab).toHaveBeenCalledWith('servers')
})
it('goes back to the linked server page', async () => {
renderProject()
fireEvent.click(await screen.findByRole('button', { name: 'Go back' }))
expect(screen.getByTestId('server-route')).toBeInTheDocument()
})
})
@@ -126,10 +126,20 @@ describe('RemoteServer', () => {
expect(mocks.listProjects).toHaveBeenCalledWith('srv_kitchen')
})
it('links the project name to the remote project page', async () => {
renderServer()
const link = await screen.findByRole('link', { name: /App/ })
expect(link).toHaveAttribute(
'href',
'/servers/srv_kitchen/projects?directory=%2Fhome%2Fme%2Fapp',
)
})
it('links each expanded project session to the remote session route', async () => {
renderServer()
fireEvent.click(await screen.findByRole('button', { name: /App/ }))
fireEvent.click(await screen.findByRole('button', { name: 'Expand App' }))
const link = await screen.findByRole('link', { name: /Fix the bug/ })
expect(link).toHaveAttribute('href', '/servers/srv_kitchen/sessions/ses_1')
+33
View File
@@ -0,0 +1,33 @@
import { create } from 'zustand'
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
import { readStoredValue, writeStoredValue } from '@/lib/persistentStorage'
export const SIDEBAR_SERVER_STORAGE_KEY = 'oc:sidebar:server'
function readStoredServerId(): string {
const stored = readStoredValue(SIDEBAR_SERVER_STORAGE_KEY)
if (stored === null) return LOCAL_OPENCODE_SERVER_ID
try {
const parsed = JSON.parse(stored)
return typeof parsed === 'string' && parsed.length > 0 ? parsed : LOCAL_OPENCODE_SERVER_ID
} catch {
return LOCAL_OPENCODE_SERVER_ID
}
}
interface SidebarServerStore {
serverId: string
selectServer: (serverId: string) => void
}
/**
* The server whose projects and sessions the sidebar lists. Shared by the desktop sidebar, its
* collapsed switcher, and the mobile repo sheet, and persisted across reloads.
*/
export const useSidebarServerStore = create<SidebarServerStore>((set) => ({
serverId: readStoredServerId(),
selectServer: (serverId) => {
writeStoredValue(SIDEBAR_SERVER_STORAGE_KEY, serverId)
set({ serverId })
},
}))