From 36b8c1b2001f0be14dbd82cb99db47cf689f895d Mon Sep 17 00:00:00 2001
From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com>
Date: Mon, 19 Oct 2026 10:16:32 -0400
Subject: [PATCH] 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.
---
frontend/src/App.tsx | 10 +
.../navigation/DesktopSessionTree.test.tsx | 9 +
.../navigation/DesktopSessionTree.tsx | 131 ++++--
.../components/navigation/DesktopSidebar.tsx | 13 +-
.../navigation/LinkedServersNav.test.tsx | 117 ++++-
.../navigation/LinkedServersNav.tsx | 165 ++++---
.../navigation/RemoteProjectNav.test.tsx | 310 +++++++++++++
.../navigation/RemoteProjectNav.tsx | 435 ++++++++++++++++++
.../navigation/RepoQuickSwitchSheet.test.tsx | 64 ++-
.../navigation/RepoQuickSwitchSheet.tsx | 61 ++-
.../components/navigation/RepoSessionNav.tsx | 44 +-
.../components/navigation/ToolSidePanel.tsx | 2 +-
.../navigation/moreDrawerItems.test.ts | 24 +
.../components/navigation/moreDrawerItems.ts | 3 +-
.../navigation/sidebar-session-tree.ts | 8 +-
.../src/components/repo/RepoSkillsDialog.tsx | 6 +-
.../servers/LinkedServerStateCard.tsx | 36 ++
frontend/src/hooks/useActiveWork.ts | 52 +++
frontend/src/hooks/useSessionSearch.ts | 8 +-
.../hooks/useSidebarServerSelection.test.tsx | 147 ++++++
.../src/hooks/useSidebarServerSelection.ts | 44 ++
frontend/src/lib/activeWork.ts | 11 +
frontend/src/lib/navigation.test.ts | 30 +-
frontend/src/lib/navigation.ts | 20 +
frontend/src/pages/RemoteProject.tsx | 221 +++++++++
frontend/src/pages/RemoteServer.tsx | 57 ++-
.../pages/__tests__/RemoteProject.test.tsx | 208 +++++++++
.../src/pages/__tests__/RemoteServer.test.tsx | 12 +-
frontend/src/stores/sidebarServerStore.ts | 33 ++
29 files changed, 2080 insertions(+), 201 deletions(-)
create mode 100644 frontend/src/components/navigation/RemoteProjectNav.test.tsx
create mode 100644 frontend/src/components/navigation/RemoteProjectNav.tsx
create mode 100644 frontend/src/components/servers/LinkedServerStateCard.tsx
create mode 100644 frontend/src/hooks/useSidebarServerSelection.test.tsx
create mode 100644 frontend/src/hooks/useSidebarServerSelection.ts
create mode 100644 frontend/src/pages/RemoteProject.tsx
create mode 100644 frontend/src/pages/__tests__/RemoteProject.test.tsx
create mode 100644 frontend/src/stores/sidebarServerStore.ts
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index a6a71151..fa1cbbe2 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -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: (
+
+
+
+ ),
+ loader: protectedLoader,
+ },
{
path: '/servers/:serverId/sessions/:sessionId',
element: (
diff --git a/frontend/src/components/navigation/DesktopSessionTree.test.tsx b/frontend/src/components/navigation/DesktopSessionTree.test.tsx
index 9a37fcf3..186e4eba 100644
--- a/frontend/src/components/navigation/DesktopSessionTree.test.tsx
+++ b/frontend/src/components/navigation/DesktopSessionTree.test.tsx
@@ -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()
diff --git a/frontend/src/components/navigation/DesktopSessionTree.tsx b/frontend/src/components/navigation/DesktopSessionTree.tsx
index e7395b4e..a31d6bf9 100644
--- a/frontend/src/components/navigation/DesktopSessionTree.tsx
+++ b/frontend/src/components/navigation/DesktopSessionTree.tsx
@@ -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 (
+
+
+
+
+
+
+ {children}
+
+
+ )
+}
+
interface SessionSearchResultsProps {
nameMatchedRepos: Repo[]
otherRepos: Repo[]
@@ -90,14 +116,21 @@ function SessionSearchResults({
{matchingGroups.map((group) => (
navigate(getRepoPath(group.repo.id))}
- actions={}
+ indicator={}
+ actions={
+ getSessionPath(group.repo.id, sessionId)}
+ onOpenSession={navigate}
+ />
+ }
>
{group.items.map((item) => (
-
-
-
-
-
- {isLoading ? (
- Loading repos...
- ) : trimmedDraft ? (
-
- ) : (
- navigate(getRepoPath(repoId))}
- onSelectSession={navigate}
- renderActions={(repo) => }
- />
- )}
-
-
+
+ {isLoading ? (
+ Loading repos...
+ ) : trimmedDraft ? (
+
+ ) : (
+ navigate(getRepoPath(repoId))}
+ onSelectSession={navigate}
+ renderActions={(repo) => (
+ getSessionPath(repo.id, sessionId)}
+ onOpenSession={navigate}
+ />
+ )}
+ />
+ )}
+
)
}
+
+function RemoteSessionTree({ serverId }: { serverId: string }) {
+ const navigate = useNavigate()
+ const [draft, setDraft] = useState('')
+
+ return (
+
+
+
+ )
+}
+
+/**
+ * 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
+ }
+
+ return
+}
diff --git a/frontend/src/components/navigation/DesktopSidebar.tsx b/frontend/src/components/navigation/DesktopSidebar.tsx
index db4b95fe..24ca5b6f 100644
--- a/frontend/src/components/navigation/DesktopSidebar.tsx
+++ b/frontend/src/components/navigation/DesktopSidebar.tsx
@@ -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() {
- Sessions
+
+ Sessions{selectedServerName ? ` ยท ${selectedServerName}` : ''}
+
diff --git a/frontend/src/components/navigation/LinkedServersNav.test.tsx b/frontend/src/components/navigation/LinkedServersNav.test.tsx
index 009e02f9..5ad9af90 100644
--- a/frontend/src/components/navigation/LinkedServersNav.test.tsx
+++ b/frontend/src/components/navigation/LinkedServersNav.test.tsx
@@ -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 {location.pathname}
+}
+
function renderNav(pathname = '/') {
return render(
+
,
)
}
@@ -43,6 +53,7 @@ function renderRail(pathname = '/') {
return render(
+
,
)
}
@@ -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(
-
-
+
+
+
,
)
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')
diff --git a/frontend/src/components/navigation/LinkedServersNav.tsx b/frontend/src/components/navigation/LinkedServersNav.tsx
index 3e9e2d61..062e1b6e 100644
--- a/frontend/src/components/navigation/LinkedServersNav.tsx
+++ b/frontend/src/components/navigation/LinkedServersNav.tsx
@@ -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 (
+
+ )
+}
+
+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 (
+
)
}
-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 (
+ selectServer(LOCAL_OPENCODE_SERVER_ID)}
+ title="Local"
+ aria-pressed={localActive}
+ aria-current={localActive ? 'true' : undefined}
+ className={railClassName(localActive)}
+ >
+
+ Local
+
{enabledServers.map((server) => {
- const path = getServerPath(server.id)
- const active = isActiveServerPath(location.pathname, path)
+ const active = selectedServerId === server.id
return (
- 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.name}
-
+
)
})}
)
}
- const rows = enabledServers.map((server) => {
- const path = getServerPath(server.id)
-
- return (
+ const rows = [
+ selectServer(LOCAL_OPENCODE_SERVER_ID)}
+ />,
+ ...enabledServers.map((server) => (
selectServer(server.id)}
/>
- )
- })
+ )),
+ ]
if (variant === 'sheet') {
return (
diff --git a/frontend/src/components/navigation/RemoteProjectNav.test.tsx b/frontend/src/components/navigation/RemoteProjectNav.test.tsx
new file mode 100644
index 00000000..33b0181b
--- /dev/null
+++ b/frontend/src/components/navigation/RemoteProjectNav.test.tsx
@@ -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()
+ 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()
+ 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 {`${pathname}${search}`}
+}
+
+function createWrapper(initialEntry: string) {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ })
+ return ({ children }: { children: React.ReactNode }) => (
+
+
+
+
+ {children}
+
+ >
+ }
+ />
+
+
+
+ )
+}
+
+const toggleFor = (name: string) => screen.getByRole('button', { name: `Show sessions in ${name}` })
+
+function RemoteListHarness({ serverId }: { serverId: string }) {
+ const navigate = useNavigate()
+ return (
+
+ )
+}
+
+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(
+ ,
+ { 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(, {
+ 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(, { 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(, { 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(, { 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(, {
+ 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(
+ ,
+ { 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(
+ ,
+ { 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(
+ ,
+ { wrapper: createWrapper('/') },
+ )
+
+ expect(await screen.findByText('Server unreachable')).toBeInTheDocument()
+ })
+})
diff --git a/frontend/src/components/navigation/RemoteProjectNav.tsx b/frontend/src/components/navigation/RemoteProjectNav.tsx
new file mode 100644
index 00000000..d3b73391
--- /dev/null
+++ b/frontend/src/components/navigation/RemoteProjectNav.tsx
@@ -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
+}
+
+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 Loading sessions...
+ if (isError) return Failed to load sessions
+ if (visibleSessions.length === 0) return No sessions
+
+ return (
+ <>
+ {visibleSessions.map((session) => {
+ const item = buildRemoteItem(session, serverId, projectLabel)
+ return (
+
+ )
+ })}
+ {hasMore && allSessionsPath && (
+ onSelectSession(allSessionsPath)}>All sessions
+ )}
+ >
+ )
+}
+
+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 (
+
+ )
+}
+
+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 (
+ onOpenProject(getServerProjectPath(serverId, project.canonical))}
+ onToggle={onToggle}
+ indicator={}
+ actions={
+ getServerSessionPath(serverId, sessionId)}
+ onOpenSession={onSelectSession}
+ />
+ }
+ >
+ {children}
+
+ )
+}
+
+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(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 (
+
+ setExpandedProjectId((current) => (current === project.id ? null : project.id))
+ }
+ onOpenProject={onOpenProject}
+ onSelectSession={onSelectSession}
+ >
+
+
+ )
+ })}
+ >
+ )
+}
+
+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()
+ 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()
+ 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 Loading sessions...
+ if (isError) return Failed to load sessions
+ if (visibleProjects.length === 0) return No sessions found
+
+ return (
+ <>
+ {visibleProjects.map((project) => {
+ const matchedSessions = sessionsByProjectId.get(project.id)
+ return (
+
+ {matchedSessions ? (
+
+ ) : (
+
+ )}
+
+ )
+ })}
+ >
+ )
+}
+
+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 Loading projects...
+ if (!server) return Server not found
+ if (!server.enabled) return Server is disabled
+ if (projectsQuery.isLoading) return Loading projects...
+ if (projectsQuery.isError) {
+ return (
+
+ {statusById[serverId]?.connected === false ? 'Server unreachable' : 'Could not load projects'}
+
+ )
+ }
+ if (projects.length === 0) return No projects
+
+ if (trimmedSearch) {
+ return (
+
+ )
+ }
+
+ return (
+
+ )
+}
diff --git a/frontend/src/components/navigation/RepoQuickSwitchSheet.test.tsx b/frontend/src/components/navigation/RepoQuickSwitchSheet.test.tsx
index 86eb5b09..88784f24 100644
--- a/frontend/src/components/navigation/RepoQuickSwitchSheet.test.tsx
+++ b/frontend/src/components/navigation/RepoQuickSwitchSheet.test.tsx
@@ -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()
+ 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>) {
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(
+
+
+
+
+
+
+ >
+ }
+ />
+
+
+ ,
+ )
+
+ 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()
})
})
diff --git a/frontend/src/components/navigation/RepoQuickSwitchSheet.tsx b/frontend/src/components/navigation/RepoQuickSwitchSheet.tsx
index 709122ff..93370096 100644
--- a/frontend/src/components/navigation/RepoQuickSwitchSheet.tsx
+++ b/frontend/src/components/navigation/RepoQuickSwitchSheet.tsx
@@ -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 && setSearchQuery('')} />}
- {
- onClose()
- setAddRepoOpen(true)
- }}
- className="flex-shrink-0"
- >
-
- Repo
- Add repository
-
+ {!isRemote && (
+ {
+ onClose()
+ setAddRepoOpen(true)
+ }}
+ className="flex-shrink-0"
+ >
+
+ Repo
+ Add repository
+
+ )}
- {isOpen && (
- navigateAndClose(path, { replace: true })}
- />
- )}
+ {isOpen && }
{isOpen && !searchQuery.trim() && (
navigateAndClose(path)} />
)}
- {isLoading ? (
+ {isRemote ? (
+ navigateAndClose(path, { replace: true })}
+ onSelectSession={(path) => navigateAndClose(path)}
+ />
+ ) : isLoading ? (
{Array.from({ length: 5 }).map((_, i) => (
@@ -124,7 +134,14 @@ export function RepoQuickSwitchSheet({ isOpen, onClose }: RepoQuickSwitchSheetPr
isVisible={isOpen}
onOpenRepo={handleClick}
onSelectSession={(path) => navigateAndClose(path)}
- renderActions={(repo) =>
navigateAndClose(path)} />}
+ renderActions={(repo) => (
+ getSessionPath(repo.id, sessionId)}
+ onOpenSession={(path) => navigateAndClose(path)}
+ />
+ )}
/>
)}
diff --git a/frontend/src/components/navigation/RepoSessionNav.tsx b/frontend/src/components/navigation/RepoSessionNav.tsx
index 926744f6..ff8656b3 100644
--- a/frontend/src/components/navigation/RepoSessionNav.tsx
+++ b/frontend/src/components/navigation/RepoSessionNav.tsx
@@ -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({
{name}
-
+ {indicator}
{branch && (
{children}
}
-function SessionNavLink({ children, onClick }: { children: ReactNode; onClick: () => void }) {
+export function SessionNavLink({ children, onClick }: { children: ReactNode; onClick: () => void }) {
return (
onOpenRepo(repo.id)}
onToggle={() => setExpandedRepoId((current) => (current === repo.id ? null : repo.id))}
+ indicator={}
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({
createSession.mutate({ agent: undefined })}
diff --git a/frontend/src/components/navigation/ToolSidePanel.tsx b/frontend/src/components/navigation/ToolSidePanel.tsx
index ac629b71..13bd9ba4 100644
--- a/frontend/src/components/navigation/ToolSidePanel.tsx
+++ b/frontend/src/components/navigation/ToolSidePanel.tsx
@@ -225,7 +225,7 @@ export function ToolSidePanel({
onDone={closePanel}
/>
) : (
-
+
)
}
if (tool === 'sourceControl') {
diff --git a/frontend/src/components/navigation/moreDrawerItems.test.ts b/frontend/src/components/navigation/moreDrawerItems.test.ts
index 18a2b146..75a33657 100644
--- a/frontend/src/components/navigation/moreDrawerItems.test.ts
+++ b/frontend/src/components/navigation/moreDrawerItems.test.ts
@@ -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'])
})
diff --git a/frontend/src/components/navigation/moreDrawerItems.ts b/frontend/src/components/navigation/moreDrawerItems.ts
index 8847f3f2..270df0fe 100644
--- a/frontend/src/components/navigation/moreDrawerItems.ts
+++ b/frontend/src/components/navigation/moreDrawerItems.ts
@@ -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: [
diff --git a/frontend/src/components/navigation/sidebar-session-tree.ts b/frontend/src/components/navigation/sidebar-session-tree.ts
index 1d842a24..ffb0b28a 100644
--- a/frontend/src/components/navigation/sidebar-session-tree.ts
+++ b/frontend/src/components/navigation/sidebar-session-tree.ts
@@ -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
}
diff --git a/frontend/src/components/repo/RepoSkillsDialog.tsx b/frontend/src/components/repo/RepoSkillsDialog.tsx
index 38aef921..49fb67b1 100644
--- a/frontend/src/components/repo/RepoSkillsDialog.tsx
+++ b/frontend/src/components/repo/RepoSkillsDialog.tsx
@@ -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
}
diff --git a/frontend/src/components/servers/LinkedServerStateCard.tsx b/frontend/src/components/servers/LinkedServerStateCard.tsx
new file mode 100644
index 00000000..84dfabb9
--- /dev/null
+++ b/frontend/src/components/servers/LinkedServerStateCard.tsx
@@ -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 (
+
+
+
+
{title}
+
{description}
+
+
+ {actionLabel}
+
+
+ )
+}
diff --git a/frontend/src/hooks/useActiveWork.ts b/frontend/src/hooks/useActiveWork.ts
index 174278ec..fe3b0325 100644
--- a/frontend/src/hooks/useActiveWork.ts
+++ b/frontend/src/hooks/useActiveWork.ts
@@ -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
diff --git a/frontend/src/hooks/useSessionSearch.ts b/frontend/src/hooks/useSessionSearch.ts
index 07b22261..f95d495b 100644
--- a/frontend/src/hooks/useSessionSearch.ts
+++ b/frontend/src/hooks/useSessionSearch.ts
@@ -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])
diff --git a/frontend/src/hooks/useSidebarServerSelection.test.tsx b/frontend/src/hooks/useSidebarServerSelection.test.tsx
new file mode 100644
index 00000000..17d458bd
--- /dev/null
+++ b/frontend/src/hooks/useSidebarServerSelection.test.tsx
@@ -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 (
+ <>
+ {serverId}
+ selectServer('srv_kitchen')}>
+ Select kitchen
+
+ navigate('/repos/2')}>
+ Go to repo
+
+ navigate('/servers/srv_office')}>
+ Go to office
+
+ >
+ )
+}
+
+function renderHarness(initialEntry = '/') {
+ return render(
+
+
+ ,
+ )
+}
+
+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',
+ )
+ })
+})
diff --git a/frontend/src/hooks/useSidebarServerSelection.ts b/frontend/src/hooks/useSidebarServerSelection.ts
new file mode 100644
index 00000000..ba0370f3
--- /dev/null
+++ b/frontend/src/hooks/useSidebarServerSelection.ts
@@ -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]
+}
diff --git a/frontend/src/lib/activeWork.ts b/frontend/src/lib/activeWork.ts
index 84d2c506..92b7be70 100644
--- a/frontend/src/lib/activeWork.ts
+++ b/frontend/src/lib/activeWork.ts
@@ -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,
+): '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.
diff --git a/frontend/src/lib/navigation.test.ts b/frontend/src/lib/navigation.test.ts
index 4e5ec0c6..07c1e304 100644
--- a/frontend/src/lib/navigation.test.ts
+++ b/frontend/src/lib/navigation.test.ts
@@ -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', () => {
diff --git a/frontend/src/lib/navigation.ts b/frontend/src/lib/navigation.ts
index b22e3d3c..7475dc8b 100644
--- a/frontend/src/lib/navigation.ts
+++ b/frontend/src/lib/navigation.ts
@@ -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);
diff --git a/frontend/src/pages/RemoteProject.tsx b/frontend/src/pages/RemoteProject.tsx
new file mode 100644
index 00000000..044cb79b
--- /dev/null
+++ b/frontend/src/pages/RemoteProject.tsx
@@ -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 (
+
+
+
+
+
+ {!serversLoading && !server ? (
+
+
+
+ ) : isDisabled ? (
+
+
+
+ ) : !directory ? (
+
+ navigate(getServerPath(serverId))}
+ />
+
+ ) : isReady ? (
+
navigate(getServerSessionPath(serverId, sessionId))}
+ />
+ ) : null}
+
+
+
+ {docked && directory ? (
+
+ ) : null}
+
+ {directory ? (
+ <>
+
+
+
setSourceControlOpen(false)}
+ />
+ setTerminalOpen(false)}
+ />
+ >
+ ) : null}
+
+ )
+}
+
+export function RemoteProject() {
+ const { serverId } = useParams<{ serverId: string }>()
+ const [searchParams] = useSearchParams()
+ const directory = searchParams.get('directory') ?? undefined
+
+ if (!serverId) {
+ return null
+ }
+
+ return
+}
diff --git a/frontend/src/pages/RemoteServer.tsx b/frontend/src/pages/RemoteServer.tsx
index 0786853a..d872cf63 100644
--- a/frontend/src/pages/RemoteServer.tsx
+++ b/frontend/src/pages/RemoteServer.tsx
@@ -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 ? (
-
+
) : (
-
+
)}
+
+
-
+
{name}
{project.canonical}
@@ -140,7 +147,7 @@ function ProjectRow({ project, serverId }: { project: OpenCodeProject; serverId:
{project.vcs}
) : null}
-
+
{!serversLoading && !server ? (
-
-
-
-
Server not found
-
- This linked server is no longer configured.
-
-
-
- Open server settings
-
-
+
) : null}
{isDisabled ? (
-
-
-
-
This server is disabled
-
- Enable it in Settings โ Servers to browse its projects and sessions.
-
-
-
- Open server settings
-
-
+
) : null}
{server && !isDisabled && projectsQuery.isError ? (
diff --git a/frontend/src/pages/__tests__/RemoteProject.test.tsx b/frontend/src/pages/__tests__/RemoteProject.test.tsx
new file mode 100644
index 00000000..2f09202e
--- /dev/null
+++ b/frontend/src/pages/__tests__/RemoteProject.test.tsx
@@ -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 {props.directory}
+ },
+}))
+
+vi.mock('@/components/navigation/ToolSidePanel', () => ({
+ ToolSidePanel: () => ,
+}))
+
+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(
+
+
+
+ } />
+ } />
+ } />
+
+
+ ,
+ )
+}
+
+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()
+ })
+})
diff --git a/frontend/src/pages/__tests__/RemoteServer.test.tsx b/frontend/src/pages/__tests__/RemoteServer.test.tsx
index 3689be29..0114ff19 100644
--- a/frontend/src/pages/__tests__/RemoteServer.test.tsx
+++ b/frontend/src/pages/__tests__/RemoteServer.test.tsx
@@ -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')
diff --git a/frontend/src/stores/sidebarServerStore.ts b/frontend/src/stores/sidebarServerStore.ts
new file mode 100644
index 00000000..b69cdd3d
--- /dev/null
+++ b/frontend/src/stores/sidebarServerStore.ts
@@ -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((set) => ({
+ serverId: readStoredServerId(),
+ selectServer: (serverId) => {
+ writeStoredValue(SIDEBAR_SERVER_STORAGE_KEY, serverId)
+ set({ serverId })
+ },
+}))