diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index fa1cbbe2..071b656d 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -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(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: ( - - - - ), + element: , loader: protectedLoader, }, { diff --git a/frontend/src/components/navigation/LinkedServersNav.test.tsx b/frontend/src/components/navigation/LinkedServersNav.test.tsx index 1c418c43..27d4cc4d 100644 --- a/frontend/src/components/navigation/LinkedServersNav.test.tsx +++ b/frontend/src/components/navigation/LinkedServersNav.test.tsx @@ -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
{`${location.pathname}${location.search}`}
} +function SidebarServerRouteSync() { + useSidebarServerRouteSync() + return null +} + function renderNav(pathname = '/', variant?: 'sidebar' | 'rail' | 'sheet') { return render( + , diff --git a/frontend/src/components/navigation/MobileTabBar.test.tsx b/frontend/src/components/navigation/MobileTabBar.test.tsx index 03f2c10f..018e19b0 100644 --- a/frontend/src/components/navigation/MobileTabBar.test.tsx +++ b/frontend/src/components/navigation/MobileTabBar.test.tsx @@ -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( , ) - 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( - + @@ -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( + + + + + , + ) + 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() diff --git a/frontend/src/components/navigation/MobileTabBar.tsx b/frontend/src/components/navigation/MobileTabBar.tsx index 2176aacc..ea581614 100644 --- a/frontend/src/components/navigation/MobileTabBar.tsx +++ b/frontend/src/components/navigation/MobileTabBar.tsx @@ -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['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, ], ) diff --git a/frontend/src/components/repo/RemoteMultiRunButton.tsx b/frontend/src/components/repo/RemoteMultiRunButton.tsx index 6396a414..2ba6e834 100644 --- a/frontend/src/components/repo/RemoteMultiRunButton.tsx +++ b/frontend/src/components/repo/RemoteMultiRunButton.tsx @@ -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 ( + + ) +} + +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 {mounted ? ( - -
-
-
-
-

- {repoName} -

- {isReady && ( -
- )} - -
- - {!manageMode && !isSelected && !hasSelectedRepos && ( - - )} -
- -
-
- {isCloning ? ( - - - Cloning... - - ) : ( - <> - - - {branchToDisplay || "main"} - - {isDirty && ( - - - - {unstagedCount > 0 && unstagedCount} - {unstagedCount > 0 && stagedCount > 0 && "/"} - {stagedCount > 0 && `${stagedCount}s`} - - - )} - {(ahead > 0 || behind > 0) && ( - - - {ahead > 0 && `↑${ahead}`} - {behind > 0 && `↓${behind}`} - - - )} - {repo.isLocal && ( - - - - )} - - )} -
- - {activityLabel && ( - - {activityLabel} - - )} -
-
-
-
+ const meta = isCloning ? ( + + + Cloning... + + ) : ( + <> + + + {branchToDisplay || "main"} + + {isDirty && ( + + + + {unstagedCount > 0 && unstagedCount} + {unstagedCount > 0 && stagedCount > 0 && "/"} + {stagedCount > 0 && `${stagedCount}s`} + + + )} + {(ahead > 0 || behind > 0) && ( + + + {ahead > 0 && `↑${ahead}`} + {behind > 0 && `↓${behind}`} + + + )} + {repo.isLocal && ( + + + + )} + ); -} \ No newline at end of file + + return ( + } + actions={ + !manageMode && !isSelected && !hasSelectedRepos ? ( + + ) : undefined + } + meta={meta} + activityLabel={activityLabel} + isInteractive={isReady} + isSelected={isSelected} + onClick={handleCardClick} + /> + ); +} diff --git a/frontend/src/components/repo/RepoCardShell.tsx b/frontend/src/components/repo/RepoCardShell.tsx new file mode 100644 index 00000000..8a5086f4 --- /dev/null +++ b/frontend/src/components/repo/RepoCardShell.tsx @@ -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 ( +
+
+
+
+
+

+ {title} +

+ {statusDotClassName && ( +
+ )} + {activity} +
+ + {actions} +
+ +
+
+ {meta} +
+ + {activityLabel && ( + + {activityLabel} + + )} +
+
+
+
+ ); +} diff --git a/frontend/src/components/repo/RepoListControls.tsx b/frontend/src/components/repo/RepoListControls.tsx index e780c04c..ba24ca88 100644 --- a/frontend/src/components/repo/RepoListControls.tsx +++ b/frontend/src/components/repo/RepoListControls.tsx @@ -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 (
-
- - onSearchChange(e.target.value)} - placeholder="Search repositories..." - className="pl-9 h-9" - autoComplete="off" - name="repo-search" - /> -
+ {isMobile ? ( diff --git a/frontend/src/components/repo/RepoSearchInput.tsx b/frontend/src/components/repo/RepoSearchInput.tsx new file mode 100644 index 00000000..61e9a084 --- /dev/null +++ b/frontend/src/components/repo/RepoSearchInput.tsx @@ -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 ( +
+ + onValueChange(event.target.value)} + placeholder={placeholder} + className="pl-9 h-9" + autoComplete="off" + name={name} + /> +
+ ); +} diff --git a/frontend/src/components/schedules/RemoteSchedulesButton.tsx b/frontend/src/components/schedules/RemoteSchedulesButton.tsx index 775db89f..6335ea27 100644 --- a/frontend/src/components/schedules/RemoteSchedulesButton.tsx +++ b/frontend/src/components/schedules/RemoteSchedulesButton.tsx @@ -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 } /** * 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 Schedules - + ) } diff --git a/frontend/src/components/servers/ConnectionStatus.tsx b/frontend/src/components/servers/ConnectionStatus.tsx new file mode 100644 index 00000000..80c86762 --- /dev/null +++ b/frontend/src/components/servers/ConnectionStatus.tsx @@ -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 Checking connection... + } + + if (!status) { + return ( + + + Unknown + + ) + } + + if (!status.connected) { + return ( + + + Unreachable + {status.error ? · {status.error} : null} + + ) + } + + return ( + + + Connected + {status.version ? · v{status.version} : null} + + ) +} diff --git a/frontend/src/components/servers/RemoteProjectList.tsx b/frontend/src/components/servers/RemoteProjectList.tsx new file mode 100644 index 00000000..0ea7b65b --- /dev/null +++ b/frontend/src/components/servers/RemoteProjectList.tsx @@ -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 ( + } + actions={} + meta={ + + {project.vcs ? ( + + ) : ( + + )} + {project.canonical} + + } + activityLabel={updatedAt > 0 ? formatShortRelativeTime(new Date(updatedAt)) : undefined} + isInteractive + onClick={() => navigate(getServerProjectPath(serverId, project.canonical))} + /> + ) +} + +function RemoteProjectListLoading() { + return ( +
+
+
+
+
+
+
+ {Array.from({ length: 6 }).map((_, index) => ( + + ))} +
+
+
+
+ ) +} + +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 ( +
+ {!serversLoading && !server ? ( + + ) : null} + + {isDisabled ? ( + + ) : null} + + {server && !isDisabled && projectsQuery.isError ? ( + + +
+

Could not load projects

+

+ {projectsQuery.error instanceof Error + ? projectsQuery.error.message + : 'The server did not respond.'} +

+
+ +
+ ) : null} + + {server && !isDisabled && !projectsQuery.isError ? ( + projectsQuery.isLoading ? ( + + ) : projects.length === 0 ? ( +
+ +

No projects on this server yet

+

+ Start a session in a directory below to create one. +

+
+ ) : ( + <> +
+ +
+
+
+ {filteredProjects.length === 0 ? ( +
+ +

+ No projects found matching "{searchQuery}" +

+
+ ) : ( +
+ {filteredProjects.map((project) => ( + + ))} +
+ )} +
+
+ + ) + ) : null} + + {server && !isDisabled ? ( +
+

Open directory

+
+ setOpenDirectory(event.target.value)} + placeholder="/absolute/path/on/the/server" + aria-label="Directory path" + autoComplete="off" + name="remote-directory" + className="font-mono text-sm" + /> + +
+
+ ) : null} +
+ ) +} + +/** + * 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 ( + + + + ) +} diff --git a/frontend/src/components/servers/RemoteProjectRowActions.tsx b/frontend/src/components/servers/RemoteProjectRowActions.tsx new file mode 100644 index 00000000..3b58840e --- /dev/null +++ b/frontend/src/components/servers/RemoteProjectRowActions.tsx @@ -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 ( + + + + + {label} + + ) +} + +/** + * 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 ( +
event.stopPropagation()}> + {isMobile ? ( + + + + + event.stopPropagation()} + onPointerDown={(event) => event.stopPropagation()} + > + { + void handleNewSession() + }} + disabled={createSession.isPending} + > + {createSession.isPending ? ( + + ) : ( + + )} + New session + + setSchedulesOpen(true)}> + + Schedules + + + + Multi-run + + + + ) : ( + +
+ { + void handleNewSession() + }} + disabled={createSession.isPending} + > + {createSession.isPending ? : } + + setSchedulesOpen(true)}> + + + + + +
+
+ )} + + + {multiRunMounted ? ( + + ) : null} +
+ ) +} diff --git a/frontend/src/components/servers/__tests__/RemoteProjectList.test.tsx b/frontend/src/components/servers/__tests__/RemoteProjectList.test.tsx new file mode 100644 index 00000000..8fd227f7 --- /dev/null +++ b/frontend/src/components/servers/__tests__/RemoteProjectList.test.tsx @@ -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 ? ( +
+ ) : null, +})) + +vi.mock('@/components/repo/MultiRunSheet', () => ({ + MultiRunSheet: ({ + open, + target, + directory, + }: { + open: boolean + target: { kind: string; serverId?: string; directory?: string } + directory?: string + }) => ( +
+ ), +})) + +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( + + + + } /> + } /> + } /> + + + , + ) +} + +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') + }) + }) +}) diff --git a/frontend/src/contexts/SwipeNavigationContext.test.tsx b/frontend/src/contexts/SwipeNavigationContext.test.tsx index 7033519c..fa6435b2 100644 --- a/frontend/src/contexts/SwipeNavigationContext.test.tsx +++ b/frontend/src/contexts/SwipeNavigationContext.test.tsx @@ -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 diff --git a/frontend/src/contexts/SwipeNavigationContext.tsx b/frontend/src/contexts/SwipeNavigationContext.tsx index e51af5a3..154e3140 100644 --- a/frontend/src/contexts/SwipeNavigationContext.tsx +++ b/frontend/src/contexts/SwipeNavigationContext.tsx @@ -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(null) function SwipeNavigationProvider({ children }: { children: ReactNode }) { const countRef = useRef(0) + const backTargetRef = useRef(null) const value = useMemo( () => ({ 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, }), [] ) diff --git a/frontend/src/hooks/useSidebarServerSelection.test.tsx b/frontend/src/hooks/useSidebarServerSelection.test.tsx index a84a999c..7d0ce93e 100644 --- a/frontend/src/hooks/useSidebarServerSelection.test.tsx +++ b/frontend/src/hooks/useSidebarServerSelection.test.tsx @@ -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 ? : null}
{serverId}
+ + + ) +} + +function renderHarness(initialEntry = '/', options?: { syncRoute?: boolean }) { return render( - + , ) } -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( + + + , ) + + 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') }) }) diff --git a/frontend/src/hooks/useSidebarServerSelection.ts b/frontend/src/hooks/useSidebarServerSelection.ts index 5f37b554..e0e18e8a 100644 --- a/frontend/src/hooks/useSidebarServerSelection.ts +++ b/frontend/src/hooks/useSidebarServerSelection.ts @@ -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] } diff --git a/frontend/src/lib/navigation.test.ts b/frontend/src/lib/navigation.test.ts index 37e8c287..d30c2a35 100644 --- a/frontend/src/lib/navigation.test.ts +++ b/frontend/src/lib/navigation.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { getSessionListPath, getSwipeBackTarget, getAssistantPath, getAssistantSessionListPath, isAssistantPath, getPathWithReturnTo, getReturnToPath, getRepoPath, getServerPath, 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', () => { diff --git a/frontend/src/lib/navigation.ts b/frontend/src/lib/navigation.ts index f6626619..e90bc011 100644 --- a/frontend/src/lib/navigation.ts +++ b/frontend/src/lib/navigation.ts @@ -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)) { diff --git a/frontend/src/pages/GlobalSchedules.tsx b/frontend/src/pages/GlobalSchedules.tsx index f41d5d7b..02f26a4e 100644 --- a/frontend/src/pages/GlobalSchedules.tsx +++ b/frontend/src/pages/GlobalSchedules.tsx @@ -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(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`) diff --git a/frontend/src/pages/LinkedServerRedirect.tsx b/frontend/src/pages/LinkedServerRedirect.tsx new file mode 100644 index 00000000..1fbbaedc --- /dev/null +++ b/frontend/src/pages/LinkedServerRedirect.tsx @@ -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 +} diff --git a/frontend/src/pages/RemoteProject.tsx b/frontend/src/pages/RemoteProject.tsx index d83fb177..3d4563ca 100644 --- a/frontend/src/pages/RemoteProject.tsx +++ b/frontend/src/pages/RemoteProject.tsx @@ -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
- + {title} @@ -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('/')} />
) : isReady ? ( diff --git a/frontend/src/pages/RemoteServer.tsx b/frontend/src/pages/RemoteServer.tsx deleted file mode 100644 index 1910ff46..00000000 --- a/frontend/src/pages/RemoteServer.tsx +++ /dev/null @@ -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 Checking connection... - } - - if (!status) { - return ( - - - Unknown - - ) - } - - if (!status.connected) { - return ( - - - Unreachable - {status.error ? · {status.error} : null} - - ) - } - - return ( - - - Connected - {status.version ? · v{status.version} : null} - - ) -} - -function ProjectSessions({ serverId, directory }: { serverId: string; directory: string }) { - useSSE(directory) - const { data: sessions, isLoading } = useSessionsAcrossDirectories([directory]) - - if (isLoading) { - return ( -
- - Loading sessions... -
- ) - } - - if (sessions.length === 0) { - return

No sessions in this project yet.

- } - - return ( -
    - {sessions.map((session) => ( -
  • - - - - {session.title || 'Untitled Session'} - - - {formatDistanceToNow(new Date(session.time.updated), { addSuffix: true })} - - -
  • - ))} -
- ) -} - -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 ( - -
- - - - - {name} - {project.canonical} - - {project.vcs ? ( - - {project.vcs} - - ) : null} - - - - -
- {expanded ? : null} -
- ) -} - -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 ( -
-
-
- - {server?.name ?? 'Linked server'} - - {server?.baseUrl} - -
- - - - -
- -
- {!serversLoading && !server ? ( - - ) : null} - - {isDisabled ? ( - - ) : null} - - {server && !isDisabled && projectsQuery.isError ? ( - - -
-

Could not load projects

-

- {projectsQuery.error instanceof Error - ? projectsQuery.error.message - : 'The server did not respond.'} -

-
- -
- ) : null} - - {server && !isDisabled && !projectsQuery.isError ? ( -
-
-

Projects

- {projectsQuery.isFetching ? ( - - - Refreshing - - ) : null} -
- - {projectsQuery.isLoading ? ( - - - Loading projects... - - ) : (projectsQuery.data ?? []).length === 0 ? ( - - -

No projects on this server yet

-

- Start a session in a directory below to create one. -

-
- ) : ( - (projectsQuery.data ?? []).map((project) => ( - - )) - )} -
- ) : null} - - {server && !isDisabled ? ( -
-

Open directory

-
- setOpenDirectory(event.target.value)} - placeholder="/absolute/path/on/the/server" - aria-label="Directory path" - autoComplete="off" - name="remote-directory" - className="font-mono text-sm" - /> - -
-
- ) : null} -
-
- ) -} - -export function RemoteServer() { - const { serverId } = useParams<{ serverId: string }>() - - if (!serverId) { - return null - } - - return -} diff --git a/frontend/src/pages/Repos.tsx b/frontend/src/pages/Repos.tsx index 6850f6f0..222c317e 100644 --- a/frontend/src/pages/Repos.tsx +++ b/frontend/src/pages/Repos.tsx @@ -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 ( + <> + + + + + + ); +} 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() {
- + {isLocalServer ? ( + + ) : ( + + )} - + {isLocalServer ? ( + + ) : null}
- - + {isLocalServer ? : }
- - + {isLocalServer ? ( + + ) : null} + {isLocalServer ? ( + + ) : null}
- {docked && } + {isLocalServer && docked ? : null}
); } diff --git a/frontend/src/pages/SessionDetail.tsx b/frontend/src/pages/SessionDetail.tsx index 3b8a4ecc..7720333d 100644 --- a/frontend/src/pages/SessionDetail.tsx +++ b/frontend/src/pages/SessionDetail.tsx @@ -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 ( ); } @@ -727,8 +740,8 @@ export function SessionDetail() { return ( ); } @@ -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 ( diff --git a/frontend/src/pages/__tests__/GlobalSchedules.test.tsx b/frontend/src/pages/__tests__/GlobalSchedules.test.tsx index b3b8ff80..190dd089 100644 --- a/frontend/src/pages/__tests__/GlobalSchedules.test.tsx +++ b/frontend/src/pages/__tests__/GlobalSchedules.test.tsx @@ -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( + + + + , + { 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 })) diff --git a/frontend/src/pages/__tests__/LinkedServerRedirect.test.tsx b/frontend/src/pages/__tests__/LinkedServerRedirect.test.tsx new file mode 100644 index 00000000..6869841b --- /dev/null +++ b/frontend/src/pages/__tests__/LinkedServerRedirect.test.tsx @@ -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( + + + } /> + home
} /> + + , + ) +} + +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') + }) +}) diff --git a/frontend/src/pages/__tests__/RemoteProject.test.tsx b/frontend/src/pages/__tests__/RemoteProject.test.tsx index ecdcd2da..1c4053a2 100644 --- a/frontend/src/pages/__tests__/RemoteProject.test.tsx +++ b/frontend/src/pages/__tests__/RemoteProject.test.tsx @@ -82,8 +82,8 @@ function renderProject(path = '/servers/srv_kitchen/projects?directory=%2Fhome%2 + } /> } /> - } /> } /> @@ -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() }) }) diff --git a/frontend/src/pages/__tests__/RemoteServer.test.tsx b/frontend/src/pages/__tests__/RemoteServer.test.tsx deleted file mode 100644 index 115490f3..00000000 --- a/frontend/src/pages/__tests__/RemoteServer.test.tsx +++ /dev/null @@ -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( - - - - } /> - } /> - - - , - ) -} - -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') - }) -}) diff --git a/frontend/src/pages/__tests__/Repos.test.tsx b/frontend/src/pages/__tests__/Repos.test.tsx new file mode 100644 index 00000000..4fb6460a --- /dev/null +++ b/frontend/src/pages/__tests__/Repos.test.tsx @@ -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: () =>
local-repos
, +})) + +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 }) => ( +
remote-projects:{serverId}
+ ), +})) + +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
{useLocation().pathname}
+} + +function renderRepos() { + return render( + + + + } /> + + , + ) +} + +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') + }) +}) diff --git a/frontend/src/pages/__tests__/SessionDetail.remote.test.tsx b/frontend/src/pages/__tests__/SessionDetail.remote.test.tsx index e6b5cdf8..fcadbc86 100644 --- a/frontend/src/pages/__tests__/SessionDetail.remote.test.tsx +++ b/frontend/src/pages/__tests__/SessionDetail.remote.test.tsx @@ -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 + +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( - - - - - } /> - - - + + + + + + + + + } /> + + + + , ) - 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()