mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
feat(servers): show linked server projects on the home page and remove the server page
The home page follows the sidebar server selection and lists a linked server's projects with the same cards, search and row actions as local repositories. /servers/:id now selects that server and redirects home. Back from a remote session goes to its project page and back from a project goes home, and the selection follows the route app-wide so mobile keeps the linked server.
This commit is contained in:
1 parent
c1e09f34a5
commit
c18c3584ef
32 files changed
+1576
-789
No files matched your search
@@ -6,7 +6,7 @@ import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import { Toaster } from 'sonner'
|
||||
import { Repos } from './pages/Repos'
|
||||
import { RepoDetail } from './pages/RepoDetail'
|
||||
import { RemoteServer } from './pages/RemoteServer'
|
||||
import { LinkedServerRedirect } from './pages/LinkedServerRedirect'
|
||||
import { RemoteProject } from './pages/RemoteProject'
|
||||
import { SessionDetail } from './pages/SessionDetail'
|
||||
import { Schedules } from './pages/Schedules'
|
||||
@@ -41,6 +41,7 @@ import { useAuth } from '@/hooks/useAuth'
|
||||
import { useOpenCodeFailureToast } from '@/hooks/useOpenCodeFailureToast'
|
||||
import { useOpenCodeServerActions } from '@/hooks/useOpenCodeServerActions'
|
||||
import { useGlobalShortcutActions } from '@/hooks/useGlobalShortcutActions'
|
||||
import { useSidebarServerRouteSync } from '@/hooks/useSidebarServerSelection'
|
||||
import { sessionQueryOptions } from '@/hooks/useOpenCode'
|
||||
import { RestartServerDialog } from '@/components/settings/RestartServerDialog'
|
||||
|
||||
@@ -164,11 +165,13 @@ function AppShell() {
|
||||
const rootRef = useRef<HTMLDivElement>(null)
|
||||
const { openSheet, open } = useMobileTabBar()
|
||||
|
||||
useSidebarServerRouteSync()
|
||||
|
||||
const swipeNav = useSwipeNavigation()
|
||||
|
||||
const getRouteSwipeBackTarget = useCallback(
|
||||
() => getSwipeBackTarget(location.pathname, location.search),
|
||||
[location.pathname, location.search]
|
||||
() => swipeNav?.backTarget() ?? getSwipeBackTarget(location.pathname, location.search),
|
||||
[swipeNav, location.pathname, location.search]
|
||||
)
|
||||
|
||||
const canSwipeBack = useCallback(
|
||||
@@ -315,11 +318,7 @@ const router = createBrowserRouter([
|
||||
},
|
||||
{
|
||||
path: '/servers/:serverId',
|
||||
element: (
|
||||
<ServerScope>
|
||||
<RemoteServer />
|
||||
</ServerScope>
|
||||
),
|
||||
element: <LinkedServerRedirect />,
|
||||
loader: protectedLoader,
|
||||
},
|
||||
{
|
||||
|
||||
@@ -4,6 +4,7 @@ import userEvent from '@testing-library/user-event'
|
||||
import { MemoryRouter, useLocation } from 'react-router-dom'
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import { LinkedServersNav } from './LinkedServersNav'
|
||||
import { useSidebarServerRouteSync } from '@/hooks/useSidebarServerSelection'
|
||||
import { useSidebarServerStore } from '@/stores/sidebarServerStore'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
@@ -41,9 +42,15 @@ function LocationDisplay() {
|
||||
return <div data-testid="location">{`${location.pathname}${location.search}`}</div>
|
||||
}
|
||||
|
||||
function SidebarServerRouteSync() {
|
||||
useSidebarServerRouteSync()
|
||||
return null
|
||||
}
|
||||
|
||||
function renderNav(pathname = '/', variant?: 'sidebar' | 'rail' | 'sheet') {
|
||||
return render(
|
||||
<MemoryRouter initialEntries={[pathname]}>
|
||||
<SidebarServerRouteSync />
|
||||
<LinkedServersNav variant={variant} />
|
||||
<LocationDisplay />
|
||||
</MemoryRouter>,
|
||||
|
||||
@@ -13,8 +13,10 @@ import userEvent from '@testing-library/user-event'
|
||||
import { describe, it, expect, beforeEach } from 'vitest'
|
||||
import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import { MobileTabBar } from './MobileTabBar'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import { useSidebarServerStore } from '@/stores/sidebarServerStore'
|
||||
|
||||
function LocationSpy() {
|
||||
const { pathname, search } = useLocation()
|
||||
@@ -24,6 +26,8 @@ function LocationSpy() {
|
||||
describe('MobileTabBar', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
localStorage.clear()
|
||||
useSidebarServerStore.setState({ serverId: LOCAL_OPENCODE_SERVER_ID })
|
||||
})
|
||||
|
||||
it('renders nothing when useMobile returns false', () => {
|
||||
@@ -194,20 +198,17 @@ describe('MobileTabBar', () => {
|
||||
expect(screen.getByTestId('location')).toHaveTextContent('/assistant')
|
||||
})
|
||||
|
||||
it('renders global tabs on a linked server page without the local Files tab', () => {
|
||||
it('hides the tab bar on a linked server page path', () => {
|
||||
vi.mocked(useMobile).mockReturnValue(true)
|
||||
const queryClient = new QueryClient()
|
||||
render(
|
||||
const { container } = render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/servers/srv_kitchen']}>
|
||||
<MobileTabBar />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
const labels = screen.getAllByRole('button').map((button) => button.textContent)
|
||||
expect(labels).toEqual(['Repos', 'Assistant', 'Schedules', 'More'])
|
||||
expect(screen.queryByText('Files')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Git')).not.toBeInTheDocument()
|
||||
expect(container.firstChild).toBeNull()
|
||||
})
|
||||
|
||||
it('renders global tabs with Git on a linked server project page', () => {
|
||||
@@ -250,14 +251,14 @@ describe('MobileTabBar', () => {
|
||||
expect(screen.getByTestId('location')).toHaveTextContent('dialog=sourceControl')
|
||||
})
|
||||
|
||||
it('opens the repos sheet from the Repos tab on a linked server page', async () => {
|
||||
it('opens the repos sheet from the Repos tab on a linked server project page', async () => {
|
||||
vi.mocked(useMobile).mockReturnValue(true)
|
||||
const queryClient = new QueryClient()
|
||||
const user = userEvent.setup()
|
||||
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/servers/srv_kitchen']}>
|
||||
<MemoryRouter initialEntries={['/servers/srv_kitchen/projects?directory=%2Fhome%2Fme%2Fapp']}>
|
||||
<Routes>
|
||||
<Route path="*" element={<>
|
||||
<MobileTabBar />
|
||||
@@ -319,6 +320,22 @@ describe('MobileTabBar', () => {
|
||||
expect(screen.queryByText('Git')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('hides the Files tab on the home page when a linked server is selected', () => {
|
||||
vi.mocked(useMobile).mockReturnValue(true)
|
||||
useSidebarServerStore.setState({ serverId: 'srv_kitchen' })
|
||||
const queryClient = new QueryClient()
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<MobileTabBar />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
const labels = screen.getAllByRole('button').map((button) => button.textContent)
|
||||
expect(labels).toEqual(['Repos', 'Assistant', 'Schedules', 'More'])
|
||||
expect(screen.queryByText('Files')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders tab bar on /schedules path', () => {
|
||||
vi.mocked(useMobile).mockReturnValue(true)
|
||||
const queryClient = new QueryClient()
|
||||
|
||||
@@ -7,6 +7,8 @@ import { useMobileTabBar } from '@/hooks/useMobileTabBar'
|
||||
import { useUrlParams } from '@/hooks/useUrlParams'
|
||||
import { useScheduleUrlState, type ScheduleTab } from '@/hooks/useScheduleUrlState'
|
||||
import { useUnreadScheduleRuns } from '@/hooks/useSchedules'
|
||||
import { useSidebarServerSelection } from '@/hooks/useSidebarServerSelection'
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import {
|
||||
getAssistantPath,
|
||||
isAssistantPath,
|
||||
@@ -35,11 +37,12 @@ interface GlobalTabsArgs {
|
||||
serverScope: ServerRouteScope
|
||||
updateParams: ReturnType<typeof useUrlParams>['updateParams']
|
||||
unreadScheduleCount: number
|
||||
localServerSelected: boolean
|
||||
}
|
||||
|
||||
type TabBarMode = 'hidden' | 'global' | 'schedule'
|
||||
|
||||
type ServerRouteScope = 'server' | 'project' | null
|
||||
type ServerRouteScope = 'project' | null
|
||||
|
||||
interface MobileTabRouteState {
|
||||
mode: TabBarMode
|
||||
@@ -48,17 +51,8 @@ interface MobileTabRouteState {
|
||||
serverScope: ServerRouteScope
|
||||
}
|
||||
|
||||
const SERVER_PAGE_PATH = /^\/servers\/[^/]+$/
|
||||
const SERVER_PROJECT_PAGE_PATH = /^\/servers\/[^/]+\/projects$/
|
||||
|
||||
function getServerRouteScope(pathname: string, search: string): ServerRouteScope {
|
||||
if (SERVER_PROJECT_PAGE_PATH.test(pathname)) {
|
||||
return parseServerProjectRoute(pathname, search) ? 'project' : 'server'
|
||||
}
|
||||
if (SERVER_PAGE_PATH.test(pathname)) {
|
||||
return 'server'
|
||||
}
|
||||
return null
|
||||
return parseServerProjectRoute(pathname, search) ? 'project' : null
|
||||
}
|
||||
|
||||
function getMobileTabRouteState(pathname: string, search: string): MobileTabRouteState {
|
||||
@@ -71,7 +65,7 @@ function getMobileTabRouteState(pathname: string, search: string): MobileTabRout
|
||||
}
|
||||
|
||||
const serverScope = getServerRouteScope(pathname, search)
|
||||
if (serverScope === 'server' || serverScope === 'project') {
|
||||
if (serverScope !== null) {
|
||||
return { mode: 'global', isInsideRepo: false, repoId: null, serverScope }
|
||||
}
|
||||
|
||||
@@ -91,7 +85,7 @@ function getMobileTabRouteState(pathname: string, search: string): MobileTabRout
|
||||
}
|
||||
}
|
||||
|
||||
function buildGlobalTabs({ pathname, openSheet, open, close, navigate, isInsideRepo, repoId, serverScope, updateParams, unreadScheduleCount }: GlobalTabsArgs): TabDef[] {
|
||||
function buildGlobalTabs({ pathname, openSheet, open, close, navigate, isInsideRepo, repoId, serverScope, updateParams, unreadScheduleCount, localServerSelected }: GlobalTabsArgs): TabDef[] {
|
||||
const openRepoDialog = (dialog: string) => {
|
||||
openDialogParam(updateParams, dialog)
|
||||
}
|
||||
@@ -99,6 +93,7 @@ function buildGlobalTabs({ pathname, openSheet, open, close, navigate, isInsideR
|
||||
const inRepo = isInsideRepo && repoId !== null
|
||||
const inServerRoute = serverScope !== null
|
||||
const filesAreScoped = inRepo || isAssistantPath(pathname)
|
||||
const showsFiles = !inServerRoute && (filesAreScoped || localServerSelected)
|
||||
const showsGit = inRepo || serverScope === 'project'
|
||||
const showsSchedules = !inRepo && serverScope !== 'project'
|
||||
|
||||
@@ -123,7 +118,7 @@ function buildGlobalTabs({ pathname, openSheet, open, close, navigate, isInsideR
|
||||
onClick: () => open('repos'),
|
||||
active: openSheet === 'repos' || (pathname === '/' && !openSheet),
|
||||
},
|
||||
...(!inServerRoute
|
||||
...(showsFiles
|
||||
? [{
|
||||
key: 'files',
|
||||
label: 'Files',
|
||||
@@ -237,6 +232,8 @@ export const MobileTabBar = memo(function MobileTabBar() {
|
||||
const { scheduleTab, setScheduleTab } = useScheduleUrlState()
|
||||
const { data: unreadRuns } = useUnreadScheduleRuns()
|
||||
const isMobile = useMobile()
|
||||
const [selectedServerId] = useSidebarServerSelection()
|
||||
const localServerSelected = selectedServerId === LOCAL_OPENCODE_SERVER_ID
|
||||
const routeState = useMemo(() => getMobileTabRouteState(pathname, search), [pathname, search])
|
||||
const unreadScheduleCount = unreadRuns?.total ?? 0
|
||||
|
||||
@@ -254,6 +251,7 @@ export const MobileTabBar = memo(function MobileTabBar() {
|
||||
serverScope: routeState.serverScope,
|
||||
updateParams,
|
||||
unreadScheduleCount,
|
||||
localServerSelected,
|
||||
})),
|
||||
[
|
||||
routeState,
|
||||
@@ -266,6 +264,7 @@ export const MobileTabBar = memo(function MobileTabBar() {
|
||||
navigate,
|
||||
updateParams,
|
||||
unreadScheduleCount,
|
||||
localServerSelected,
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
@@ -3,12 +3,28 @@ import { Layers } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { MultiRunSheet } from '@/components/repo/MultiRunSheet'
|
||||
|
||||
interface RemoteMultiRunButtonProps {
|
||||
interface RemoteMultiRunProps {
|
||||
serverId: string
|
||||
directory: string
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
}
|
||||
|
||||
export function RemoteMultiRunButton({ serverId, directory }: RemoteMultiRunButtonProps) {
|
||||
/**
|
||||
* The multi-run sheet for one project on a linked OpenCode server, controlled by its caller.
|
||||
*/
|
||||
export function RemoteMultiRun({ serverId, directory, open, onOpenChange }: RemoteMultiRunProps) {
|
||||
return (
|
||||
<MultiRunSheet
|
||||
target={{ kind: 'server', serverId, directory }}
|
||||
directory={directory}
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export function RemoteMultiRunButton({ serverId, directory }: { serverId: string; directory: string }) {
|
||||
const [mounted, setMounted] = useState(false)
|
||||
const [open, setOpen] = useState(false)
|
||||
|
||||
@@ -24,8 +40,8 @@ export function RemoteMultiRunButton({ serverId, directory }: RemoteMultiRunButt
|
||||
Multi-run
|
||||
</Button>
|
||||
{mounted ? (
|
||||
<MultiRunSheet
|
||||
target={{ kind: 'server', serverId, directory }}
|
||||
<RemoteMultiRun
|
||||
serverId={serverId}
|
||||
directory={directory}
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { getRepoDisplayName } from "@/lib/utils";
|
||||
import type { Repo } from "@/api/types";
|
||||
import type { GitStatusResponse } from "@/types/git"
|
||||
import { RepoActivityIndicator } from "@/components/activity/RepoActivityIndicator"
|
||||
import { RepoCardShell } from "./RepoCardShell"
|
||||
import { RepoRowActions } from "./RepoRowActions"
|
||||
|
||||
interface RepoCardProps {
|
||||
@@ -58,90 +59,65 @@ export function RepoCard({
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
onClick={handleCardClick}
|
||||
className={`relative border rounded-xl overflow-hidden transition-all duration-200 w-full ${
|
||||
isReady ? "cursor-pointer active:scale-[0.98] hover:border-primary/50 hover:bg-accent/50 hover:shadow-md" : "cursor-default"
|
||||
} ${
|
||||
isSelected
|
||||
? "border-primary bg-primary/5"
|
||||
: "border-border bg-card"
|
||||
}`}
|
||||
>
|
||||
<div className="p-1.5">
|
||||
<div>
|
||||
<div className="flex items-start gap-2 mb-1">
|
||||
<div className="flex items-center gap-2 min-w-0 flex-1">
|
||||
<h3 className="font-semibold text-base text-foreground truncate">
|
||||
{repoName}
|
||||
</h3>
|
||||
{isReady && (
|
||||
<div className={`w-2 h-2 rounded-full shrink-0 ${isDirty ? 'bg-highlight' : 'bg-success'}`} />
|
||||
)}
|
||||
<RepoActivityIndicator repo={repo} />
|
||||
</div>
|
||||
|
||||
{!manageMode && !isSelected && !hasSelectedRepos && (
|
||||
<RepoRowActions
|
||||
repo={repo}
|
||||
gitStatus={gitStatus}
|
||||
onDelete={onDelete}
|
||||
isDeleting={isDeleting}
|
||||
isMobile={isMobile}
|
||||
onActionsOpenChange={setActionsOpen}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<div className="flex flex-1 items-center gap-2 min-w-0 overflow-hidden">
|
||||
{isCloning ? (
|
||||
<span className="flex items-center gap-1.5">
|
||||
<Loader2 className="w-3.5 h-3.5 animate-spin text-primary" />
|
||||
Cloning...
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
<span className={`flex items-center gap-1 shrink-0 ${repo.isWorktree ? 'text-primary' : ''}`}>
|
||||
<GitBranch className="w-3.5 h-3.5 shrink-0" />
|
||||
<span className="truncate max-w-[80px]">{branchToDisplay || "main"}</span>
|
||||
</span>
|
||||
{isDirty && (
|
||||
<span className="flex items-center gap-1 text-highlight shrink-0">
|
||||
<AlertCircle className="w-3.5 h-3.5 shrink-0" />
|
||||
<span className="text-xs whitespace-nowrap">
|
||||
{unstagedCount > 0 && unstagedCount}
|
||||
{unstagedCount > 0 && stagedCount > 0 && "/"}
|
||||
{stagedCount > 0 && `${stagedCount}s`}
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
{(ahead > 0 || behind > 0) && (
|
||||
<span className="flex items-center gap-1 text-info shrink-0">
|
||||
<span className="text-xs whitespace-nowrap">
|
||||
{ahead > 0 && `↑${ahead}`}
|
||||
{behind > 0 && `↓${behind}`}
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
{repo.isLocal && (
|
||||
<span className="flex items-center gap-1 shrink-0">
|
||||
<FolderOpen className="w-3.5 h-3.5 shrink-0" />
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{activityLabel && (
|
||||
<span className="text-xs text-muted-foreground/70 shrink-0">
|
||||
{activityLabel}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
const meta = isCloning ? (
|
||||
<span className="flex items-center gap-1.5">
|
||||
<Loader2 className="w-3.5 h-3.5 animate-spin text-primary" />
|
||||
Cloning...
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
<span className={`flex items-center gap-1 shrink-0 ${repo.isWorktree ? 'text-primary' : ''}`}>
|
||||
<GitBranch className="w-3.5 h-3.5 shrink-0" />
|
||||
<span className="truncate max-w-[80px]">{branchToDisplay || "main"}</span>
|
||||
</span>
|
||||
{isDirty && (
|
||||
<span className="flex items-center gap-1 text-highlight shrink-0">
|
||||
<AlertCircle className="w-3.5 h-3.5 shrink-0" />
|
||||
<span className="text-xs whitespace-nowrap">
|
||||
{unstagedCount > 0 && unstagedCount}
|
||||
{unstagedCount > 0 && stagedCount > 0 && "/"}
|
||||
{stagedCount > 0 && `${stagedCount}s`}
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
{(ahead > 0 || behind > 0) && (
|
||||
<span className="flex items-center gap-1 text-info shrink-0">
|
||||
<span className="text-xs whitespace-nowrap">
|
||||
{ahead > 0 && `↑${ahead}`}
|
||||
{behind > 0 && `↓${behind}`}
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
{repo.isLocal && (
|
||||
<span className="flex items-center gap-1 shrink-0">
|
||||
<FolderOpen className="w-3.5 h-3.5 shrink-0" />
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<RepoCardShell
|
||||
title={repoName}
|
||||
statusDotClassName={isReady ? (isDirty ? 'bg-highlight' : 'bg-success') : undefined}
|
||||
activity={<RepoActivityIndicator repo={repo} />}
|
||||
actions={
|
||||
!manageMode && !isSelected && !hasSelectedRepos ? (
|
||||
<RepoRowActions
|
||||
repo={repo}
|
||||
gitStatus={gitStatus}
|
||||
onDelete={onDelete}
|
||||
isDeleting={isDeleting}
|
||||
isMobile={isMobile}
|
||||
onActionsOpenChange={setActionsOpen}
|
||||
/>
|
||||
) : undefined
|
||||
}
|
||||
meta={meta}
|
||||
activityLabel={activityLabel}
|
||||
isInteractive={isReady}
|
||||
isSelected={isSelected}
|
||||
onClick={handleCardClick}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
interface RepoCardShellProps {
|
||||
title: string;
|
||||
meta: ReactNode;
|
||||
statusDotClassName?: string;
|
||||
activity?: ReactNode;
|
||||
actions?: ReactNode;
|
||||
activityLabel?: string;
|
||||
isInteractive?: boolean;
|
||||
isSelected?: boolean;
|
||||
onClick?: () => void;
|
||||
}
|
||||
|
||||
export function RepoCardShell({
|
||||
title,
|
||||
meta,
|
||||
statusDotClassName,
|
||||
activity,
|
||||
actions,
|
||||
activityLabel,
|
||||
isInteractive = false,
|
||||
isSelected = false,
|
||||
onClick,
|
||||
}: RepoCardShellProps) {
|
||||
return (
|
||||
<div
|
||||
onClick={onClick}
|
||||
className={`relative border rounded-xl overflow-hidden transition-all duration-200 w-full ${
|
||||
isInteractive ? "cursor-pointer active:scale-[0.98] hover:border-primary/50 hover:bg-accent/50 hover:shadow-md" : "cursor-default"
|
||||
} ${
|
||||
isSelected ? "border-primary bg-primary/5" : "border-border bg-card"
|
||||
}`}
|
||||
>
|
||||
<div className="p-1.5">
|
||||
<div>
|
||||
<div className="flex items-start gap-2 mb-1">
|
||||
<div className="flex items-center gap-2 min-w-0 flex-1">
|
||||
<h3 className="font-semibold text-base text-foreground truncate">
|
||||
{title}
|
||||
</h3>
|
||||
{statusDotClassName && (
|
||||
<div className={`w-2 h-2 rounded-full shrink-0 ${statusDotClassName}`} />
|
||||
)}
|
||||
{activity}
|
||||
</div>
|
||||
|
||||
{actions}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<div className="flex flex-1 items-center gap-2 min-w-0 overflow-hidden">
|
||||
{meta}
|
||||
</div>
|
||||
|
||||
{activityLabel && (
|
||||
<span className="text-xs text-muted-foreground/70 shrink-0">
|
||||
{activityLabel}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useState } from "react";
|
||||
import { Search, SlidersHorizontal, Trash2, X } from "lucide-react";
|
||||
import { SlidersHorizontal, Trash2, X } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { RepoSearchInput } from "./RepoSearchInput";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
@@ -120,17 +120,7 @@ export function RepoListControls({
|
||||
return (
|
||||
<div className="px-2 md:px-0 space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
|
||||
<Input
|
||||
value={searchQuery}
|
||||
onChange={(e) => onSearchChange(e.target.value)}
|
||||
placeholder="Search repositories..."
|
||||
className="pl-9 h-9"
|
||||
autoComplete="off"
|
||||
name="repo-search"
|
||||
/>
|
||||
</div>
|
||||
<RepoSearchInput value={searchQuery} onValueChange={onSearchChange} />
|
||||
|
||||
{isMobile ? (
|
||||
<DropdownMenu open={showMenu} onOpenChange={setShowMenu}>
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { Search } from "lucide-react";
|
||||
import { Input } from "@/components/ui/input";
|
||||
|
||||
interface RepoSearchInputProps {
|
||||
value: string;
|
||||
onValueChange: (query: string) => void;
|
||||
placeholder?: string;
|
||||
name?: string;
|
||||
}
|
||||
|
||||
export function RepoSearchInput({
|
||||
value,
|
||||
onValueChange,
|
||||
placeholder = "Search repositories...",
|
||||
name = "repo-search",
|
||||
}: RepoSearchInputProps) {
|
||||
return (
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
|
||||
<Input
|
||||
value={value}
|
||||
onChange={(event) => onValueChange(event.target.value)}
|
||||
placeholder={placeholder}
|
||||
className="pl-9 h-9"
|
||||
autoComplete="off"
|
||||
name={name}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -4,17 +4,27 @@ import { Button } from '@/components/ui/button'
|
||||
import type { ScheduleServerTarget } from '@/api/schedules'
|
||||
import { ServerSchedulesDialog } from './ServerSchedulesDialog'
|
||||
|
||||
interface RemoteSchedulesButtonProps {
|
||||
interface RemoteSchedulesDialogProps {
|
||||
serverId: string
|
||||
directory: string
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* The schedule list for one project on a linked OpenCode server, controlled by its caller.
|
||||
*/
|
||||
export function RemoteSchedulesDialog({ serverId, directory, open, onOpenChange }: RemoteSchedulesDialogProps) {
|
||||
const target: ScheduleServerTarget = { serverId, directory }
|
||||
|
||||
return <ServerSchedulesDialog open={open} onOpenChange={onOpenChange} target={target} />
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the schedule list for one project on a linked OpenCode server.
|
||||
*/
|
||||
export function RemoteSchedulesButton({ serverId, directory }: RemoteSchedulesButtonProps) {
|
||||
export function RemoteSchedulesButton({ serverId, directory }: { serverId: string; directory: string }) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const target: ScheduleServerTarget = { serverId, directory }
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -28,7 +38,12 @@ export function RemoteSchedulesButton({ serverId, directory }: RemoteSchedulesBu
|
||||
<CalendarClock className="mr-1 h-4 w-4" />
|
||||
<span className="hidden sm:inline">Schedules</span>
|
||||
</Button>
|
||||
<ServerSchedulesDialog open={open} onOpenChange={setOpen} target={target} />
|
||||
<RemoteSchedulesDialog
|
||||
serverId={serverId}
|
||||
directory={directory}
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { OpenCodeServerStatus } from '@opencode-manager/shared/schemas'
|
||||
|
||||
interface ConnectionStatusProps {
|
||||
status?: OpenCodeServerStatus
|
||||
isLoading: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Connection indicator for a linked server: checking, unknown, unreachable with its error, or
|
||||
* connected with the server version.
|
||||
*/
|
||||
export function ConnectionStatus({ status, isLoading }: ConnectionStatusProps) {
|
||||
if (isLoading) {
|
||||
return <span className="text-xs text-muted-foreground">Checking connection...</span>
|
||||
}
|
||||
|
||||
if (!status) {
|
||||
return (
|
||||
<span className="flex items-center gap-1.5 text-xs text-muted-foreground">
|
||||
<span className="h-2 w-2 rounded-full bg-muted-foreground/50" />
|
||||
Unknown
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
if (!status.connected) {
|
||||
return (
|
||||
<span className="flex items-center gap-1.5 text-xs text-destructive" title={status.error ?? undefined}>
|
||||
<span className="h-2 w-2 rounded-full bg-destructive" />
|
||||
Unreachable
|
||||
{status.error ? <span className="text-muted-foreground">· {status.error}</span> : null}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<span className="flex items-center gap-1.5 text-xs text-success">
|
||||
<span className="h-2 w-2 rounded-full bg-success" />
|
||||
Connected
|
||||
{status.version ? <span className="text-muted-foreground">· v{status.version}</span> : null}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
import { useMemo, useState, type FormEvent } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { Folder, FolderGit2, GitBranch, Loader2, Plus, Search, Server } from 'lucide-react'
|
||||
import { listProjects, type OpenCodeProject } from '@/api/opencode'
|
||||
import { useCreateSession } from '@/hooks/useOpenCode'
|
||||
import { useOpenCodeServers } from '@/hooks/useOpenCodeServers'
|
||||
import { useSettingsDialog } from '@/hooks/useSettingsDialog'
|
||||
import { useProjectActivityState } from '@/hooks/useActiveWork'
|
||||
import { serverScopedKey } from '@/lib/serverScope'
|
||||
import { getServerProjectPath, getServerSessionPath } from '@/lib/navigation'
|
||||
import { formatShortRelativeTime, getDirectoryName } from '@/lib/utils'
|
||||
import { OpenCodeServerProvider } from '@/contexts/OpenCodeServerContext'
|
||||
import { ActivityStateIndicator } from '@/components/activity/ActivityStateIndicator'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card } from '@/components/ui/card'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { LinkedServerStateCard } from '@/components/servers/LinkedServerStateCard'
|
||||
import { RemoteProjectRowActions } from '@/components/servers/RemoteProjectRowActions'
|
||||
import { RepoCardShell } from '@/components/repo/RepoCardShell'
|
||||
import { RepoCardSkeleton } from '@/components/repo/RepoCardSkeleton'
|
||||
import { RepoSearchInput } from '@/components/repo/RepoSearchInput'
|
||||
|
||||
function projectName(project: OpenCodeProject): string {
|
||||
return project.name?.trim() || getDirectoryName(project.canonical)
|
||||
}
|
||||
|
||||
function RemoteProjectCard({ project, serverId }: { project: OpenCodeProject; serverId: string }) {
|
||||
const navigate = useNavigate()
|
||||
const activityState = useProjectActivityState(serverId, project.canonical)
|
||||
const updatedAt = project.time.updated
|
||||
|
||||
return (
|
||||
<RepoCardShell
|
||||
title={projectName(project)}
|
||||
statusDotClassName="bg-success"
|
||||
activity={<ActivityStateIndicator state={activityState} />}
|
||||
actions={<RemoteProjectRowActions serverId={serverId} directory={project.canonical} />}
|
||||
meta={
|
||||
<span className="flex items-center gap-1 min-w-0">
|
||||
{project.vcs ? (
|
||||
<GitBranch className="w-3.5 h-3.5 shrink-0" aria-label={project.vcs} />
|
||||
) : (
|
||||
<Folder className="w-3.5 h-3.5 shrink-0" />
|
||||
)}
|
||||
<span className="truncate">{project.canonical}</span>
|
||||
</span>
|
||||
}
|
||||
activityLabel={updatedAt > 0 ? formatShortRelativeTime(new Date(updatedAt)) : undefined}
|
||||
isInteractive
|
||||
onClick={() => navigate(getServerProjectPath(serverId, project.canonical))}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function RemoteProjectListLoading() {
|
||||
return (
|
||||
<div className="flex flex-1 flex-col">
|
||||
<div className="px-2 md:px-0">
|
||||
<div className="h-10 bg-muted/50 animate-pulse rounded w-full" />
|
||||
</div>
|
||||
<div className="mx-2 md:mx-0 flex-1 min-h-0">
|
||||
<div className="h-full overflow-y-auto pt-4 pb-2 md:pb-0">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-2 gap-3 md:gap-4 w-full">
|
||||
{Array.from({ length: 6 }).map((_, index) => (
|
||||
<RepoCardSkeleton key={index} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function RemoteProjectListContent({ serverId }: { serverId: string }) {
|
||||
const navigate = useNavigate()
|
||||
const { servers, isLoading: serversLoading } = useOpenCodeServers()
|
||||
const { openTab } = useSettingsDialog()
|
||||
const createSession = useCreateSession()
|
||||
const [openDirectory, setOpenDirectory] = useState('')
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
|
||||
const server = servers.find((candidate) => candidate.id === serverId)
|
||||
const isDisabled = server !== undefined && !server.enabled
|
||||
|
||||
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 filteredProjects = useMemo(() => {
|
||||
const query = searchQuery.trim().toLowerCase()
|
||||
if (!query) return projects
|
||||
|
||||
return projects.filter((project) =>
|
||||
projectName(project).toLowerCase().includes(query) ||
|
||||
project.canonical.toLowerCase().includes(query),
|
||||
)
|
||||
}, [projects, searchQuery])
|
||||
|
||||
const openSettings = () => openTab('servers')
|
||||
|
||||
const handleOpenDirectory = async (event: FormEvent) => {
|
||||
event.preventDefault()
|
||||
const directory = openDirectory.trim()
|
||||
if (!directory) return
|
||||
try {
|
||||
const session = await createSession.mutateAsync({ directory })
|
||||
navigate(getServerSessionPath(serverId, session.id))
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col px-0 md:p-4">
|
||||
{!serversLoading && !server ? (
|
||||
<LinkedServerStateCard
|
||||
icon={Server}
|
||||
title="Server not found"
|
||||
description="This linked server is no longer configured."
|
||||
actionLabel="Open server settings"
|
||||
onAction={openSettings}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{isDisabled ? (
|
||||
<LinkedServerStateCard
|
||||
icon={Server}
|
||||
title="This server is disabled"
|
||||
description="Enable it in Settings → Servers to browse its projects and sessions."
|
||||
actionLabel="Open server settings"
|
||||
onAction={openSettings}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{server && !isDisabled && projectsQuery.isError ? (
|
||||
<Card className="flex flex-col items-center gap-3 p-6 text-center">
|
||||
<Server className="h-8 w-8 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="font-medium">Could not load projects</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{projectsQuery.error instanceof Error
|
||||
? projectsQuery.error.message
|
||||
: 'The server did not respond.'}
|
||||
</p>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" onClick={() => void projectsQuery.refetch()}>
|
||||
Retry
|
||||
</Button>
|
||||
</Card>
|
||||
) : null}
|
||||
|
||||
{server && !isDisabled && !projectsQuery.isError ? (
|
||||
projectsQuery.isLoading ? (
|
||||
<RemoteProjectListLoading />
|
||||
) : projects.length === 0 ? (
|
||||
<div className="flex flex-1 flex-col items-center justify-center p-12 text-center">
|
||||
<FolderGit2 className="w-12 h-12 mx-auto mb-4 text-muted-foreground" />
|
||||
<p className="font-medium">No projects on this server yet</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Start a session in a directory below to create one.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="px-2 md:px-0">
|
||||
<RepoSearchInput
|
||||
value={searchQuery}
|
||||
onValueChange={setSearchQuery}
|
||||
placeholder="Search projects..."
|
||||
name="remote-project-search"
|
||||
/>
|
||||
</div>
|
||||
<div className="mx-2 flex min-h-0 flex-1 md:mx-0">
|
||||
<div className="h-full w-full overflow-y-auto pt-4 md:pb-0 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
|
||||
{filteredProjects.length === 0 ? (
|
||||
<div className="text-center p-12">
|
||||
<Search className="w-12 h-12 mx-auto mb-4 text-muted-foreground" />
|
||||
<p className="text-muted-foreground">
|
||||
No projects found matching "{searchQuery}"
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-2 gap-3 md:gap-4 w-full md:pb-0">
|
||||
{filteredProjects.map((project) => (
|
||||
<RemoteProjectCard
|
||||
key={project.id}
|
||||
project={project}
|
||||
serverId={serverId}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
) : null}
|
||||
|
||||
{server && !isDisabled ? (
|
||||
<section aria-label="Open directory" className="mt-4 flex shrink-0 flex-col gap-2 px-2 md:px-0">
|
||||
<h2 className="text-xs font-medium uppercase tracking-wider text-muted-foreground">Open directory</h2>
|
||||
<form onSubmit={handleOpenDirectory} className="flex items-center gap-2">
|
||||
<Input
|
||||
value={openDirectory}
|
||||
onChange={(event) => setOpenDirectory(event.target.value)}
|
||||
placeholder="/absolute/path/on/the/server"
|
||||
aria-label="Directory path"
|
||||
autoComplete="off"
|
||||
name="remote-directory"
|
||||
className="font-mono text-sm"
|
||||
/>
|
||||
<Button type="submit" disabled={!openDirectory.trim() || createSession.isPending} className="shrink-0">
|
||||
{createSession.isPending ? (
|
||||
<Loader2 className="mr-1 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Plus className="mr-1 h-4 w-4" />
|
||||
)}
|
||||
Start session
|
||||
</Button>
|
||||
</form>
|
||||
</section>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The projects of one linked server with their sessions and project actions, scoped to that server
|
||||
* so every hook inside it targets the linked server rather than the local one.
|
||||
*/
|
||||
export function RemoteProjectList({ serverId }: { serverId: string }) {
|
||||
return (
|
||||
<OpenCodeServerProvider serverId={serverId}>
|
||||
<RemoteProjectListContent serverId={serverId} />
|
||||
</OpenCodeServerProvider>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
import { useState, type ReactNode } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { CalendarClock, Layers, Loader2, MoreVertical, Plus } from 'lucide-react'
|
||||
import { useCreateSession } from '@/hooks/useOpenCode'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import { getServerSessionPath } from '@/lib/navigation'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
|
||||
import { RemoteSchedulesDialog } from '@/components/schedules/RemoteSchedulesButton'
|
||||
import { RemoteMultiRun } from '@/components/repo/RemoteMultiRunButton'
|
||||
|
||||
interface RemoteProjectRowActionsProps {
|
||||
serverId: string
|
||||
directory: string
|
||||
}
|
||||
|
||||
interface ProjectActionButtonProps {
|
||||
label: string
|
||||
onClick: () => void
|
||||
disabled?: boolean
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
function ProjectActionButton({ label, onClick, disabled, children }: ProjectActionButtonProps) {
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
aria-label={label}
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={onClick}
|
||||
disabled={disabled}
|
||||
className="h-8 w-8 p-0"
|
||||
title={label}
|
||||
>
|
||||
{children}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{label}</TooltipContent>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The project actions for one remote project: new session, schedules, and multi-run. Desktop shows
|
||||
* inline icon buttons and mobile shows a menu, matching local repository rows.
|
||||
*/
|
||||
export function RemoteProjectRowActions({ serverId, directory }: RemoteProjectRowActionsProps) {
|
||||
const navigate = useNavigate()
|
||||
const isMobile = useMobile()
|
||||
const createSession = useCreateSession(directory)
|
||||
const [schedulesOpen, setSchedulesOpen] = useState(false)
|
||||
const [multiRunMounted, setMultiRunMounted] = useState(false)
|
||||
const [multiRunOpen, setMultiRunOpen] = useState(false)
|
||||
|
||||
const handleNewSession = async () => {
|
||||
try {
|
||||
const session = await createSession.mutateAsync({ agent: undefined })
|
||||
navigate(getServerSessionPath(serverId, session.id))
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
const handleMultiRunOpen = () => {
|
||||
setMultiRunMounted(true)
|
||||
setMultiRunOpen(true)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="contents" onClick={(event) => event.stopPropagation()}>
|
||||
{isMobile ? (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
aria-label="Project actions"
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="h-8 w-8 p-0"
|
||||
title="Project actions"
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<MoreVertical className="w-4 h-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent
|
||||
align="end"
|
||||
className="z-[200]"
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
onPointerDown={(event) => event.stopPropagation()}
|
||||
>
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
void handleNewSession()
|
||||
}}
|
||||
disabled={createSession.isPending}
|
||||
>
|
||||
{createSession.isPending ? (
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
) : (
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
)}
|
||||
New session
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setSchedulesOpen(true)}>
|
||||
<CalendarClock className="w-4 h-4 mr-2" />
|
||||
Schedules
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={handleMultiRunOpen}>
|
||||
<Layers className="w-4 h-4 mr-2" />
|
||||
Multi-run
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
) : (
|
||||
<TooltipProvider delayDuration={200}>
|
||||
<div className="flex items-center gap-1">
|
||||
<ProjectActionButton
|
||||
label="New session"
|
||||
onClick={() => {
|
||||
void handleNewSession()
|
||||
}}
|
||||
disabled={createSession.isPending}
|
||||
>
|
||||
{createSession.isPending ? <Loader2 className="w-4 h-4 animate-spin" /> : <Plus className="w-4 h-4" />}
|
||||
</ProjectActionButton>
|
||||
<ProjectActionButton label="Schedules" onClick={() => setSchedulesOpen(true)}>
|
||||
<CalendarClock className="w-4 h-4" />
|
||||
</ProjectActionButton>
|
||||
<ProjectActionButton label="Multi-run" onClick={handleMultiRunOpen}>
|
||||
<Layers className="w-4 h-4" />
|
||||
</ProjectActionButton>
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
)}
|
||||
|
||||
<RemoteSchedulesDialog
|
||||
serverId={serverId}
|
||||
directory={directory}
|
||||
open={schedulesOpen}
|
||||
onOpenChange={setSchedulesOpen}
|
||||
/>
|
||||
{multiRunMounted ? (
|
||||
<RemoteMultiRun
|
||||
serverId={serverId}
|
||||
directory={directory}
|
||||
open={multiRunOpen}
|
||||
onOpenChange={setMultiRunOpen}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { MemoryRouter, Route, Routes } from 'react-router-dom'
|
||||
import { RemoteProjectList } from '../RemoteProjectList'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
listProjects: vi.fn(),
|
||||
useCreateSession: vi.fn(),
|
||||
useOpenCodeServers: vi.fn(),
|
||||
useSettingsDialog: vi.fn(),
|
||||
openTab: vi.fn(),
|
||||
createSession: vi.fn(),
|
||||
isMobile: true,
|
||||
}))
|
||||
|
||||
vi.mock('@/api/opencode', () => ({
|
||||
listProjects: mocks.listProjects,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useOpenCode', () => ({
|
||||
useCreateSession: mocks.useCreateSession,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useOpenCodeServers', () => ({
|
||||
useOpenCodeServers: mocks.useOpenCodeServers,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useSettingsDialog', () => ({
|
||||
useSettingsDialog: mocks.useSettingsDialog,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useMobile', () => ({
|
||||
useMobile: () => mocks.isMobile,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useActiveWork', () => ({
|
||||
useProjectActivityState: () => null,
|
||||
}))
|
||||
|
||||
vi.mock('@/components/schedules/ServerSchedulesDialog', () => ({
|
||||
ServerSchedulesDialog: ({
|
||||
open,
|
||||
target,
|
||||
}: {
|
||||
open: boolean
|
||||
target: { serverId: string; directory: string } | null
|
||||
}) =>
|
||||
open ? (
|
||||
<div
|
||||
data-testid="schedules-dialog"
|
||||
data-server={target?.serverId}
|
||||
data-directory={target?.directory}
|
||||
/>
|
||||
) : null,
|
||||
}))
|
||||
|
||||
vi.mock('@/components/repo/MultiRunSheet', () => ({
|
||||
MultiRunSheet: ({
|
||||
open,
|
||||
target,
|
||||
directory,
|
||||
}: {
|
||||
open: boolean
|
||||
target: { kind: string; serverId?: string; directory?: string }
|
||||
directory?: string
|
||||
}) => (
|
||||
<div
|
||||
data-testid="multi-run-sheet"
|
||||
data-open={String(open)}
|
||||
data-kind={target.kind}
|
||||
data-server={target.serverId}
|
||||
data-directory={directory}
|
||||
/>
|
||||
),
|
||||
}))
|
||||
|
||||
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',
|
||||
vcs: 'git',
|
||||
time: { created: Date.now() - 120_000, updated: Date.now() - 60_000, active: 2 },
|
||||
sandboxes: [],
|
||||
}
|
||||
|
||||
const otherProject = {
|
||||
id: 'prj_2',
|
||||
canonical: '/srv/other',
|
||||
name: 'Other',
|
||||
time: { created: Date.now() - 120_000, updated: Date.now() - 60_000, active: 2 },
|
||||
sandboxes: [],
|
||||
}
|
||||
|
||||
function createQueryClient() {
|
||||
return new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
}
|
||||
|
||||
function renderProjectList(serverId = 'srv_kitchen') {
|
||||
return render(
|
||||
<QueryClientProvider client={createQueryClient()}>
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<Routes>
|
||||
<Route path="/" element={<RemoteProjectList serverId={serverId} />} />
|
||||
<Route path="/servers/:serverId/projects" element={<div data-testid="project-route" />} />
|
||||
<Route path="/servers/:serverId/sessions/:sessionId" element={<div data-testid="session-route" />} />
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
}
|
||||
|
||||
describe('RemoteProjectList', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.isMobile = true
|
||||
mocks.listProjects.mockResolvedValue([project])
|
||||
mocks.useCreateSession.mockReturnValue({ mutateAsync: mocks.createSession, isPending: false })
|
||||
mocks.useOpenCodeServers.mockReturnValue({ servers: [server], isLoading: false })
|
||||
mocks.useSettingsDialog.mockReturnValue({ openTab: mocks.openTab })
|
||||
})
|
||||
|
||||
it('lists projects from the remote server', async () => {
|
||||
renderProjectList()
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('App')).toBeInTheDocument()
|
||||
})
|
||||
expect(screen.getByText('/home/me/app')).toBeInTheDocument()
|
||||
expect(mocks.listProjects).toHaveBeenCalledWith('srv_kitchen')
|
||||
})
|
||||
|
||||
it('opens the remote project page when a project card is clicked', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderProjectList()
|
||||
|
||||
await user.click(await screen.findByText('App'))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('project-route')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
it('creates a session in a project directory from the actions menu and navigates to it', async () => {
|
||||
const user = userEvent.setup()
|
||||
mocks.createSession.mockResolvedValue({ id: 'ses_new' })
|
||||
renderProjectList()
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'Project actions' }))
|
||||
await user.click(await screen.findByRole('menuitem', { name: /New session/ }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.createSession).toHaveBeenCalledWith({ agent: undefined })
|
||||
})
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('session-route')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
it('opens the project schedules from the actions menu', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderProjectList()
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'Project actions' }))
|
||||
await user.click(await screen.findByRole('menuitem', { name: /Schedules/ }))
|
||||
|
||||
const dialog = await screen.findByTestId('schedules-dialog')
|
||||
expect(dialog).toHaveAttribute('data-server', 'srv_kitchen')
|
||||
expect(dialog).toHaveAttribute('data-directory', '/home/me/app')
|
||||
|
||||
await user.click(dialog)
|
||||
expect(screen.queryByTestId('project-route')).not.toBeInTheDocument()
|
||||
expect(screen.getByTestId('schedules-dialog')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('opens multi-run for the project from the actions menu', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderProjectList()
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'Project actions' }))
|
||||
await user.click(await screen.findByRole('menuitem', { name: /Multi-run/ }))
|
||||
|
||||
const sheet = await screen.findByTestId('multi-run-sheet')
|
||||
expect(sheet).toHaveAttribute('data-open', 'true')
|
||||
expect(sheet).toHaveAttribute('data-kind', 'server')
|
||||
expect(sheet).toHaveAttribute('data-server', 'srv_kitchen')
|
||||
expect(sheet).toHaveAttribute('data-directory', '/home/me/app')
|
||||
})
|
||||
|
||||
it('shows inline project actions on desktop without opening the project', async () => {
|
||||
const user = userEvent.setup()
|
||||
mocks.isMobile = false
|
||||
renderProjectList()
|
||||
|
||||
await screen.findByText('App')
|
||||
expect(screen.queryByRole('button', { name: 'Project actions' })).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'New session' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Multi-run' })).toBeInTheDocument()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Schedules' }))
|
||||
|
||||
expect(await screen.findByTestId('schedules-dialog')).toHaveAttribute('data-directory', '/home/me/app')
|
||||
expect(screen.queryByTestId('project-route')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('opens a session in an arbitrary directory', async () => {
|
||||
const user = userEvent.setup()
|
||||
mocks.createSession.mockResolvedValue({ id: 'ses_other' })
|
||||
renderProjectList()
|
||||
|
||||
await user.type(screen.getByLabelText('Directory path'), '/srv/other')
|
||||
await user.click(screen.getByRole('button', { name: /Start session/ }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.createSession).toHaveBeenCalledWith({ directory: '/srv/other' })
|
||||
})
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('session-route')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
it('filters projects by name and path', async () => {
|
||||
const user = userEvent.setup()
|
||||
mocks.listProjects.mockResolvedValue([project, otherProject])
|
||||
renderProjectList()
|
||||
|
||||
await screen.findByText('App')
|
||||
const search = screen.getByPlaceholderText('Search projects...')
|
||||
|
||||
await user.type(search, '/srv/other')
|
||||
expect(screen.queryByText('App')).not.toBeInTheDocument()
|
||||
expect(screen.getByText('Other')).toBeInTheDocument()
|
||||
|
||||
await user.clear(search)
|
||||
await user.type(search, 'app')
|
||||
expect(screen.getByText('App')).toBeInTheDocument()
|
||||
expect(screen.queryByText('Other')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows an empty search result state', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderProjectList()
|
||||
|
||||
await screen.findByText('App')
|
||||
await user.type(screen.getByPlaceholderText('Search projects...'), 'missing')
|
||||
|
||||
expect(screen.getByText('No projects found matching "missing"')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows the disabled state without loading projects', async () => {
|
||||
mocks.useOpenCodeServers.mockReturnValue({
|
||||
servers: [{ ...server, enabled: false }],
|
||||
isLoading: false,
|
||||
})
|
||||
|
||||
renderProjectList()
|
||||
|
||||
expect(screen.getByText('This server is disabled')).toBeInTheDocument()
|
||||
expect(mocks.listProjects).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('shows a missing server state when the server is no longer configured', async () => {
|
||||
mocks.useOpenCodeServers.mockReturnValue({ servers: [], isLoading: false })
|
||||
|
||||
renderProjectList('srv_gone')
|
||||
|
||||
expect(screen.getByText('Server not found')).toBeInTheDocument()
|
||||
expect(mocks.listProjects).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('shows an empty state when the server has no projects', async () => {
|
||||
mocks.listProjects.mockResolvedValue([])
|
||||
|
||||
renderProjectList()
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('No projects on this server yet')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
it('scopes the list to the given server rather than the route', async () => {
|
||||
renderProjectList('srv_kitchen')
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.listProjects).toHaveBeenCalledWith('srv_kitchen')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { renderHook } from '@testing-library/react'
|
||||
import { renderHook, act } from '@testing-library/react'
|
||||
import { SwipeNavigationProvider, useSwipeNavigation } from './SwipeNavigationContext'
|
||||
|
||||
describe('SwipeNavigationContext', () => {
|
||||
@@ -47,6 +47,24 @@ describe('SwipeNavigationContext', () => {
|
||||
expect(current?.isSuspended()).toBe(false)
|
||||
})
|
||||
|
||||
it('round-trips a page back target', () => {
|
||||
const { result } = renderHook(() => useSwipeNavigation(), {
|
||||
wrapper: SwipeNavigationProvider,
|
||||
})
|
||||
|
||||
expect(result.current?.backTarget()).toBeNull()
|
||||
|
||||
act(() => {
|
||||
result.current?.setBackTarget('/servers/srv_kitchen/projects?directory=%2Fhome%2Fme%2Fapp')
|
||||
})
|
||||
expect(result.current?.backTarget()).toBe('/servers/srv_kitchen/projects?directory=%2Fhome%2Fme%2Fapp')
|
||||
|
||||
act(() => {
|
||||
result.current?.setBackTarget(null)
|
||||
})
|
||||
expect(result.current?.backTarget()).toBeNull()
|
||||
})
|
||||
|
||||
it('clamps resume below zero to zero', () => {
|
||||
let current: ReturnType<typeof useSwipeNavigation>
|
||||
|
||||
|
||||
@@ -5,12 +5,17 @@ interface SwipeNavigationValue {
|
||||
suspend: () => void
|
||||
resume: () => void
|
||||
isSuspended: () => boolean
|
||||
/** Overrides the URL-derived swipe-back destination for the current page; pass null to clear it. */
|
||||
setBackTarget: (path: string | null) => void
|
||||
/** Returns the page-registered swipe-back destination, or null when the URL should decide. */
|
||||
backTarget: () => string | null
|
||||
}
|
||||
|
||||
export const SwipeNavigationContext = createContext<SwipeNavigationValue | null>(null)
|
||||
|
||||
function SwipeNavigationProvider({ children }: { children: ReactNode }) {
|
||||
const countRef = useRef(0)
|
||||
const backTargetRef = useRef<string | null>(null)
|
||||
const value = useMemo<SwipeNavigationValue>(
|
||||
() => ({
|
||||
suspend: () => {
|
||||
@@ -20,6 +25,10 @@ function SwipeNavigationProvider({ children }: { children: ReactNode }) {
|
||||
countRef.current = Math.max(0, countRef.current - 1)
|
||||
},
|
||||
isSuspended: () => countRef.current > 0,
|
||||
setBackTarget: (path) => {
|
||||
backTargetRef.current = path
|
||||
},
|
||||
backTarget: () => backTargetRef.current,
|
||||
}),
|
||||
[]
|
||||
)
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
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 { MemoryRouter, useLocation, useNavigate } from 'react-router-dom'
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import { useSidebarServerSelection } from './useSidebarServerSelection'
|
||||
import { useSidebarServerRouteSync, useSidebarServerSelection } from './useSidebarServerSelection'
|
||||
import { SIDEBAR_SERVER_STORAGE_KEY, useSidebarServerStore } from '@/stores/sidebarServerStore'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
@@ -27,12 +27,18 @@ const kitchen = {
|
||||
|
||||
const office = { ...kitchen, id: 'srv_office', name: 'Office' }
|
||||
|
||||
function SelectionHarness() {
|
||||
function RouteSync() {
|
||||
useSidebarServerRouteSync()
|
||||
return null
|
||||
}
|
||||
|
||||
function SelectionHarness({ syncRoute = true }: { syncRoute?: boolean }) {
|
||||
const [serverId, selectServer] = useSidebarServerSelection()
|
||||
const navigate = useNavigate()
|
||||
|
||||
return (
|
||||
<>
|
||||
{syncRoute ? <RouteSync /> : null}
|
||||
<div data-testid="selected">{serverId}</div>
|
||||
<button type="button" onClick={() => selectServer('srv_kitchen')}>
|
||||
Select kitchen
|
||||
@@ -47,31 +53,74 @@ function SelectionHarness() {
|
||||
)
|
||||
}
|
||||
|
||||
function renderHarness(initialEntry = '/') {
|
||||
function RouteOnlyHarness() {
|
||||
useSidebarServerRouteSync()
|
||||
const navigate = useNavigate()
|
||||
const { pathname } = useLocation()
|
||||
|
||||
return (
|
||||
<>
|
||||
<div data-testid="location">{pathname}</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => navigate('/servers/srv_kitchen/projects?directory=%2Fprojects%2Falpha')}
|
||||
>
|
||||
Open remote project
|
||||
</button>
|
||||
<button type="button" onClick={() => navigate('/')}>
|
||||
Go home
|
||||
</button>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function renderHarness(initialEntry = '/', options?: { syncRoute?: boolean }) {
|
||||
return render(
|
||||
<MemoryRouter initialEntries={[initialEntry]}>
|
||||
<SelectionHarness />
|
||||
<SelectionHarness syncRoute={options?.syncRoute} />
|
||||
</MemoryRouter>,
|
||||
)
|
||||
}
|
||||
|
||||
describe('useSidebarServerSelection', () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear()
|
||||
useSidebarServerStore.setState({ serverId: LOCAL_OPENCODE_SERVER_ID })
|
||||
mocks.useOpenCodeServers.mockReturnValue({
|
||||
servers: [kitchen, office],
|
||||
isLoading: false,
|
||||
isSuccess: true,
|
||||
})
|
||||
function resetSelection() {
|
||||
localStorage.clear()
|
||||
useSidebarServerStore.setState({ serverId: LOCAL_OPENCODE_SERVER_ID })
|
||||
mocks.useOpenCodeServers.mockReturnValue({
|
||||
servers: [kitchen, office],
|
||||
isLoading: false,
|
||||
isSuccess: true,
|
||||
})
|
||||
}
|
||||
|
||||
describe('useSidebarServerSelection', () => {
|
||||
beforeEach(resetSelection)
|
||||
|
||||
it('defaults to the local server', () => {
|
||||
renderHarness()
|
||||
renderHarness('/', { syncRoute: false })
|
||||
|
||||
expect(screen.getByTestId('selected')).toHaveTextContent(LOCAL_OPENCODE_SERVER_ID)
|
||||
})
|
||||
|
||||
it('persists the selection', () => {
|
||||
renderHarness('/', { syncRoute: false })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Select kitchen' }))
|
||||
|
||||
expect(JSON.parse(localStorage.getItem(SIDEBAR_SERVER_STORAGE_KEY) ?? 'null')).toBe(
|
||||
'srv_kitchen',
|
||||
)
|
||||
})
|
||||
|
||||
it('does not follow the route without the route sync', () => {
|
||||
renderHarness('/servers/srv_kitchen', { syncRoute: false })
|
||||
|
||||
expect(screen.getByTestId('selected')).toHaveTextContent(LOCAL_OPENCODE_SERVER_ID)
|
||||
})
|
||||
})
|
||||
|
||||
describe('useSidebarServerRouteSync', () => {
|
||||
beforeEach(resetSelection)
|
||||
|
||||
it('selects the server named by a linked server route', async () => {
|
||||
renderHarness('/servers/srv_kitchen/projects?directory=%2Fprojects%2Falpha')
|
||||
|
||||
@@ -88,6 +137,14 @@ describe('useSidebarServerSelection', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('keeps a persisted linked selection on the home route', async () => {
|
||||
useSidebarServerStore.setState({ serverId: 'srv_kitchen' })
|
||||
|
||||
renderHarness('/')
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('selected')).toHaveTextContent('srv_kitchen'))
|
||||
})
|
||||
|
||||
it('keeps a manual selection while the local route stays unchanged', async () => {
|
||||
renderHarness('/repos/1')
|
||||
|
||||
@@ -158,13 +215,20 @@ describe('useSidebarServerSelection', () => {
|
||||
)
|
||||
})
|
||||
|
||||
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',
|
||||
it('follows a linked server route with no sidebar consumer mounted', async () => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<RouteOnlyHarness />
|
||||
</MemoryRouter>,
|
||||
)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Open remote project' }))
|
||||
|
||||
await waitFor(() => expect(useSidebarServerStore.getState().serverId).toBe('srv_kitchen'))
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Go home' }))
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('location').textContent).toBe('/'))
|
||||
expect(useSidebarServerStore.getState().serverId).toBe('srv_kitchen')
|
||||
})
|
||||
})
|
||||
@@ -10,11 +10,12 @@ function isLocalRoute(pathname: string): boolean {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 in a successfully loaded list falls back to local.
|
||||
* Keeps the sidebar server selection in step with the location and the linked server list: a linked
|
||||
* server route selects that server, a local repo or assistant route selects local, and a selected
|
||||
* server that is missing or disabled in a successfully loaded list falls back to local. Mounted once
|
||||
* by the app shell so the selection follows the route even when no sidebar consumer is rendered.
|
||||
*/
|
||||
export function useSidebarServerSelection(): [string, (serverId: string) => void] {
|
||||
export function useSidebarServerRouteSync(): void {
|
||||
const { pathname } = useLocation()
|
||||
const routeServerId = useMatch('/servers/:serverId/*')?.params.serverId
|
||||
const { servers, isSuccess } = useOpenCodeServers()
|
||||
@@ -39,6 +40,15 @@ export function useSidebarServerSelection(): [string, (serverId: string) => void
|
||||
selectServer(LOCAL_OPENCODE_SERVER_ID)
|
||||
}
|
||||
}, [isSuccess, servers, serverId, selectServer])
|
||||
}
|
||||
|
||||
/**
|
||||
* The linked server selected in the sidebar, defaulting to the local server. Selecting a server
|
||||
* never navigates; `useSidebarServerRouteSync` keeps the selection aligned with the route.
|
||||
*/
|
||||
export function useSidebarServerSelection(): [string, (serverId: string) => void] {
|
||||
const serverId = useSidebarServerStore((state) => state.serverId)
|
||||
const selectServer = useSidebarServerStore((state) => state.selectServer)
|
||||
|
||||
return [serverId, selectServer]
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { getSessionListPath, getSwipeBackTarget, getAssistantPath, getAssistantSessionListPath, isAssistantPath, getPathWithReturnTo, getReturnToPath, getRepoPath, getServerPath, getServerProjectPath, getServerSessionPath, getSessionPath, parseRepoRoute, parseServerProjectRoute, parseServerSessionRoute } from './navigation';
|
||||
import { getSessionListPath, getSwipeBackTarget, getAssistantPath, getAssistantSessionListPath, isAssistantPath, getPathWithReturnTo, getReturnToPath, getRepoPath, getServerProjectPath, getServerSessionPath, getSessionPath, parseRepoRoute, parseServerProjectRoute, parseServerSessionRoute } from './navigation';
|
||||
|
||||
describe('getAssistantPath', () => {
|
||||
it('returns /assistant', () => {
|
||||
@@ -97,7 +97,6 @@ describe('getSessionPath', () => {
|
||||
|
||||
describe('linked server paths', () => {
|
||||
it('builds server and server session paths with encoded segments', () => {
|
||||
expect(getServerPath('srv_kitchen')).toBe('/servers/srv_kitchen');
|
||||
expect(getServerSessionPath('srv_kitchen', 'ses_1')).toBe('/servers/srv_kitchen/sessions/ses_1');
|
||||
expect(getServerSessionPath('srv a/b', 'ses 1')).toBe('/servers/srv%20a%2Fb/sessions/ses%201');
|
||||
});
|
||||
@@ -247,18 +246,18 @@ describe('getSwipeBackTarget', () => {
|
||||
});
|
||||
|
||||
describe('linked server routes', () => {
|
||||
it('returns the server page for a remote session detail', () => {
|
||||
expect(getSwipeBackTarget('/servers/srv_kitchen/sessions/ses_1', '')).toBe('/servers/srv_kitchen');
|
||||
it('returns root for a remote session detail', () => {
|
||||
expect(getSwipeBackTarget('/servers/srv_kitchen/sessions/ses_1', '')).toBe('/');
|
||||
});
|
||||
|
||||
it('returns root for a server page', () => {
|
||||
expect(getSwipeBackTarget('/servers/srv_kitchen', '')).toBe('/');
|
||||
});
|
||||
|
||||
it('returns the server page for a remote project page', () => {
|
||||
it('returns root for a remote project page', () => {
|
||||
expect(
|
||||
getSwipeBackTarget('/servers/srv_kitchen/projects', '?directory=%2Fhome%2Fme%2Fapp')
|
||||
).toBe('/servers/srv_kitchen');
|
||||
).toBe('/');
|
||||
});
|
||||
|
||||
it('does not throw for a malformed server session path', () => {
|
||||
|
||||
@@ -28,10 +28,6 @@ export function getSessionPath(repoId: number | string, sessionId: string, optio
|
||||
return buildSessionPath(repoId, sessionId, options);
|
||||
}
|
||||
|
||||
export function getServerPath(serverId: string): string {
|
||||
return `/servers/${encodeURIComponent(serverId)}`;
|
||||
}
|
||||
|
||||
export function getServerSessionPath(serverId: string, sessionId: string): string {
|
||||
return buildServerSessionPath(serverId, sessionId);
|
||||
}
|
||||
@@ -119,12 +115,12 @@ 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);
|
||||
return '/';
|
||||
}
|
||||
|
||||
const serverSession = parseServerSessionRoute(pathname);
|
||||
if (serverSession) {
|
||||
return getServerPath(serverSession.serverId);
|
||||
return '/';
|
||||
}
|
||||
|
||||
if (/^\/servers\/[^/]+$/.test(pathname)) {
|
||||
|
||||
@@ -29,7 +29,7 @@ import { useDebouncedValue } from '@/hooks/useDebouncedValue'
|
||||
|
||||
import type { ScheduleJobWithRepo, ScheduleRunWithContext } from '@/api/schedules'
|
||||
import { Combobox } from '@/components/ui/combobox'
|
||||
import { getRepoPath, getServerPath } from '@/lib/navigation'
|
||||
import { getRepoPath, getServerProjectPath } from '@/lib/navigation'
|
||||
|
||||
type StatusFilter = 'all' | 'enabled' | 'disabled'
|
||||
type ScheduleModeFilter = 'all' | 'cron' | 'interval'
|
||||
@@ -49,6 +49,10 @@ function targetForRun(run: ScheduleRunWithContext): ScheduleTargetRef | null {
|
||||
return run.serverId ? { kind: 'server', serverId: run.serverId } : null
|
||||
}
|
||||
|
||||
function getLinkedServerJobPath(job: ScheduleJobWithRepo): string {
|
||||
return job.serverId && job.directory ? getServerProjectPath(job.serverId, job.directory) : '/'
|
||||
}
|
||||
|
||||
export function GlobalSchedules() {
|
||||
const navigate = useNavigate()
|
||||
const [selectedRepoId, setSelectedRepoId] = useState<number | undefined>(undefined)
|
||||
@@ -352,7 +356,7 @@ export function GlobalSchedules() {
|
||||
const job = jobs.find((entry) => jobBucket(entry) === repoPath)
|
||||
if (!job) return
|
||||
if (job.repoId === null) {
|
||||
if (job.serverId) navigate(getServerPath(job.serverId))
|
||||
if (job.serverId) navigate(getLinkedServerJobPath(job))
|
||||
return
|
||||
}
|
||||
navigate(getRepoPath(job.repoId))
|
||||
@@ -360,7 +364,7 @@ export function GlobalSchedules() {
|
||||
|
||||
const handleOpenJobPage = (job: ScheduleJobWithRepo) => {
|
||||
if (job.repoId === null) {
|
||||
if (job.serverId) navigate(getServerPath(job.serverId))
|
||||
if (job.serverId) navigate(getLinkedServerJobPath(job))
|
||||
return
|
||||
}
|
||||
navigate(`/repos/${job.repoId}/schedules`)
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { useEffect } from 'react'
|
||||
import { Navigate, useParams } from 'react-router-dom'
|
||||
import { useSidebarServerStore } from '@/stores/sidebarServerStore'
|
||||
|
||||
/**
|
||||
* Legacy `/servers/:serverId` entry point: selects that server in the sidebar and returns home,
|
||||
* where the center section lists the selected server's projects.
|
||||
*/
|
||||
export function LinkedServerRedirect() {
|
||||
const { serverId } = useParams<{ serverId: string }>()
|
||||
const selectServer = useSidebarServerStore((state) => state.selectServer)
|
||||
|
||||
useEffect(() => {
|
||||
if (serverId) selectServer(serverId)
|
||||
}, [serverId, selectServer])
|
||||
|
||||
return <Navigate to="/" replace />
|
||||
}
|
||||
@@ -11,7 +11,7 @@ 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 { getServerSessionPath } from '@/lib/navigation'
|
||||
import { getDirectoryName } from '@/lib/utils'
|
||||
import { Header } from '@/components/ui/header'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
@@ -76,7 +76,7 @@ function RemoteProjectContent({ serverId, directory }: { serverId: string; direc
|
||||
<div className="flex h-full max-h-full min-w-0 flex-1 flex-col overflow-hidden bg-gradient-to-br from-background via-background to-background pb-[calc(env(safe-area-inset-bottom)+56px)] sm:pb-0">
|
||||
<Header>
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2 sm:gap-3">
|
||||
<Header.BackButton to={getServerPath(serverId)} />
|
||||
<Header.BackButton to="/" />
|
||||
<Header.Title>{title}</Header.Title>
|
||||
<Badge variant="outline" className="hidden shrink-0 sm:inline-flex">
|
||||
<Server className="mr-1 h-3 w-3" />
|
||||
@@ -152,8 +152,8 @@ function RemoteProjectContent({ serverId, directory }: { serverId: string; direc
|
||||
icon={FolderGit2}
|
||||
title="No project selected"
|
||||
description="This project link is missing its directory on the server."
|
||||
actionLabel="Back to server"
|
||||
onAction={() => navigate(getServerPath(serverId))}
|
||||
actionLabel="Back to projects"
|
||||
onAction={() => navigate('/')}
|
||||
/>
|
||||
</div>
|
||||
) : isReady ? (
|
||||
|
||||
@@ -1,330 +0,0 @@
|
||||
import { useState, type FormEvent } from 'react'
|
||||
import { Link, useNavigate, useParams } from 'react-router-dom'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { formatDistanceToNow } from 'date-fns'
|
||||
import {
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
FolderGit2,
|
||||
Loader2,
|
||||
Plus,
|
||||
Server,
|
||||
Settings,
|
||||
} from 'lucide-react'
|
||||
import type { OpenCodeServerStatus } from '@opencode-manager/shared/schemas'
|
||||
import { listProjects, type OpenCodeProject } from '@/api/opencode'
|
||||
import { useCreateSession, useSessionsAcrossDirectories } from '@/hooks/useOpenCode'
|
||||
import { useOpenCodeServers, useOpenCodeServerStatuses } from '@/hooks/useOpenCodeServers'
|
||||
import { useSettingsDialog } from '@/hooks/useSettingsDialog'
|
||||
import { useSSE } from '@/hooks/useSSE'
|
||||
import { serverScopedKey } from '@/lib/serverScope'
|
||||
import { getServerProjectPath, 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 { 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'
|
||||
|
||||
function ConnectionStatus({ status, isLoading }: { status?: OpenCodeServerStatus; isLoading: boolean }) {
|
||||
if (isLoading) {
|
||||
return <span className="text-xs text-muted-foreground">Checking connection...</span>
|
||||
}
|
||||
|
||||
if (!status) {
|
||||
return (
|
||||
<span className="flex items-center gap-1.5 text-xs text-muted-foreground">
|
||||
<span className="h-2 w-2 rounded-full bg-muted-foreground/50" />
|
||||
Unknown
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
if (!status.connected) {
|
||||
return (
|
||||
<span className="flex items-center gap-1.5 text-xs text-destructive" title={status.error ?? undefined}>
|
||||
<span className="h-2 w-2 rounded-full bg-destructive" />
|
||||
Unreachable
|
||||
{status.error ? <span className="text-muted-foreground">· {status.error}</span> : null}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<span className="flex items-center gap-1.5 text-xs text-success">
|
||||
<span className="h-2 w-2 rounded-full bg-success" />
|
||||
Connected
|
||||
{status.version ? <span className="text-muted-foreground">· v{status.version}</span> : null}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
function ProjectSessions({ serverId, directory }: { serverId: string; directory: string }) {
|
||||
useSSE(directory)
|
||||
const { data: sessions, isLoading } = useSessionsAcrossDirectories([directory])
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 px-3 py-3 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
Loading sessions...
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (sessions.length === 0) {
|
||||
return <p className="px-3 py-3 text-sm text-muted-foreground">No sessions in this project yet.</p>
|
||||
}
|
||||
|
||||
return (
|
||||
<ul className="flex flex-col gap-1 px-2 pb-2">
|
||||
{sessions.map((session) => (
|
||||
<li key={session.id}>
|
||||
<Link
|
||||
to={getServerSessionPath(serverId, session.id)}
|
||||
className="flex items-center justify-between gap-3 rounded-md px-3 py-2 text-sm transition-colors hover:bg-accent"
|
||||
>
|
||||
<span className="min-w-0 flex items-center gap-2">
|
||||
<SessionStatusIndicator sessionID={session.id} size="sm" />
|
||||
<span className="truncate font-medium">{session.title || 'Untitled Session'}</span>
|
||||
</span>
|
||||
<span className="shrink-0 text-xs text-muted-foreground">
|
||||
{formatDistanceToNow(new Date(session.time.updated), { addSuffix: true })}
|
||||
</span>
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
|
||||
function ProjectRow({ project, serverId }: { project: OpenCodeProject; serverId: string }) {
|
||||
const navigate = useNavigate()
|
||||
const [expanded, setExpanded] = useState(false)
|
||||
const createSession = useCreateSession(project.canonical)
|
||||
const name = project.name?.trim() || getDirectoryName(project.canonical)
|
||||
|
||||
const handleNewSession = async () => {
|
||||
try {
|
||||
const session = await createSession.mutateAsync({ agent: undefined })
|
||||
navigate(getServerSessionPath(serverId, session.id))
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Card className="overflow-hidden">
|
||||
<div className="flex items-center gap-2 p-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setExpanded((current) => !current)}
|
||||
aria-expanded={expanded}
|
||||
aria-label={`${expanded ? 'Collapse' : 'Expand'} ${name}`}
|
||||
className="shrink-0 rounded-md p-1 text-muted-foreground transition-colors hover:bg-accent/50"
|
||||
>
|
||||
{expanded ? (
|
||||
<ChevronDown className="h-4 w-4 shrink-0" />
|
||||
) : (
|
||||
<ChevronRight className="h-4 w-4 shrink-0" />
|
||||
)}
|
||||
</button>
|
||||
<Link
|
||||
to={getServerProjectPath(serverId, project.canonical)}
|
||||
className="flex min-w-0 flex-1 items-center gap-2 rounded-md p-1 text-left transition-colors hover:bg-accent/50"
|
||||
>
|
||||
<FolderGit2 className="h-4 w-4 shrink-0 text-muted-foreground" />
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-sm font-semibold">{name}</span>
|
||||
<span className="block truncate font-mono text-xs text-muted-foreground">{project.canonical}</span>
|
||||
</span>
|
||||
{project.vcs ? (
|
||||
<Badge variant="outline" className="ml-1 hidden shrink-0 sm:inline-flex">
|
||||
{project.vcs}
|
||||
</Badge>
|
||||
) : null}
|
||||
</Link>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={handleNewSession}
|
||||
disabled={createSession.isPending}
|
||||
className="shrink-0"
|
||||
>
|
||||
{createSession.isPending ? <Loader2 className="mr-1 h-4 w-4 animate-spin" /> : <Plus className="mr-1 h-4 w-4" />}
|
||||
New session
|
||||
</Button>
|
||||
<RemoteSchedulesButton serverId={serverId} directory={project.canonical} />
|
||||
<RemoteMultiRunButton serverId={serverId} directory={project.canonical} />
|
||||
</div>
|
||||
{expanded ? <ProjectSessions serverId={serverId} directory={project.canonical} /> : null}
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
function RemoteServerContent({ serverId }: { serverId: string }) {
|
||||
const navigate = useNavigate()
|
||||
const { servers, isLoading: serversLoading } = useOpenCodeServers()
|
||||
const { statusById, isLoading: statusLoading } = useOpenCodeServerStatuses()
|
||||
const { openTab } = useSettingsDialog()
|
||||
const createSession = useCreateSession()
|
||||
const [openDirectory, setOpenDirectory] = useState('')
|
||||
|
||||
const server = servers.find((candidate) => candidate.id === serverId)
|
||||
const status = statusById[serverId]
|
||||
const isDisabled = server !== undefined && !server.enabled
|
||||
|
||||
const projectsQuery = useQuery({
|
||||
queryKey: serverScopedKey(['opencode', 'projects'], serverId),
|
||||
queryFn: () => listProjects(serverId),
|
||||
enabled: server?.enabled === true,
|
||||
retry: false,
|
||||
})
|
||||
|
||||
const openSettings = () => openTab('servers')
|
||||
|
||||
const handleOpenDirectory = async (event: FormEvent) => {
|
||||
event.preventDefault()
|
||||
const directory = openDirectory.trim()
|
||||
if (!directory) return
|
||||
try {
|
||||
const session = await createSession.mutateAsync({ directory })
|
||||
navigate(getServerSessionPath(serverId, session.id))
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-full max-h-full min-w-0 flex-col overflow-hidden bg-gradient-to-br from-background via-background to-background">
|
||||
<Header>
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2">
|
||||
<Header.BackButton to="/" />
|
||||
<Header.Title>{server?.name ?? 'Linked server'}</Header.Title>
|
||||
<span className="hidden min-w-0 truncate font-mono text-xs text-muted-foreground sm:block">
|
||||
{server?.baseUrl}
|
||||
</span>
|
||||
</div>
|
||||
<Header.Actions>
|
||||
<ConnectionStatus status={status} isLoading={statusLoading && !status} />
|
||||
<Button variant="outline" size="sm" onClick={openSettings}>
|
||||
<Settings className="mr-1 h-4 w-4" />
|
||||
<span className="hidden sm:inline">Manage servers</span>
|
||||
<span className="sr-only sm:hidden">Manage servers</span>
|
||||
</Button>
|
||||
</Header.Actions>
|
||||
</Header>
|
||||
|
||||
<div className="mx-auto flex w-full max-w-4xl flex-1 flex-col gap-4 overflow-y-auto p-3 pb-[calc(env(safe-area-inset-bottom)+60px)] sm:pb-4">
|
||||
{!serversLoading && !server ? (
|
||||
<LinkedServerStateCard
|
||||
icon={Server}
|
||||
title="Server not found"
|
||||
description="This linked server is no longer configured."
|
||||
actionLabel="Open server settings"
|
||||
onAction={openSettings}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{isDisabled ? (
|
||||
<LinkedServerStateCard
|
||||
icon={Server}
|
||||
title="This server is disabled"
|
||||
description="Enable it in Settings → Servers to browse its projects and sessions."
|
||||
actionLabel="Open server settings"
|
||||
onAction={openSettings}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{server && !isDisabled && projectsQuery.isError ? (
|
||||
<Card className="flex flex-col items-center gap-3 p-6 text-center">
|
||||
<Server className="h-8 w-8 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="font-medium">Could not load projects</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{projectsQuery.error instanceof Error
|
||||
? projectsQuery.error.message
|
||||
: 'The server did not respond.'}
|
||||
</p>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" onClick={() => void projectsQuery.refetch()}>
|
||||
Retry
|
||||
</Button>
|
||||
</Card>
|
||||
) : null}
|
||||
|
||||
{server && !isDisabled && !projectsQuery.isError ? (
|
||||
<section aria-label="Projects" className="flex flex-col gap-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-xs font-medium uppercase tracking-wider text-muted-foreground">Projects</h2>
|
||||
{projectsQuery.isFetching ? (
|
||||
<span className="flex items-center gap-1 text-xs text-muted-foreground">
|
||||
<Loader2 className="h-3 w-3 animate-spin" />
|
||||
Refreshing
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{projectsQuery.isLoading ? (
|
||||
<Card className="flex items-center gap-2 p-4 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
Loading projects...
|
||||
</Card>
|
||||
) : (projectsQuery.data ?? []).length === 0 ? (
|
||||
<Card className="flex flex-col items-center gap-2 p-6 text-center">
|
||||
<FolderGit2 className="h-8 w-8 text-muted-foreground" />
|
||||
<p className="font-medium">No projects on this server yet</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Start a session in a directory below to create one.
|
||||
</p>
|
||||
</Card>
|
||||
) : (
|
||||
(projectsQuery.data ?? []).map((project) => (
|
||||
<ProjectRow key={project.id} project={project} serverId={serverId} />
|
||||
))
|
||||
)}
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{server && !isDisabled ? (
|
||||
<section aria-label="Open directory" className="flex flex-col gap-2">
|
||||
<h2 className="text-xs font-medium uppercase tracking-wider text-muted-foreground">Open directory</h2>
|
||||
<form onSubmit={handleOpenDirectory} className="flex items-center gap-2">
|
||||
<Input
|
||||
value={openDirectory}
|
||||
onChange={(event) => setOpenDirectory(event.target.value)}
|
||||
placeholder="/absolute/path/on/the/server"
|
||||
aria-label="Directory path"
|
||||
autoComplete="off"
|
||||
name="remote-directory"
|
||||
className="font-mono text-sm"
|
||||
/>
|
||||
<Button type="submit" disabled={!openDirectory.trim() || createSession.isPending} className="shrink-0">
|
||||
{createSession.isPending ? (
|
||||
<Loader2 className="mr-1 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Plus className="mr-1 h-4 w-4" />
|
||||
)}
|
||||
Start session
|
||||
</Button>
|
||||
</form>
|
||||
</section>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function RemoteServer() {
|
||||
const { serverId } = useParams<{ serverId: string }>()
|
||||
|
||||
if (!serverId) {
|
||||
return null
|
||||
}
|
||||
|
||||
return <RemoteServerContent serverId={serverId} />
|
||||
}
|
||||
@@ -1,16 +1,40 @@
|
||||
import { useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { Plus, FolderOpen, CalendarClock, Settings } from "lucide-react";
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from "@opencode-manager/shared/schemas";
|
||||
import { RepoList } from "@/components/repo/RepoList";
|
||||
import { AddRepoDialog } from "@/components/repo/AddRepoDialog";
|
||||
import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet";
|
||||
import { RemoteProjectList } from "@/components/servers/RemoteProjectList";
|
||||
import { ConnectionStatus } from "@/components/servers/ConnectionStatus";
|
||||
import { Header } from "@/components/ui/header";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Plus, FolderOpen, CalendarClock } from "lucide-react";
|
||||
import { PendingActionsGroup } from "@/components/notifications/PendingActionsGroup";
|
||||
import { ToolSidePanel } from "@/components/navigation/ToolSidePanel";
|
||||
import { useDialogParam } from "@/hooks/useDialogParam";
|
||||
import { useMobile } from "@/hooks/useMobile";
|
||||
import { useOpenCodeServerStatuses } from "@/hooks/useOpenCodeServers";
|
||||
import { useSettingsDialog } from "@/hooks/useSettingsDialog";
|
||||
import { useSidebarServerSelection } from "@/hooks/useSidebarServerSelection";
|
||||
import { useToolPanel } from "@/hooks/useToolPanel";
|
||||
import { ToolSidePanel } from "@/components/navigation/ToolSidePanel";
|
||||
|
||||
function LinkedServerHeaderActions({ serverId }: { serverId: string }) {
|
||||
const { statusById, isLoading } = useOpenCodeServerStatuses();
|
||||
const { openTab } = useSettingsDialog();
|
||||
const status = statusById[serverId];
|
||||
|
||||
return (
|
||||
<>
|
||||
<span className="flex max-w-[45vw] items-center overflow-hidden sm:max-w-none">
|
||||
<ConnectionStatus status={status} isLoading={isLoading && !status} />
|
||||
</span>
|
||||
<Button variant="outline" size="sm" className="hidden sm:flex" onClick={() => openTab('servers')}>
|
||||
<Settings className="mr-1 h-4 w-4" />
|
||||
Manage servers
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function Repos() {
|
||||
const navigate = useNavigate();
|
||||
@@ -18,6 +42,8 @@ export function Repos() {
|
||||
const [fileBrowserOpen, setFileBrowserOpen] = useDialogParam('files');
|
||||
const docked = !useMobile();
|
||||
const toolPanel = useToolPanel(docked);
|
||||
const [selectedServerId] = useSidebarServerSelection();
|
||||
const isLocalServer = selectedServerId === LOCAL_OPENCODE_SERVER_ID;
|
||||
|
||||
const handleCloseFileBrowser = () => {
|
||||
setFileBrowserOpen(false);
|
||||
@@ -34,15 +60,19 @@ export function Repos() {
|
||||
<div className="flex items-center gap-1">
|
||||
<PendingActionsGroup />
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => setFileBrowserOpen(true)}
|
||||
aria-label="Open files"
|
||||
className="hidden sm:flex text-muted-foreground hover:text-foreground hover:bg-accent transition-all duration-200 h-8 w-8"
|
||||
>
|
||||
<FolderOpen className="w-4 h-4" />
|
||||
</Button>
|
||||
{isLocalServer ? (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => setFileBrowserOpen(true)}
|
||||
aria-label="Open files"
|
||||
className="hidden sm:flex text-muted-foreground hover:text-foreground hover:bg-accent transition-all duration-200 h-8 w-8"
|
||||
>
|
||||
<FolderOpen className="w-4 h-4" />
|
||||
</Button>
|
||||
) : (
|
||||
<LinkedServerHeaderActions serverId={selectedServerId} />
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => navigate('/schedules')}
|
||||
@@ -52,29 +82,34 @@ export function Repos() {
|
||||
<CalendarClock className="w-4 h-4 mr-2" />
|
||||
All Schedules
|
||||
</Button>
|
||||
<Button onClick={() => setAddRepoOpen(true)} size="sm">
|
||||
<Plus className="w-4 h-4 mr-1" />
|
||||
Repo
|
||||
</Button>
|
||||
{isLocalServer ? (
|
||||
<Button onClick={() => setAddRepoOpen(true)} size="sm">
|
||||
<Plus className="w-4 h-4 mr-1" />
|
||||
Repo
|
||||
</Button>
|
||||
) : null}
|
||||
<span>
|
||||
<Header.Settings />
|
||||
</span>
|
||||
</Header.Actions>
|
||||
</Header>
|
||||
<div className="container mx-auto flex-1 pt-2 px-2 min-h-0 overflow-auto pb-[calc(env(safe-area-inset-bottom)+60px)] sm:pb-0">
|
||||
|
||||
<RepoList />
|
||||
{isLocalServer ? <RepoList /> : <RemoteProjectList serverId={selectedServerId} />}
|
||||
</div>
|
||||
<AddRepoDialog open={addRepoOpen} onOpenChange={setAddRepoOpen} />
|
||||
<FileBrowserSheet
|
||||
isOpen={!docked && fileBrowserOpen}
|
||||
onClose={handleCloseFileBrowser}
|
||||
basePath=""
|
||||
repoName="Workspace Root"
|
||||
allowNavigateAboveBase={true}
|
||||
/>
|
||||
{isLocalServer ? (
|
||||
<AddRepoDialog open={addRepoOpen} onOpenChange={setAddRepoOpen} />
|
||||
) : null}
|
||||
{isLocalServer ? (
|
||||
<FileBrowserSheet
|
||||
isOpen={!docked && fileBrowserOpen}
|
||||
onClose={handleCloseFileBrowser}
|
||||
basePath=""
|
||||
repoName="Workspace Root"
|
||||
allowNavigateAboveBase={true}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
{docked && <ToolSidePanel panel={toolPanel} filesBasePath="" allowNavigateAboveBase />}
|
||||
{isLocalServer && docked ? <ToolSidePanel panel={toolPanel} filesBasePath="" allowNavigateAboveBase /> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import { SquareFill } from "@/components/ui/square-fill";
|
||||
import { Header } from "@/components/ui/header";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { SessionPickerDialog } from "@/components/session/SessionPickerDialog";
|
||||
import { getRepoPath, getServerPath, getServerSessionPath, getSessionListPath, getSessionPath } from '@/lib/navigation'
|
||||
import { getRepoPath, getServerProjectPath, getServerSessionPath, getSessionListPath, getSessionPath } from '@/lib/navigation'
|
||||
import { FetchError } from '@/api/fetchWrapper'
|
||||
|
||||
import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet";
|
||||
@@ -49,6 +49,7 @@ import { ResetPermissionsDialog } from "@/components/repo/ResetPermissionsDialog
|
||||
import { RepoSkillsDialog } from "@/components/repo/RepoSkillsDialog";
|
||||
import { compactSession, forkSession, listProjects, listSessionMessages } from "@/api/opencode";
|
||||
import { useOpenCodeServerId, isLocalOpenCodeServer } from "@/contexts/OpenCodeServerContext";
|
||||
import { useSwipeNavigation } from "@/contexts/SwipeNavigationContext";
|
||||
import { useOpenCodeServers, useOpenCodeServerStatuses } from "@/hooks/useOpenCodeServers";
|
||||
import { serverScopedKey } from "@/lib/serverScope";
|
||||
import { useSessionStatus } from "@/stores/sessionStatusStore";
|
||||
@@ -128,6 +129,7 @@ export function SessionDetail() {
|
||||
const { id, sessionId } = useParams<{ id: string; sessionId: string }>();
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const swipeNav = useSwipeNavigation();
|
||||
const repoId = Number(id) || 0;
|
||||
const isAssistantSession = new URLSearchParams(location.search).get('assistant') === '1';
|
||||
const { preferences, updateSettings } = useSettings();
|
||||
@@ -198,6 +200,17 @@ export function SessionDetail() {
|
||||
: undefined
|
||||
);
|
||||
const sessionDirectory = isRemoteServer ? resolvedDirectory : resolvedDirectory ?? repoDirectory;
|
||||
const remoteProjectBackPath = isRemoteServer && sessionDirectory
|
||||
? getServerProjectPath(serverId, sessionDirectory)
|
||||
: '/';
|
||||
|
||||
useEffect(() => {
|
||||
if (!isRemoteServer) return;
|
||||
swipeNav?.setBackTarget(remoteProjectBackPath);
|
||||
return () => {
|
||||
swipeNav?.setBackTarget(null);
|
||||
};
|
||||
}, [isRemoteServer, remoteProjectBackPath, swipeNav]);
|
||||
|
||||
const { data: repoSiblings } = useRepoSiblings(!isAssistantSession && !isRemoteServer && repo && !repo.isWorktree ? repoId : undefined);
|
||||
|
||||
@@ -501,12 +514,12 @@ export function SessionDetail() {
|
||||
|
||||
const handleCloseSession = useCallback(() => {
|
||||
if (isRemoteServer) {
|
||||
navigate(getServerPath(serverId))
|
||||
navigate(remoteProjectBackPath)
|
||||
return
|
||||
}
|
||||
const tab = new URLSearchParams(location.search).get('repoTab') ?? undefined;
|
||||
navigate(getSessionListPath(repoId, isAssistantSession, tab))
|
||||
}, [navigate, repoId, isAssistantSession, isRemoteServer, serverId, location.search])
|
||||
}, [navigate, repoId, isAssistantSession, isRemoteServer, remoteProjectBackPath, location.search])
|
||||
|
||||
const handleOpenModelDialog = useCallback(() => {
|
||||
promptInputRef.current?.openModelPicker();
|
||||
@@ -716,8 +729,8 @@ export function SessionDetail() {
|
||||
return (
|
||||
<SessionRouteFallback
|
||||
message="Session not found"
|
||||
backTo={isRemoteServer ? getServerPath(serverId) : getSessionListPath(repoId, isAssistantSession, listTab)}
|
||||
backLabel={isRemoteServer ? 'Back to server' : 'Back to sessions'}
|
||||
backTo={isRemoteServer ? remoteProjectBackPath : getSessionListPath(repoId, isAssistantSession, listTab)}
|
||||
backLabel={isRemoteServer ? 'Back to projects' : 'Back to sessions'}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -727,8 +740,8 @@ export function SessionDetail() {
|
||||
return (
|
||||
<SessionRouteFallback
|
||||
message="Failed to load session"
|
||||
backTo={getServerPath(serverId)}
|
||||
backLabel="Back to server"
|
||||
backTo={remoteProjectBackPath}
|
||||
backLabel="Back to projects"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -755,7 +768,7 @@ export function SessionDetail() {
|
||||
: getRepoDisplayName(repo);
|
||||
const tabFromUrl = new URLSearchParams(location.search).get('repoTab') ?? undefined;
|
||||
const sessionBackPath = isRemoteServer
|
||||
? getServerPath(serverId)
|
||||
? remoteProjectBackPath
|
||||
: getSessionListPath(repoId, isAssistantSession, tabFromUrl);
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { render, screen, waitFor, act } from '@testing-library/react'
|
||||
import { MemoryRouter } from 'react-router-dom'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { LocationCatcher } from '@/test/test-utils'
|
||||
import { GlobalSchedules } from '../GlobalSchedules'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
@@ -153,6 +154,19 @@ const renderGlobalSchedules = () => {
|
||||
)
|
||||
}
|
||||
|
||||
const renderGlobalSchedulesWithLocation = () => {
|
||||
const capturedPathname = { current: '' }
|
||||
const capturedSearch = { current: '' }
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/schedules']}>
|
||||
<LocationCatcher capturedSearch={capturedSearch} capturedPathname={capturedPathname} />
|
||||
<GlobalSchedules />
|
||||
</MemoryRouter>,
|
||||
{ wrapper: createWrapper() }
|
||||
)
|
||||
return { capturedPathname, capturedSearch }
|
||||
}
|
||||
|
||||
const runsTableProps = () => mocks.ScheduleRunsTable.mock.calls.at(-1)?.[0] as {
|
||||
runs: Array<{ id: number }>
|
||||
selectedRunId: number | null
|
||||
@@ -333,6 +347,23 @@ describe('GlobalSchedules run history', () => {
|
||||
expect(selectRun).toHaveBeenCalledWith(5)
|
||||
})
|
||||
|
||||
it('opens a linked-server job on its project page', async () => {
|
||||
const job = makeJob({ repoId: null, serverId: 'srv_kitchen', directory: '/home/me/app', lastRun: null })
|
||||
mocks.useAllSchedules.mockReturnValue({ data: [job], isLoading: false, error: null })
|
||||
mocks.useScheduleUrlState.mockReturnValue(createMockScheduleUrlState({ scheduleTab: 'jobs', runId: null }))
|
||||
|
||||
const { capturedPathname, capturedSearch } = renderGlobalSchedulesWithLocation()
|
||||
|
||||
act(() => {
|
||||
jobsTableProps().onOpen(job)
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(capturedPathname.current).toBe('/servers/srv_kitchen/projects')
|
||||
})
|
||||
expect(capturedSearch.current).toBe('?directory=%2Fhome%2Fme%2Fapp')
|
||||
})
|
||||
|
||||
it('keeps the jobs tab visible with the empty state when there are no jobs', () => {
|
||||
mocks.useScheduleUrlState.mockReturnValue(createMockScheduleUrlState({ scheduleTab: 'jobs', runId: null }))
|
||||
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import { MemoryRouter, Route, Routes } from 'react-router-dom'
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import { LinkedServerRedirect } from '../LinkedServerRedirect'
|
||||
import { SIDEBAR_SERVER_STORAGE_KEY, useSidebarServerStore } from '@/stores/sidebarServerStore'
|
||||
|
||||
function renderRedirect(serverId = 'srv_x') {
|
||||
return render(
|
||||
<MemoryRouter initialEntries={[`/servers/${serverId}`]}>
|
||||
<Routes>
|
||||
<Route path="/servers/:serverId" element={<LinkedServerRedirect />} />
|
||||
<Route path="/" element={<div>home</div>} />
|
||||
</Routes>
|
||||
</MemoryRouter>,
|
||||
)
|
||||
}
|
||||
|
||||
describe('LinkedServerRedirect', () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear()
|
||||
useSidebarServerStore.setState({ serverId: LOCAL_OPENCODE_SERVER_ID })
|
||||
})
|
||||
|
||||
it('lands on home with the server selected', async () => {
|
||||
renderRedirect('srv_x')
|
||||
|
||||
await waitFor(() => expect(screen.getByText('home')).toBeInTheDocument())
|
||||
expect(useSidebarServerStore.getState().serverId).toBe('srv_x')
|
||||
expect(JSON.parse(localStorage.getItem(SIDEBAR_SERVER_STORAGE_KEY) ?? 'null')).toBe('srv_x')
|
||||
})
|
||||
})
|
||||
@@ -82,8 +82,8 @@ function renderProject(path = '/servers/srv_kitchen/projects?directory=%2Fhome%2
|
||||
<QueryClientProvider client={createQueryClient()}>
|
||||
<MemoryRouter initialEntries={[path]}>
|
||||
<Routes>
|
||||
<Route path="/" element={<div data-testid="home-route" />} />
|
||||
<Route path="/servers/:serverId/projects" element={<RemoteProject />} />
|
||||
<Route path="/servers/:serverId" element={<div data-testid="server-route" />} />
|
||||
<Route path="/servers/:serverId/sessions/:sessionId" element={<div data-testid="session-route" />} />
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
@@ -164,6 +164,14 @@ describe('RemoteProject', () => {
|
||||
expect(screen.queryByTestId('session-list')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('goes back to the projects list from the missing-directory state', async () => {
|
||||
renderProject('/servers/srv_kitchen/projects')
|
||||
|
||||
fireEvent.click(await screen.findByRole('button', { name: 'Back to projects' }))
|
||||
|
||||
expect(screen.getByTestId('home-route')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows the disabled state without loading projects', async () => {
|
||||
mocks.useOpenCodeServers.mockReturnValue({
|
||||
servers: [{ ...server, enabled: false }],
|
||||
@@ -198,11 +206,11 @@ describe('RemoteProject', () => {
|
||||
expect(mocks.openTab).toHaveBeenCalledWith('servers')
|
||||
})
|
||||
|
||||
it('goes back to the linked server page', async () => {
|
||||
it('goes back to the projects list', async () => {
|
||||
renderProject()
|
||||
|
||||
fireEvent.click(await screen.findByRole('button', { name: 'Go back' }))
|
||||
|
||||
expect(screen.getByTestId('server-route')).toBeInTheDocument()
|
||||
expect(screen.getByTestId('home-route')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -1,228 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, waitFor, fireEvent } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { MemoryRouter, Route, Routes } from 'react-router-dom'
|
||||
import { RemoteServer } from '../RemoteServer'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
listProjects: vi.fn(),
|
||||
useSessionsAcrossDirectories: vi.fn(),
|
||||
useCreateSession: vi.fn(),
|
||||
useOpenCodeServers: vi.fn(),
|
||||
useOpenCodeServerStatuses: vi.fn(),
|
||||
useSettingsDialog: vi.fn(),
|
||||
useSSE: vi.fn(),
|
||||
openTab: vi.fn(),
|
||||
createSession: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/opencode', () => ({
|
||||
listProjects: mocks.listProjects,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useOpenCode', () => ({
|
||||
useSessionsAcrossDirectories: mocks.useSessionsAcrossDirectories,
|
||||
useCreateSession: mocks.useCreateSession,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useOpenCodeServers', () => ({
|
||||
useOpenCodeServers: mocks.useOpenCodeServers,
|
||||
useOpenCodeServerStatuses: mocks.useOpenCodeServerStatuses,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useSettingsDialog', () => ({
|
||||
useSettingsDialog: mocks.useSettingsDialog,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useSSE', () => ({
|
||||
useSSE: mocks.useSSE,
|
||||
}))
|
||||
|
||||
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: [],
|
||||
}
|
||||
|
||||
const session = {
|
||||
id: 'ses_1',
|
||||
projectID: 'prj_1',
|
||||
title: 'Fix the bug',
|
||||
time: { created: 1, updated: Date.now() - 60000 },
|
||||
location: { directory: '/home/me/app' },
|
||||
}
|
||||
|
||||
function createQueryClient() {
|
||||
return new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
}
|
||||
|
||||
function renderServer(serverId = 'srv_kitchen') {
|
||||
return render(
|
||||
<QueryClientProvider client={createQueryClient()}>
|
||||
<MemoryRouter initialEntries={[`/servers/${serverId}`]}>
|
||||
<Routes>
|
||||
<Route path="/servers/:serverId" element={<RemoteServer />} />
|
||||
<Route path="/servers/:serverId/sessions/:sessionId" element={<div data-testid="session-route" />} />
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
}
|
||||
|
||||
describe('RemoteServer', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.listProjects.mockResolvedValue([project])
|
||||
mocks.useSessionsAcrossDirectories.mockReturnValue({ data: [session], isLoading: false })
|
||||
mocks.useCreateSession.mockReturnValue({ mutateAsync: mocks.createSession, isPending: false })
|
||||
mocks.useOpenCodeServers.mockReturnValue({ servers: [server], isLoading: false })
|
||||
mocks.useOpenCodeServerStatuses.mockReturnValue({
|
||||
statuses: [],
|
||||
statusById: {
|
||||
srv_kitchen: {
|
||||
serverId: 'srv_kitchen',
|
||||
connected: true,
|
||||
version: '2.0.15',
|
||||
error: null,
|
||||
},
|
||||
},
|
||||
isLoading: false,
|
||||
})
|
||||
mocks.useSettingsDialog.mockReturnValue({ openTab: mocks.openTab })
|
||||
mocks.useSSE.mockReturnValue({ isConnected: true, isReconnecting: false })
|
||||
})
|
||||
|
||||
it('renders the server identity and connection status', async () => {
|
||||
renderServer()
|
||||
|
||||
expect(screen.getByText('Kitchen')).toBeInTheDocument()
|
||||
expect(screen.getByText('https://kitchen.example.com')).toBeInTheDocument()
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/Connected/)).toBeInTheDocument()
|
||||
})
|
||||
expect(screen.getByText(/v2\.0\.15/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('lists projects from the remote server', async () => {
|
||||
renderServer()
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('App')).toBeInTheDocument()
|
||||
})
|
||||
expect(screen.getByText('/home/me/app')).toBeInTheDocument()
|
||||
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: 'Expand App' }))
|
||||
|
||||
const link = await screen.findByRole('link', { name: /Fix the bug/ })
|
||||
expect(link).toHaveAttribute('href', '/servers/srv_kitchen/sessions/ses_1')
|
||||
expect(mocks.useSessionsAcrossDirectories).toHaveBeenCalledWith(['/home/me/app'])
|
||||
})
|
||||
|
||||
it('creates a session in a project directory and navigates to it', async () => {
|
||||
mocks.createSession.mockResolvedValue({ id: 'ses_new' })
|
||||
renderServer()
|
||||
|
||||
await screen.findByText('App')
|
||||
fireEvent.click(screen.getByRole('button', { name: /New session/ }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.createSession).toHaveBeenCalledWith({ agent: undefined })
|
||||
})
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('session-route')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
it('opens a session in an arbitrary directory', async () => {
|
||||
mocks.createSession.mockResolvedValue({ id: 'ses_other' })
|
||||
renderServer()
|
||||
|
||||
fireEvent.change(screen.getByLabelText('Directory path'), { target: { value: '/srv/other' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: /Start session/ }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.createSession).toHaveBeenCalledWith({ directory: '/srv/other' })
|
||||
})
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('session-route')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
it('shows the disabled state without loading projects', async () => {
|
||||
mocks.useOpenCodeServers.mockReturnValue({
|
||||
servers: [{ ...server, enabled: false }],
|
||||
isLoading: false,
|
||||
})
|
||||
|
||||
renderServer()
|
||||
|
||||
expect(screen.getByText('This server is disabled')).toBeInTheDocument()
|
||||
expect(mocks.listProjects).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('shows an empty state when the server has no projects', async () => {
|
||||
mocks.listProjects.mockResolvedValue([])
|
||||
|
||||
renderServer()
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('No projects on this server yet')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
it('shows the unreachable state from the status hook', async () => {
|
||||
mocks.useOpenCodeServerStatuses.mockReturnValue({
|
||||
statuses: [],
|
||||
statusById: {
|
||||
srv_kitchen: {
|
||||
serverId: 'srv_kitchen',
|
||||
connected: false,
|
||||
version: null,
|
||||
error: 'connection refused',
|
||||
},
|
||||
},
|
||||
isLoading: false,
|
||||
})
|
||||
|
||||
renderServer()
|
||||
|
||||
expect(screen.getByText('Unreachable')).toBeInTheDocument()
|
||||
expect(screen.getByText(/connection refused/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('opens the servers settings tab from the header', () => {
|
||||
renderServer()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Manage servers/ }))
|
||||
|
||||
expect(mocks.openTab).toHaveBeenCalledWith('servers')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,190 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { act, fireEvent, render, screen } from '@testing-library/react'
|
||||
import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import { Repos } from '../Repos'
|
||||
import { useSidebarServerStore } from '@/stores/sidebarServerStore'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
useOpenCodeServers: vi.fn(),
|
||||
useOpenCodeServerStatuses: vi.fn(),
|
||||
openTab: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useOpenCodeServers', () => ({
|
||||
useOpenCodeServers: mocks.useOpenCodeServers,
|
||||
useOpenCodeServerStatuses: mocks.useOpenCodeServerStatuses,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useSettingsDialog', () => ({
|
||||
useSettingsDialog: () => ({
|
||||
isOpen: false,
|
||||
open: vi.fn(),
|
||||
openTab: mocks.openTab,
|
||||
close: vi.fn(),
|
||||
toggle: vi.fn(),
|
||||
activeTab: 'account',
|
||||
selectedTab: null,
|
||||
setActiveTab: vi.fn(),
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useMobile', () => ({
|
||||
isMobileViewport: () => false,
|
||||
useMobile: () => false,
|
||||
}))
|
||||
|
||||
vi.mock('@/components/repo/RepoList', () => ({
|
||||
RepoList: () => <div>local-repos</div>,
|
||||
}))
|
||||
|
||||
vi.mock('@/components/repo/AddRepoDialog', () => ({
|
||||
AddRepoDialog: () => null,
|
||||
}))
|
||||
|
||||
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({
|
||||
FileBrowserSheet: () => null,
|
||||
}))
|
||||
|
||||
vi.mock('@/components/navigation/ToolSidePanel', () => ({
|
||||
ToolSidePanel: () => null,
|
||||
}))
|
||||
|
||||
vi.mock('@/components/notifications/PendingActionsGroup', () => ({
|
||||
PendingActionsGroup: () => null,
|
||||
}))
|
||||
|
||||
vi.mock('@/components/servers/RemoteProjectList', () => ({
|
||||
RemoteProjectList: ({ serverId }: { serverId: string }) => (
|
||||
<div>remote-projects:{serverId}</div>
|
||||
),
|
||||
}))
|
||||
|
||||
const kitchen = {
|
||||
id: 'srv_kitchen',
|
||||
name: 'Kitchen',
|
||||
baseUrl: 'https://kitchen.example.com',
|
||||
username: 'opencode',
|
||||
enabled: true,
|
||||
hasPassword: true,
|
||||
createdAt: 1,
|
||||
updatedAt: 2,
|
||||
}
|
||||
|
||||
function LocationDisplay() {
|
||||
return <div data-testid="location">{useLocation().pathname}</div>
|
||||
}
|
||||
|
||||
function renderRepos() {
|
||||
return render(
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<LocationDisplay />
|
||||
<Routes>
|
||||
<Route path="/" element={<Repos />} />
|
||||
</Routes>
|
||||
</MemoryRouter>,
|
||||
)
|
||||
}
|
||||
|
||||
describe('Repos', () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear()
|
||||
useSidebarServerStore.setState({ serverId: LOCAL_OPENCODE_SERVER_ID })
|
||||
mocks.useOpenCodeServers.mockReturnValue({
|
||||
servers: [kitchen],
|
||||
isLoading: false,
|
||||
isSuccess: true,
|
||||
})
|
||||
mocks.useOpenCodeServerStatuses.mockReturnValue({
|
||||
statuses: [],
|
||||
statusById: {
|
||||
srv_kitchen: {
|
||||
serverId: 'srv_kitchen',
|
||||
connected: true,
|
||||
version: '2.0.15',
|
||||
error: null,
|
||||
},
|
||||
},
|
||||
isLoading: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('shows the local repositories and local-only actions', () => {
|
||||
renderRepos()
|
||||
|
||||
expect(screen.getByText('local-repos')).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Repo' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Open files' })).toBeInTheDocument()
|
||||
expect(screen.queryByText(/remote-projects/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows the selected linked server projects and hides local-only actions', () => {
|
||||
useSidebarServerStore.setState({ serverId: 'srv_kitchen' })
|
||||
|
||||
renderRepos()
|
||||
|
||||
expect(screen.getByText('remote-projects:srv_kitchen')).toBeInTheDocument()
|
||||
expect(screen.queryByText('local-repos')).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Repo' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Open files' })).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: /Manage servers/ })).toHaveClass('hidden', 'sm:flex')
|
||||
expect(screen.getByRole('button', { name: 'All Schedules' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Settings' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('swaps the center section without navigating when the selection changes', () => {
|
||||
renderRepos()
|
||||
|
||||
act(() => useSidebarServerStore.getState().selectServer('srv_kitchen'))
|
||||
|
||||
expect(screen.getByText('remote-projects:srv_kitchen')).toBeInTheDocument()
|
||||
expect(screen.queryByText('local-repos')).not.toBeInTheDocument()
|
||||
expect(screen.getByTestId('location')).toHaveTextContent('/')
|
||||
|
||||
act(() => useSidebarServerStore.getState().selectServer(LOCAL_OPENCODE_SERVER_ID))
|
||||
|
||||
expect(screen.getByText('local-repos')).toBeInTheDocument()
|
||||
expect(screen.queryByText(/remote-projects/)).not.toBeInTheDocument()
|
||||
expect(screen.getByTestId('location')).toHaveTextContent('/')
|
||||
})
|
||||
|
||||
it('shows the connection status of the selected linked server', () => {
|
||||
useSidebarServerStore.setState({ serverId: 'srv_kitchen' })
|
||||
|
||||
renderRepos()
|
||||
|
||||
expect(screen.getByText(/Connected/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/v2\.0\.15/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows an unreachable linked server with its error', () => {
|
||||
useSidebarServerStore.setState({ serverId: 'srv_kitchen' })
|
||||
mocks.useOpenCodeServerStatuses.mockReturnValue({
|
||||
statuses: [],
|
||||
statusById: {
|
||||
srv_kitchen: {
|
||||
serverId: 'srv_kitchen',
|
||||
connected: false,
|
||||
version: null,
|
||||
error: 'connection refused',
|
||||
},
|
||||
},
|
||||
isLoading: false,
|
||||
})
|
||||
|
||||
renderRepos()
|
||||
|
||||
expect(screen.getByText(/Unreachable/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/connection refused/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('opens the servers settings tab from the header', () => {
|
||||
useSidebarServerStore.setState({ serverId: 'srv_kitchen' })
|
||||
|
||||
renderRepos()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Manage servers/ }))
|
||||
|
||||
expect(mocks.openTab).toHaveBeenCalledWith('servers')
|
||||
})
|
||||
})
|
||||
@@ -1,8 +1,11 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, waitFor, act } from '@testing-library/react'
|
||||
import { render, screen, waitFor, act, fireEvent } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { MemoryRouter, Route, Routes } from 'react-router-dom'
|
||||
import { FetchError } from '@/api/fetchWrapper'
|
||||
import { OpenCodeServerProvider } from '@/contexts/OpenCodeServerContext'
|
||||
import { SwipeNavigationProvider, useSwipeNavigation } from '@/contexts/SwipeNavigationContext'
|
||||
import { getServerProjectPath } from '@/lib/navigation'
|
||||
import { LocationCatcher } from '@/test/test-utils'
|
||||
import { MessageThread } from '@/components/message/MessageThread'
|
||||
import { ContextUsageIndicator } from '@/components/session/ContextUsageIndicator'
|
||||
@@ -183,23 +186,36 @@ function createQueryClient() {
|
||||
return new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
}
|
||||
|
||||
type SwipeNavigation = ReturnType<typeof useSwipeNavigation>
|
||||
|
||||
function SwipeNavigationProbe({ captured }: { captured: { current: SwipeNavigation } }) {
|
||||
captured.current = useSwipeNavigation()
|
||||
return null
|
||||
}
|
||||
|
||||
function renderRemoteSession(sessionId = 'ses_remote') {
|
||||
const capturedPathname = { current: '' }
|
||||
const capturedSearch = { current: '' }
|
||||
const capturedSwipeNavigation = { current: null as SwipeNavigation }
|
||||
const rendered = render(
|
||||
<OpenCodeServerProvider serverId="srv_kitchen">
|
||||
<QueryClientProvider client={createQueryClient()}>
|
||||
<MemoryRouter initialEntries={[`/servers/srv_kitchen/sessions/${sessionId}`]}>
|
||||
<LocationCatcher capturedSearch={capturedSearch} capturedPathname={capturedPathname} />
|
||||
<Routes>
|
||||
<Route path="/servers/:serverId/sessions/:sessionId" element={<SessionDetail />} />
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>
|
||||
<SwipeNavigationProvider>
|
||||
<QueryClientProvider client={createQueryClient()}>
|
||||
<MemoryRouter initialEntries={[`/servers/srv_kitchen/sessions/${sessionId}`]}>
|
||||
<LocationCatcher capturedSearch={capturedSearch} capturedPathname={capturedPathname} />
|
||||
<SwipeNavigationProbe captured={capturedSwipeNavigation} />
|
||||
<Routes>
|
||||
<Route path="/" element={null} />
|
||||
<Route path="/servers/:serverId/projects" element={null} />
|
||||
<Route path="/servers/:serverId/sessions/:sessionId" element={<SessionDetail />} />
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>
|
||||
</SwipeNavigationProvider>
|
||||
</OpenCodeServerProvider>,
|
||||
)
|
||||
|
||||
return { ...rendered, capturedPathname }
|
||||
return { ...rendered, capturedPathname, capturedSearch, capturedSwipeNavigation }
|
||||
}
|
||||
|
||||
describe('SessionDetail remote server mode', () => {
|
||||
@@ -271,6 +287,47 @@ describe('SessionDetail remote server mode', () => {
|
||||
expect(screen.getByText('Kitchen').parentElement).toHaveTextContent('Kitchen · app')
|
||||
})
|
||||
|
||||
it('returns to the project page from the header back button', async () => {
|
||||
const { capturedPathname, capturedSearch } = renderRemoteSession()
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Kitchen').parentElement).toHaveTextContent('Kitchen · app')
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Go back' }))
|
||||
|
||||
expect(capturedPathname.current).toBe('/servers/srv_kitchen/projects')
|
||||
expect(capturedSearch.current).toBe('?directory=%2Fhome%2Fme%2Fapp')
|
||||
})
|
||||
|
||||
it('registers the remote project page as the swipe-back target once the directory resolves', async () => {
|
||||
const { capturedSwipeNavigation, unmount } = renderRemoteSession()
|
||||
|
||||
await waitFor(() => {
|
||||
expect(capturedSwipeNavigation.current?.backTarget()).toBe(
|
||||
getServerProjectPath('srv_kitchen', '/home/me/app'),
|
||||
)
|
||||
})
|
||||
|
||||
unmount()
|
||||
|
||||
expect(capturedSwipeNavigation.current?.backTarget()).toBeNull()
|
||||
})
|
||||
|
||||
it('falls back to the projects list when the session is not found', async () => {
|
||||
mocks.useSession.mockReturnValue({
|
||||
data: undefined,
|
||||
isLoading: false,
|
||||
error: new FetchError('Session not found', 404),
|
||||
})
|
||||
|
||||
const { capturedPathname } = renderRemoteSession()
|
||||
|
||||
fireEvent.click(await screen.findByRole('button', { name: 'Back to projects' }))
|
||||
|
||||
expect(capturedPathname.current).toBe('/')
|
||||
})
|
||||
|
||||
it('uses the session directory as the only directory source', async () => {
|
||||
renderRemoteSession()
|
||||
|
||||
|
||||
Reference in new issue
Block a user