feat(schedules): switch repository from the schedules header

- add ScheduleRepoSwitcher: the header title opens a picker with All
  repos and every repository, on desktop (dropdown) and mobile (sheet
  with search)
- wire it into the per-repo schedules header and the all-repos header so
  the scope can be changed from either page
- mark the current scope active and navigate on selection
This commit is contained in:
Chris Scott committed 2026-10-06 11:21:51 -04:00
1 parent 8ac0f31758
commit 7612ee31e5
7 files changed
+329 -4

No files matched your search

@@ -0,0 +1,143 @@
import { render, screen, waitFor, fireEvent, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, it, expect, vi } from 'vitest'
import { MemoryRouter, useLocation } from 'react-router-dom'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { ScheduleRepoSwitcher } from './ScheduleRepoSwitcher'
import { listRepos } from '@/api/repos'
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
const mobileState = { current: false }
vi.mock('@/hooks/useMobile', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/hooks/useMobile')>()
return { ...actual, useMobile: () => mobileState.current }
})
vi.mock('@/api/repos')
function createRepo(id: number, name: string) {
return {
id,
name,
repoUrl: `https://github.com/test/${name}.git`,
localPath: `${name}-path`,
fullPath: `/repos/${name}-path`,
sourcePath: null,
currentBranch: 'main',
defaultBranch: 'main',
cloneStatus: 'ready' as const,
clonedAt: 0,
lastAccessedAt: 0,
isLocal: false,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
}
}
function LocationSpy() {
const { pathname } = useLocation()
return <div data-testid="location">{pathname}</div>
}
function renderSwitcher(repoId: number | undefined, name: string) {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
return render(
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={['/repos/1/schedules']}>
<ScheduleRepoSwitcher repoId={repoId} name={name} />
<LocationSpy />
</MemoryRouter>
</QueryClientProvider>,
)
}
describe('ScheduleRepoSwitcher', () => {
beforeEach(() => {
vi.clearAllMocks()
mobileState.current = false
vi.mocked(listRepos).mockResolvedValue([
createRepo(1, 'repo1'),
createRepo(2, 'repo2'),
createRepo(ASSISTANT_REPO_ID, 'Assistant'),
])
})
it('shows the current repository and switches to another repo (desktop)', async () => {
const user = userEvent.setup()
renderSwitcher(1, 'repo1')
await user.click(screen.getByRole('button', { name: 'Switch repository (repo1)' }))
await waitFor(() => expect(screen.getByText('All repos')).toBeInTheDocument())
expect(screen.getByText('repo2')).toBeInTheDocument()
await user.click(screen.getByText('repo2'))
await waitFor(() => expect(screen.getByTestId('location')).toHaveTextContent('/repos/2/schedules'))
})
it('switches to all repos', async () => {
const user = userEvent.setup()
renderSwitcher(1, 'repo1')
await user.click(screen.getByRole('button', { name: 'Switch repository (repo1)' }))
await waitFor(() => expect(screen.getByText('All repos')).toBeInTheDocument())
await user.click(screen.getByText('All repos'))
await waitFor(() => expect(screen.getByTestId('location')).toHaveTextContent('/schedules'))
})
it('marks the current repository as active', async () => {
const user = userEvent.setup()
renderSwitcher(1, 'repo1')
await user.click(screen.getByRole('button', { name: 'Switch repository (repo1)' }))
const menu = await screen.findByRole('menu')
expect(within(menu).getByText('repo1').closest('[aria-current="true"]')).not.toBeNull()
expect(within(menu).getByText('repo2').closest('[aria-current="true"]')).toBeNull()
})
it('navigates to the assistant schedules for repo 0', async () => {
const user = userEvent.setup()
renderSwitcher(ASSISTANT_REPO_ID, 'Assistant')
await user.click(screen.getByRole('button', { name: 'Switch repository (Assistant)' }))
await waitFor(() => expect(screen.getByText('repo2')).toBeInTheDocument())
await user.click(screen.getByText('repo2'))
await waitFor(() => expect(screen.getByTestId('location')).toHaveTextContent('/repos/2/schedules'))
})
it('filters repositories by search on mobile', async () => {
mobileState.current = true
renderSwitcher(1, 'repo1')
fireEvent.click(screen.getByRole('button', { name: 'Switch repository (repo1)' }))
const search = await screen.findByPlaceholderText('Search repositories...')
fireEvent.change(search, { target: { value: 'repo2' } })
const sheet = screen.getByRole('dialog', { name: 'Switch repository' })
await waitFor(() => {
expect(within(sheet).getByText('repo2')).toBeInTheDocument()
expect(within(sheet).queryByText('repo1')).not.toBeInTheDocument()
})
})
it('switches repositories from the mobile sheet', async () => {
mobileState.current = true
renderSwitcher(1, 'repo1')
fireEvent.click(screen.getByRole('button', { name: 'Switch repository (repo1)' }))
await screen.findByPlaceholderText('Search repositories...')
await waitFor(() => expect(screen.getByText('repo2')).toBeInTheDocument())
fireEvent.click(screen.getByText('repo2'))
await waitFor(() => expect(screen.getByTestId('location')).toHaveTextContent('/repos/2/schedules'))
})
})
@@ -0,0 +1,176 @@
import { Fragment, useMemo, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Check, ChevronsUpDown, FolderGit2, LayoutGrid } from 'lucide-react'
import { getRepoDisplayName } from '@/lib/utils'
import { useMobile } from '@/hooks/useMobile'
import { useNavigableRepos } from '@/hooks/useSidebarRepoGroups'
import { Input } from '@/components/ui/input'
import { BottomSheet, BottomSheetContent, BottomSheetHeader } from '@/components/ui/bottom-sheet'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
const ALL_REPOS_PATH = '/schedules'
interface ScheduleRepoSwitcherProps {
repoId?: number
name: string
}
interface RepoOption {
key: string
label: string
description: string
path: string
active: boolean
isAllRepos: boolean
}
function schedulePath(repoId: number): string {
return `/repos/${repoId}/schedules`
}
export function ScheduleRepoSwitcher({ repoId, name }: ScheduleRepoSwitcherProps) {
const navigate = useNavigate()
const isMobile = useMobile()
const [open, setOpen] = useState(false)
const [search, setSearch] = useState('')
const { repos } = useNavigableRepos()
const options = useMemo<RepoOption[]>(() => {
const allRepos: RepoOption = {
key: 'all',
label: 'All repos',
description: 'Every repository',
path: ALL_REPOS_PATH,
active: repoId === undefined,
isAllRepos: true,
}
const repoOptions = repos.map((repo): RepoOption => {
const label = getRepoDisplayName(repo)
const localPath = repo.localPath ?? ''
return {
key: String(repo.id),
label,
description: localPath && localPath !== label ? localPath : '',
path: schedulePath(repo.id),
active: repo.id === repoId,
isAllRepos: false,
}
})
return [allRepos, ...repoOptions]
}, [repos, repoId])
const filteredOptions = useMemo(() => {
const term = search.trim().toLowerCase()
if (!term) return options
return options.filter((option) => (
option.label.toLowerCase().includes(term) || option.description.toLowerCase().includes(term)
))
}, [options, search])
const close = () => {
setOpen(false)
setSearch('')
}
const select = (option: RepoOption) => {
close()
if (!option.active) navigate(option.path)
}
const renderOptionContent = (option: RepoOption) => (
<>
{option.isAllRepos ? (
<LayoutGrid className="h-4 w-4 shrink-0 text-muted-foreground" />
) : (
<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-medium">{option.label}</span>
{option.description && <span className="block truncate text-xs text-muted-foreground">{option.description}</span>}
</span>
{option.active && <Check className="h-4 w-4 shrink-0 text-primary" />}
</>
)
const trigger = (onClick?: () => void) => (
<button
type="button"
onClick={onClick}
aria-haspopup="menu"
aria-expanded={open}
aria-label={`Switch repository (${name})`}
className="group flex min-w-0 items-center gap-1.5 rounded px-1 -mx-1 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
<span className="truncate text-xl font-semibold bg-gradient-to-r from-foreground to-muted-foreground bg-clip-text text-transparent">{name}</span>
<ChevronsUpDown className="h-4 w-4 shrink-0 text-muted-foreground transition-colors group-hover:text-foreground" />
</button>
)
if (isMobile) {
return (
<>
{trigger(() => setOpen(true))}
<BottomSheet isOpen={open} onClose={close} heightClass="h-[70dvh]" ariaLabel="Switch repository">
<BottomSheetHeader title="Switch repository" className="border-b-0">
<Input
type="text"
placeholder="Search repositories..."
value={search}
onChange={(event) => setSearch(event.target.value)}
autoComplete="off"
name="schedule-repo-switch"
className="mt-2"
/>
</BottomSheetHeader>
<BottomSheetContent className="px-0 pt-0">
{filteredOptions.length === 0 ? (
<div className="flex flex-col items-center justify-center px-4 py-12 text-muted-foreground">
<FolderGit2 className="mb-3 h-12 w-12 opacity-50" />
<p className="text-sm">No repositories found</p>
</div>
) : (
<div className="flex flex-col">
{filteredOptions.map((option) => (
<button
key={option.key}
type="button"
onClick={() => select(option)}
aria-current={option.active ? 'true' : undefined}
className="flex items-center gap-3 px-4 py-3 text-left hover:bg-accent"
>
{renderOptionContent(option)}
</button>
))}
</div>
)}
<div aria-hidden="true" className="h-16 shrink-0" />
</BottomSheetContent>
</BottomSheet>
</>
)
}
return (
<DropdownMenu open={open} onOpenChange={(next) => (next ? setOpen(true) : close())}>
<DropdownMenuTrigger asChild>{trigger()}</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="max-h-[60vh] w-64 overflow-auto">
<DropdownMenuLabel>Switch repository</DropdownMenuLabel>
{options.map((option, index) => (
<Fragment key={option.key}>
{index === 1 && <DropdownMenuSeparator />}
<DropdownMenuItem onSelect={() => select(option)} aria-current={option.active ? 'true' : undefined} className="gap-2">
{renderOptionContent(option)}
</DropdownMenuItem>
</Fragment>
))}
</DropdownMenuContent>
</DropdownMenu>
)
}
@@ -10,3 +10,4 @@ export { ScheduleRunMarkdown } from './ScheduleRunMarkdown'
export { ScheduleTabMenu } from './ScheduleTabMenu'
export { PromptsTab } from './PromptsTab'
export { ScheduleListToolbar } from './ScheduleListToolbar'
export { ScheduleRepoSwitcher } from './ScheduleRepoSwitcher'
+5 -2
View File
@@ -2,7 +2,7 @@ import { useState, useMemo, useEffect, useRef, useCallback } from 'react'
import { useNavigate } from 'react-router-dom'
import { useAllSchedules, useAllScheduleRuns, useCancelRepoScheduleRun, useUnreadScheduleRuns } from '@/hooks/useSchedules'
import { useDeleteRepoSchedule, useRunRepoSchedule, useUpdateRepoSchedule, useCreateRepoSchedule } from '@/hooks/useSchedules'
import { ScheduleJobDialog, PromptsTab, ScheduleJobsTable, ScheduleListToolbar, ScheduleRunDrawer, ScheduleRunsTable } from '@/components/schedules'
import { ScheduleJobDialog, PromptsTab, ScheduleJobsTable, ScheduleListToolbar, ScheduleRunDrawer, ScheduleRunsTable, ScheduleRepoSwitcher } from '@/components/schedules'
import type { CreateScheduleJobRequest } from '@opencode-manager/shared/types'
import { DELETE_SCHEDULE_DESCRIPTION, matchesScheduleJobSearch, toUpdateScheduleRequest } from '@/components/schedules/schedule-utils'
import { Header } from '@/components/ui/header'
@@ -402,7 +402,10 @@ export function GlobalSchedules() {
<div className="h-dvh max-h-dvh overflow-hidden bg-background flex flex-col">
<Header>
<Header.BackButton to="/" />
<Header.Title>Schedules</Header.Title>
<div className="min-w-0 flex-1 px-3">
<ScheduleRepoSwitcher name="All repos" />
<p className="text-xs text-muted-foreground truncate">Schedules</p>
</div>
<div className="flex items-center gap-2">
<Header.Actions>
<ScheduleReportsBell />
+2 -2
View File
@@ -17,7 +17,7 @@ import {
import { useRepoActivity } from '@/hooks/useRepoActivity'
import { useScheduleTarget } from '@/hooks/useScheduleTarget'
import { useScheduleUrlState } from '@/hooks/useScheduleUrlState'
import { ScheduleJobDialog, ScheduleJobsTable, ScheduleListToolbar, JobDetailTab, RunHistoryTab, ScheduleRunRemovalDialog, ScheduleTabMenu } from '@/components/schedules'
import { ScheduleJobDialog, ScheduleJobsTable, ScheduleListToolbar, JobDetailTab, RunHistoryTab, ScheduleRunRemovalDialog, ScheduleTabMenu, ScheduleRepoSwitcher } from '@/components/schedules'
import { DELETE_SCHEDULE_DESCRIPTION, matchesScheduleJobSearch, toUpdateScheduleRequest } from '@/components/schedules/schedule-utils'
import type { ScheduleJobWithRepo } from '@/api/schedules'
import { Header } from '@/components/ui/header'
@@ -261,7 +261,7 @@ export function Schedules() {
<Header>
<Header.BackButton to={backHref} />
<div className="min-w-0 flex-1 px-3">
<Header.Title className="truncate">{scheduleTarget.name}</Header.Title>
<ScheduleRepoSwitcher repoId={repoId} name={scheduleTarget.name} />
<p className="text-xs text-muted-foreground truncate">{scheduleTarget.subtitle}</p>
</div>
<div className="flex items-center gap-2">
@@ -45,6 +45,7 @@ vi.mock('@/components/schedules', () => ({
ScheduleRunDrawer: mocks.ScheduleRunDrawer,
ScheduleListToolbar: ({ children }: { children?: React.ReactNode }) => <div>{children}</div>,
PromptsTab: vi.fn(() => null),
ScheduleRepoSwitcher: ({ name }: { name: string }) => <div>{name}</div>,
}))
function makeRun(overrides: Record<string, unknown> = {}) {
@@ -77,6 +77,7 @@ vi.mock('@/components/schedules', () => ({
RunHistoryTab: vi.fn(() => <div>RunHistoryTab</div>),
ScheduleRunRemovalDialog: () => null,
ScheduleTabMenu: vi.fn(() => <div>ScheduleTabMenu</div>),
ScheduleRepoSwitcher: ({ name }: { name: string }) => <div>{name}</div>,
}))
function createMockScheduleUrlState(overrides: Record<string, unknown> = {}) {