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

+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]
}